beautify.js 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  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, <[email protected]>
  25. http://jsbeautifier.org/
  26. Originally converted to javascript by Vital, <[email protected]>
  27. "End braces on own line" added by Chris J. Shull, <[email protected]>
  28. Parsing improvements for brace-less statements by Liam Newman <[email protected]>
  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 = /\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 js_beautify(js_source_text, options) {
  120. "use strict";
  121. var beautifier = new Beautifier(js_source_text, options);
  122. return beautifier.beautify();
  123. }
  124. var MODE = {
  125. BlockStatement: 'BlockStatement', // 'BLOCK'
  126. Statement: 'Statement', // 'STATEMENT'
  127. ObjectLiteral: 'ObjectLiteral', // 'OBJECT',
  128. ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]',
  129. ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)',
  130. Conditional: 'Conditional', //'(COND-EXPRESSION)',
  131. Expression: 'Expression' //'(EXPRESSION)'
  132. };
  133. function Beautifier(js_source_text, options) {
  134. "use strict";
  135. var output
  136. var tokens = [], token_pos;
  137. var Tokenizer;
  138. var current_token;
  139. var last_type, last_last_text, indent_string;
  140. var flags, previous_flags, flag_store;
  141. var prefix;
  142. var handlers, opt;
  143. var baseIndentString = '';
  144. handlers = {
  145. 'TK_START_EXPR': handle_start_expr,
  146. 'TK_END_EXPR': handle_end_expr,
  147. 'TK_START_BLOCK': handle_start_block,
  148. 'TK_END_BLOCK': handle_end_block,
  149. 'TK_WORD': handle_word,
  150. 'TK_RESERVED': handle_word,
  151. 'TK_SEMICOLON': handle_semicolon,
  152. 'TK_STRING': handle_string,
  153. 'TK_EQUALS': handle_equals,
  154. 'TK_OPERATOR': handle_operator,
  155. 'TK_COMMA': handle_comma,
  156. 'TK_BLOCK_COMMENT': handle_block_comment,
  157. 'TK_INLINE_COMMENT': handle_inline_comment,
  158. 'TK_COMMENT': handle_comment,
  159. 'TK_DOT': handle_dot,
  160. 'TK_UNKNOWN': handle_unknown,
  161. 'TK_EOF': handle_eof
  162. };
  163. function create_flags(flags_base, mode) {
  164. var next_indent_level = 0;
  165. if (flags_base) {
  166. next_indent_level = flags_base.indentation_level;
  167. if (!output.just_added_newline() &&
  168. flags_base.line_indent_level > next_indent_level) {
  169. next_indent_level = flags_base.line_indent_level;
  170. }
  171. }
  172. var next_flags = {
  173. mode: mode,
  174. parent: flags_base,
  175. last_text: flags_base ? flags_base.last_text : '', // last token text
  176. last_word: flags_base ? flags_base.last_word : '', // last 'TK_WORD' passed
  177. declaration_statement: false,
  178. declaration_assignment: false,
  179. multiline_frame: false,
  180. if_block: false,
  181. else_block: false,
  182. do_block: false,
  183. do_while: false,
  184. in_case_statement: false, // switch(..){ INSIDE HERE }
  185. in_case: false, // we're on the exact line with "case 0:"
  186. case_body: false, // the indented case-action block
  187. indentation_level: next_indent_level,
  188. line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level,
  189. start_line_index: output.get_line_number(),
  190. ternary_depth: 0
  191. };
  192. return next_flags;
  193. }
  194. // Some interpreters have unexpected results with foo = baz || bar;
  195. options = options ? options : {};
  196. opt = {};
  197. // compatibility
  198. if (options.braces_on_own_line !== undefined) { //graceful handling of deprecated option
  199. opt.brace_style = options.braces_on_own_line ? "expand" : "collapse";
  200. }
  201. opt.brace_style = options.brace_style ? options.brace_style : (opt.brace_style ? opt.brace_style : "collapse");
  202. // graceful handling of deprecated option
  203. if (opt.brace_style === "expand-strict") {
  204. opt.brace_style = "expand";
  205. }
  206. opt.indent_size = options.indent_size ? parseInt(options.indent_size, 10) : 4;
  207. opt.indent_char = options.indent_char ? options.indent_char : ' ';
  208. opt.preserve_newlines = (options.preserve_newlines === undefined) ? true : options.preserve_newlines;
  209. opt.break_chained_methods = (options.break_chained_methods === undefined) ? false : options.break_chained_methods;
  210. opt.max_preserve_newlines = (options.max_preserve_newlines === undefined) ? 0 : parseInt(options.max_preserve_newlines, 10);
  211. opt.space_in_paren = (options.space_in_paren === undefined) ? false : options.space_in_paren;
  212. opt.space_in_empty_paren = (options.space_in_empty_paren === undefined) ? false : options.space_in_empty_paren;
  213. opt.jslint_happy = (options.jslint_happy === undefined) ? false : options.jslint_happy;
  214. opt.space_after_anon_function = (options.space_after_anon_function === undefined) ? false : options.space_after_anon_function;
  215. opt.keep_array_indentation = (options.keep_array_indentation === undefined) ? false : options.keep_array_indentation;
  216. opt.space_before_conditional = (options.space_before_conditional === undefined) ? true : options.space_before_conditional;
  217. opt.unescape_strings = (options.unescape_strings === undefined) ? false : options.unescape_strings;
  218. opt.wrap_line_length = (options.wrap_line_length === undefined) ? 0 : parseInt(options.wrap_line_length, 10);
  219. opt.e4x = (options.e4x === undefined) ? false : options.e4x;
  220. opt.end_with_newline = (options.end_with_newline === undefined) ? false : options.end_with_newline;
  221. // force opt.space_after_anon_function to true if opt.jslint_happy
  222. if(opt.jslint_happy) {
  223. opt.space_after_anon_function = true;
  224. }
  225. if(options.indent_with_tabs){
  226. opt.indent_char = '\t';
  227. opt.indent_size = 1;
  228. }
  229. //----------------------------------
  230. indent_string = '';
  231. while (opt.indent_size > 0) {
  232. indent_string += opt.indent_char;
  233. opt.indent_size -= 1;
  234. }
  235. var preindent_index = 0;
  236. if(js_source_text && js_source_text.length) {
  237. while ( (js_source_text.charAt(preindent_index) === ' ' ||
  238. js_source_text.charAt(preindent_index) === '\t')) {
  239. baseIndentString += js_source_text.charAt(preindent_index);
  240. preindent_index += 1;
  241. }
  242. js_source_text = js_source_text.substring(preindent_index);
  243. }
  244. last_type = 'TK_START_BLOCK'; // last token type
  245. last_last_text = ''; // pre-last token text
  246. output = new Output(indent_string, baseIndentString);
  247. // Stack of parsing/formatting states, including MODE.
  248. // We tokenize, parse, and output in an almost purely a forward-only stream of token input
  249. // and formatted output. This makes the beautifier less accurate than full parsers
  250. // but also far more tolerant of syntax errors.
  251. //
  252. // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type
  253. // MODE.BlockStatement on the the stack, even though it could be object literal. If we later
  254. // encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";",
  255. // most full parsers would die, but the beautifier gracefully falls back to
  256. // MODE.BlockStatement and continues on.
  257. flag_store = [];
  258. set_mode(MODE.BlockStatement);
  259. this.beautify = function() {
  260. /*jshint onevar:true */
  261. var local_token, sweet_code;
  262. Tokenizer = new tokenizer(js_source_text, opt, indent_string);
  263. tokens = Tokenizer.tokenize();
  264. token_pos = 0;
  265. while (local_token = get_token()) {
  266. for(var i = 0; i < local_token.comments_before.length; i++) {
  267. // The cleanest handling of inline comments is to treat them as though they aren't there.
  268. // Just continue formatting and the behavior should be logical.
  269. // Also ignore unknown tokens. Again, this should result in better behavior.
  270. handle_token(local_token.comments_before[i]);
  271. }
  272. handle_token(local_token);
  273. last_last_text = flags.last_text;
  274. last_type = local_token.type;
  275. flags.last_text = local_token.text;
  276. token_pos += 1;
  277. }
  278. sweet_code = output.get_code();
  279. if (opt.end_with_newline) {
  280. sweet_code += '\n';
  281. }
  282. return sweet_code;
  283. };
  284. function handle_token(local_token) {
  285. var newlines = local_token.newlines;
  286. var keep_whitespace = opt.keep_array_indentation && is_array(flags.mode);
  287. if (keep_whitespace) {
  288. for (i = 0; i < newlines; i += 1) {
  289. print_newline(i > 0);
  290. }
  291. } else {
  292. if (opt.max_preserve_newlines && newlines > opt.max_preserve_newlines) {
  293. newlines = opt.max_preserve_newlines;
  294. }
  295. if (opt.preserve_newlines) {
  296. if (local_token.newlines > 1) {
  297. print_newline();
  298. for (var i = 1; i < newlines; i += 1) {
  299. print_newline(true);
  300. }
  301. }
  302. }
  303. }
  304. current_token = local_token;
  305. handlers[current_token.type]();
  306. }
  307. // we could use just string.split, but
  308. // IE doesn't like returning empty strings
  309. function split_newlines(s) {
  310. //return s.split(/\x0d\x0a|\x0a/);
  311. s = s.replace(/\x0d/g, '');
  312. var out = [],
  313. idx = s.indexOf("\n");
  314. while (idx !== -1) {
  315. out.push(s.substring(0, idx));
  316. s = s.substring(idx + 1);
  317. idx = s.indexOf("\n");
  318. }
  319. if (s.length) {
  320. out.push(s);
  321. }
  322. return out;
  323. }
  324. function allow_wrap_or_preserved_newline(force_linewrap) {
  325. force_linewrap = (force_linewrap === undefined) ? false : force_linewrap;
  326. // Never wrap the first token on a line
  327. if (output.just_added_newline()) {
  328. return
  329. }
  330. if ((opt.preserve_newlines && current_token.wanted_newline) || force_linewrap) {
  331. print_newline(false, true);
  332. } else if (opt.wrap_line_length) {
  333. var proposed_line_length = output.current_line.get_character_count() + current_token.text.length +
  334. (output.space_before_token ? 1 : 0);
  335. if (proposed_line_length >= opt.wrap_line_length) {
  336. print_newline(false, true);
  337. }
  338. }
  339. }
  340. function print_newline(force_newline, preserve_statement_flags) {
  341. if (!preserve_statement_flags) {
  342. if (flags.last_text !== ';' && flags.last_text !== ',' && flags.last_text !== '=' && last_type !== 'TK_OPERATOR') {
  343. while (flags.mode === MODE.Statement && !flags.if_block && !flags.do_block) {
  344. restore_mode();
  345. }
  346. }
  347. }
  348. if (output.add_new_line(force_newline)) {
  349. flags.multiline_frame = true;
  350. }
  351. }
  352. function print_token_line_indentation() {
  353. if (output.just_added_newline()) {
  354. if (opt.keep_array_indentation && is_array(flags.mode) && current_token.wanted_newline) {
  355. output.current_line.push(current_token.whitespace_before);
  356. output.space_before_token = false;
  357. } else if (output.set_indent(flags.indentation_level)) {
  358. flags.line_indent_level = flags.indentation_level;
  359. }
  360. }
  361. }
  362. function print_token(printable_token) {
  363. printable_token = printable_token || current_token.text;
  364. print_token_line_indentation();
  365. output.add_token(printable_token);
  366. }
  367. function indent() {
  368. flags.indentation_level += 1;
  369. }
  370. function deindent() {
  371. if (flags.indentation_level > 0 &&
  372. ((!flags.parent) || flags.indentation_level > flags.parent.indentation_level))
  373. flags.indentation_level -= 1;
  374. }
  375. function set_mode(mode) {
  376. if (flags) {
  377. flag_store.push(flags);
  378. previous_flags = flags;
  379. } else {
  380. previous_flags = create_flags(null, mode);
  381. }
  382. flags = create_flags(previous_flags, mode);
  383. }
  384. function is_array(mode) {
  385. return mode === MODE.ArrayLiteral;
  386. }
  387. function is_expression(mode) {
  388. return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]);
  389. }
  390. function restore_mode() {
  391. if (flag_store.length > 0) {
  392. previous_flags = flags;
  393. flags = flag_store.pop();
  394. if (previous_flags.mode === MODE.Statement) {
  395. output.remove_redundant_indentation(previous_flags);
  396. }
  397. }
  398. }
  399. function start_of_object_property() {
  400. return flags.parent.mode === MODE.ObjectLiteral && flags.mode === MODE.Statement && (
  401. (flags.last_text === ':' && flags.ternary_depth === 0) || (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set'])));
  402. }
  403. function start_of_statement() {
  404. if (
  405. (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const']) && current_token.type === 'TK_WORD') ||
  406. (last_type === 'TK_RESERVED' && flags.last_text === 'do') ||
  407. (last_type === 'TK_RESERVED' && flags.last_text === 'return' && !current_token.wanted_newline) ||
  408. (last_type === 'TK_RESERVED' && flags.last_text === 'else' && !(current_token.type === 'TK_RESERVED' && current_token.text === 'if')) ||
  409. (last_type === 'TK_END_EXPR' && (previous_flags.mode === MODE.ForInitializer || previous_flags.mode === MODE.Conditional)) ||
  410. (last_type === 'TK_WORD' && flags.mode === MODE.BlockStatement
  411. && !flags.in_case
  412. && !(current_token.text === '--' || current_token.text === '++')
  413. && current_token.type !== 'TK_WORD' && current_token.type !== 'TK_RESERVED') ||
  414. (flags.mode === MODE.ObjectLiteral && (
  415. (flags.last_text === ':' && flags.ternary_depth === 0) || (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set']))))
  416. ) {
  417. set_mode(MODE.Statement);
  418. indent();
  419. if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const']) && current_token.type === 'TK_WORD') {
  420. flags.declaration_statement = true;
  421. }
  422. // Issue #276:
  423. // If starting a new statement with [if, for, while, do], push to a new line.
  424. // if (a) if (b) if(c) d(); else e(); else f();
  425. if (!start_of_object_property()) {
  426. allow_wrap_or_preserved_newline(
  427. current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['do', 'for', 'if', 'while']));
  428. }
  429. return true;
  430. }
  431. return false;
  432. }
  433. function all_lines_start_with(lines, c) {
  434. for (var i = 0; i < lines.length; i++) {
  435. var line = trim(lines[i]);
  436. if (line.charAt(0) !== c) {
  437. return false;
  438. }
  439. }
  440. return true;
  441. }
  442. function each_line_matches_indent(lines, indent) {
  443. var i = 0,
  444. len = lines.length,
  445. line;
  446. for (; i < len; i++) {
  447. line = lines[i];
  448. // allow empty lines to pass through
  449. if (line && line.indexOf(indent) !== 0) {
  450. return false;
  451. }
  452. }
  453. return true;
  454. }
  455. function is_special_word(word) {
  456. return in_array(word, ['case', 'return', 'do', 'if', 'throw', 'else']);
  457. }
  458. function get_token(offset) {
  459. var index = token_pos + (offset || 0);
  460. return (index < 0 || index >= tokens.length) ? null : tokens[index];
  461. }
  462. function handle_start_expr() {
  463. if (start_of_statement()) {
  464. // The conditional starts the statement if appropriate.
  465. }
  466. var next_mode = MODE.Expression;
  467. if (current_token.text === '[') {
  468. if (last_type === 'TK_WORD' || flags.last_text === ')') {
  469. // this is array index specifier, break immediately
  470. // a[x], fn()[x]
  471. if (last_type === 'TK_RESERVED' && in_array(flags.last_text, Tokenizer.line_starters)) {
  472. output.space_before_token = true;
  473. }
  474. set_mode(next_mode);
  475. print_token();
  476. indent();
  477. if (opt.space_in_paren) {
  478. output.space_before_token = true;
  479. }
  480. return;
  481. }
  482. next_mode = MODE.ArrayLiteral;
  483. if (is_array(flags.mode)) {
  484. if (flags.last_text === '[' ||
  485. (flags.last_text === ',' && (last_last_text === ']' || last_last_text === '}'))) {
  486. // ], [ goes to new line
  487. // }, [ goes to new line
  488. if (!opt.keep_array_indentation) {
  489. print_newline();
  490. }
  491. }
  492. }
  493. } else {
  494. if (last_type === 'TK_RESERVED' && flags.last_text === 'for') {
  495. next_mode = MODE.ForInitializer;
  496. } else if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['if', 'while'])) {
  497. next_mode = MODE.Conditional;
  498. } else {
  499. // next_mode = MODE.Expression;
  500. }
  501. }
  502. if (flags.last_text === ';' || last_type === 'TK_START_BLOCK') {
  503. print_newline();
  504. } else if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || flags.last_text === '.') {
  505. // TODO: Consider whether forcing this is required. Review failing tests when removed.
  506. allow_wrap_or_preserved_newline(current_token.wanted_newline);
  507. // do nothing on (( and )( and ][ and ]( and .(
  508. } else if (!(last_type === 'TK_RESERVED' && current_token.text === '(') && last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') {
  509. output.space_before_token = true;
  510. } else if ((last_type === 'TK_RESERVED' && (flags.last_word === 'function' || flags.last_word === 'typeof')) ||
  511. (flags.last_text === '*' && last_last_text === 'function')) {
  512. // function() vs function ()
  513. if (opt.space_after_anon_function) {
  514. output.space_before_token = true;
  515. }
  516. } else if (last_type === 'TK_RESERVED' && (in_array(flags.last_text, Tokenizer.line_starters) || flags.last_text === 'catch')) {
  517. if (opt.space_before_conditional) {
  518. output.space_before_token = true;
  519. }
  520. }
  521. // Support of this kind of newline preservation.
  522. // a = (b &&
  523. // (c || d));
  524. if (current_token.text === '(') {
  525. if (last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
  526. if (!start_of_object_property()) {
  527. allow_wrap_or_preserved_newline();
  528. }
  529. }
  530. }
  531. set_mode(next_mode);
  532. print_token();
  533. if (opt.space_in_paren) {
  534. output.space_before_token = true;
  535. }
  536. // In all cases, if we newline while inside an expression it should be indented.
  537. indent();
  538. }
  539. function handle_end_expr() {
  540. // statements inside expressions are not valid syntax, but...
  541. // statements must all be closed when their container closes
  542. while (flags.mode === MODE.Statement) {
  543. restore_mode();
  544. }
  545. if (flags.multiline_frame) {
  546. allow_wrap_or_preserved_newline(current_token.text === ']' && is_array(flags.mode) && !opt.keep_array_indentation);
  547. }
  548. if (opt.space_in_paren) {
  549. if (last_type === 'TK_START_EXPR' && ! opt.space_in_empty_paren) {
  550. // () [] no inner space in empty parens like these, ever, ref #320
  551. output.trim();
  552. output.space_before_token = false;
  553. } else {
  554. output.space_before_token = true;
  555. }
  556. }
  557. if (current_token.text === ']' && opt.keep_array_indentation) {
  558. print_token();
  559. restore_mode();
  560. } else {
  561. restore_mode();
  562. print_token();
  563. }
  564. output.remove_redundant_indentation(previous_flags);
  565. // do {} while () // no statement required after
  566. if (flags.do_while && previous_flags.mode === MODE.Conditional) {
  567. previous_flags.mode = MODE.Expression;
  568. flags.do_block = false;
  569. flags.do_while = false;
  570. }
  571. }
  572. function handle_start_block() {
  573. // Check if this is should be treated as a ObjectLiteral
  574. var next_token = get_token(1)
  575. var second_token = get_token(2)
  576. if (second_token && (
  577. (second_token.text === ':' && in_array(next_token.type, ['TK_STRING', 'TK_WORD', 'TK_RESERVED']))
  578. || (in_array(next_token.text, ['get', 'set']) && in_array(second_token.type, ['TK_WORD', 'TK_RESERVED']))
  579. )) {
  580. // We don't support TypeScript,but we didn't break it for a very long time.
  581. // We'll try to keep not breaking it.
  582. if (!in_array(last_last_text, ['class','interface'])) {
  583. set_mode(MODE.ObjectLiteral);
  584. } else {
  585. set_mode(MODE.BlockStatement);
  586. }
  587. } else {
  588. set_mode(MODE.BlockStatement);
  589. }
  590. var empty_braces = !next_token.comments_before.length && next_token.text === '}';
  591. var empty_anonymous_function = empty_braces && flags.last_word === 'function' &&
  592. last_type === 'TK_END_EXPR';
  593. if (opt.brace_style === "expand" ||
  594. (opt.brace_style === "none" && current_token.wanted_newline)) {
  595. if (last_type !== 'TK_OPERATOR' &&
  596. (empty_anonymous_function ||
  597. last_type === 'TK_EQUALS' ||
  598. (last_type === 'TK_RESERVED' && is_special_word(flags.last_text) && flags.last_text !== 'else'))) {
  599. output.space_before_token = true;
  600. } else {
  601. print_newline(false, true);
  602. }
  603. } else { // collapse
  604. if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') {
  605. if (last_type === 'TK_START_BLOCK') {
  606. print_newline();
  607. } else {
  608. output.space_before_token = true;
  609. }
  610. } else {
  611. // if TK_OPERATOR or TK_START_EXPR
  612. if (is_array(previous_flags.mode) && flags.last_text === ',') {
  613. if (last_last_text === '}') {
  614. // }, { in array context
  615. output.space_before_token = true;
  616. } else {
  617. print_newline(); // [a, b, c, {
  618. }
  619. }
  620. }
  621. }
  622. print_token();
  623. indent();
  624. }
  625. function handle_end_block() {
  626. // statements must all be closed when their container closes
  627. while (flags.mode === MODE.Statement) {
  628. restore_mode();
  629. }
  630. var empty_braces = last_type === 'TK_START_BLOCK';
  631. if (opt.brace_style === "expand") {
  632. if (!empty_braces) {
  633. print_newline();
  634. }
  635. } else {
  636. // skip {}
  637. if (!empty_braces) {
  638. if (is_array(flags.mode) && opt.keep_array_indentation) {
  639. // we REALLY need a newline here, but newliner would skip that
  640. opt.keep_array_indentation = false;
  641. print_newline();
  642. opt.keep_array_indentation = true;
  643. } else {
  644. print_newline();
  645. }
  646. }
  647. }
  648. restore_mode();
  649. print_token();
  650. }
  651. function handle_word() {
  652. if (current_token.type === 'TK_RESERVED' && flags.mode !== MODE.ObjectLiteral &&
  653. in_array(current_token.text, ['set', 'get'])) {
  654. current_token.type = 'TK_WORD';
  655. }
  656. if (current_token.type === 'TK_RESERVED' && flags.mode === MODE.ObjectLiteral) {
  657. var next_token = get_token(1);
  658. if (next_token.text == ':') {
  659. current_token.type = 'TK_WORD';
  660. }
  661. }
  662. if (start_of_statement()) {
  663. // The conditional starts the statement if appropriate.
  664. } else if (current_token.wanted_newline && !is_expression(flags.mode) &&
  665. (last_type !== 'TK_OPERATOR' || (flags.last_text === '--' || flags.last_text === '++')) &&
  666. last_type !== 'TK_EQUALS' &&
  667. (opt.preserve_newlines || !(last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const', 'set', 'get'])))) {
  668. print_newline();
  669. }
  670. if (flags.do_block && !flags.do_while) {
  671. if (current_token.type === 'TK_RESERVED' && current_token.text === 'while') {
  672. // do {} ## while ()
  673. output.space_before_token = true;
  674. print_token();
  675. output.space_before_token = true;
  676. flags.do_while = true;
  677. return;
  678. } else {
  679. // do {} should always have while as the next word.
  680. // if we don't see the expected while, recover
  681. print_newline();
  682. flags.do_block = false;
  683. }
  684. }
  685. // if may be followed by else, or not
  686. // Bare/inline ifs are tricky
  687. // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e();
  688. if (flags.if_block) {
  689. if (!flags.else_block && (current_token.type === 'TK_RESERVED' && current_token.text === 'else')) {
  690. flags.else_block = true;
  691. } else {
  692. while (flags.mode === MODE.Statement) {
  693. restore_mode();
  694. }
  695. flags.if_block = false;
  696. flags.else_block = false;
  697. }
  698. }
  699. if (current_token.type === 'TK_RESERVED' && (current_token.text === 'case' || (current_token.text === 'default' && flags.in_case_statement))) {
  700. print_newline();
  701. if (flags.case_body || opt.jslint_happy) {
  702. // switch cases following one another
  703. deindent();
  704. flags.case_body = false;
  705. }
  706. print_token();
  707. flags.in_case = true;
  708. flags.in_case_statement = true;
  709. return;
  710. }
  711. if (current_token.type === 'TK_RESERVED' && current_token.text === 'function') {
  712. if (in_array(flags.last_text, ['}', ';']) || (output.just_added_newline() && ! in_array(flags.last_text, ['[', '{', ':', '=', ',']))) {
  713. // make sure there is a nice clean space of at least one blank line
  714. // before a new function definition
  715. if ( !output.just_added_blankline() && !current_token.comments_before.length) {
  716. print_newline();
  717. print_newline(true);
  718. }
  719. }
  720. if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD') {
  721. if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set', 'new', 'return', 'export'])) {
  722. output.space_before_token = true;
  723. } else if (last_type === 'TK_RESERVED' && flags.last_text === 'default' && last_last_text === 'export') {
  724. output.space_before_token = true;
  725. } else {
  726. print_newline();
  727. }
  728. } else if (last_type === 'TK_OPERATOR' || flags.last_text === '=') {
  729. // foo = function
  730. output.space_before_token = true;
  731. } else if (!flags.multiline_frame && (is_expression(flags.mode) || is_array(flags.mode))) {
  732. // (function
  733. } else {
  734. print_newline();
  735. }
  736. }
  737. if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
  738. if (!start_of_object_property()) {
  739. allow_wrap_or_preserved_newline();
  740. }
  741. }
  742. if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['function', 'get', 'set'])) {
  743. print_token();
  744. flags.last_word = current_token.text;
  745. return;
  746. }
  747. prefix = 'NONE';
  748. if (last_type === 'TK_END_BLOCK') {
  749. if (!(current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['else', 'catch', 'finally']))) {
  750. prefix = 'NEWLINE';
  751. } else {
  752. if (opt.brace_style === "expand" ||
  753. opt.brace_style === "end-expand" ||
  754. (opt.brace_style === "none" && current_token.wanted_newline)) {
  755. prefix = 'NEWLINE';
  756. } else {
  757. prefix = 'SPACE';
  758. output.space_before_token = true;
  759. }
  760. }
  761. } else if (last_type === 'TK_SEMICOLON' && flags.mode === MODE.BlockStatement) {
  762. // TODO: Should this be for STATEMENT as well?
  763. prefix = 'NEWLINE';
  764. } else if (last_type === 'TK_SEMICOLON' && is_expression(flags.mode)) {
  765. prefix = 'SPACE';
  766. } else if (last_type === 'TK_STRING') {
  767. prefix = 'NEWLINE';
  768. } else if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD' ||
  769. (flags.last_text === '*' && last_last_text === 'function')) {
  770. prefix = 'SPACE';
  771. } else if (last_type === 'TK_START_BLOCK') {
  772. prefix = 'NEWLINE';
  773. } else if (last_type === 'TK_END_EXPR') {
  774. output.space_before_token = true;
  775. prefix = 'NEWLINE';
  776. }
  777. if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, Tokenizer.line_starters) && flags.last_text !== ')') {
  778. if (flags.last_text === 'else' || flags.last_text === 'export') {
  779. prefix = 'SPACE';
  780. } else {
  781. prefix = 'NEWLINE';
  782. }
  783. }
  784. if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['else', 'catch', 'finally'])) {
  785. if (last_type !== 'TK_END_BLOCK' ||
  786. opt.brace_style === "expand" ||
  787. opt.brace_style === "end-expand" ||
  788. (opt.brace_style === "none" && current_token.wanted_newline)) {
  789. print_newline();
  790. } else {
  791. output.trim(true);
  792. var line = output.current_line;
  793. // If we trimmed and there's something other than a close block before us
  794. // put a newline back in. Handles '} // comment' scenario.
  795. if (line.last() !== '}') {
  796. print_newline();
  797. }
  798. output.space_before_token = true;
  799. }
  800. } else if (prefix === 'NEWLINE') {
  801. if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
  802. // no newline between 'return nnn'
  803. output.space_before_token = true;
  804. } else if (last_type !== 'TK_END_EXPR') {
  805. if ((last_type !== 'TK_START_EXPR' || !(current_token.type === 'TK_RESERVED' && in_array(current_token.text, ['var', 'let', 'const']))) && flags.last_text !== ':') {
  806. // no need to force newline on 'var': for (var x = 0...)
  807. if (current_token.type === 'TK_RESERVED' && current_token.text === 'if' && flags.last_text === 'else') {
  808. // no newline for } else if {
  809. output.space_before_token = true;
  810. } else {
  811. print_newline();
  812. }
  813. }
  814. } else if (current_token.type === 'TK_RESERVED' && in_array(current_token.text, Tokenizer.line_starters) && flags.last_text !== ')') {
  815. print_newline();
  816. }
  817. } else if (flags.multiline_frame && is_array(flags.mode) && flags.last_text === ',' && last_last_text === '}') {
  818. print_newline(); // }, in lists get a newline treatment
  819. } else if (prefix === 'SPACE') {
  820. output.space_before_token = true;
  821. }
  822. print_token();
  823. flags.last_word = current_token.text;
  824. if (current_token.type === 'TK_RESERVED' && current_token.text === 'do') {
  825. flags.do_block = true;
  826. }
  827. if (current_token.type === 'TK_RESERVED' && current_token.text === 'if') {
  828. flags.if_block = true;
  829. }
  830. }
  831. function handle_semicolon() {
  832. if (start_of_statement()) {
  833. // The conditional starts the statement if appropriate.
  834. // Semicolon can be the start (and end) of a statement
  835. output.space_before_token = false;
  836. }
  837. while (flags.mode === MODE.Statement && !flags.if_block && !flags.do_block) {
  838. restore_mode();
  839. }
  840. print_token();
  841. }
  842. function handle_string() {
  843. if (start_of_statement()) {
  844. // The conditional starts the statement if appropriate.
  845. // One difference - strings want at least a space before
  846. output.space_before_token = true;
  847. } else if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD') {
  848. output.space_before_token = true;
  849. } else if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
  850. if (!start_of_object_property()) {
  851. allow_wrap_or_preserved_newline();
  852. }
  853. } else {
  854. print_newline();
  855. }
  856. print_token();
  857. }
  858. function handle_equals() {
  859. if (start_of_statement()) {
  860. // The conditional starts the statement if appropriate.
  861. }
  862. if (flags.declaration_statement) {
  863. // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done
  864. flags.declaration_assignment = true;
  865. }
  866. output.space_before_token = true;
  867. print_token();
  868. output.space_before_token = true;
  869. }
  870. function handle_comma() {
  871. if (flags.declaration_statement) {
  872. if (is_expression(flags.parent.mode)) {
  873. // do not break on comma, for(var a = 1, b = 2)
  874. flags.declaration_assignment = false;
  875. }
  876. print_token();
  877. if (flags.declaration_assignment) {
  878. flags.declaration_assignment = false;
  879. print_newline(false, true);
  880. } else {
  881. output.space_before_token = true;
  882. }
  883. return;
  884. }
  885. print_token();
  886. if (flags.mode === MODE.ObjectLiteral ||
  887. (flags.mode === MODE.Statement && flags.parent.mode === MODE.ObjectLiteral)) {
  888. if (flags.mode === MODE.Statement) {
  889. restore_mode();
  890. }
  891. print_newline();
  892. } else {
  893. // EXPR or DO_BLOCK
  894. output.space_before_token = true;
  895. }
  896. }
  897. function handle_operator() {
  898. if (start_of_statement()) {
  899. // The conditional starts the statement if appropriate.
  900. }
  901. if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
  902. // "return" had a special handling in TK_WORD. Now we need to return the favor
  903. output.space_before_token = true;
  904. print_token();
  905. return;
  906. }
  907. // hack for actionscript's import .*;
  908. if (current_token.text === '*' && last_type === 'TK_DOT') {
  909. print_token();
  910. return;
  911. }
  912. if (current_token.text === ':' && flags.in_case) {
  913. flags.case_body = true;
  914. indent();
  915. print_token();
  916. print_newline();
  917. flags.in_case = false;
  918. return;
  919. }
  920. if (current_token.text === '::') {
  921. // no spaces around exotic namespacing syntax operator
  922. print_token();
  923. return;
  924. }
  925. // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1
  926. // if there is a newline between -- or ++ and anything else we should preserve it.
  927. if (current_token.wanted_newline && (current_token.text === '--' || current_token.text === '++')) {
  928. print_newline(false, true);
  929. }
  930. // Allow line wrapping between operators
  931. if (last_type === 'TK_OPERATOR') {
  932. allow_wrap_or_preserved_newline();
  933. }
  934. var space_before = true;
  935. var space_after = true;
  936. 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 === ','))) {
  937. // unary operators (and binary +/- pretending to be unary) special cases
  938. space_before = false;
  939. space_after = false;
  940. if (flags.last_text === ';' && is_expression(flags.mode)) {
  941. // for (;; ++i)
  942. // ^^^
  943. space_before = true;
  944. }
  945. if (last_type === 'TK_RESERVED' || last_type === 'TK_END_EXPR') {
  946. space_before = true;
  947. } else if (last_type === 'TK_OPERATOR') {
  948. space_before =
  949. (in_array(current_token.text, ['--', '-']) && in_array(flags.last_text, ['--', '-'])) ||
  950. (in_array(current_token.text, ['++', '+']) && in_array(flags.last_text, ['++', '+']));
  951. }
  952. if ((flags.mode === MODE.BlockStatement || flags.mode === MODE.Statement) && (flags.last_text === '{' || flags.last_text === ';')) {
  953. // { foo; --i }
  954. // foo(); --bar;
  955. print_newline();
  956. }
  957. } else if (current_token.text === ':') {
  958. if (flags.ternary_depth === 0) {
  959. // Colon is invalid javascript outside of ternary and object, but do our best to guess what was meant.
  960. space_before = false;
  961. } else {
  962. flags.ternary_depth -= 1;
  963. }
  964. } else if (current_token.text === '?') {
  965. flags.ternary_depth += 1;
  966. } else if (current_token.text === '*' && last_type === 'TK_RESERVED' && flags.last_text === 'function') {
  967. space_before = false;
  968. space_after = false;
  969. }
  970. output.space_before_token = output.space_before_token || space_before;
  971. print_token();
  972. output.space_before_token = space_after;
  973. }
  974. function handle_block_comment() {
  975. var lines = split_newlines(current_token.text);
  976. var j; // iterator for this case
  977. var javadoc = false;
  978. var starless = false;
  979. var lastIndent = current_token.whitespace_before;
  980. var lastIndentLength = lastIndent.length;
  981. // block comment starts with a new line
  982. print_newline(false, true);
  983. if (lines.length > 1) {
  984. if (all_lines_start_with(lines.slice(1), '*')) {
  985. javadoc = true;
  986. }
  987. else if (each_line_matches_indent(lines.slice(1), lastIndent)) {
  988. starless = true;
  989. }
  990. }
  991. // first line always indented
  992. print_token(lines[0]);
  993. for (j = 1; j < lines.length; j++) {
  994. print_newline(false, true);
  995. if (javadoc) {
  996. // javadoc: reformat and re-indent
  997. print_token(' ' + trim(lines[j]));
  998. } else if (starless && lines[j].length > lastIndentLength) {
  999. // starless: re-indent non-empty content, avoiding trim
  1000. print_token(lines[j].substring(lastIndentLength));
  1001. } else {
  1002. // normal comments output raw
  1003. output.add_token(lines[j]);
  1004. }
  1005. }
  1006. // for comments of more than one line, make sure there's a new line after
  1007. print_newline(false, true);
  1008. }
  1009. function handle_inline_comment() {
  1010. output.space_before_token = true;
  1011. print_token();
  1012. output.space_before_token = true;
  1013. }
  1014. function handle_comment() {
  1015. if (current_token.wanted_newline) {
  1016. print_newline(false, true);
  1017. } else {
  1018. output.trim(true);
  1019. }
  1020. output.space_before_token = true;
  1021. print_token();
  1022. print_newline(false, true);
  1023. }
  1024. function handle_dot() {
  1025. if (start_of_statement()) {
  1026. // The conditional starts the statement if appropriate.
  1027. }
  1028. if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
  1029. output.space_before_token = true;
  1030. } else {
  1031. // allow preserved newlines before dots in general
  1032. // force newlines on dots after close paren when break_chained - for bar().baz()
  1033. allow_wrap_or_preserved_newline(flags.last_text === ')' && opt.break_chained_methods);
  1034. }
  1035. print_token();
  1036. }
  1037. function handle_unknown() {
  1038. print_token();
  1039. if (current_token.text[current_token.text.length - 1] === '\n') {
  1040. print_newline();
  1041. }
  1042. }
  1043. function handle_eof() {
  1044. // Unwind any open statements
  1045. while (flags.mode === MODE.Statement) {
  1046. restore_mode();
  1047. }
  1048. }
  1049. }
  1050. function OutputLine(parent) {
  1051. var _character_count = 0;
  1052. // use indent_count as a marker for lines that have preserved indentation
  1053. var _indent_count = -1;
  1054. var _items = [];
  1055. var _empty = true;
  1056. this.set_indent = function(level) {
  1057. _character_count = parent.baseIndentLength + level * parent.indent_length
  1058. _indent_count = level;
  1059. }
  1060. this.get_character_count = function() {
  1061. return _character_count;
  1062. }
  1063. this.is_empty = function() {
  1064. return _empty;
  1065. }
  1066. this.last = function() {
  1067. if (!this._empty) {
  1068. return _items[_items.length - 1];
  1069. } else {
  1070. return null;
  1071. }
  1072. }
  1073. this.push = function(input) {
  1074. _items.push(input);
  1075. _character_count += input.length;
  1076. _empty = false;
  1077. }
  1078. this.remove_indent = function() {
  1079. if (_indent_count > 0) {
  1080. _indent_count -= 1;
  1081. _character_count -= parent.indent_length
  1082. }
  1083. }
  1084. this.trim = function() {
  1085. while (this.last() === ' ') {
  1086. var item = _items.pop();
  1087. _character_count -= 1;
  1088. }
  1089. _empty = _items.length === 0;
  1090. }
  1091. this.toString = function() {
  1092. var result = '';
  1093. if (!this._empty) {
  1094. if (_indent_count >= 0) {
  1095. result = parent.indent_cache[_indent_count];
  1096. }
  1097. result += _items.join('')
  1098. }
  1099. return result;
  1100. }
  1101. }
  1102. function Output(indent_string, baseIndentString) {
  1103. baseIndentString = baseIndentString || '';
  1104. this.indent_cache = [ baseIndentString ];
  1105. this.baseIndentLength = baseIndentString.length;
  1106. this.indent_length = indent_string.length;
  1107. var lines =[];
  1108. this.baseIndentString = baseIndentString;
  1109. this.indent_string = indent_string;
  1110. this.current_line = null;
  1111. this.space_before_token = false;
  1112. this.get_line_number = function() {
  1113. return lines.length;
  1114. }
  1115. // Using object instead of string to allow for later expansion of info about each line
  1116. this.add_new_line = function(force_newline) {
  1117. if (this.get_line_number() === 1 && this.just_added_newline()) {
  1118. return false; // no newline on start of file
  1119. }
  1120. if (force_newline || !this.just_added_newline()) {
  1121. this.current_line = new OutputLine(this);
  1122. lines.push(this.current_line);
  1123. return true;
  1124. }
  1125. return false;
  1126. }
  1127. // initialize
  1128. this.add_new_line(true);
  1129. this.get_code = function() {
  1130. var sweet_code = lines.join('\n').replace(/[\r\n\t ]+$/, '');
  1131. return sweet_code;
  1132. }
  1133. this.set_indent = function(level) {
  1134. // Never indent your first output indent at the start of the file
  1135. if (lines.length > 1) {
  1136. while(level >= this.indent_cache.length) {
  1137. this.indent_cache.push(this.indent_cache[this.indent_cache.length - 1] + this.indent_string);
  1138. }
  1139. this.current_line.set_indent(level);
  1140. return true;
  1141. }
  1142. this.current_line.set_indent(0);
  1143. return false;
  1144. }
  1145. this.add_token = function(printable_token) {
  1146. this.add_space_before_token();
  1147. this.current_line.push(printable_token);
  1148. }
  1149. this.add_space_before_token = function() {
  1150. if (this.space_before_token && !this.just_added_newline()) {
  1151. this.current_line.push(' ');
  1152. }
  1153. this.space_before_token = false;
  1154. }
  1155. this.remove_redundant_indentation = function (frame) {
  1156. // This implementation is effective but has some issues:
  1157. // - can cause line wrap to happen too soon due to indent removal
  1158. // after wrap points are calculated
  1159. // These issues are minor compared to ugly indentation.
  1160. if (frame.multiline_frame ||
  1161. frame.mode === MODE.ForInitializer ||
  1162. frame.mode === MODE.Conditional) {
  1163. return;
  1164. }
  1165. // remove one indent from each line inside this section
  1166. var index = frame.start_line_index;
  1167. var line;
  1168. var output_length = lines.length;
  1169. while (index < output_length) {
  1170. lines[index].remove_indent();
  1171. index++;
  1172. }
  1173. }
  1174. this.trim = function(eat_newlines) {
  1175. eat_newlines = (eat_newlines === undefined) ? false : eat_newlines;
  1176. this.current_line.trim(indent_string, baseIndentString);
  1177. while (eat_newlines && lines.length > 1 &&
  1178. this.current_line.is_empty()) {
  1179. lines.pop();
  1180. this.current_line = lines[lines.length - 1]
  1181. this.current_line.trim();
  1182. }
  1183. }
  1184. this.just_added_newline = function() {
  1185. return this.current_line.is_empty();
  1186. }
  1187. this.just_added_blankline = function() {
  1188. if (this.just_added_newline()) {
  1189. if (lines.length === 1) {
  1190. return true; // start of the file and newline = blank
  1191. }
  1192. var line = lines[lines.length - 2];
  1193. return line.is_empty();
  1194. }
  1195. return false;
  1196. }
  1197. }
  1198. var Token = function(type, text, newlines, whitespace_before, mode, parent) {
  1199. this.type = type;
  1200. this.text = text;
  1201. this.comments_before = [];
  1202. this.newlines = newlines || 0;
  1203. this.wanted_newline = newlines > 0;
  1204. this.whitespace_before = whitespace_before || '';
  1205. this.parent = null;
  1206. }
  1207. function tokenizer(input, opts, indent_string) {
  1208. var whitespace = "\n\r\t ".split('');
  1209. var digit = /[0-9]/;
  1210. var punct = ('+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! ~ , : ? ^ ^= |= :: =>'
  1211. +' <%= <% %> <?= <? ?>').split(' '); // try to be a good boy and try not to break the markup language identifiers
  1212. // words which should always start on new line.
  1213. this.line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,yield,import,export'.split(',');
  1214. var reserved_words = this.line_starters.concat(['do', 'in', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof']);
  1215. var n_newlines, whitespace_before_token, in_html_comment, tokens, parser_pos;
  1216. var input_length;
  1217. this.tokenize = function() {
  1218. // cache the source's length.
  1219. input_length = input.length
  1220. parser_pos = 0;
  1221. in_html_comment = false
  1222. tokens = [];
  1223. var next, last;
  1224. var token_values;
  1225. var open = null;
  1226. var open_stack = [];
  1227. var comments = [];
  1228. while (!(last && last.type === 'TK_EOF')) {
  1229. token_values = tokenize_next();
  1230. next = new Token(token_values[1], token_values[0], n_newlines, whitespace_before_token);
  1231. while(next.type === 'TK_INLINE_COMMENT' || next.type === 'TK_COMMENT' ||
  1232. next.type === 'TK_BLOCK_COMMENT' || next.type === 'TK_UNKNOWN') {
  1233. comments.push(next);
  1234. token_values = tokenize_next();
  1235. next = new Token(token_values[1], token_values[0], n_newlines, whitespace_before_token);
  1236. }
  1237. if (comments.length) {
  1238. next.comments_before = comments;
  1239. comments = [];
  1240. }
  1241. if (next.type === 'TK_START_BLOCK' || next.type === 'TK_START_EXPR') {
  1242. next.parent = last;
  1243. open = next;
  1244. open_stack.push(next);
  1245. } else if ((next.type === 'TK_END_BLOCK' || next.type === 'TK_END_EXPR') &&
  1246. (open && (
  1247. (next.text === ']' && open.text === '[') ||
  1248. (next.text === ')' && open.text === '(') ||
  1249. (next.text === '}' && open.text === '}')))) {
  1250. next.parent = open.parent;
  1251. open = open_stack.pop();
  1252. }
  1253. tokens.push(next);
  1254. last = next;
  1255. }
  1256. return tokens;
  1257. }
  1258. function tokenize_next() {
  1259. var i, resulting_string;
  1260. var whitespace_on_this_line = [];
  1261. n_newlines = 0;
  1262. whitespace_before_token = '';
  1263. if (parser_pos >= input_length) {
  1264. return ['', 'TK_EOF'];
  1265. }
  1266. var last_token;
  1267. if (tokens.length) {
  1268. last_token = tokens[tokens.length-1];
  1269. } else {
  1270. // For the sake of tokenizing we can pretend that there was on open brace to start
  1271. last_token = new Token('TK_START_BLOCK', '{');
  1272. }
  1273. var c = input.charAt(parser_pos);
  1274. parser_pos += 1;
  1275. while (in_array(c, whitespace)) {
  1276. if (c === '\n') {
  1277. n_newlines += 1;
  1278. whitespace_on_this_line = [];
  1279. } else if (n_newlines) {
  1280. if (c === indent_string) {
  1281. whitespace_on_this_line.push(indent_string);
  1282. } else if (c !== '\r') {
  1283. whitespace_on_this_line.push(' ');
  1284. }
  1285. }
  1286. if (parser_pos >= input_length) {
  1287. return ['', 'TK_EOF'];
  1288. }
  1289. c = input.charAt(parser_pos);
  1290. parser_pos += 1;
  1291. }
  1292. if(whitespace_on_this_line.length) {
  1293. whitespace_before_token = whitespace_on_this_line.join('');
  1294. }
  1295. if (digit.test(c)) {
  1296. var allow_decimal = true;
  1297. var allow_e = true;
  1298. var local_digit = digit;
  1299. if (c === '0' && parser_pos < input_length && /[Xx]/.test(input.charAt(parser_pos))) {
  1300. // switch to hex number, no decimal or e, just hex digits
  1301. allow_decimal = false;
  1302. allow_e = false;
  1303. c += input.charAt(parser_pos);
  1304. parser_pos += 1;
  1305. local_digit = /[0123456789abcdefABCDEF]/
  1306. } else {
  1307. // we know this first loop will run. It keeps the logic simpler.
  1308. c = '';
  1309. parser_pos -= 1
  1310. }
  1311. // Add the digits
  1312. while (parser_pos < input_length && local_digit.test(input.charAt(parser_pos))) {
  1313. c += input.charAt(parser_pos);
  1314. parser_pos += 1;
  1315. if (allow_decimal && parser_pos < input_length && input.charAt(parser_pos) === '.') {
  1316. c += input.charAt(parser_pos);
  1317. parser_pos += 1;
  1318. allow_decimal = false;
  1319. }
  1320. if (allow_e && parser_pos < input_length && /[Ee]/.test(input.charAt(parser_pos))) {
  1321. c += input.charAt(parser_pos);
  1322. parser_pos += 1;
  1323. if (parser_pos < input_length && /[+-]/.test(input.charAt(parser_pos))) {
  1324. c += input.charAt(parser_pos);
  1325. parser_pos += 1;
  1326. }
  1327. allow_e = false;
  1328. allow_decimal = false;
  1329. }
  1330. }
  1331. return [c, 'TK_WORD'];
  1332. }
  1333. if (acorn.isIdentifierStart(input.charCodeAt(parser_pos-1))) {
  1334. if (parser_pos < input_length) {
  1335. while (acorn.isIdentifierChar(input.charCodeAt(parser_pos))) {
  1336. c += input.charAt(parser_pos);
  1337. parser_pos += 1;
  1338. if (parser_pos === input_length) {
  1339. break;
  1340. }
  1341. }
  1342. }
  1343. if (!(last_token.type === 'TK_DOT' ||
  1344. (last_token.type === 'TK_RESERVED' && in_array(last_token.text, ['set', 'get'])))
  1345. && in_array(c, reserved_words)) {
  1346. if (c === 'in') { // hack for 'in' operator
  1347. return [c, 'TK_OPERATOR'];
  1348. }
  1349. return [c, 'TK_RESERVED'];
  1350. }
  1351. return [c, 'TK_WORD'];
  1352. }
  1353. if (c === '(' || c === '[') {
  1354. return [c, 'TK_START_EXPR'];
  1355. }
  1356. if (c === ')' || c === ']') {
  1357. return [c, 'TK_END_EXPR'];
  1358. }
  1359. if (c === '{') {
  1360. return [c, 'TK_START_BLOCK'];
  1361. }
  1362. if (c === '}') {
  1363. return [c, 'TK_END_BLOCK'];
  1364. }
  1365. if (c === ';') {
  1366. return [c, 'TK_SEMICOLON'];
  1367. }
  1368. if (c === '/') {
  1369. var comment = '';
  1370. // peek for comment /* ... */
  1371. var inline_comment = true;
  1372. if (input.charAt(parser_pos) === '*') {
  1373. parser_pos += 1;
  1374. if (parser_pos < input_length) {
  1375. while (parser_pos < input_length && !(input.charAt(parser_pos) === '*' && input.charAt(parser_pos + 1) && input.charAt(parser_pos + 1) === '/')) {
  1376. c = input.charAt(parser_pos);
  1377. comment += c;
  1378. if (c === "\n" || c === "\r") {
  1379. inline_comment = false;
  1380. }
  1381. parser_pos += 1;
  1382. if (parser_pos >= input_length) {
  1383. break;
  1384. }
  1385. }
  1386. }
  1387. parser_pos += 2;
  1388. if (inline_comment && n_newlines === 0) {
  1389. return ['/*' + comment + '*/', 'TK_INLINE_COMMENT'];
  1390. } else {
  1391. return ['/*' + comment + '*/', 'TK_BLOCK_COMMENT'];
  1392. }
  1393. }
  1394. // peek for comment // ...
  1395. if (input.charAt(parser_pos) === '/') {
  1396. comment = c;
  1397. while (input.charAt(parser_pos) !== '\r' && input.charAt(parser_pos) !== '\n') {
  1398. comment += input.charAt(parser_pos);
  1399. parser_pos += 1;
  1400. if (parser_pos >= input_length) {
  1401. break;
  1402. }
  1403. }
  1404. return [comment, 'TK_COMMENT'];
  1405. }
  1406. }
  1407. if (c === '`' || c === "'" || c === '"' || // string
  1408. (
  1409. (c === '/') //|| // regexp
  1410. //(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*>/)) // xml
  1411. ) && ( // regex and xml can only appear in specific locations during parsing
  1412. (last_token.type === 'TK_RESERVED' && in_array(last_token.text , ['return', 'case', 'throw', 'else', 'do', 'typeof', 'yield'])) ||
  1413. (last_token.type === 'TK_END_EXPR' && last_token.text === ')' &&
  1414. last_token.parent && last_token.parent.type === 'TK_RESERVED' && in_array(last_token.parent.text, ['if', 'while', 'for'])) ||
  1415. (in_array(last_token.type, ['TK_COMMENT', 'TK_START_EXPR', 'TK_START_BLOCK',
  1416. 'TK_END_BLOCK', 'TK_OPERATOR', 'TK_EQUALS', 'TK_EOF', 'TK_SEMICOLON', 'TK_COMMA'
  1417. ]))
  1418. )) {
  1419. var sep = c,
  1420. esc = false,
  1421. has_char_escapes = false;
  1422. resulting_string = c;
  1423. if (sep === '/') {
  1424. //
  1425. // handle regexp
  1426. //
  1427. var in_char_class = false;
  1428. while (parser_pos < input_length &&
  1429. ((esc || in_char_class || input.charAt(parser_pos) !== sep) &&
  1430. !acorn.newline.test(input.charAt(parser_pos)))) {
  1431. resulting_string += input.charAt(parser_pos);
  1432. if (!esc) {
  1433. esc = input.charAt(parser_pos) === '\\';
  1434. if (input.charAt(parser_pos) === '[') {
  1435. in_char_class = true;
  1436. } else if (input.charAt(parser_pos) === ']') {
  1437. in_char_class = false;
  1438. }
  1439. } else {
  1440. esc = false;
  1441. }
  1442. parser_pos += 1;
  1443. }
  1444. } else if (opts.e4x && sep === '<') {
  1445. //
  1446. // handle e4x xml literals
  1447. //
  1448. //var xmlRegExp = /<(\/?)([-a-zA-Z:0-9_.]+|{[^{}]*}|!\[CDATA\[[\s\S]*?\]\])\s*([-a-zA-Z:0-9_.]+=('[^']*'|"[^"]*"|{[^{}]*})\s*)*(\/?)\s*>/g;
  1449. var xmlStr = input.slice(parser_pos - 1);
  1450. var match = xmlRegExp.exec(xmlStr);
  1451. if (match && match.index === 0) {
  1452. var rootTag = match[2];
  1453. var depth = 0;
  1454. while (match) {
  1455. var isEndTag = !! match[1];
  1456. var tagName = match[2];
  1457. var isSingletonTag = ( !! match[match.length - 1]) || (tagName.slice(0, 8) === "![CDATA[");
  1458. if (tagName === rootTag && !isSingletonTag) {
  1459. if (isEndTag) {
  1460. --depth;
  1461. } else {
  1462. ++depth;
  1463. }
  1464. }
  1465. if (depth <= 0) {
  1466. break;
  1467. }
  1468. match = xmlRegExp.exec(xmlStr);
  1469. }
  1470. var xmlLength = match ? match.index + match[0].length : xmlStr.length;
  1471. parser_pos += xmlLength - 1;
  1472. return [xmlStr.slice(0, xmlLength), "TK_STRING"];
  1473. }
  1474. } else {
  1475. //
  1476. // handle string
  1477. //
  1478. // Template strings can travers lines without escape characters.
  1479. // Other strings cannot
  1480. while (parser_pos < input_length &&
  1481. (esc || (input.charAt(parser_pos) !== sep &&
  1482. (sep === '`' || !acorn.newline.test(input.charAt(parser_pos)))))) {
  1483. resulting_string += input.charAt(parser_pos);
  1484. if (esc) {
  1485. if (input.charAt(parser_pos) === 'x' || input.charAt(parser_pos) === 'u') {
  1486. has_char_escapes = true;
  1487. }
  1488. esc = false;
  1489. } else {
  1490. esc = input.charAt(parser_pos) === '\\';
  1491. }
  1492. parser_pos += 1;
  1493. }
  1494. }
  1495. if (has_char_escapes && opts.unescape_strings) {
  1496. resulting_string = unescape_string(resulting_string);
  1497. }
  1498. if (parser_pos < input_length && input.charAt(parser_pos) === sep) {
  1499. resulting_string += sep;
  1500. parser_pos += 1;
  1501. if (sep === '/') {
  1502. // regexps may have modifiers /regexp/MOD , so fetch those, too
  1503. // Only [gim] are valid, but if the user puts in garbage, do what we can to take it.
  1504. while (parser_pos < input_length && acorn.isIdentifierStart(input.charCodeAt(parser_pos))) {
  1505. resulting_string += input.charAt(parser_pos);
  1506. parser_pos += 1;
  1507. }
  1508. }
  1509. }
  1510. return [resulting_string, 'TK_STRING'];
  1511. }
  1512. if (c === '#') {
  1513. if (tokens.length === 0 && input.charAt(parser_pos) === '!') {
  1514. // shebang
  1515. resulting_string = c;
  1516. while (parser_pos < input_length && c !== '\n') {
  1517. c = input.charAt(parser_pos);
  1518. resulting_string += c;
  1519. parser_pos += 1;
  1520. }
  1521. return [trim(resulting_string) + '\n', 'TK_UNKNOWN'];
  1522. }
  1523. // Spidermonkey-specific sharp variables for circular references
  1524. // https://developer.mozilla.org/En/Sharp_variables_in_JavaScript
  1525. // http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp around line 1935
  1526. var sharp = '#';
  1527. if (parser_pos < input_length && digit.test(input.charAt(parser_pos))) {
  1528. do {
  1529. c = input.charAt(parser_pos);
  1530. sharp += c;
  1531. parser_pos += 1;
  1532. } while (parser_pos < input_length && c !== '#' && c !== '=');
  1533. if (c === '#') {
  1534. //
  1535. } else if (input.charAt(parser_pos) === '[' && input.charAt(parser_pos + 1) === ']') {
  1536. sharp += '[]';
  1537. parser_pos += 2;
  1538. } else if (input.charAt(parser_pos) === '{' && input.charAt(parser_pos + 1) === '}') {
  1539. sharp += '{}';
  1540. parser_pos += 2;
  1541. }
  1542. return [sharp, 'TK_WORD'];
  1543. }
  1544. }
  1545. if (c === '<' && input.substring(parser_pos - 1, parser_pos + 3) === '<!--') {
  1546. parser_pos += 3;
  1547. c = '<!--';
  1548. while (input.charAt(parser_pos) !== '\n' && parser_pos < input_length) {
  1549. c += input.charAt(parser_pos);
  1550. parser_pos++;
  1551. }
  1552. in_html_comment = true;
  1553. return [c, 'TK_COMMENT'];
  1554. }
  1555. if (c === '-' && in_html_comment && input.substring(parser_pos - 1, parser_pos + 2) === '-->') {
  1556. in_html_comment = false;
  1557. parser_pos += 2;
  1558. return ['-->', 'TK_COMMENT'];
  1559. }
  1560. if (c === '.') {
  1561. return [c, 'TK_DOT'];
  1562. }
  1563. if (in_array(c, punct)) {
  1564. while (parser_pos < input_length && in_array(c + input.charAt(parser_pos), punct)) {
  1565. c += input.charAt(parser_pos);
  1566. parser_pos += 1;
  1567. if (parser_pos >= input_length) {
  1568. break;
  1569. }
  1570. }
  1571. if (c === ',') {
  1572. return [c, 'TK_COMMA'];
  1573. } else if (c === '=') {
  1574. return [c, 'TK_EQUALS'];
  1575. } else {
  1576. return [c, 'TK_OPERATOR'];
  1577. }
  1578. }
  1579. return [c, 'TK_UNKNOWN'];
  1580. }
  1581. function unescape_string(s) {
  1582. var esc = false,
  1583. out = '',
  1584. pos = 0,
  1585. s_hex = '',
  1586. escaped = 0,
  1587. c;
  1588. while (esc || pos < s.length) {
  1589. c = s.charAt(pos);
  1590. pos++;
  1591. if (esc) {
  1592. esc = false;
  1593. if (c === 'x') {
  1594. // simple hex-escape \x24
  1595. s_hex = s.substr(pos, 2);
  1596. pos += 2;
  1597. } else if (c === 'u') {
  1598. // unicode-escape, \u2134
  1599. s_hex = s.substr(pos, 4);
  1600. pos += 4;
  1601. } else {
  1602. // some common escape, e.g \n
  1603. out += '\\' + c;
  1604. continue;
  1605. }
  1606. if (!s_hex.match(/^[0123456789abcdefABCDEF]+$/)) {
  1607. // some weird escaping, bail out,
  1608. // leaving whole string intact
  1609. return s;
  1610. }
  1611. escaped = parseInt(s_hex, 16);
  1612. if (escaped >= 0x00 && escaped < 0x20) {
  1613. // leave 0x00...0x1f escaped
  1614. if (c === 'x') {
  1615. out += '\\x' + s_hex;
  1616. } else {
  1617. out += '\\u' + s_hex;
  1618. }
  1619. continue;
  1620. } else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) {
  1621. // single-quote, apostrophe, backslash - escape these
  1622. out += '\\' + String.fromCharCode(escaped);
  1623. } else if (c === 'x' && escaped > 0x7e && escaped <= 0xff) {
  1624. // we bail out on \x7f..\xff,
  1625. // leaving whole string escaped,
  1626. // as it's probably completely binary
  1627. return s;
  1628. } else {
  1629. out += String.fromCharCode(escaped);
  1630. }
  1631. } else if (c === '\\') {
  1632. esc = true;
  1633. } else {
  1634. out += c;
  1635. }
  1636. }
  1637. return out;
  1638. }
  1639. }
  1640. if (typeof define === "function" && define.amd) {
  1641. // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
  1642. define([], function() {
  1643. return { js_beautify: js_beautify };
  1644. });
  1645. } else if (typeof exports !== "undefined") {
  1646. // Add support for CommonJS. Just put this file somewhere on your require.paths
  1647. // and you will be able to `var js_beautify = require("beautify").js_beautify`.
  1648. exports.js_beautify = js_beautify;
  1649. } else if (typeof window !== "undefined") {
  1650. // If we're running a web page and don't have either of the above, add our one global
  1651. window.js_beautify = js_beautify;
  1652. } else if (typeof global !== "undefined") {
  1653. // If we don't even have window, try global.
  1654. global.js_beautify = js_beautify;
  1655. }
  1656. }());