beautify.js 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  1. /*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
  2. /*
  3. The MIT License (MIT)
  4. Copyright (c) 2007-2013 Einar Lielmanis and contributors.
  5. Permission is hereby granted, free of charge, to any person
  6. obtaining a copy of this software and associated documentation files
  7. (the "Software"), to deal in the Software without restriction,
  8. including without limitation the rights to use, copy, modify, merge,
  9. publish, distribute, sublicense, and/or sell copies of the Software,
  10. and to permit persons to whom the Software is furnished to do so,
  11. subject to the following conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  19. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. JS Beautifier
  23. ---------------
  24. Written by Einar Lielmanis, <einar@jsbeautifier.org>
  25. http://jsbeautifier.org/
  26. Originally converted to javascript by Vital, <vital76@gmail.com>
  27. "End braces on own line" added by Chris J. Shull, <chrisjshull@gmail.com>
  28. Parsing improvements for brace-less statements by Liam Newman <bitwiseman@gmail.com>
  29. Usage:
  30. js_beautify(js_source_text);
  31. js_beautify(js_source_text, options);
  32. The options are:
  33. indent_size (default 4) - indentation size,
  34. indent_char (default space) - character to indent with,
  35. preserve_newlines (default true) - whether existing line breaks should be preserved,
  36. max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk,
  37. jslint_happy (default false) - if true, then jslint-stricter mode is enforced.
  38. jslint_happy !jslint_happy
  39. ---------------------------------
  40. function () function()
  41. switch () { switch() {
  42. case 1: case 1:
  43. break; break;
  44. } }
  45. space_after_anon_function (default false) - should the space before an anonymous function's parens be added, "function()" vs "function ()",
  46. NOTE: This option is overriden by jslint_happy (i.e. if jslint_happy is true, space_after_anon_function is true by design)
  47. brace_style (default "collapse") - "collapse" | "expand" | "end-expand" | "none"
  48. put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line, or attempt to keep them where they are.
  49. space_before_conditional (default true) - should the space before conditional statement be added, "if(true)" vs "if (true)",
  50. unescape_strings (default false) - should printable characters in strings encoded in \xNN notation be unescaped, "example" vs "\x65\x78\x61\x6d\x70\x6c\x65"
  51. wrap_line_length (default unlimited) - lines should wrap at next opportunity after this number of characters.
  52. NOTE: This is not a hard limit. Lines will continue until a point where a newline would
  53. be preserved if it were present.
  54. end_with_newline (default false) - end output with a newline
  55. e.g
  56. js_beautify(js_source_text, {
  57. 'indent_size': 1,
  58. 'indent_char': '\t'
  59. });
  60. */
  61. (function() {
  62. var acorn = {};
  63. (function (exports) {
  64. // This section of code is taken from acorn.
  65. //
  66. // Acorn was written by Marijn Haverbeke and released under an MIT
  67. // license. The Unicode regexps (for identifiers and whitespace) were
  68. // taken from [Esprima](http://esprima.org) by Ariya Hidayat.
  69. //
  70. // Git repositories for Acorn are available at
  71. //
  72. // http://marijnhaverbeke.nl/git/acorn
  73. // https://github.com/marijnh/acorn.git
  74. // ## Character categories
  75. // Big ugly regular expressions that match characters in the
  76. // whitespace, identifier, and identifier-start categories. These
  77. // are only applied when a character is found to actually have a
  78. // code point above 128.
  79. var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  80. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  81. var nonASCIIidentifierChars = "\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  82. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  83. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  84. // Whether a single character denotes a newline.
  85. var newline = exports.newline = /[\n\r\u2028\u2029]/;
  86. // Matches a whole line break (where CRLF is considered a single
  87. // line break). Used to count lines.
  88. var lineBreak = exports.lineBreak = /\r\n|[\n\r\u2028\u2029]/g;
  89. // Test whether a given character code starts an identifier.
  90. var isIdentifierStart = exports.isIdentifierStart = function(code) {
  91. if (code < 65) return code === 36;
  92. if (code < 91) return true;
  93. if (code < 97) return code === 95;
  94. if (code < 123)return true;
  95. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  96. };
  97. // Test whether a given character is part of an identifier.
  98. var isIdentifierChar = exports.isIdentifierChar = function(code) {
  99. if (code < 48) return code === 36;
  100. if (code < 58) return true;
  101. if (code < 65) return false;
  102. if (code < 91) return true;
  103. if (code < 97) return code === 95;
  104. if (code < 123)return true;
  105. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  106. };
  107. })(acorn);
  108. function in_array(what, arr) {
  109. for (var i = 0; i < arr.length; i += 1) {
  110. if (arr[i] === what) {
  111. return true;
  112. }
  113. }
  114. return false;
  115. }
  116. function trim(s) {
  117. return s.replace(/^\s+|\s+$/g, '');
  118. }
  119. function ltrim(s) {
  120. return s.replace(/^\s+/g, '');
  121. }
  122. function rtrim(s) {
  123. return s.replace(/\s+$/g, '');
  124. }
  125. function js_beautify(js_source_text, options) {
  126. "use strict";
  127. var beautifier = new Beautifier(js_source_text, options);
  128. return beautifier.beautify();
  129. }
  130. var MODE = {
  131. BlockStatement: 'BlockStatement', // 'BLOCK'
  132. Statement: 'Statement', // 'STATEMENT'
  133. ObjectLiteral: 'ObjectLiteral', // 'OBJECT',
  134. ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]',
  135. ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)',
  136. Conditional: 'Conditional', //'(COND-EXPRESSION)',
  137. Expression: 'Expression' //'(EXPRESSION)'
  138. };
  139. function Beautifier(js_source_text, options) {
  140. "use strict";
  141. var output
  142. var tokens = [], token_pos;
  143. var Tokenizer;
  144. var current_token;
  145. var last_type, last_last_text, indent_string;
  146. var flags, previous_flags, flag_store;
  147. var prefix;
  148. var handlers, opt;
  149. var baseIndentString = '';
  150. handlers = {
  151. 'TK_START_EXPR': handle_start_expr,
  152. 'TK_END_EXPR': handle_end_expr,
  153. 'TK_START_BLOCK': handle_start_block,
  154. 'TK_END_BLOCK': handle_end_block,
  155. 'TK_WORD': handle_word,
  156. 'TK_RESERVED': handle_word,
  157. 'TK_SEMICOLON': handle_semicolon,
  158. 'TK_STRING': handle_string,
  159. 'TK_EQUALS': handle_equals,
  160. 'TK_OPERATOR': handle_operator,
  161. 'TK_COMMA': handle_comma,
  162. 'TK_BLOCK_COMMENT': handle_block_comment,
  163. 'TK_COMMENT': handle_comment,
  164. 'TK_DOT': handle_dot,
  165. 'TK_UNKNOWN': handle_unknown,
  166. 'TK_EOF': handle_eof
  167. };
  168. function create_flags(flags_base, mode) {
  169. var next_indent_level = 0;
  170. if (flags_base) {
  171. next_indent_level = flags_base.indentation_level;
  172. if (!output.just_added_newline() &&
  173. flags_base.line_indent_level > next_indent_level) {
  174. next_indent_level = flags_base.line_indent_level;
  175. }
  176. }
  177. var next_flags = {
  178. mode: mode,
  179. parent: flags_base,
  180. last_text: flags_base ? flags_base.last_text : '', // last token text
  181. last_word: flags_base ? flags_base.last_word : '', // last 'TK_WORD' passed
  182. declaration_statement: false,
  183. declaration_assignment: false,
  184. multiline_frame: false,
  185. if_block: false,
  186. else_block: false,
  187. do_block: false,
  188. do_while: false,
  189. in_case_statement: false, // switch(..){ INSIDE HERE }
  190. in_case: false, // we're on the exact line with "case 0:"
  191. case_body: false, // the indented case-action block
  192. indentation_level: next_indent_level,
  193. line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level,
  194. start_line_index: output.get_line_number(),
  195. ternary_depth: 0
  196. };
  197. return next_flags;
  198. }
  199. // Some interpreters have unexpected results with foo = baz || bar;
  200. options = options ? options : {};
  201. opt = {};
  202. // compatibility
  203. if (options.braces_on_own_line !== undefined) { //graceful handling of deprecated option
  204. opt.brace_style = options.braces_on_own_line ? "expand" : "collapse";
  205. }
  206. opt.brace_style = options.brace_style ? options.brace_style : (opt.brace_style ? opt.brace_style : "collapse");
  207. // graceful handling of deprecated option
  208. if (opt.brace_style === "expand-strict") {
  209. opt.brace_style = "expand";
  210. }
  211. opt.indent_size = options.indent_size ? parseInt(options.indent_size, 10) : 4;
  212. opt.indent_char = options.indent_char ? options.indent_char : ' ';
  213. opt.eol = options.eol ? options.eol : '\n';
  214. opt.preserve_newlines = (options.preserve_newlines === undefined) ? true : options.preserve_newlines;
  215. opt.break_chained_methods = (options.break_chained_methods === undefined) ? false : options.break_chained_methods;
  216. opt.max_preserve_newlines = (options.max_preserve_newlines === undefined) ? 0 : parseInt(options.max_preserve_newlines, 10);
  217. opt.space_in_paren = (options.space_in_paren === undefined) ? false : options.space_in_paren;
  218. opt.space_in_empty_paren = (options.space_in_empty_paren === undefined) ? false : options.space_in_empty_paren;
  219. opt.jslint_happy = (options.jslint_happy === undefined) ? false : options.jslint_happy;
  220. opt.space_after_anon_function = (options.space_after_anon_function === undefined) ? false : options.space_after_anon_function;
  221. opt.keep_array_indentation = (options.keep_array_indentation === undefined) ? false : options.keep_array_indentation;
  222. opt.space_before_conditional = (options.space_before_conditional === undefined) ? true : options.space_before_conditional;
  223. opt.unescape_strings = (options.unescape_strings === undefined) ? false : options.unescape_strings;
  224. opt.wrap_line_length = (options.wrap_line_length === undefined) ? 0 : parseInt(options.wrap_line_length, 10);
  225. opt.e4x = (options.e4x === undefined) ? false : options.e4x;
  226. opt.end_with_newline = (options.end_with_newline === undefined) ? false : options.end_with_newline;
  227. opt.comma_first = (options.comma_first === undefined) ? false : options.comma_first;
  228. // For testing of beautify ignore:start directive
  229. opt.test_output_raw = (options.test_output_raw === undefined) ? false : options.test_output_raw;
  230. // force opt.space_after_anon_function to true if opt.jslint_happy
  231. if(opt.jslint_happy) {
  232. opt.space_after_anon_function = true;
  233. }
  234. if(options.indent_with_tabs){
  235. opt.indent_char = '\t';
  236. opt.indent_size = 1;
  237. }
  238. opt.eol = opt.eol.replace(/\\r/, '\r').replace(/\\n/, '\n')
  239. //----------------------------------
  240. indent_string = '';
  241. while (opt.indent_size > 0) {
  242. indent_string += opt.indent_char;
  243. opt.indent_size -= 1;
  244. }
  245. var preindent_index = 0;
  246. if(js_source_text && js_source_text.length) {
  247. while ( (js_source_text.charAt(preindent_index) === ' ' ||
  248. js_source_text.charAt(preindent_index) === '\t')) {
  249. baseIndentString += js_source_text.charAt(preindent_index);
  250. preindent_index += 1;
  251. }
  252. js_source_text = js_source_text.substring(preindent_index);
  253. }
  254. last_type = 'TK_START_BLOCK'; // last token type
  255. last_last_text = ''; // pre-last token text
  256. output = new Output(indent_string, baseIndentString);
  257. // If testing the ignore directive, start with output disable set to true
  258. output.raw = opt.test_output_raw;
  259. // Stack of parsing/formatting states, including MODE.
  260. // We tokenize, parse, and output in an almost purely a forward-only stream of token input
  261. // and formatted output. This makes the beautifier less accurate than full parsers
  262. // but also far more tolerant of syntax errors.
  263. //
  264. // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type
  265. // MODE.BlockStatement on the the stack, even though it could be object literal. If we later
  266. // encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";",
  267. // most full parsers would die, but the beautifier gracefully falls back to
  268. // MODE.BlockStatement and continues on.
  269. flag_store = [];
  270. set_mode(MODE.BlockStatement);
  271. this.beautify = function() {
  272. /*jshint onevar:true */
  273. var local_token, sweet_code;
  274. Tokenizer = new tokenizer(js_source_text, opt, indent_string);
  275. tokens = Tokenizer.tokenize();
  276. token_pos = 0;
  277. while (local_token = get_token()) {
  278. for(var i = 0; i < local_token.comments_before.length; i++) {
  279. // The cleanest handling of inline comments is to treat them as though they aren't there.
  280. // Just continue formatting and the behavior should be logical.
  281. // Also ignore unknown tokens. Again, this should result in better behavior.
  282. handle_token(local_token.comments_before[i]);
  283. }
  284. handle_token(local_token);
  285. last_last_text = flags.last_text;
  286. last_type = local_token.type;
  287. flags.last_text = local_token.text;
  288. token_pos += 1;
  289. }
  290. sweet_code = output.get_code();
  291. if (opt.end_with_newline) {
  292. sweet_code += '\n';
  293. }
  294. if (opt.eol != '\n') {
  295. sweet_code = sweet_code.replace(/[\n]/g, opt.eol);
  296. }
  297. return sweet_code;
  298. };
  299. function handle_token(local_token) {
  300. var newlines = local_token.newlines;
  301. var keep_whitespace = opt.keep_array_indentation && is_array(flags.mode);
  302. if (keep_whitespace) {
  303. for (i = 0; i < newlines; i += 1) {
  304. print_newline(i > 0);
  305. }
  306. } else {
  307. if (opt.max_preserve_newlines && newlines > opt.max_preserve_newlines) {
  308. newlines = opt.max_preserve_newlines;
  309. }
  310. if (opt.preserve_newlines) {
  311. if (local_token.newlines > 1) {
  312. print_newline();
  313. for (var i = 1; i < newlines; i += 1) {
  314. print_newline(true);
  315. }
  316. }
  317. }
  318. }
  319. current_token = local_token;
  320. handlers[current_token.type]();
  321. }
  322. // we could use just string.split, but
  323. // IE doesn't like returning empty strings
  324. function split_newlines(s) {
  325. //return s.split(/\x0d\x0a|\x0a/);
  326. s = s.replace(/\x0d/g, '');
  327. var out = [],
  328. idx = s.indexOf("\n");
  329. while (idx !== -1) {
  330. out.push(s.substring(0, idx));
  331. s = s.substring(idx + 1);
  332. idx = s.indexOf("\n");
  333. }
  334. if (s.length) {
  335. out.push(s);
  336. }
  337. return out;
  338. }
  339. function allow_wrap_or_preserved_newline(force_linewrap) {
  340. force_linewrap = (force_linewrap === undefined) ? false : force_linewrap;
  341. // Never wrap the first token on a line
  342. if (output.just_added_newline()) {
  343. return
  344. }
  345. if ((opt.preserve_newlines && current_token.wanted_newline) || force_linewrap) {
  346. print_newline(false, true);
  347. } else if (opt.wrap_line_length) {
  348. var proposed_line_length = output.current_line.get_character_count() + current_token.text.length +
  349. (output.space_before_token ? 1 : 0);
  350. if (proposed_line_length >= opt.wrap_line_length) {
  351. print_newline(false, true);
  352. }
  353. }
  354. }
  355. function print_newline(force_newline, preserve_statement_flags) {
  356. if (!preserve_statement_flags) {
  357. if (flags.last_text !== ';' && flags.last_text !== ',' && flags.last_text !== '=' && last_type !== 'TK_OPERATOR') {
  358. while (flags.mode === MODE.Statement && !flags.if_block && !flags.do_block) {
  359. restore_mode();
  360. }
  361. }
  362. }
  363. if (output.add_new_line(force_newline)) {
  364. flags.multiline_frame = true;
  365. }
  366. }
  367. function print_token_line_indentation() {
  368. if (output.just_added_newline()) {
  369. if (opt.keep_array_indentation && is_array(flags.mode) && current_token.wanted_newline) {
  370. output.current_line.push(current_token.whitespace_before);
  371. output.space_before_token = false;
  372. } else if (output.set_indent(flags.indentation_level)) {
  373. flags.line_indent_level = flags.indentation_level;
  374. }
  375. }
  376. }
  377. function print_token(printable_token) {
  378. if (output.raw) {
  379. output.add_raw_token(current_token)
  380. return;
  381. }
  382. if (opt.comma_first && last_type === 'TK_COMMA'
  383. && output.just_added_newline()) {
  384. if(output.previous_line.last() === ',') {
  385. output.previous_line.pop();
  386. print_token_line_indentation();
  387. output.add_token(',');
  388. output.space_before_token = true;
  389. }
  390. }
  391. printable_token = printable_token || current_token.text;
  392. print_token_line_indentation();
  393. output.add_token(printable_token);
  394. }
  395. function indent() {
  396. flags.indentation_level += 1;
  397. }
  398. function deindent() {
  399. if (flags.indentation_level > 0 &&
  400. ((!flags.parent) || flags.indentation_level > flags.parent.indentation_level))
  401. flags.indentation_level -= 1;
  402. }
  403. function set_mode(mode) {
  404. if (flags) {
  405. flag_store.push(flags);
  406. previous_flags = flags;
  407. } else {
  408. previous_flags = create_flags(null, mode);
  409. }
  410. flags = create_flags(previous_flags, mode);
  411. }
  412. function is_array(mode) {
  413. return mode === MODE.ArrayLiteral;
  414. }
  415. function is_expression(mode) {
  416. return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]);
  417. }
  418. function restore_mode() {
  419. if (flag_store.length > 0) {
  420. previous_flags = flags;
  421. flags = flag_store.pop();
  422. if (previous_flags.mode === MODE.Statement) {
  423. output.remove_redundant_indentation(previous_flags);
  424. }
  425. }
  426. }
  427. function start_of_object_property() {
  428. return flags.parent.mode === MODE.ObjectLiteral && flags.mode === MODE.Statement && (
  429. (flags.last_text === ':' && flags.ternary_depth === 0) || (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set'])));
  430. }
  431. function start_of_statement() {
  432. if (
  433. (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const']) && current_token.type === 'TK_WORD') ||
  434. (last_type === 'TK_RESERVED' && flags.last_text === 'do') ||
  435. (last_type === 'TK_RESERVED' && flags.last_text === 'return' && !current_token.wanted_newline) ||
  436. (last_type === 'TK_RESERVED' && flags.last_text === 'else' && !(current_token.type === 'TK_RESERVED' && current_token.text === 'if')) ||
  437. (last_type === 'TK_END_EXPR' && (previous_flags.mode === MODE.ForInitializer || previous_flags.mode === MODE.Conditional)) ||
  438. (last_type === 'TK_WORD' && flags.mode === MODE.BlockStatement
  439. && !flags.in_case
  440. && !(current_token.text === '--' || current_token.text === '++')
  441. && last_last_text !== 'function'
  442. && current_token.type !== 'TK_WORD' && current_token.type !== 'TK_RESERVED') ||
  443. (flags.mode === MODE.ObjectLiteral && (
  444. (flags.last_text === ':' && flags.ternary_depth === 0) || (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set']))))
  445. ) {
  446. set_mode(MODE.Statement);
  447. indent();
  448. if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const']) && current_token.type === 'TK_WORD') {
  449. flags.declaration_statement = true;
  450. }
  451. // Issue #276:
  452. // If starting a new statement with [if, for, while, do], push to a new line.
  453. // if (a) if (b) if(c) d(); else e(); else f();
  454. if (!start_of_object_property()) {
  455. allow_wrap_or_preserved_newline(
  456. current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['do', 'for', 'if', 'while']));
  457. }
  458. return true;
  459. }
  460. return false;
  461. }
  462. function all_lines_start_with(lines, c) {
  463. for (var i = 0; i < lines.length; i++) {
  464. var line = trim(lines[i]);
  465. if (line.charAt(0) !== c) {
  466. return false;
  467. }
  468. }
  469. return true;
  470. }
  471. function each_line_matches_indent(lines, indent) {
  472. var i = 0,
  473. len = lines.length,
  474. line;
  475. for (; i < len; i++) {
  476. line = lines[i];
  477. // allow empty lines to pass through
  478. if (line && line.indexOf(indent) !== 0) {
  479. return false;
  480. }
  481. }
  482. return true;
  483. }
  484. function is_special_word(word) {
  485. return in_array(word, ['case', 'return', 'do', 'if', 'throw', 'else']);
  486. }
  487. function get_token(offset) {
  488. var index = token_pos + (offset || 0);
  489. return (index < 0 || index >= tokens.length) ? null : tokens[index];
  490. }
  491. function handle_start_expr() {
  492. if (start_of_statement()) {
  493. // The conditional starts the statement if appropriate.
  494. }
  495. var next_mode = MODE.Expression;
  496. if (current_token.text === '[') {
  497. if (last_type === 'TK_WORD' || flags.last_text === ')') {
  498. // this is array index specifier, break immediately
  499. // a[x], fn()[x]
  500. if (last_type === 'TK_RESERVED' && in_array(flags.last_text, Tokenizer.line_starters)) {
  501. output.space_before_token = true;
  502. }
  503. set_mode(next_mode);
  504. print_token();
  505. indent();
  506. if (opt.space_in_paren) {
  507. output.space_before_token = true;
  508. }
  509. return;
  510. }
  511. next_mode = MODE.ArrayLiteral;
  512. if (is_array(flags.mode)) {
  513. if (flags.last_text === '[' ||
  514. (flags.last_text === ',' && (last_last_text === ']' || last_last_text === '}'))) {
  515. // ], [ goes to new line
  516. // }, [ goes to new line
  517. if (!opt.keep_array_indentation) {
  518. print_newline();
  519. }
  520. }
  521. }
  522. } else {
  523. if (last_type === 'TK_RESERVED' && flags.last_text === 'for') {
  524. next_mode = MODE.ForInitializer;
  525. } else if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['if', 'while'])) {
  526. next_mode = MODE.Conditional;
  527. } else {
  528. // next_mode = MODE.Expression;
  529. }
  530. }
  531. if (flags.last_text === ';' || last_type === 'TK_START_BLOCK') {
  532. print_newline();
  533. } else if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || flags.last_text === '.') {
  534. // TODO: Consider whether forcing this is required. Review failing tests when removed.
  535. allow_wrap_or_preserved_newline(current_token.wanted_newline);
  536. // do nothing on (( and )( and ][ and ]( and .(
  537. } else if (!(last_type === 'TK_RESERVED' && current_token.text === '(') && last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') {
  538. output.space_before_token = true;
  539. } else if ((last_type === 'TK_RESERVED' && (flags.last_word === 'function' || flags.last_word === 'typeof')) ||
  540. (flags.last_text === '*' && last_last_text === 'function')) {
  541. // function() vs function ()
  542. if (opt.space_after_anon_function) {
  543. output.space_before_token = true;
  544. }
  545. } else if (last_type === 'TK_RESERVED' && (in_array(flags.last_text, Tokenizer.line_starters) || flags.last_text === 'catch')) {
  546. if (opt.space_before_conditional) {
  547. output.space_before_token = true;
  548. }
  549. }
  550. // Should be a space between await and an IIFE
  551. if(current_token.text === '(' && last_type === 'TK_RESERVED' && flags.last_word === 'await'){
  552. output.space_before_token = true;
  553. }
  554. // Support of this kind of newline preservation.
  555. // a = (b &&
  556. // (c || d));
  557. if (current_token.text === '(') {
  558. if (last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
  559. if (!start_of_object_property()) {
  560. allow_wrap_or_preserved_newline();
  561. }
  562. }
  563. }
  564. set_mode(next_mode);
  565. print_token();
  566. if (opt.space_in_paren) {
  567. output.space_before_token = true;
  568. }
  569. // In all cases, if we newline while inside an expression it should be indented.
  570. indent();
  571. }
  572. function handle_end_expr() {
  573. // statements inside expressions are not valid syntax, but...
  574. // statements must all be closed when their container closes
  575. while (flags.mode === MODE.Statement) {
  576. restore_mode();
  577. }
  578. if (flags.multiline_frame) {
  579. allow_wrap_or_preserved_newline(current_token.text === ']' && is_array(flags.mode) && !opt.keep_array_indentation);
  580. }
  581. if (opt.space_in_paren) {
  582. if (last_type === 'TK_START_EXPR' && ! opt.space_in_empty_paren) {
  583. // () [] no inner space in empty parens like these, ever, ref #320
  584. output.trim();
  585. output.space_before_token = false;
  586. } else {
  587. output.space_before_token = true;
  588. }
  589. }
  590. if (current_token.text === ']' && opt.keep_array_indentation) {
  591. print_token();
  592. restore_mode();
  593. } else {
  594. restore_mode();
  595. print_token();
  596. }
  597. output.remove_redundant_indentation(previous_flags);
  598. // do {} while () // no statement required after
  599. if (flags.do_while && previous_flags.mode === MODE.Conditional) {
  600. previous_flags.mode = MODE.Expression;
  601. flags.do_block = false;
  602. flags.do_while = false;
  603. }
  604. }
  605. function handle_start_block() {
  606. // Check if this is should be treated as a ObjectLiteral
  607. var next_token = get_token(1)
  608. var second_token = get_token(2)
  609. if (second_token && (
  610. (second_token.text === ':' && in_array(next_token.type, ['TK_STRING', 'TK_WORD', 'TK_RESERVED']))
  611. || (in_array(next_token.text, ['get', 'set']) && in_array(second_token.type, ['TK_WORD', 'TK_RESERVED']))
  612. )) {
  613. // We don't support TypeScript,but we didn't break it for a very long time.
  614. // We'll try to keep not breaking it.
  615. if (!in_array(last_last_text, ['class','interface'])) {
  616. set_mode(MODE.ObjectLiteral);
  617. } else {
  618. set_mode(MODE.BlockStatement);
  619. }
  620. } else {
  621. set_mode(MODE.BlockStatement);
  622. }
  623. var empty_braces = !next_token.comments_before.length && next_token.text === '}';
  624. var empty_anonymous_function = empty_braces && flags.last_word === 'function' &&
  625. last_type === 'TK_END_EXPR';
  626. if (opt.brace_style === "expand" ||
  627. (opt.brace_style === "none" && current_token.wanted_newline)) {
  628. if (last_type !== 'TK_OPERATOR' &&
  629. (empty_anonymous_function ||
  630. last_type === 'TK_EQUALS' ||
  631. (last_type === 'TK_RESERVED' && is_special_word(flags.last_text) && flags.last_text !== 'else'))) {
  632. output.space_before_token = true;
  633. } else {
  634. print_newline(false, true);
  635. }
  636. } else { // collapse
  637. if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') {
  638. if (last_type === 'TK_START_BLOCK') {
  639. print_newline();
  640. } else {
  641. output.space_before_token = true;
  642. }
  643. } else {
  644. // if TK_OPERATOR or TK_START_EXPR
  645. if (is_array(previous_flags.mode) && flags.last_text === ',') {
  646. if (last_last_text === '}') {
  647. // }, { in array context
  648. output.space_before_token = true;
  649. } else {
  650. print_newline(); // [a, b, c, {
  651. }
  652. }
  653. }
  654. }
  655. print_token();
  656. indent();
  657. }
  658. function handle_end_block() {
  659. // statements must all be closed when their container closes
  660. while (flags.mode === MODE.Statement) {
  661. restore_mode();
  662. }
  663. var empty_braces = last_type === 'TK_START_BLOCK';
  664. if (opt.brace_style === "expand") {
  665. if (!empty_braces) {
  666. print_newline();
  667. }
  668. } else {
  669. // skip {}
  670. if (!empty_braces) {
  671. if (is_array(flags.mode) && opt.keep_array_indentation) {
  672. // we REALLY need a newline here, but newliner would skip that
  673. opt.keep_array_indentation = false;
  674. print_newline();
  675. opt.keep_array_indentation = true;
  676. } else {
  677. print_newline();
  678. }
  679. }
  680. }
  681. restore_mode();
  682. print_token();
  683. }
  684. function handle_word() {
  685. if (current_token.type === 'TK_RESERVED' && flags.mode !== MODE.ObjectLiteral &&
  686. in_array(current_token.text, ['set', 'get'])) {
  687. current_token.type = 'TK_WORD';
  688. }
  689. if (current_token.type === 'TK_RESERVED' && flags.mode === MODE.ObjectLiteral) {
  690. var next_token = get_token(1);
  691. if (next_token.text == ':') {
  692. current_token.type = 'TK_WORD';
  693. }
  694. }
  695. if (start_of_statement()) {
  696. // The conditional starts the statement if appropriate.
  697. } else if (current_token.wanted_newline && !is_expression(flags.mode) &&
  698. (last_type !== 'TK_OPERATOR' || (flags.last_text === '--' || flags.last_text === '++')) &&
  699. last_type !== 'TK_EQUALS' &&
  700. (opt.preserve_newlines || !(last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const', 'set', 'get'])))) {
  701. print_newline();
  702. }
  703. if (flags.do_block && !flags.do_while) {
  704. if (current_token.type === 'TK_RESERVED' && current_token.text === 'while') {
  705. // do {} ## while ()
  706. output.space_before_token = true;
  707. print_token();
  708. output.space_before_token = true;
  709. flags.do_while = true;
  710. return;
  711. } else {
  712. // do {} should always have while as the next word.
  713. // if we don't see the expected while, recover
  714. print_newline();
  715. flags.do_block = false;
  716. }
  717. }
  718. // if may be followed by else, or not
  719. // Bare/inline ifs are tricky
  720. // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e();
  721. if (flags.if_block) {
  722. if (!flags.else_block && (current_token.type === 'TK_RESERVED' && current_token.text === 'else')) {
  723. flags.else_block = true;
  724. } else {
  725. while (flags.mode === MODE.Statement) {
  726. restore_mode();
  727. }
  728. flags.if_block = false;
  729. flags.else_block = false;
  730. }
  731. }
  732. if (current_token.type === 'TK_RESERVED' && (current_token.text === 'case' || (current_token.text === 'default' && flags.in_case_statement))) {
  733. print_newline();
  734. if (flags.case_body || opt.jslint_happy) {
  735. // switch cases following one another
  736. deindent();
  737. flags.case_body = false;
  738. }
  739. print_token();
  740. flags.in_case = true;
  741. flags.in_case_statement = true;
  742. return;
  743. }
  744. if (current_token.type === 'TK_RESERVED' && current_token.text === 'function') {
  745. if (in_array(flags.last_text, ['}', ';']) || (output.just_added_newline() && ! in_array(flags.last_text, ['[', '{', ':', '=', ',']))) {
  746. // make sure there is a nice clean space of at least one blank line
  747. // before a new function definition
  748. if ( !output.just_added_blankline() && !current_token.comments_before.length) {
  749. print_newline();
  750. print_newline(true);
  751. }
  752. }
  753. if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD') {
  754. if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set', 'new', 'return', 'export', 'async'])) {
  755. output.space_before_token = true;
  756. } else if (last_type === 'TK_RESERVED' && flags.last_text === 'default' && last_last_text === 'export') {
  757. output.space_before_token = true;
  758. } else {
  759. print_newline();
  760. }
  761. } else if (last_type === 'TK_OPERATOR' || flags.last_text === '=') {
  762. // foo = function
  763. output.space_before_token = true;
  764. } else if (!flags.multiline_frame && (is_expression(flags.mode) || is_array(flags.mode))) {
  765. // (function
  766. } else {
  767. print_newline();
  768. }
  769. }
  770. if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
  771. if (!start_of_object_property()) {
  772. allow_wrap_or_preserved_newline();
  773. }
  774. }
  775. if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['function', 'get', 'set'])) {
  776. print_token();
  777. flags.last_word = current_token.text;
  778. return;
  779. }
  780. prefix = 'NONE';
  781. if (last_type === 'TK_END_BLOCK') {
  782. if (!(current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['else', 'catch', 'finally']))) {
  783. prefix = 'NEWLINE';
  784. } else {
  785. if (opt.brace_style === "expand" ||
  786. opt.brace_style === "end-expand" ||
  787. (opt.brace_style === "none" && current_token.wanted_newline)) {
  788. prefix = 'NEWLINE';
  789. } else {
  790. prefix = 'SPACE';
  791. output.space_before_token = true;
  792. }
  793. }
  794. } else if (last_type === 'TK_SEMICOLON' && flags.mode === MODE.BlockStatement) {
  795. // TODO: Should this be for STATEMENT as well?
  796. prefix = 'NEWLINE';
  797. } else if (last_type === 'TK_SEMICOLON' && is_expression(flags.mode)) {
  798. prefix = 'SPACE';
  799. } else if (last_type === 'TK_STRING') {
  800. prefix = 'NEWLINE';
  801. } else if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD' ||
  802. (flags.last_text === '*' && last_last_text === 'function')) {
  803. prefix = 'SPACE';
  804. } else if (last_type === 'TK_START_BLOCK') {
  805. prefix = 'NEWLINE';
  806. } else if (last_type === 'TK_END_EXPR') {
  807. output.space_before_token = true;
  808. prefix = 'NEWLINE';
  809. }
  810. if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, Tokenizer.line_starters) && flags.last_text !== ')') {
  811. if (flags.last_text === 'else' || flags.last_text === 'export') {
  812. prefix = 'SPACE';
  813. } else {
  814. prefix = 'NEWLINE';
  815. }
  816. }
  817. if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['else', 'catch', 'finally'])) {
  818. if (last_type !== 'TK_END_BLOCK' ||
  819. opt.brace_style === "expand" ||
  820. opt.brace_style === "end-expand" ||
  821. (opt.brace_style === "none" && current_token.wanted_newline)) {
  822. print_newline();
  823. } else {
  824. output.trim(true);
  825. var line = output.current_line;
  826. // If we trimmed and there's something other than a close block before us
  827. // put a newline back in. Handles '} // comment' scenario.
  828. if (line.last() !== '}') {
  829. print_newline();
  830. }
  831. output.space_before_token = true;
  832. }
  833. } else if (prefix === 'NEWLINE') {
  834. if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
  835. // no newline between 'return nnn'
  836. output.space_before_token = true;
  837. } else if (last_type !== 'TK_END_EXPR') {
  838. if ((last_type !== 'TK_START_EXPR' || !(current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['var', 'let', 'const']))) && flags.last_text !== ':') {
  839. // no need to force newline on 'var': for (var x = 0...)
  840. if (current_token.type === 'TK_RESERVED' && current_token.text === 'if' && flags.last_text === 'else') {
  841. // no newline for } else if {
  842. output.space_before_token = true;
  843. } else {
  844. print_newline();
  845. }
  846. }
  847. } else if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, Tokenizer.line_starters) && flags.last_text !== ')') {
  848. print_newline();
  849. }
  850. } else if (flags.multiline_frame && is_array(flags.mode) && flags.last_text === ',' && last_last_text === '}') {
  851. print_newline(); // }, in lists get a newline treatment
  852. } else if (prefix === 'SPACE') {
  853. output.space_before_token = true;
  854. }
  855. print_token();
  856. flags.last_word = current_token.text;
  857. if (current_token.type === 'TK_RESERVED' && current_token.text === 'do') {
  858. flags.do_block = true;
  859. }
  860. if (current_token.type === 'TK_RESERVED' && current_token.text === 'if') {
  861. flags.if_block = true;
  862. }
  863. }
  864. function handle_semicolon() {
  865. if (start_of_statement()) {
  866. // The conditional starts the statement if appropriate.
  867. // Semicolon can be the start (and end) of a statement
  868. output.space_before_token = false;
  869. }
  870. while (flags.mode === MODE.Statement && !flags.if_block && !flags.do_block) {
  871. restore_mode();
  872. }
  873. print_token();
  874. }
  875. function handle_string() {
  876. if (start_of_statement()) {
  877. // The conditional starts the statement if appropriate.
  878. // One difference - strings want at least a space before
  879. output.space_before_token = true;
  880. } else if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD') {
  881. output.space_before_token = true;
  882. } else if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
  883. if (!start_of_object_property()) {
  884. allow_wrap_or_preserved_newline();
  885. }
  886. } else {
  887. print_newline();
  888. }
  889. print_token();
  890. }
  891. function handle_equals() {
  892. if (start_of_statement()) {
  893. // The conditional starts the statement if appropriate.
  894. }
  895. if (flags.declaration_statement) {
  896. // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done
  897. flags.declaration_assignment = true;
  898. }
  899. output.space_before_token = true;
  900. print_token();
  901. output.space_before_token = true;
  902. }
  903. function handle_comma() {
  904. if (flags.declaration_statement) {
  905. if (is_expression(flags.parent.mode)) {
  906. // do not break on comma, for(var a = 1, b = 2)
  907. flags.declaration_assignment = false;
  908. }
  909. print_token();
  910. if (flags.declaration_assignment) {
  911. flags.declaration_assignment = false;
  912. print_newline(false, true);
  913. } else {
  914. output.space_before_token = true;
  915. // for comma-first, we want to allow a newline before the comma
  916. // to turn into a newline after the comma, which we will fixup later
  917. if (opt.comma_first) {
  918. allow_wrap_or_preserved_newline();
  919. }
  920. }
  921. return;
  922. }
  923. print_token();
  924. if (flags.mode === MODE.ObjectLiteral ||
  925. (flags.mode === MODE.Statement && flags.parent.mode === MODE.ObjectLiteral)) {
  926. if (flags.mode === MODE.Statement) {
  927. restore_mode();
  928. }
  929. print_newline();
  930. } else {
  931. // EXPR or DO_BLOCK
  932. output.space_before_token = true;
  933. // for comma-first, we want to allow a newline before the comma
  934. // to turn into a newline after the comma, which we will fixup later
  935. if (opt.comma_first) {
  936. allow_wrap_or_preserved_newline();
  937. }
  938. }
  939. }
  940. function handle_operator() {
  941. if (start_of_statement()) {
  942. // The conditional starts the statement if appropriate.
  943. }
  944. if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
  945. // "return" had a special handling in TK_WORD. Now we need to return the favor
  946. output.space_before_token = true;
  947. print_token();
  948. return;
  949. }
  950. // hack for actionscript's import .*;
  951. if (current_token.text === '*' && last_type === 'TK_DOT') {
  952. print_token();
  953. return;
  954. }
  955. if (current_token.text === ':' && flags.in_case) {
  956. flags.case_body = true;
  957. indent();
  958. print_token();
  959. print_newline();
  960. flags.in_case = false;
  961. return;
  962. }
  963. if (current_token.text === '::') {
  964. // no spaces around exotic namespacing syntax operator
  965. print_token();
  966. return;
  967. }
  968. // Allow line wrapping between operators
  969. if (last_type === 'TK_OPERATOR') {
  970. allow_wrap_or_preserved_newline();
  971. }
  972. var space_before = true;
  973. var space_after = true;
  974. if (in_array(current_token.text, ['--', '++', '!', '~']) || (in_array(current_token.text, ['-', '+']) && (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) || in_array(flags.last_text, Tokenizer.line_starters) || flags.last_text === ','))) {
  975. // unary operators (and binary +/- pretending to be unary) special cases
  976. space_before = false;
  977. space_after = false;
  978. // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1
  979. // if there is a newline between -- or ++ and anything else we should preserve it.
  980. if (current_token.wanted_newline && (current_token.text === '--' || current_token.text === '++')) {
  981. print_newline(false, true);
  982. }
  983. if (flags.last_text === ';' && is_expression(flags.mode)) {
  984. // for (;; ++i)
  985. // ^^^
  986. space_before = true;
  987. }
  988. if (last_type === 'TK_RESERVED') {
  989. space_before = true;
  990. } else if (last_type === 'TK_END_EXPR') {
  991. space_before = !(flags.last_text === ']' && (current_token.text === '--' || current_token.text === '++'));
  992. } else if (last_type === 'TK_OPERATOR') {
  993. // a++ + ++b;
  994. // a - -b
  995. space_before = in_array(current_token.text, ['--', '-', '++', '+']) && in_array(flags.last_text, ['--', '-', '++', '+']);
  996. // + and - are not unary when preceeded by -- or ++ operator
  997. // a-- + b
  998. // a * +b
  999. // a - -b
  1000. if (in_array(current_token.text, ['+', '-']) && in_array(flags.last_text, ['--', '++'])) {
  1001. space_after = true;
  1002. }
  1003. }
  1004. if ((flags.mode === MODE.BlockStatement || flags.mode === MODE.Statement) && (flags.last_text === '{' || flags.last_text === ';')) {
  1005. // { foo; --i }
  1006. // foo(); --bar;
  1007. print_newline();
  1008. }
  1009. } else if (current_token.text === ':') {
  1010. if (flags.ternary_depth === 0) {
  1011. // Colon is invalid javascript outside of ternary and object, but do our best to guess what was meant.
  1012. space_before = false;
  1013. } else {
  1014. flags.ternary_depth -= 1;
  1015. }
  1016. } else if (current_token.text === '?') {
  1017. flags.ternary_depth += 1;
  1018. } else if (current_token.text === '*' && last_type === 'TK_RESERVED' && flags.last_text === 'function') {
  1019. space_before = false;
  1020. space_after = false;
  1021. }
  1022. output.space_before_token = output.space_before_token || space_before;
  1023. print_token();
  1024. output.space_before_token = space_after;
  1025. }
  1026. function handle_block_comment() {
  1027. if (output.raw) {
  1028. output.add_raw_token(current_token)
  1029. if (current_token.directives && current_token.directives['preserve'] === 'end') {
  1030. // If we're testing the raw output behavior, do not allow a directive to turn it off.
  1031. if (!opt.test_output_raw) {
  1032. output.raw = false;
  1033. }
  1034. }
  1035. return;
  1036. }
  1037. if (current_token.directives) {
  1038. print_newline(false, true);
  1039. print_token();
  1040. if (current_token.directives['preserve'] === 'start') {
  1041. output.raw = true;
  1042. }
  1043. print_newline(false, true);
  1044. return;
  1045. }
  1046. // inline block
  1047. if (!acorn.newline.test(current_token.text) && !current_token.wanted_newline) {
  1048. output.space_before_token = true;
  1049. print_token();
  1050. output.space_before_token = true;
  1051. return;
  1052. }
  1053. var lines = split_newlines(current_token.text);
  1054. var j; // iterator for this case
  1055. var javadoc = false;
  1056. var starless = false;
  1057. var lastIndent = current_token.whitespace_before;
  1058. var lastIndentLength = lastIndent.length;
  1059. // block comment starts with a new line
  1060. print_newline(false, true);
  1061. if (lines.length > 1) {
  1062. if (all_lines_start_with(lines.slice(1), '*')) {
  1063. javadoc = true;
  1064. }
  1065. else if (each_line_matches_indent(lines.slice(1), lastIndent)) {
  1066. starless = true;
  1067. }
  1068. }
  1069. // first line always indented
  1070. print_token(lines[0]);
  1071. for (j = 1; j < lines.length; j++) {
  1072. print_newline(false, true);
  1073. if (javadoc) {
  1074. // javadoc: reformat and re-indent
  1075. print_token(' ' + ltrim(lines[j]));
  1076. } else if (starless && lines[j].length > lastIndentLength) {
  1077. // starless: re-indent non-empty content, avoiding trim
  1078. print_token(lines[j].substring(lastIndentLength));
  1079. } else {
  1080. // normal comments output raw
  1081. output.add_token(lines[j]);
  1082. }
  1083. }
  1084. // for comments of more than one line, make sure there's a new line after
  1085. print_newline(false, true);
  1086. }
  1087. function handle_comment() {
  1088. if (current_token.wanted_newline) {
  1089. print_newline(false, true);
  1090. } else {
  1091. output.trim(true);
  1092. }
  1093. output.space_before_token = true;
  1094. print_token();
  1095. print_newline(false, true);
  1096. }
  1097. function handle_dot() {
  1098. if (start_of_statement()) {
  1099. // The conditional starts the statement if appropriate.
  1100. }
  1101. if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
  1102. output.space_before_token = true;
  1103. } else {
  1104. // allow preserved newlines before dots in general
  1105. // force newlines on dots after close paren when break_chained - for bar().baz()
  1106. allow_wrap_or_preserved_newline(flags.last_text === ')' && opt.break_chained_methods);
  1107. }
  1108. print_token();
  1109. }
  1110. function handle_unknown() {
  1111. print_token();
  1112. if (current_token.text[current_token.text.length - 1] === '\n') {
  1113. print_newline();
  1114. }
  1115. }
  1116. function handle_eof() {
  1117. // Unwind any open statements
  1118. while (flags.mode === MODE.Statement) {
  1119. restore_mode();
  1120. }
  1121. }
  1122. }
  1123. function OutputLine(parent) {
  1124. var _character_count = 0;
  1125. // use indent_count as a marker for lines that have preserved indentation
  1126. var _indent_count = -1;
  1127. var _items = [];
  1128. var _empty = true;
  1129. this.set_indent = function(level) {
  1130. _character_count = parent.baseIndentLength + level * parent.indent_length
  1131. _indent_count = level;
  1132. }
  1133. this.get_character_count = function() {
  1134. return _character_count;
  1135. }
  1136. this.is_empty = function() {
  1137. return _empty;
  1138. }
  1139. this.last = function() {
  1140. if (!this._empty) {
  1141. return _items[_items.length - 1];
  1142. } else {
  1143. return null;
  1144. }
  1145. }
  1146. this.push = function(input) {
  1147. _items.push(input);
  1148. _character_count += input.length;
  1149. _empty = false;
  1150. }
  1151. this.pop = function() {
  1152. var item = null;
  1153. if (!_empty) {
  1154. item = _items.pop();
  1155. _character_count -= item.length;
  1156. _empty = _items.length === 0;
  1157. }
  1158. return item;
  1159. }
  1160. this.remove_indent = function() {
  1161. if (_indent_count > 0) {
  1162. _indent_count -= 1;
  1163. _character_count -= parent.indent_length
  1164. }
  1165. }
  1166. this.trim = function() {
  1167. while (this.last() === ' ') {
  1168. var item = _items.pop();
  1169. _character_count -= 1;
  1170. }
  1171. _empty = _items.length === 0;
  1172. }
  1173. this.toString = function() {
  1174. var result = '';
  1175. if (!this._empty) {
  1176. if (_indent_count >= 0) {
  1177. result = parent.indent_cache[_indent_count];
  1178. }
  1179. result += _items.join('')
  1180. }
  1181. return result;
  1182. }
  1183. }
  1184. function Output(indent_string, baseIndentString) {
  1185. baseIndentString = baseIndentString || '';
  1186. this.indent_cache = [ baseIndentString ];
  1187. this.baseIndentLength = baseIndentString.length;
  1188. this.indent_length = indent_string.length;
  1189. this.raw = false;
  1190. var lines =[];
  1191. this.baseIndentString = baseIndentString;
  1192. this.indent_string = indent_string;
  1193. this.previous_line = null;
  1194. this.current_line = null;
  1195. this.space_before_token = false;
  1196. this.add_outputline = function() {
  1197. this.previous_line = this.current_line;
  1198. this.current_line = new OutputLine(this);
  1199. lines.push(this.current_line);
  1200. }
  1201. // initialize
  1202. this.add_outputline();
  1203. this.get_line_number = function() {
  1204. return lines.length;
  1205. }
  1206. // Using object instead of string to allow for later expansion of info about each line
  1207. this.add_new_line = function(force_newline) {
  1208. if (this.get_line_number() === 1 && this.just_added_newline()) {
  1209. return false; // no newline on start of file
  1210. }
  1211. if (force_newline || !this.just_added_newline()) {
  1212. if (!this.raw) {
  1213. this.add_outputline();
  1214. }
  1215. return true;
  1216. }
  1217. return false;
  1218. }
  1219. this.get_code = function() {
  1220. var sweet_code = lines.join('\n').replace(/[\r\n\t ]+$/, '');
  1221. return sweet_code;
  1222. }
  1223. this.set_indent = function(level) {
  1224. // Never indent your first output indent at the start of the file
  1225. if (lines.length > 1) {
  1226. while(level >= this.indent_cache.length) {
  1227. this.indent_cache.push(this.indent_cache[this.indent_cache.length - 1] + this.indent_string);
  1228. }
  1229. this.current_line.set_indent(level);
  1230. return true;
  1231. }
  1232. this.current_line.set_indent(0);
  1233. return false;
  1234. }
  1235. this.add_raw_token = function(token) {
  1236. for (var x = 0; x < token.newlines; x++) {
  1237. this.add_outputline();
  1238. }
  1239. this.current_line.push(token.whitespace_before);
  1240. this.current_line.push(token.text);
  1241. this.space_before_token = false;
  1242. }
  1243. this.add_token = function(printable_token) {
  1244. this.add_space_before_token();
  1245. this.current_line.push(printable_token);
  1246. }
  1247. this.add_space_before_token = function() {
  1248. if (this.space_before_token && !this.just_added_newline()) {
  1249. this.current_line.push(' ');
  1250. }
  1251. this.space_before_token = false;
  1252. }
  1253. this.remove_redundant_indentation = function (frame) {
  1254. // This implementation is effective but has some issues:
  1255. // - can cause line wrap to happen too soon due to indent removal
  1256. // after wrap points are calculated
  1257. // These issues are minor compared to ugly indentation.
  1258. if (frame.multiline_frame ||
  1259. frame.mode === MODE.ForInitializer ||
  1260. frame.mode === MODE.Conditional) {
  1261. return;
  1262. }
  1263. // remove one indent from each line inside this section
  1264. var index = frame.start_line_index;
  1265. var line;
  1266. var output_length = lines.length;
  1267. while (index < output_length) {
  1268. lines[index].remove_indent();
  1269. index++;
  1270. }
  1271. }
  1272. this.trim = function(eat_newlines) {
  1273. eat_newlines = (eat_newlines === undefined) ? false : eat_newlines;
  1274. this.current_line.trim(indent_string, baseIndentString);
  1275. while (eat_newlines && lines.length > 1 &&
  1276. this.current_line.is_empty()) {
  1277. lines.pop();
  1278. this.current_line = lines[lines.length - 1]
  1279. this.current_line.trim();
  1280. }
  1281. this.previous_line = lines.length > 1 ? lines[lines.length - 2] : null;
  1282. }
  1283. this.just_added_newline = function() {
  1284. return this.current_line.is_empty();
  1285. }
  1286. this.just_added_blankline = function() {
  1287. if (this.just_added_newline()) {
  1288. if (lines.length === 1) {
  1289. return true; // start of the file and newline = blank
  1290. }
  1291. var line = lines[lines.length - 2];
  1292. return line.is_empty();
  1293. }
  1294. return false;
  1295. }
  1296. }
  1297. var Token = function(type, text, newlines, whitespace_before, mode, parent) {
  1298. this.type = type;
  1299. this.text = text;
  1300. this.comments_before = [];
  1301. this.newlines = newlines || 0;
  1302. this.wanted_newline = newlines > 0;
  1303. this.whitespace_before = whitespace_before || '';
  1304. this.parent = null;
  1305. this.directives = null;
  1306. }
  1307. function tokenizer(input, opts, indent_string) {
  1308. var whitespace = "\n\r\t ".split('');
  1309. var digit = /[0-9]/;
  1310. var digit_hex = /[0123456789abcdefABCDEF]/;
  1311. var punct = ('+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! ~ , : ? ^ ^= |= :: =>'
  1312. +' <%= <% %> <?= <? ?>').split(' '); // try to be a good boy and try not to break the markup language identifiers
  1313. // words which should always start on new line.
  1314. this.line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export'.split(',');
  1315. var reserved_words = this.line_starters.concat(['do', 'in', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof', 'yield', 'async', 'await']);
  1316. // /* ... */ comment ends with nearest */ or end of file
  1317. var block_comment_pattern = /([\s\S]*?)((?:\*\/)|$)/g;
  1318. // comment ends just before nearest linefeed or end of file
  1319. var comment_pattern = /([^\n\r\u2028\u2029]*)/g;
  1320. var directives_block_pattern = /\/\* beautify( \w+[:]\w+)+ \*\//g;
  1321. var directive_pattern = / (\w+)[:](\w+)/g;
  1322. var directives_end_ignore_pattern = /([\s\S]*?)((?:\/\*\sbeautify\signore:end\s\*\/)|$)/g;
  1323. var template_pattern = /((<\?php|<\?=)[\s\S]*?\?>)|(<%[\s\S]*?%>)/g
  1324. var n_newlines, whitespace_before_token, in_html_comment, tokens, parser_pos;
  1325. var input_length;
  1326. this.tokenize = function() {
  1327. // cache the source's length.
  1328. input_length = input.length
  1329. parser_pos = 0;
  1330. in_html_comment = false
  1331. tokens = [];
  1332. var next, last;
  1333. var token_values;
  1334. var open = null;
  1335. var open_stack = [];
  1336. var comments = [];
  1337. while (!(last && last.type === 'TK_EOF')) {
  1338. token_values = tokenize_next();
  1339. next = new Token(token_values[1], token_values[0], n_newlines, whitespace_before_token);
  1340. while(next.type === 'TK_COMMENT' || next.type === 'TK_BLOCK_COMMENT' || next.type === 'TK_UNKNOWN') {
  1341. if (next.type === 'TK_BLOCK_COMMENT') {
  1342. next.directives = token_values[2];
  1343. }
  1344. comments.push(next);
  1345. token_values = tokenize_next();
  1346. next = new Token(token_values[1], token_values[0], n_newlines, whitespace_before_token);
  1347. }
  1348. if (comments.length) {
  1349. next.comments_before = comments;
  1350. comments = [];
  1351. }
  1352. if (next.type === 'TK_START_BLOCK' || next.type === 'TK_START_EXPR') {
  1353. next.parent = last;
  1354. open_stack.push(open);
  1355. open = next;
  1356. } else if ((next.type === 'TK_END_BLOCK' || next.type === 'TK_END_EXPR') &&
  1357. (open && (
  1358. (next.text === ']' && open.text === '[') ||
  1359. (next.text === ')' && open.text === '(') ||
  1360. (next.text === '}' && open.text === '{')))) {
  1361. next.parent = open.parent;
  1362. open = open_stack.pop();
  1363. }
  1364. tokens.push(next);
  1365. last = next;
  1366. }
  1367. return tokens;
  1368. }
  1369. function get_directives (text) {
  1370. if (!text.match(directives_block_pattern)) {
  1371. return null;
  1372. }
  1373. var directives = {};
  1374. directive_pattern.lastIndex = 0;
  1375. var directive_match = directive_pattern.exec(text);
  1376. while (directive_match) {
  1377. directives[directive_match[1]] = directive_match[2];
  1378. directive_match = directive_pattern.exec(text);
  1379. }
  1380. return directives;
  1381. }
  1382. function tokenize_next() {
  1383. var i, resulting_string;
  1384. var whitespace_on_this_line = [];
  1385. n_newlines = 0;
  1386. whitespace_before_token = '';
  1387. if (parser_pos >= input_length) {
  1388. return ['', 'TK_EOF'];
  1389. }
  1390. var last_token;
  1391. if (tokens.length) {
  1392. last_token = tokens[tokens.length-1];
  1393. } else {
  1394. // For the sake of tokenizing we can pretend that there was on open brace to start
  1395. last_token = new Token('TK_START_BLOCK', '{');
  1396. }
  1397. var c = input.charAt(parser_pos);
  1398. parser_pos += 1;
  1399. while (in_array(c, whitespace)) {
  1400. if (acorn.newline.test(c)) {
  1401. if (!(c === '\n' && input.charAt(parser_pos-2) === '\r')) {
  1402. n_newlines += 1;
  1403. whitespace_on_this_line = [];
  1404. }
  1405. } else {
  1406. whitespace_on_this_line.push(c);
  1407. }
  1408. if (parser_pos >= input_length) {
  1409. return ['', 'TK_EOF'];
  1410. }
  1411. c = input.charAt(parser_pos);
  1412. parser_pos += 1;
  1413. }
  1414. if(whitespace_on_this_line.length) {
  1415. whitespace_before_token = whitespace_on_this_line.join('');
  1416. }
  1417. if (digit.test(c)) {
  1418. var allow_decimal = true;
  1419. var allow_e = true;
  1420. var local_digit = digit;
  1421. if (c === '0' && parser_pos < input_length && /[Xx]/.test(input.charAt(parser_pos))) {
  1422. // switch to hex number, no decimal or e, just hex digits
  1423. allow_decimal = false;
  1424. allow_e = false;
  1425. c += input.charAt(parser_pos);
  1426. parser_pos += 1;
  1427. local_digit = digit_hex
  1428. } else {
  1429. // we know this first loop will run. It keeps the logic simpler.
  1430. c = '';
  1431. parser_pos -= 1
  1432. }
  1433. // Add the digits
  1434. while (parser_pos < input_length && local_digit.test(input.charAt(parser_pos))) {
  1435. c += input.charAt(parser_pos);
  1436. parser_pos += 1;
  1437. if (allow_decimal && parser_pos < input_length && input.charAt(parser_pos) === '.') {
  1438. c += input.charAt(parser_pos);
  1439. parser_pos += 1;
  1440. allow_decimal = false;
  1441. }
  1442. if (allow_e && parser_pos < input_length && /[Ee]/.test(input.charAt(parser_pos))) {
  1443. c += input.charAt(parser_pos);
  1444. parser_pos += 1;
  1445. if (parser_pos < input_length && /[+-]/.test(input.charAt(parser_pos))) {
  1446. c += input.charAt(parser_pos);
  1447. parser_pos += 1;
  1448. }
  1449. allow_e = false;
  1450. allow_decimal = false;
  1451. }
  1452. }
  1453. return [c, 'TK_WORD'];
  1454. }
  1455. if (acorn.isIdentifierStart(input.charCodeAt(parser_pos-1))) {
  1456. if (parser_pos < input_length) {
  1457. while (acorn.isIdentifierChar(input.charCodeAt(parser_pos))) {
  1458. c += input.charAt(parser_pos);
  1459. parser_pos += 1;
  1460. if (parser_pos === input_length) {
  1461. break;
  1462. }
  1463. }
  1464. }
  1465. if (!(last_token.type === 'TK_DOT' ||
  1466. (last_token.type === 'TK_RESERVED' && in_array(last_token.text, ['set', 'get'])))
  1467. && in_array(c, reserved_words)) {
  1468. if (c === 'in') { // hack for 'in' operator
  1469. return [c, 'TK_OPERATOR'];
  1470. }
  1471. return [c, 'TK_RESERVED'];
  1472. }
  1473. return [c, 'TK_WORD'];
  1474. }
  1475. if (c === '(' || c === '[') {
  1476. return [c, 'TK_START_EXPR'];
  1477. }
  1478. if (c === ')' || c === ']') {
  1479. return [c, 'TK_END_EXPR'];
  1480. }
  1481. if (c === '{') {
  1482. return [c, 'TK_START_BLOCK'];
  1483. }
  1484. if (c === '}') {
  1485. return [c, 'TK_END_BLOCK'];
  1486. }
  1487. if (c === ';') {
  1488. return [c, 'TK_SEMICOLON'];
  1489. }
  1490. if (c === '/') {
  1491. var comment = '';
  1492. // peek for comment /* ... */
  1493. if (input.charAt(parser_pos) === '*') {
  1494. parser_pos += 1;
  1495. block_comment_pattern.lastIndex = parser_pos;
  1496. var comment_match = block_comment_pattern.exec(input);
  1497. comment = '/*' + comment_match[0];
  1498. parser_pos += comment_match[0].length;
  1499. var directives = get_directives(comment);
  1500. if (directives && directives['ignore'] === 'start') {
  1501. directives_end_ignore_pattern.lastIndex = parser_pos;
  1502. comment_match = directives_end_ignore_pattern.exec(input)
  1503. comment += comment_match[0];
  1504. parser_pos += comment_match[0].length;
  1505. }
  1506. comment = comment.replace(acorn.lineBreak, '\n');
  1507. return [comment, 'TK_BLOCK_COMMENT', directives];
  1508. }
  1509. // peek for comment // ...
  1510. if (input.charAt(parser_pos) === '/') {
  1511. parser_pos += 1;
  1512. comment_pattern.lastIndex = parser_pos;
  1513. var comment_match = comment_pattern.exec(input);
  1514. comment = '//' + comment_match[0];
  1515. parser_pos += comment_match[0].length;
  1516. return [comment, 'TK_COMMENT'];
  1517. }
  1518. }
  1519. if (c === '`' || c === "'" || c === '"' || // string
  1520. (
  1521. (c === '/') || // regexp
  1522. (opts.e4x && c === "<" && input.slice(parser_pos - 1).match(/^<([-a-zA-Z:0-9_.]+|{[^{}]*}|!\[CDATA\[[\s\S]*?\]\])(\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{.*?}))*\s*(\/?)\s*>/)) // xml
  1523. ) && ( // regex and xml can only appear in specific locations during parsing
  1524. (last_token.type === 'TK_RESERVED' && in_array(last_token.text , ['return', 'case', 'throw', 'else', 'do', 'typeof', 'yield'])) ||
  1525. (last_token.type === 'TK_END_EXPR' && last_token.text === ')' &&
  1526. last_token.parent && last_token.parent.type === 'TK_RESERVED' && in_array(last_token.parent.text, ['if', 'while', 'for'])) ||
  1527. (in_array(last_token.type, ['TK_COMMENT', 'TK_START_EXPR', 'TK_START_BLOCK',
  1528. 'TK_END_BLOCK', 'TK_OPERATOR', 'TK_EQUALS', 'TK_EOF', 'TK_SEMICOLON', 'TK_COMMA'
  1529. ]))
  1530. )) {
  1531. var sep = c,
  1532. esc = false,
  1533. has_char_escapes = false;
  1534. resulting_string = c;
  1535. if (sep === '/') {
  1536. //
  1537. // handle regexp
  1538. //
  1539. var in_char_class = false;
  1540. while (parser_pos < input_length &&
  1541. ((esc || in_char_class || input.charAt(parser_pos) !== sep) &&
  1542. !acorn.newline.test(input.charAt(parser_pos)))) {
  1543. resulting_string += input.charAt(parser_pos);
  1544. if (!esc) {
  1545. esc = input.charAt(parser_pos) === '\\';
  1546. if (input.charAt(parser_pos) === '[') {
  1547. in_char_class = true;
  1548. } else if (input.charAt(parser_pos) === ']') {
  1549. in_char_class = false;
  1550. }
  1551. } else {
  1552. esc = false;
  1553. }
  1554. parser_pos += 1;
  1555. }
  1556. } else if (opts.e4x && sep === '<') {
  1557. //
  1558. // handle e4x xml literals
  1559. //
  1560. var xmlRegExp = /<(\/?)([-a-zA-Z:0-9_.]+|{[^{}]*}|!\[CDATA\[[\s\S]*?\]\])(\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{.*?}))*\s*(\/?)\s*>/g;
  1561. var xmlStr = input.slice(parser_pos - 1);
  1562. var match = xmlRegExp.exec(xmlStr);
  1563. if (match && match.index === 0) {
  1564. var rootTag = match[2];
  1565. var depth = 0;
  1566. while (match) {
  1567. var isEndTag = !! match[1];
  1568. var tagName = match[2];
  1569. var isSingletonTag = ( !! match[match.length - 1]) || (tagName.slice(0, 8) === "![CDATA[");
  1570. if (tagName === rootTag && !isSingletonTag) {
  1571. if (isEndTag) {
  1572. --depth;
  1573. } else {
  1574. ++depth;
  1575. }
  1576. }
  1577. if (depth <= 0) {
  1578. break;
  1579. }
  1580. match = xmlRegExp.exec(xmlStr);
  1581. }
  1582. var xmlLength = match ? match.index + match[0].length : xmlStr.length;
  1583. xmlStr = xmlStr.slice(0, xmlLength);
  1584. parser_pos += xmlLength - 1;
  1585. xmlStr = xmlStr.replace(acorn.lineBreak, '\n');
  1586. return [xmlStr, "TK_STRING"];
  1587. }
  1588. } else {
  1589. //
  1590. // handle string
  1591. //
  1592. // Template strings can travers lines without escape characters.
  1593. // Other strings cannot
  1594. while (parser_pos < input_length &&
  1595. (esc || (input.charAt(parser_pos) !== sep &&
  1596. (sep === '`' || !acorn.newline.test(input.charAt(parser_pos)))))) {
  1597. // Handle \r\n linebreaks after escapes or in template strings
  1598. if ((esc || sep === '`') && acorn.newline.test(input.charAt(parser_pos))) {
  1599. if (input.charAt(parser_pos) === '\r' && input.charAt(parser_pos + 1) === '\n') {
  1600. parser_pos += 1;
  1601. }
  1602. resulting_string += '\n';
  1603. } else {
  1604. resulting_string += input.charAt(parser_pos);
  1605. }
  1606. if (esc) {
  1607. if (input.charAt(parser_pos) === 'x' || input.charAt(parser_pos) === 'u') {
  1608. has_char_escapes = true;
  1609. }
  1610. esc = false;
  1611. } else {
  1612. esc = input.charAt(parser_pos) === '\\';
  1613. }
  1614. parser_pos += 1;
  1615. }
  1616. }
  1617. if (has_char_escapes && opts.unescape_strings) {
  1618. resulting_string = unescape_string(resulting_string);
  1619. }
  1620. if (parser_pos < input_length && input.charAt(parser_pos) === sep) {
  1621. resulting_string += sep;
  1622. parser_pos += 1;
  1623. if (sep === '/') {
  1624. // regexps may have modifiers /regexp/MOD , so fetch those, too
  1625. // Only [gim] are valid, but if the user puts in garbage, do what we can to take it.
  1626. while (parser_pos < input_length && acorn.isIdentifierStart(input.charCodeAt(parser_pos))) {
  1627. resulting_string += input.charAt(parser_pos);
  1628. parser_pos += 1;
  1629. }
  1630. }
  1631. }
  1632. return [resulting_string, 'TK_STRING'];
  1633. }
  1634. if (c === '#') {
  1635. if (tokens.length === 0 && input.charAt(parser_pos) === '!') {
  1636. // shebang
  1637. resulting_string = c;
  1638. while (parser_pos < input_length && c !== '\n') {
  1639. c = input.charAt(parser_pos);
  1640. resulting_string += c;
  1641. parser_pos += 1;
  1642. }
  1643. return [trim(resulting_string) + '\n', 'TK_UNKNOWN'];
  1644. }
  1645. // Spidermonkey-specific sharp variables for circular references
  1646. // https://developer.mozilla.org/En/Sharp_variables_in_JavaScript
  1647. // http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp around line 1935
  1648. var sharp = '#';
  1649. if (parser_pos < input_length && digit.test(input.charAt(parser_pos))) {
  1650. do {
  1651. c = input.charAt(parser_pos);
  1652. sharp += c;
  1653. parser_pos += 1;
  1654. } while (parser_pos < input_length && c !== '#' && c !== '=');
  1655. if (c === '#') {
  1656. //
  1657. } else if (input.charAt(parser_pos) === '[' && input.charAt(parser_pos + 1) === ']') {
  1658. sharp += '[]';
  1659. parser_pos += 2;
  1660. } else if (input.charAt(parser_pos) === '{' && input.charAt(parser_pos + 1) === '}') {
  1661. sharp += '{}';
  1662. parser_pos += 2;
  1663. }
  1664. return [sharp, 'TK_WORD'];
  1665. }
  1666. }
  1667. if (c === '<' && (input.charAt(parser_pos) === '?' || input.charAt(parser_pos) === '%')) {
  1668. template_pattern.lastIndex = parser_pos - 1;
  1669. var template_match = template_pattern.exec(input);
  1670. if(template_match) {
  1671. c = template_match[0];
  1672. parser_pos += c.length - 1;
  1673. c = c.replace(acorn.lineBreak, '\n');
  1674. return [c, 'TK_STRING'];
  1675. }
  1676. }
  1677. if (c === '<' && input.substring(parser_pos - 1, parser_pos + 3) === '<!--') {
  1678. parser_pos += 3;
  1679. c = '<!--';
  1680. while (!acorn.newline.test(input.charAt(parser_pos)) && parser_pos < input_length) {
  1681. c += input.charAt(parser_pos);
  1682. parser_pos++;
  1683. }
  1684. in_html_comment = true;
  1685. return [c, 'TK_COMMENT'];
  1686. }
  1687. if (c === '-' && in_html_comment && input.substring(parser_pos - 1, parser_pos + 2) === '-->') {
  1688. in_html_comment = false;
  1689. parser_pos += 2;
  1690. return ['-->', 'TK_COMMENT'];
  1691. }
  1692. if (c === '.') {
  1693. return [c, 'TK_DOT'];
  1694. }
  1695. if (in_array(c, punct)) {
  1696. while (parser_pos < input_length && in_array(c + input.charAt(parser_pos), punct)) {
  1697. c += input.charAt(parser_pos);
  1698. parser_pos += 1;
  1699. if (parser_pos >= input_length) {
  1700. break;
  1701. }
  1702. }
  1703. if (c === ',') {
  1704. return [c, 'TK_COMMA'];
  1705. } else if (c === '=') {
  1706. return [c, 'TK_EQUALS'];
  1707. } else {
  1708. return [c, 'TK_OPERATOR'];
  1709. }
  1710. }
  1711. return [c, 'TK_UNKNOWN'];
  1712. }
  1713. function unescape_string(s) {
  1714. var esc = false,
  1715. out = '',
  1716. pos = 0,
  1717. s_hex = '',
  1718. escaped = 0,
  1719. c;
  1720. while (esc || pos < s.length) {
  1721. c = s.charAt(pos);
  1722. pos++;
  1723. if (esc) {
  1724. esc = false;
  1725. if (c === 'x') {
  1726. // simple hex-escape \x24
  1727. s_hex = s.substr(pos, 2);
  1728. pos += 2;
  1729. } else if (c === 'u') {
  1730. // unicode-escape, \u2134
  1731. s_hex = s.substr(pos, 4);
  1732. pos += 4;
  1733. } else {
  1734. // some common escape, e.g \n
  1735. out += '\\' + c;
  1736. continue;
  1737. }
  1738. if (!s_hex.match(/^[0123456789abcdefABCDEF]+$/)) {
  1739. // some weird escaping, bail out,
  1740. // leaving whole string intact
  1741. return s;
  1742. }
  1743. escaped = parseInt(s_hex, 16);
  1744. if (escaped >= 0x00 && escaped < 0x20) {
  1745. // leave 0x00...0x1f escaped
  1746. if (c === 'x') {
  1747. out += '\\x' + s_hex;
  1748. } else {
  1749. out += '\\u' + s_hex;
  1750. }
  1751. continue;
  1752. } else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) {
  1753. // single-quote, apostrophe, backslash - escape these
  1754. out += '\\' + String.fromCharCode(escaped);
  1755. } else if (c === 'x' && escaped > 0x7e && escaped <= 0xff) {
  1756. // we bail out on \x7f..\xff,
  1757. // leaving whole string escaped,
  1758. // as it's probably completely binary
  1759. return s;
  1760. } else {
  1761. out += String.fromCharCode(escaped);
  1762. }
  1763. } else if (c === '\\') {
  1764. esc = true;
  1765. } else {
  1766. out += c;
  1767. }
  1768. }
  1769. return out;
  1770. }
  1771. }
  1772. if (typeof define === "function" && define.amd) {
  1773. // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
  1774. define([], function() {
  1775. return { js_beautify: js_beautify };
  1776. });
  1777. } else if (typeof exports !== "undefined") {
  1778. // Add support for CommonJS. Just put this file somewhere on your require.paths
  1779. // and you will be able to `var js_beautify = require("beautify").js_beautify`.
  1780. exports.js_beautify = js_beautify;
  1781. } else if (typeof window !== "undefined") {
  1782. // If we're running a web page and don't have either of the above, add our one global
  1783. window.js_beautify = js_beautify;
  1784. } else if (typeof global !== "undefined") {
  1785. // If we don't even have window, try global.
  1786. global.js_beautify = js_beautify;
  1787. }
  1788. }());