js.el 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372
  1. ;;; js.el --- Major mode for editing JavaScript
  2. ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
  3. ;; Author: Karl Landstrom <karl.landstrom@brgeight.se>
  4. ;; Daniel Colascione <dan.colascione@gmail.com>
  5. ;; Maintainer: Daniel Colascione <dan.colascione@gmail.com>
  6. ;; Version: 9
  7. ;; Date: 2009-07-25
  8. ;; Keywords: languages, javascript
  9. ;; This file is part of GNU Emacs.
  10. ;; GNU Emacs is free software: you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation, either version 3 of the License, or
  13. ;; (at your option) any later version.
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;; GNU General Public License for more details.
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  20. ;;; Commentary
  21. ;; This is based on Karl Landstrom's barebones javascript-mode. This
  22. ;; is much more robust and works with cc-mode's comment filling
  23. ;; (mostly).
  24. ;;
  25. ;; The main features of this JavaScript mode are syntactic
  26. ;; highlighting (enabled with `font-lock-mode' or
  27. ;; `global-font-lock-mode'), automatic indentation and filling of
  28. ;; comments, C preprocessor fontification, and MozRepl integration.
  29. ;;
  30. ;; General Remarks:
  31. ;;
  32. ;; XXX: This mode assumes that block comments are not nested inside block
  33. ;; XXX: comments
  34. ;;
  35. ;; Exported names start with "js-"; private names start with
  36. ;; "js--".
  37. ;;; Code:
  38. (require 'cc-mode)
  39. (require 'newcomment)
  40. (require 'thingatpt) ; forward-symbol etc
  41. (require 'imenu)
  42. (require 'moz nil t)
  43. (require 'json nil t)
  44. (eval-when-compile
  45. (require 'cl)
  46. (require 'comint)
  47. (require 'ido))
  48. (defvar inferior-moz-buffer)
  49. (defvar moz-repl-name)
  50. (defvar ido-cur-list)
  51. (defvar electric-layout-rules)
  52. (declare-function ido-mode "ido")
  53. (declare-function inferior-moz-process "ext:mozrepl" ())
  54. ;;; Constants
  55. (defconst js--name-start-re "[a-zA-Z_$]"
  56. "Regexp matching the start of a JavaScript identifier, without grouping.")
  57. (defconst js--stmt-delim-chars "^;{}?:")
  58. (defconst js--name-re (concat js--name-start-re
  59. "\\(?:\\s_\\|\\sw\\)*")
  60. "Regexp matching a JavaScript identifier, without grouping.")
  61. (defconst js--objfield-re (concat js--name-re ":")
  62. "Regexp matching the start of a JavaScript object field.")
  63. (defconst js--dotted-name-re
  64. (concat js--name-re "\\(?:\\." js--name-re "\\)*")
  65. "Regexp matching a dot-separated sequence of JavaScript names.")
  66. (defconst js--cpp-name-re js--name-re
  67. "Regexp matching a C preprocessor name.")
  68. (defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
  69. "Regexp matching the prefix of a cpp directive.
  70. This includes the directive name, or nil in languages without
  71. preprocessor support. The first submatch surrounds the directive
  72. name.")
  73. (defconst js--plain-method-re
  74. (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
  75. "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
  76. "Regexp matching an explicit JavaScript prototype \"method\" declaration.
  77. Group 1 is a (possibly-dotted) class name, group 2 is a method name,
  78. and group 3 is the 'function' keyword.")
  79. (defconst js--plain-class-re
  80. (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
  81. "\\s-*=\\s-*{")
  82. "Regexp matching a JavaScript explicit prototype \"class\" declaration.
  83. An example of this is \"Class.prototype = { method1: ...}\".")
  84. ;; var NewClass = BaseClass.extend(
  85. (defconst js--mp-class-decl-re
  86. (concat "^\\s-*var\\s-+"
  87. "\\(" js--name-re "\\)"
  88. "\\s-*=\\s-*"
  89. "\\(" js--dotted-name-re
  90. "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
  91. ;; var NewClass = Class.create()
  92. (defconst js--prototype-obsolete-class-decl-re
  93. (concat "^\\s-*\\(?:var\\s-+\\)?"
  94. "\\(" js--dotted-name-re "\\)"
  95. "\\s-*=\\s-*Class\\.create()"))
  96. (defconst js--prototype-objextend-class-decl-re-1
  97. (concat "^\\s-*Object\\.extend\\s-*("
  98. "\\(" js--dotted-name-re "\\)"
  99. "\\s-*,\\s-*{"))
  100. (defconst js--prototype-objextend-class-decl-re-2
  101. (concat "^\\s-*\\(?:var\\s-+\\)?"
  102. "\\(" js--dotted-name-re "\\)"
  103. "\\s-*=\\s-*Object\\.extend\\s-*\("))
  104. ;; var NewClass = Class.create({
  105. (defconst js--prototype-class-decl-re
  106. (concat "^\\s-*\\(?:var\\s-+\\)?"
  107. "\\(" js--name-re "\\)"
  108. "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
  109. "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
  110. ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
  111. ;; matched with dedicated font-lock matchers
  112. (defconst js--dojo-class-decl-re
  113. (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re "\\)"))
  114. (defconst js--extjs-class-decl-re-1
  115. (concat "^\\s-*Ext\\.extend\\s-*("
  116. "\\s-*\\(" js--dotted-name-re "\\)"
  117. "\\s-*,\\s-*\\(" js--dotted-name-re "\\)")
  118. "Regexp matching an ExtJS class declaration (style 1).")
  119. (defconst js--extjs-class-decl-re-2
  120. (concat "^\\s-*\\(?:var\\s-+\\)?"
  121. "\\(" js--name-re "\\)"
  122. "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
  123. "\\(" js--dotted-name-re "\\)")
  124. "Regexp matching an ExtJS class declaration (style 2).")
  125. (defconst js--mochikit-class-re
  126. (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
  127. "\\(" js--dotted-name-re "\\)")
  128. "Regexp matching a MochiKit class declaration.")
  129. (defconst js--dummy-class-style
  130. '(:name "[Automatically Generated Class]"))
  131. (defconst js--class-styles
  132. `((:name "Plain"
  133. :class-decl ,js--plain-class-re
  134. :prototype t
  135. :contexts (toplevel)
  136. :framework javascript)
  137. (:name "MochiKit"
  138. :class-decl ,js--mochikit-class-re
  139. :prototype t
  140. :contexts (toplevel)
  141. :framework mochikit)
  142. (:name "Prototype (Obsolete)"
  143. :class-decl ,js--prototype-obsolete-class-decl-re
  144. :contexts (toplevel)
  145. :framework prototype)
  146. (:name "Prototype (Modern)"
  147. :class-decl ,js--prototype-class-decl-re
  148. :contexts (toplevel)
  149. :framework prototype)
  150. (:name "Prototype (Object.extend)"
  151. :class-decl ,js--prototype-objextend-class-decl-re-1
  152. :prototype t
  153. :contexts (toplevel)
  154. :framework prototype)
  155. (:name "Prototype (Object.extend) 2"
  156. :class-decl ,js--prototype-objextend-class-decl-re-2
  157. :prototype t
  158. :contexts (toplevel)
  159. :framework prototype)
  160. (:name "Dojo"
  161. :class-decl ,js--dojo-class-decl-re
  162. :contexts (toplevel)
  163. :framework dojo)
  164. (:name "ExtJS (style 1)"
  165. :class-decl ,js--extjs-class-decl-re-1
  166. :prototype t
  167. :contexts (toplevel)
  168. :framework extjs)
  169. (:name "ExtJS (style 2)"
  170. :class-decl ,js--extjs-class-decl-re-2
  171. :contexts (toplevel)
  172. :framework extjs)
  173. (:name "Merrill Press"
  174. :class-decl ,js--mp-class-decl-re
  175. :contexts (toplevel)
  176. :framework merrillpress))
  177. "List of JavaScript class definition styles.
  178. A class definition style is a plist with the following keys:
  179. :name is a human-readable name of the class type
  180. :class-decl is a regular expression giving the start of the
  181. class. Its first group must match the name of its class. If there
  182. is a parent class, the second group should match, and it should be
  183. the name of the class.
  184. If :prototype is present and non-nil, the parser will merge
  185. declarations for this constructs with others at the same lexical
  186. level that have the same name. Otherwise, multiple definitions
  187. will create multiple top-level entries. Don't use :prototype
  188. unnecessarily: it has an associated cost in performance.
  189. If :strip-prototype is present and non-nil, then if the class
  190. name as matched contains
  191. ")
  192. (defconst js--available-frameworks
  193. (loop with available-frameworks
  194. for style in js--class-styles
  195. for framework = (plist-get style :framework)
  196. unless (memq framework available-frameworks)
  197. collect framework into available-frameworks
  198. finally return available-frameworks)
  199. "List of available JavaScript frameworks symbols.")
  200. (defconst js--function-heading-1-re
  201. (concat
  202. "^\\s-*function\\s-+\\(" js--name-re "\\)")
  203. "Regexp matching the start of a JavaScript function header.
  204. Match group 1 is the name of the function.")
  205. (defconst js--function-heading-2-re
  206. (concat
  207. "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
  208. "Regexp matching the start of a function entry in an associative array.
  209. Match group 1 is the name of the function.")
  210. (defconst js--function-heading-3-re
  211. (concat
  212. "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
  213. "\\s-*=\\s-*function\\_>")
  214. "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
  215. Match group 1 is MUMBLE.")
  216. (defconst js--macro-decl-re
  217. (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
  218. "Regexp matching a CPP macro definition, up to the opening parenthesis.
  219. Match group 1 is the name of the macro.")
  220. (defun js--regexp-opt-symbol (list)
  221. "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
  222. (concat "\\_<" (regexp-opt list t) "\\_>"))
  223. (defconst js--keyword-re
  224. (js--regexp-opt-symbol
  225. '("abstract" "break" "case" "catch" "class" "const"
  226. "continue" "debugger" "default" "delete" "do" "else"
  227. "enum" "export" "extends" "final" "finally" "for"
  228. "function" "goto" "if" "implements" "import" "in"
  229. "instanceof" "interface" "native" "new" "package"
  230. "private" "protected" "public" "return" "static"
  231. "super" "switch" "synchronized" "throw"
  232. "throws" "transient" "try" "typeof" "var" "void" "let"
  233. "yield" "volatile" "while" "with"))
  234. "Regexp matching any JavaScript keyword.")
  235. (defconst js--basic-type-re
  236. (js--regexp-opt-symbol
  237. '("boolean" "byte" "char" "double" "float" "int" "long"
  238. "short" "void"))
  239. "Regular expression matching any predefined type in JavaScript.")
  240. (defconst js--constant-re
  241. (js--regexp-opt-symbol '("false" "null" "undefined"
  242. "Infinity" "NaN"
  243. "true" "arguments" "this"))
  244. "Regular expression matching any future reserved words in JavaScript.")
  245. (defconst js--font-lock-keywords-1
  246. (list
  247. "\\_<import\\_>"
  248. (list js--function-heading-1-re 1 font-lock-function-name-face)
  249. (list js--function-heading-2-re 1 font-lock-function-name-face))
  250. "Level one font lock keywords for `js-mode'.")
  251. (defconst js--font-lock-keywords-2
  252. (append js--font-lock-keywords-1
  253. (list (list js--keyword-re 1 font-lock-keyword-face)
  254. (list "\\_<for\\_>"
  255. "\\s-+\\(each\\)\\_>" nil nil
  256. (list 1 'font-lock-keyword-face))
  257. (cons js--basic-type-re font-lock-type-face)
  258. (cons js--constant-re font-lock-constant-face)))
  259. "Level two font lock keywords for `js-mode'.")
  260. ;; js--pitem is the basic building block of the lexical
  261. ;; database. When one refers to a real part of the buffer, the region
  262. ;; of text to which it refers is split into a conceptual header and
  263. ;; body. Consider the (very short) block described by a hypothetical
  264. ;; js--pitem:
  265. ;;
  266. ;; function foo(a,b,c) { return 42; }
  267. ;; ^ ^ ^
  268. ;; | | |
  269. ;; +- h-begin +- h-end +- b-end
  270. ;;
  271. ;; (Remember that these are buffer positions, and therefore point
  272. ;; between characters, not at them. An arrow drawn to a character
  273. ;; indicates the corresponding position is between that character and
  274. ;; the one immediately preceding it.)
  275. ;;
  276. ;; The header is the region of text [h-begin, h-end], and is
  277. ;; the text needed to unambiguously recognize the start of the
  278. ;; construct. If the entire header is not present, the construct is
  279. ;; not recognized at all. No other pitems may be nested inside the
  280. ;; header.
  281. ;;
  282. ;; The body is the region [h-end, b-end]. It may contain nested
  283. ;; js--pitem instances. The body of a pitem may be empty: in
  284. ;; that case, b-end is equal to header-end.
  285. ;;
  286. ;; The three points obey the following relationship:
  287. ;;
  288. ;; h-begin < h-end <= b-end
  289. ;;
  290. ;; We put a text property in the buffer on the character *before*
  291. ;; h-end, and if we see it, on the character *before* b-end.
  292. ;;
  293. ;; The text property for h-end, js--pstate, is actually a list
  294. ;; of all js--pitem instances open after the marked character.
  295. ;;
  296. ;; The text property for b-end, js--pend, is simply the
  297. ;; js--pitem that ends after the marked character. (Because
  298. ;; pitems always end when the paren-depth drops below a critical
  299. ;; value, and because we can only drop one level per character, only
  300. ;; one pitem may end at a given character.)
  301. ;;
  302. ;; In the structure below, we only store h-begin and (sometimes)
  303. ;; b-end. We can trivially and quickly find h-end by going to h-begin
  304. ;; and searching for an js--pstate text property. Since no other
  305. ;; js--pitem instances can be nested inside the header of a
  306. ;; pitem, the location after the character with this text property
  307. ;; must be h-end.
  308. ;;
  309. ;; js--pitem instances are never modified (with the exception
  310. ;; of the b-end field). Instead, modified copies are added at
  311. ;; subsequence parse points.
  312. ;; (The exception for b-end and its caveats is described below.)
  313. ;;
  314. (defstruct (js--pitem (:type list))
  315. ;; IMPORTANT: Do not alter the position of fields within the list.
  316. ;; Various bits of code depend on their positions, particularly
  317. ;; anything that manipulates the list of children.
  318. ;; List of children inside this pitem's body
  319. (children nil :read-only t)
  320. ;; When we reach this paren depth after h-end, the pitem ends
  321. (paren-depth nil :read-only t)
  322. ;; Symbol or class-style plist if this is a class
  323. (type nil :read-only t)
  324. ;; See above
  325. (h-begin nil :read-only t)
  326. ;; List of strings giving the parts of the name of this pitem (e.g.,
  327. ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
  328. (name nil :read-only t)
  329. ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
  330. ;; this pitem: when we copy-and-modify pitem instances, we share
  331. ;; their tail structures, so all the copies actually have the same
  332. ;; terminating cons cell. We modify that shared cons cell directly.
  333. ;;
  334. ;; The field value is either a number (buffer location) or nil if
  335. ;; unknown.
  336. ;;
  337. ;; If the field's value is greater than `js--cache-end', the
  338. ;; value is stale and must be treated as if it were nil. Conversely,
  339. ;; if this field is nil, it is guaranteed that this pitem is open up
  340. ;; to at least `js--cache-end'. (This property is handy when
  341. ;; computing whether we're inside a given pitem.)
  342. ;;
  343. (b-end nil))
  344. ;; The pitem we start parsing with.
  345. (defconst js--initial-pitem
  346. (make-js--pitem
  347. :paren-depth most-negative-fixnum
  348. :type 'toplevel))
  349. ;;; User Customization
  350. (defgroup js nil
  351. "Customization variables for JavaScript mode."
  352. :tag "JavaScript"
  353. :group 'languages)
  354. (defcustom js-indent-level 4
  355. "Number of spaces for each indentation step in `js-mode'."
  356. :type 'integer
  357. :group 'js)
  358. (defcustom js-expr-indent-offset 0
  359. "Number of additional spaces for indenting continued expressions.
  360. The value must be no less than minus `js-indent-level'."
  361. :type 'integer
  362. :group 'js)
  363. (defcustom js-paren-indent-offset 0
  364. "Number of additional spaces for indenting expressions in parentheses.
  365. The value must be no less than minus `js-indent-level'."
  366. :type 'integer
  367. :group 'js
  368. :version "24.1")
  369. (defcustom js-square-indent-offset 0
  370. "Number of additional spaces for indenting expressions in square braces.
  371. The value must be no less than minus `js-indent-level'."
  372. :type 'integer
  373. :group 'js
  374. :version "24.1")
  375. (defcustom js-curly-indent-offset 0
  376. "Number of additional spaces for indenting expressions in curly braces.
  377. The value must be no less than minus `js-indent-level'."
  378. :type 'integer
  379. :group 'js
  380. :version "24.1")
  381. (defcustom js-auto-indent-flag t
  382. "Whether to automatically indent when typing punctuation characters.
  383. If non-nil, the characters {}();,: also indent the current line
  384. in Javascript mode."
  385. :type 'boolean
  386. :group 'js)
  387. (defcustom js-flat-functions nil
  388. "Treat nested functions as top-level functions in `js-mode'.
  389. This applies to function movement, marking, and so on."
  390. :type 'boolean
  391. :group 'js)
  392. (defcustom js-comment-lineup-func #'c-lineup-C-comments
  393. "Lineup function for `cc-mode-style', for C comments in `js-mode'."
  394. :type 'function
  395. :group 'js)
  396. (defcustom js-enabled-frameworks js--available-frameworks
  397. "Frameworks recognized by `js-mode'.
  398. To improve performance, you may turn off some frameworks you
  399. seldom use, either globally or on a per-buffer basis."
  400. :type (cons 'set (mapcar (lambda (x)
  401. (list 'const x))
  402. js--available-frameworks))
  403. :group 'js)
  404. (defcustom js-js-switch-tabs
  405. (and (memq system-type '(darwin)) t)
  406. "Whether `js-mode' should display tabs while selecting them.
  407. This is useful only if the windowing system has a good mechanism
  408. for preventing Firefox from stealing the keyboard focus."
  409. :type 'boolean
  410. :group 'js)
  411. (defcustom js-js-tmpdir
  412. "~/.emacs.d/js/js"
  413. "Temporary directory used by `js-mode' to communicate with Mozilla.
  414. This directory must be readable and writable by both Mozilla and Emacs."
  415. :type 'directory
  416. :group 'js)
  417. (defcustom js-js-timeout 5
  418. "Reply timeout for executing commands in Mozilla via `js-mode'.
  419. The value is given in seconds. Increase this value if you are
  420. getting timeout messages."
  421. :type 'integer
  422. :group 'js)
  423. ;;; KeyMap
  424. (defvar js-mode-map
  425. (let ((keymap (make-sparse-keymap)))
  426. (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
  427. (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
  428. (define-key keymap [(control meta ?x)] #'js-eval-defun)
  429. (define-key keymap [(meta ?.)] #'js-find-symbol)
  430. (easy-menu-define nil keymap "Javascript Menu"
  431. '("Javascript"
  432. ["Select New Mozilla Context..." js-set-js-context
  433. (fboundp #'inferior-moz-process)]
  434. ["Evaluate Expression in Mozilla Context..." js-eval
  435. (fboundp #'inferior-moz-process)]
  436. ["Send Current Function to Mozilla..." js-eval-defun
  437. (fboundp #'inferior-moz-process)]))
  438. keymap)
  439. "Keymap for `js-mode'.")
  440. ;;; Syntax table and parsing
  441. (defvar js-mode-syntax-table
  442. (let ((table (make-syntax-table)))
  443. (c-populate-syntax-table table)
  444. (modify-syntax-entry ?$ "_" table)
  445. table)
  446. "Syntax table for `js-mode'.")
  447. (defvar js--quick-match-re nil
  448. "Autogenerated regexp used by `js-mode' to match buffer constructs.")
  449. (defvar js--quick-match-re-func nil
  450. "Autogenerated regexp used by `js-mode' to match constructs and functions.")
  451. (make-variable-buffer-local 'js--quick-match-re)
  452. (make-variable-buffer-local 'js--quick-match-re-func)
  453. (defvar js--cache-end 1
  454. "Last valid buffer position for the `js-mode' function cache.")
  455. (make-variable-buffer-local 'js--cache-end)
  456. (defvar js--last-parse-pos nil
  457. "Latest parse position reached by `js--ensure-cache'.")
  458. (make-variable-buffer-local 'js--last-parse-pos)
  459. (defvar js--state-at-last-parse-pos nil
  460. "Parse state at `js--last-parse-pos'.")
  461. (make-variable-buffer-local 'js--state-at-last-parse-pos)
  462. (defun js--flatten-list (list)
  463. (loop for item in list
  464. nconc (cond ((consp item)
  465. (js--flatten-list item))
  466. (item (list item)))))
  467. (defun js--maybe-join (prefix separator suffix &rest list)
  468. "Helper function for `js--update-quick-match-re'.
  469. If LIST contains any element that is not nil, return its non-nil
  470. elements, separated by SEPARATOR, prefixed by PREFIX, and ended
  471. with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
  472. nil. If any element in LIST is itself a list, flatten that
  473. element."
  474. (setq list (js--flatten-list list))
  475. (when list
  476. (concat prefix (mapconcat #'identity list separator) suffix)))
  477. (defun js--update-quick-match-re ()
  478. "Internal function used by `js-mode' for caching buffer constructs.
  479. This updates `js--quick-match-re', based on the current set of
  480. enabled frameworks."
  481. (setq js--quick-match-re
  482. (js--maybe-join
  483. "^[ \t]*\\(?:" "\\|" "\\)"
  484. ;; #define mumble
  485. "#define[ \t]+[a-zA-Z_]"
  486. (when (memq 'extjs js-enabled-frameworks)
  487. "Ext\\.extend")
  488. (when (memq 'prototype js-enabled-frameworks)
  489. "Object\\.extend")
  490. ;; var mumble = THING (
  491. (js--maybe-join
  492. "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
  493. "\\|"
  494. "\\)[ \t]*\("
  495. (when (memq 'prototype js-enabled-frameworks)
  496. "Class\\.create")
  497. (when (memq 'extjs js-enabled-frameworks)
  498. "Ext\\.extend")
  499. (when (memq 'merrillpress js-enabled-frameworks)
  500. "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
  501. (when (memq 'dojo js-enabled-frameworks)
  502. "dojo\\.declare[ \t]*\(")
  503. (when (memq 'mochikit js-enabled-frameworks)
  504. "MochiKit\\.Base\\.update[ \t]*\(")
  505. ;; mumble.prototypeTHING
  506. (js--maybe-join
  507. "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
  508. (when (memq 'javascript js-enabled-frameworks)
  509. '( ;; foo.prototype.bar = function(
  510. "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
  511. ;; mumble.prototype = {
  512. "[ \t]*=[ \t]*{")))))
  513. (setq js--quick-match-re-func
  514. (concat "function\\|" js--quick-match-re)))
  515. (defun js--forward-text-property (propname)
  516. "Move over the next value of PROPNAME in the buffer.
  517. If found, return that value and leave point after the character
  518. having that value; otherwise, return nil and leave point at EOB."
  519. (let ((next-value (get-text-property (point) propname)))
  520. (if next-value
  521. (forward-char)
  522. (goto-char (next-single-property-change
  523. (point) propname nil (point-max)))
  524. (unless (eobp)
  525. (setq next-value (get-text-property (point) propname))
  526. (forward-char)))
  527. next-value))
  528. (defun js--backward-text-property (propname)
  529. "Move over the previous value of PROPNAME in the buffer.
  530. If found, return that value and leave point just before the
  531. character that has that value, otherwise return nil and leave
  532. point at BOB."
  533. (unless (bobp)
  534. (let ((prev-value (get-text-property (1- (point)) propname)))
  535. (if prev-value
  536. (backward-char)
  537. (goto-char (previous-single-property-change
  538. (point) propname nil (point-min)))
  539. (unless (bobp)
  540. (backward-char)
  541. (setq prev-value (get-text-property (point) propname))))
  542. prev-value)))
  543. (defsubst js--forward-pstate ()
  544. (js--forward-text-property 'js--pstate))
  545. (defsubst js--backward-pstate ()
  546. (js--backward-text-property 'js--pstate))
  547. (defun js--pitem-goto-h-end (pitem)
  548. (goto-char (js--pitem-h-begin pitem))
  549. (js--forward-pstate))
  550. (defun js--re-search-forward-inner (regexp &optional bound count)
  551. "Helper function for `js--re-search-forward'."
  552. (let ((parse)
  553. str-terminator
  554. (orig-macro-end (save-excursion
  555. (when (js--beginning-of-macro)
  556. (c-end-of-macro)
  557. (point)))))
  558. (while (> count 0)
  559. (re-search-forward regexp bound)
  560. (setq parse (syntax-ppss))
  561. (cond ((setq str-terminator (nth 3 parse))
  562. (when (eq str-terminator t)
  563. (setq str-terminator ?/))
  564. (re-search-forward
  565. (concat "\\([^\\]\\|^\\)" (string str-terminator))
  566. (point-at-eol) t))
  567. ((nth 7 parse)
  568. (forward-line))
  569. ((or (nth 4 parse)
  570. (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
  571. (re-search-forward "\\*/"))
  572. ((and (not (and orig-macro-end
  573. (<= (point) orig-macro-end)))
  574. (js--beginning-of-macro))
  575. (c-end-of-macro))
  576. (t
  577. (setq count (1- count))))))
  578. (point))
  579. (defun js--re-search-forward (regexp &optional bound noerror count)
  580. "Search forward, ignoring strings, cpp macros, and comments.
  581. This function invokes `re-search-forward', but treats the buffer
  582. as if strings, cpp macros, and comments have been removed.
  583. If invoked while inside a macro, it treats the contents of the
  584. macro as normal text."
  585. (unless count (setq count 1))
  586. (let ((saved-point (point))
  587. (search-fun
  588. (cond ((< count 0) (setq count (- count))
  589. #'js--re-search-backward-inner)
  590. ((> count 0) #'js--re-search-forward-inner)
  591. (t #'ignore))))
  592. (condition-case err
  593. (funcall search-fun regexp bound count)
  594. (search-failed
  595. (goto-char saved-point)
  596. (unless noerror
  597. (signal (car err) (cdr err)))))))
  598. (defun js--re-search-backward-inner (regexp &optional bound count)
  599. "Auxiliary function for `js--re-search-backward'."
  600. (let ((parse)
  601. str-terminator
  602. (orig-macro-start
  603. (save-excursion
  604. (and (js--beginning-of-macro)
  605. (point)))))
  606. (while (> count 0)
  607. (re-search-backward regexp bound)
  608. (when (and (> (point) (point-min))
  609. (save-excursion (backward-char) (looking-at "/[/*]")))
  610. (forward-char))
  611. (setq parse (syntax-ppss))
  612. (cond ((setq str-terminator (nth 3 parse))
  613. (when (eq str-terminator t)
  614. (setq str-terminator ?/))
  615. (re-search-backward
  616. (concat "\\([^\\]\\|^\\)" (string str-terminator))
  617. (point-at-bol) t))
  618. ((nth 7 parse)
  619. (goto-char (nth 8 parse)))
  620. ((or (nth 4 parse)
  621. (and (eq (char-before) ?/) (eq (char-after) ?*)))
  622. (re-search-backward "/\\*"))
  623. ((and (not (and orig-macro-start
  624. (>= (point) orig-macro-start)))
  625. (js--beginning-of-macro)))
  626. (t
  627. (setq count (1- count))))))
  628. (point))
  629. (defun js--re-search-backward (regexp &optional bound noerror count)
  630. "Search backward, ignoring strings, preprocessor macros, and comments.
  631. This function invokes `re-search-backward' but treats the buffer
  632. as if strings, preprocessor macros, and comments have been
  633. removed.
  634. If invoked while inside a macro, treat the macro as normal text."
  635. (js--re-search-forward regexp bound noerror (if count (- count) -1)))
  636. (defun js--forward-expression ()
  637. "Move forward over a whole JavaScript expression.
  638. This function doesn't move over expressions continued across
  639. lines."
  640. (loop
  641. ;; non-continued case; simplistic, but good enough?
  642. do (loop until (or (eolp)
  643. (progn
  644. (forward-comment most-positive-fixnum)
  645. (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
  646. do (forward-sexp))
  647. while (and (eq (char-after) ?\n)
  648. (save-excursion
  649. (forward-char)
  650. (js--continued-expression-p)))))
  651. (defun js--forward-function-decl ()
  652. "Move forward over a JavaScript function declaration.
  653. This puts point at the 'function' keyword.
  654. If this is a syntactically-correct non-expression function,
  655. return the name of the function, or t if the name could not be
  656. determined. Otherwise, return nil."
  657. (assert (looking-at "\\_<function\\_>"))
  658. (let ((name t))
  659. (forward-word)
  660. (forward-comment most-positive-fixnum)
  661. (when (looking-at js--name-re)
  662. (setq name (match-string-no-properties 0))
  663. (goto-char (match-end 0)))
  664. (forward-comment most-positive-fixnum)
  665. (and (eq (char-after) ?\( )
  666. (ignore-errors (forward-list) t)
  667. (progn (forward-comment most-positive-fixnum)
  668. (and (eq (char-after) ?{)
  669. name)))))
  670. (defun js--function-prologue-beginning (&optional pos)
  671. "Return the start of the JavaScript function prologue containing POS.
  672. A function prologue is everything from start of the definition up
  673. to and including the opening brace. POS defaults to point.
  674. If POS is not in a function prologue, return nil."
  675. (let (prologue-begin)
  676. (save-excursion
  677. (if pos
  678. (goto-char pos)
  679. (setq pos (point)))
  680. (when (save-excursion
  681. (forward-line 0)
  682. (or (looking-at js--function-heading-2-re)
  683. (looking-at js--function-heading-3-re)))
  684. (setq prologue-begin (match-beginning 1))
  685. (when (<= prologue-begin pos)
  686. (goto-char (match-end 0))))
  687. (skip-syntax-backward "w_")
  688. (and (or (looking-at "\\_<function\\_>")
  689. (js--re-search-backward "\\_<function\\_>" nil t))
  690. (save-match-data (goto-char (match-beginning 0))
  691. (js--forward-function-decl))
  692. (<= pos (point))
  693. (or prologue-begin (match-beginning 0))))))
  694. (defun js--beginning-of-defun-raw ()
  695. "Helper function for `js-beginning-of-defun'.
  696. Go to previous defun-beginning and return the parse state for it,
  697. or nil if we went all the way back to bob and don't find
  698. anything."
  699. (js--ensure-cache)
  700. (let (pstate)
  701. (while (and (setq pstate (js--backward-pstate))
  702. (not (eq 'function (js--pitem-type (car pstate))))))
  703. (and (not (bobp)) pstate)))
  704. (defun js--pstate-is-toplevel-defun (pstate)
  705. "Helper function for `js--beginning-of-defun-nested'.
  706. If PSTATE represents a non-empty top-level defun, return the
  707. top-most pitem. Otherwise, return nil."
  708. (loop for pitem in pstate
  709. with func-depth = 0
  710. with func-pitem
  711. if (eq 'function (js--pitem-type pitem))
  712. do (incf func-depth)
  713. and do (setq func-pitem pitem)
  714. finally return (if (eq func-depth 1) func-pitem)))
  715. (defun js--beginning-of-defun-nested ()
  716. "Helper function for `js--beginning-of-defun'.
  717. Return the pitem of the function we went to the beginning of."
  718. (or
  719. ;; Look for the smallest function that encloses point...
  720. (loop for pitem in (js--parse-state-at-point)
  721. if (and (eq 'function (js--pitem-type pitem))
  722. (js--inside-pitem-p pitem))
  723. do (goto-char (js--pitem-h-begin pitem))
  724. and return pitem)
  725. ;; ...and if that isn't found, look for the previous top-level
  726. ;; defun
  727. (loop for pstate = (js--backward-pstate)
  728. while pstate
  729. if (js--pstate-is-toplevel-defun pstate)
  730. do (goto-char (js--pitem-h-begin it))
  731. and return it)))
  732. (defun js--beginning-of-defun-flat ()
  733. "Helper function for `js-beginning-of-defun'."
  734. (let ((pstate (js--beginning-of-defun-raw)))
  735. (when pstate
  736. (goto-char (js--pitem-h-begin (car pstate))))))
  737. (defun js-beginning-of-defun (&optional arg)
  738. "Value of `beginning-of-defun-function' for `js-mode'."
  739. (setq arg (or arg 1))
  740. (while (and (not (eobp)) (< arg 0))
  741. (incf arg)
  742. (when (and (not js-flat-functions)
  743. (or (eq (js-syntactic-context) 'function)
  744. (js--function-prologue-beginning)))
  745. (js-end-of-defun))
  746. (if (js--re-search-forward
  747. "\\_<function\\_>" nil t)
  748. (goto-char (js--function-prologue-beginning))
  749. (goto-char (point-max))))
  750. (while (> arg 0)
  751. (decf arg)
  752. ;; If we're just past the end of a function, the user probably wants
  753. ;; to go to the beginning of *that* function
  754. (when (eq (char-before) ?})
  755. (backward-char))
  756. (let ((prologue-begin (js--function-prologue-beginning)))
  757. (cond ((and prologue-begin (< prologue-begin (point)))
  758. (goto-char prologue-begin))
  759. (js-flat-functions
  760. (js--beginning-of-defun-flat))
  761. (t
  762. (js--beginning-of-defun-nested))))))
  763. (defun js--flush-caches (&optional beg ignored)
  764. "Flush the `js-mode' syntax cache after position BEG.
  765. BEG defaults to `point-min', meaning to flush the entire cache."
  766. (interactive)
  767. (setq beg (or beg (save-restriction (widen) (point-min))))
  768. (setq js--cache-end (min js--cache-end beg)))
  769. (defmacro js--debug (&rest _arguments)
  770. ;; `(message ,@arguments)
  771. )
  772. (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
  773. (let ((top-item (car open-items)))
  774. (when (<= paren-depth (js--pitem-paren-depth top-item))
  775. (assert (not (get-text-property (1- (point)) 'js-pend)))
  776. (put-text-property (1- (point)) (point) 'js--pend top-item)
  777. (setf (js--pitem-b-end top-item) (point))
  778. (setq open-items
  779. ;; open-items must contain at least two items for this to
  780. ;; work, but because we push a dummy item to start with,
  781. ;; that assumption holds.
  782. (cons (js--pitem-add-child (second open-items) top-item)
  783. (cddr open-items)))))
  784. open-items)
  785. (defmacro js--ensure-cache--update-parse ()
  786. "Helper function for `js--ensure-cache'.
  787. Update parsing information up to point, referring to parse,
  788. prev-parse-point, goal-point, and open-items bound lexically in
  789. the body of `js--ensure-cache'."
  790. `(progn
  791. (setq goal-point (point))
  792. (goto-char prev-parse-point)
  793. (while (progn
  794. (setq open-items (js--ensure-cache--pop-if-ended
  795. open-items (car parse)))
  796. ;; Make sure parse-partial-sexp doesn't stop because we *entered*
  797. ;; the given depth -- i.e., make sure we're deeper than the target
  798. ;; depth.
  799. (assert (> (nth 0 parse)
  800. (js--pitem-paren-depth (car open-items))))
  801. (setq parse (parse-partial-sexp
  802. prev-parse-point goal-point
  803. (js--pitem-paren-depth (car open-items))
  804. nil parse))
  805. ;; (let ((overlay (make-overlay prev-parse-point (point))))
  806. ;; (overlay-put overlay 'face '(:background "red"))
  807. ;; (unwind-protect
  808. ;; (progn
  809. ;; (js--debug "parsed: %S" parse)
  810. ;; (sit-for 1))
  811. ;; (delete-overlay overlay)))
  812. (setq prev-parse-point (point))
  813. (< (point) goal-point)))
  814. (setq open-items (js--ensure-cache--pop-if-ended
  815. open-items (car parse)))))
  816. (defun js--show-cache-at-point ()
  817. (interactive)
  818. (require 'pp)
  819. (let ((prop (get-text-property (point) 'js--pstate)))
  820. (with-output-to-temp-buffer "*Help*"
  821. (pp prop))))
  822. (defun js--split-name (string)
  823. "Split a JavaScript name into its dot-separated parts.
  824. This also removes any prototype parts from the split name
  825. \(unless the name is just \"prototype\" to start with)."
  826. (let ((name (save-match-data
  827. (split-string string "\\." t))))
  828. (unless (and (= (length name) 1)
  829. (equal (car name) "prototype"))
  830. (setq name (remove "prototype" name)))))
  831. (defvar js--guess-function-name-start nil)
  832. (defun js--guess-function-name (position)
  833. "Guess the name of the JavaScript function at POSITION.
  834. POSITION should be just after the end of the word \"function\".
  835. Return the name of the function, or nil if the name could not be
  836. guessed.
  837. This function clobbers match data. If we find the preamble
  838. begins earlier than expected while guessing the function name,
  839. set `js--guess-function-name-start' to that position; otherwise,
  840. set that variable to nil."
  841. (setq js--guess-function-name-start nil)
  842. (save-excursion
  843. (goto-char position)
  844. (forward-line 0)
  845. (cond
  846. ((looking-at js--function-heading-3-re)
  847. (and (eq (match-end 0) position)
  848. (setq js--guess-function-name-start (match-beginning 1))
  849. (match-string-no-properties 1)))
  850. ((looking-at js--function-heading-2-re)
  851. (and (eq (match-end 0) position)
  852. (setq js--guess-function-name-start (match-beginning 1))
  853. (match-string-no-properties 1))))))
  854. (defun js--clear-stale-cache ()
  855. ;; Clear any endings that occur after point
  856. (let (end-prop)
  857. (save-excursion
  858. (while (setq end-prop (js--forward-text-property
  859. 'js--pend))
  860. (setf (js--pitem-b-end end-prop) nil))))
  861. ;; Remove any cache properties after this point
  862. (remove-text-properties (point) (point-max)
  863. '(js--pstate t js--pend t)))
  864. (defun js--ensure-cache (&optional limit)
  865. "Ensures brace cache is valid up to the character before LIMIT.
  866. LIMIT defaults to point."
  867. (setq limit (or limit (point)))
  868. (when (< js--cache-end limit)
  869. (c-save-buffer-state
  870. (open-items
  871. orig-match-start
  872. orig-match-end
  873. orig-depth
  874. parse
  875. prev-parse-point
  876. name
  877. case-fold-search
  878. filtered-class-styles
  879. new-item
  880. goal-point
  881. end-prop)
  882. ;; Figure out which class styles we need to look for
  883. (setq filtered-class-styles
  884. (loop for style in js--class-styles
  885. if (memq (plist-get style :framework)
  886. js-enabled-frameworks)
  887. collect style))
  888. (save-excursion
  889. (save-restriction
  890. (widen)
  891. ;; Find last known good position
  892. (goto-char js--cache-end)
  893. (unless (bobp)
  894. (setq open-items (get-text-property
  895. (1- (point)) 'js--pstate))
  896. (unless open-items
  897. (goto-char (previous-single-property-change
  898. (point) 'js--pstate nil (point-min)))
  899. (unless (bobp)
  900. (setq open-items (get-text-property (1- (point))
  901. 'js--pstate))
  902. (assert open-items))))
  903. (unless open-items
  904. ;; Make a placeholder for the top-level definition
  905. (setq open-items (list js--initial-pitem)))
  906. (setq parse (syntax-ppss))
  907. (setq prev-parse-point (point))
  908. (js--clear-stale-cache)
  909. (narrow-to-region (point-min) limit)
  910. (loop while (re-search-forward js--quick-match-re-func nil t)
  911. for orig-match-start = (goto-char (match-beginning 0))
  912. for orig-match-end = (match-end 0)
  913. do (js--ensure-cache--update-parse)
  914. for orig-depth = (nth 0 parse)
  915. ;; Each of these conditions should return non-nil if
  916. ;; we should add a new item and leave point at the end
  917. ;; of the new item's header (h-end in the
  918. ;; js--pitem diagram). This point is the one
  919. ;; after the last character we need to unambiguously
  920. ;; detect this construct. If one of these evaluates to
  921. ;; nil, the location of the point is ignored.
  922. if (cond
  923. ;; In comment or string
  924. ((nth 8 parse) nil)
  925. ;; Regular function declaration
  926. ((and (looking-at "\\_<function\\_>")
  927. (setq name (js--forward-function-decl)))
  928. (when (eq name t)
  929. (setq name (js--guess-function-name orig-match-end))
  930. (if name
  931. (when js--guess-function-name-start
  932. (setq orig-match-start
  933. js--guess-function-name-start))
  934. (setq name t)))
  935. (assert (eq (char-after) ?{))
  936. (forward-char)
  937. (make-js--pitem
  938. :paren-depth orig-depth
  939. :h-begin orig-match-start
  940. :type 'function
  941. :name (if (eq name t)
  942. name
  943. (js--split-name name))))
  944. ;; Macro
  945. ((looking-at js--macro-decl-re)
  946. ;; Macros often contain unbalanced parentheses.
  947. ;; Make sure that h-end is at the textual end of
  948. ;; the macro no matter what the parenthesis say.
  949. (c-end-of-macro)
  950. (js--ensure-cache--update-parse)
  951. (make-js--pitem
  952. :paren-depth (nth 0 parse)
  953. :h-begin orig-match-start
  954. :type 'macro
  955. :name (list (match-string-no-properties 1))))
  956. ;; "Prototype function" declaration
  957. ((looking-at js--plain-method-re)
  958. (goto-char (match-beginning 3))
  959. (when (save-match-data
  960. (js--forward-function-decl))
  961. (forward-char)
  962. (make-js--pitem
  963. :paren-depth orig-depth
  964. :h-begin orig-match-start
  965. :type 'function
  966. :name (nconc (js--split-name
  967. (match-string-no-properties 1))
  968. (list (match-string-no-properties 2))))))
  969. ;; Class definition
  970. ((loop with syntactic-context =
  971. (js--syntactic-context-from-pstate open-items)
  972. for class-style in filtered-class-styles
  973. if (and (memq syntactic-context
  974. (plist-get class-style :contexts))
  975. (looking-at (plist-get class-style
  976. :class-decl)))
  977. do (goto-char (match-end 0))
  978. and return
  979. (make-js--pitem
  980. :paren-depth orig-depth
  981. :h-begin orig-match-start
  982. :type class-style
  983. :name (js--split-name
  984. (match-string-no-properties 1))))))
  985. do (js--ensure-cache--update-parse)
  986. and do (push it open-items)
  987. and do (put-text-property
  988. (1- (point)) (point) 'js--pstate open-items)
  989. else do (goto-char orig-match-end))
  990. (goto-char limit)
  991. (js--ensure-cache--update-parse)
  992. (setq js--cache-end limit)
  993. (setq js--last-parse-pos limit)
  994. (setq js--state-at-last-parse-pos open-items)
  995. )))))
  996. (defun js--end-of-defun-flat ()
  997. "Helper function for `js-end-of-defun'."
  998. (loop while (js--re-search-forward "}" nil t)
  999. do (js--ensure-cache)
  1000. if (get-text-property (1- (point)) 'js--pend)
  1001. if (eq 'function (js--pitem-type it))
  1002. return t
  1003. finally do (goto-char (point-max))))
  1004. (defun js--end-of-defun-nested ()
  1005. "Helper function for `js-end-of-defun'."
  1006. (message "test")
  1007. (let* (pitem
  1008. (this-end (save-excursion
  1009. (and (setq pitem (js--beginning-of-defun-nested))
  1010. (js--pitem-goto-h-end pitem)
  1011. (progn (backward-char)
  1012. (forward-list)
  1013. (point)))))
  1014. found)
  1015. (if (and this-end (< (point) this-end))
  1016. ;; We're already inside a function; just go to its end.
  1017. (goto-char this-end)
  1018. ;; Otherwise, go to the end of the next function...
  1019. (while (and (js--re-search-forward "\\_<function\\_>" nil t)
  1020. (not (setq found (progn
  1021. (goto-char (match-beginning 0))
  1022. (js--forward-function-decl))))))
  1023. (if found (forward-list)
  1024. ;; ... or eob.
  1025. (goto-char (point-max))))))
  1026. (defun js-end-of-defun (&optional arg)
  1027. "Value of `end-of-defun-function' for `js-mode'."
  1028. (setq arg (or arg 1))
  1029. (while (and (not (bobp)) (< arg 0))
  1030. (incf arg)
  1031. (js-beginning-of-defun)
  1032. (js-beginning-of-defun)
  1033. (unless (bobp)
  1034. (js-end-of-defun)))
  1035. (while (> arg 0)
  1036. (decf arg)
  1037. ;; look for function backward. if we're inside it, go to that
  1038. ;; function's end. otherwise, search for the next function's end and
  1039. ;; go there
  1040. (if js-flat-functions
  1041. (js--end-of-defun-flat)
  1042. ;; if we're doing nested functions, see whether we're in the
  1043. ;; prologue. If we are, go to the end of the function; otherwise,
  1044. ;; call js--end-of-defun-nested to do the real work
  1045. (let ((prologue-begin (js--function-prologue-beginning)))
  1046. (cond ((and prologue-begin (<= prologue-begin (point)))
  1047. (goto-char prologue-begin)
  1048. (re-search-forward "\\_<function")
  1049. (goto-char (match-beginning 0))
  1050. (js--forward-function-decl)
  1051. (forward-list))
  1052. (t (js--end-of-defun-nested)))))))
  1053. (defun js--beginning-of-macro (&optional lim)
  1054. (let ((here (point)))
  1055. (save-restriction
  1056. (if lim (narrow-to-region lim (point-max)))
  1057. (beginning-of-line)
  1058. (while (eq (char-before (1- (point))) ?\\)
  1059. (forward-line -1))
  1060. (back-to-indentation)
  1061. (if (and (<= (point) here)
  1062. (looking-at js--opt-cpp-start))
  1063. t
  1064. (goto-char here)
  1065. nil))))
  1066. (defun js--backward-syntactic-ws (&optional lim)
  1067. "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
  1068. (save-restriction
  1069. (when lim (narrow-to-region lim (point-max)))
  1070. (let ((in-macro (save-excursion (js--beginning-of-macro)))
  1071. (pos (point)))
  1072. (while (progn (unless in-macro (js--beginning-of-macro))
  1073. (forward-comment most-negative-fixnum)
  1074. (/= (point)
  1075. (prog1
  1076. pos
  1077. (setq pos (point)))))))))
  1078. (defun js--forward-syntactic-ws (&optional lim)
  1079. "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
  1080. (save-restriction
  1081. (when lim (narrow-to-region (point-min) lim))
  1082. (let ((pos (point)))
  1083. (while (progn
  1084. (forward-comment most-positive-fixnum)
  1085. (when (eq (char-after) ?#)
  1086. (c-end-of-macro))
  1087. (/= (point)
  1088. (prog1
  1089. pos
  1090. (setq pos (point)))))))))
  1091. ;; Like (up-list -1), but only considers lists that end nearby"
  1092. (defun js--up-nearby-list ()
  1093. (save-restriction
  1094. ;; Look at a very small region so our computation time doesn't
  1095. ;; explode in pathological cases.
  1096. (narrow-to-region (max (point-min) (- (point) 500)) (point))
  1097. (up-list -1)))
  1098. (defun js--inside-param-list-p ()
  1099. "Return non-nil iff point is in a function parameter list."
  1100. (ignore-errors
  1101. (save-excursion
  1102. (js--up-nearby-list)
  1103. (and (looking-at "(")
  1104. (progn (forward-symbol -1)
  1105. (or (looking-at "function")
  1106. (progn (forward-symbol -1)
  1107. (looking-at "function"))))))))
  1108. (defun js--inside-dojo-class-list-p ()
  1109. "Return non-nil iff point is in a Dojo multiple-inheritance class block."
  1110. (ignore-errors
  1111. (save-excursion
  1112. (js--up-nearby-list)
  1113. (let ((list-begin (point)))
  1114. (forward-line 0)
  1115. (and (looking-at js--dojo-class-decl-re)
  1116. (goto-char (match-end 0))
  1117. (looking-at "\"\\s-*,\\s-*\\[")
  1118. (eq (match-end 0) (1+ list-begin)))))))
  1119. (defun js--syntax-begin-function ()
  1120. (when (< js--cache-end (point))
  1121. (goto-char (max (point-min) js--cache-end)))
  1122. (let ((pitem))
  1123. (while (and (setq pitem (car (js--backward-pstate)))
  1124. (not (eq 0 (js--pitem-paren-depth pitem)))))
  1125. (when pitem
  1126. (goto-char (js--pitem-h-begin pitem )))))
  1127. ;;; Font Lock
  1128. (defun js--make-framework-matcher (framework &rest regexps)
  1129. "Helper function for building `js--font-lock-keywords'.
  1130. Create a byte-compiled function for matching a concatenation of
  1131. REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
  1132. (setq regexps (apply #'concat regexps))
  1133. (byte-compile
  1134. `(lambda (limit)
  1135. (when (memq (quote ,framework) js-enabled-frameworks)
  1136. (re-search-forward ,regexps limit t)))))
  1137. (defvar js--tmp-location nil)
  1138. (make-variable-buffer-local 'js--tmp-location)
  1139. (defun js--forward-destructuring-spec (&optional func)
  1140. "Move forward over a JavaScript destructuring spec.
  1141. If FUNC is supplied, call it with no arguments before every
  1142. variable name in the spec. Return true iff this was actually a
  1143. spec. FUNC must preserve the match data."
  1144. (case (char-after)
  1145. (?\[
  1146. (forward-char)
  1147. (while
  1148. (progn
  1149. (forward-comment most-positive-fixnum)
  1150. (cond ((memq (char-after) '(?\[ ?\{))
  1151. (js--forward-destructuring-spec func))
  1152. ((eq (char-after) ?,)
  1153. (forward-char)
  1154. t)
  1155. ((looking-at js--name-re)
  1156. (and func (funcall func))
  1157. (goto-char (match-end 0))
  1158. t))))
  1159. (when (eq (char-after) ?\])
  1160. (forward-char)
  1161. t))
  1162. (?\{
  1163. (forward-char)
  1164. (forward-comment most-positive-fixnum)
  1165. (while
  1166. (when (looking-at js--objfield-re)
  1167. (goto-char (match-end 0))
  1168. (forward-comment most-positive-fixnum)
  1169. (and (cond ((memq (char-after) '(?\[ ?\{))
  1170. (js--forward-destructuring-spec func))
  1171. ((looking-at js--name-re)
  1172. (and func (funcall func))
  1173. (goto-char (match-end 0))
  1174. t))
  1175. (progn (forward-comment most-positive-fixnum)
  1176. (when (eq (char-after) ?\,)
  1177. (forward-char)
  1178. (forward-comment most-positive-fixnum)
  1179. t)))))
  1180. (when (eq (char-after) ?\})
  1181. (forward-char)
  1182. t))))
  1183. (defun js--variable-decl-matcher (limit)
  1184. "Font-lock matcher for variable names in a variable declaration.
  1185. This is a cc-mode-style matcher that *always* fails, from the
  1186. point of view of font-lock. It applies highlighting directly with
  1187. `font-lock-apply-highlight'."
  1188. (condition-case nil
  1189. (save-restriction
  1190. (narrow-to-region (point-min) limit)
  1191. (let ((first t))
  1192. (forward-comment most-positive-fixnum)
  1193. (while
  1194. (and (or first
  1195. (when (eq (char-after) ?,)
  1196. (forward-char)
  1197. (forward-comment most-positive-fixnum)
  1198. t))
  1199. (cond ((looking-at js--name-re)
  1200. (font-lock-apply-highlight
  1201. '(0 font-lock-variable-name-face))
  1202. (goto-char (match-end 0)))
  1203. ((save-excursion
  1204. (js--forward-destructuring-spec))
  1205. (js--forward-destructuring-spec
  1206. (lambda ()
  1207. (font-lock-apply-highlight
  1208. '(0 font-lock-variable-name-face)))))))
  1209. (forward-comment most-positive-fixnum)
  1210. (when (eq (char-after) ?=)
  1211. (forward-char)
  1212. (js--forward-expression)
  1213. (forward-comment most-positive-fixnum))
  1214. (setq first nil))))
  1215. ;; Conditions to handle
  1216. (scan-error nil)
  1217. (end-of-buffer nil))
  1218. ;; Matcher always "fails"
  1219. nil)
  1220. (defconst js--font-lock-keywords-3
  1221. `(
  1222. ;; This goes before keywords-2 so it gets used preferentially
  1223. ;; instead of the keywords in keywords-2. Don't use override
  1224. ;; because that will override syntactic fontification too, which
  1225. ;; will fontify commented-out directives as if they weren't
  1226. ;; commented out.
  1227. ,@cpp-font-lock-keywords ; from font-lock.el
  1228. ,@js--font-lock-keywords-2
  1229. ("\\.\\(prototype\\)\\_>"
  1230. (1 font-lock-constant-face))
  1231. ;; Highlights class being declared, in parts
  1232. (js--class-decl-matcher
  1233. ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
  1234. (goto-char (match-beginning 1))
  1235. nil
  1236. (1 font-lock-type-face))
  1237. ;; Highlights parent class, in parts, if available
  1238. (js--class-decl-matcher
  1239. ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
  1240. (if (match-beginning 2)
  1241. (progn
  1242. (setq js--tmp-location (match-end 2))
  1243. (goto-char js--tmp-location)
  1244. (insert "=")
  1245. (goto-char (match-beginning 2)))
  1246. (setq js--tmp-location nil)
  1247. (goto-char (point-at-eol)))
  1248. (when js--tmp-location
  1249. (save-excursion
  1250. (goto-char js--tmp-location)
  1251. (delete-char 1)))
  1252. (1 font-lock-type-face))
  1253. ;; Highlights parent class
  1254. (js--class-decl-matcher
  1255. (2 font-lock-type-face nil t))
  1256. ;; Dojo needs its own matcher to override the string highlighting
  1257. (,(js--make-framework-matcher
  1258. 'dojo
  1259. "^\\s-*dojo\\.declare\\s-*(\""
  1260. "\\(" js--dotted-name-re "\\)"
  1261. "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
  1262. (1 font-lock-type-face t)
  1263. (2 font-lock-type-face nil t))
  1264. ;; Match Dojo base classes. Of course Mojo has to be different
  1265. ;; from everything else under the sun...
  1266. (,(js--make-framework-matcher
  1267. 'dojo
  1268. "^\\s-*dojo\\.declare\\s-*(\""
  1269. "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
  1270. ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
  1271. "\\(?:\\].*$\\)?")
  1272. (backward-char)
  1273. (end-of-line)
  1274. (1 font-lock-type-face))
  1275. ;; continued Dojo base-class list
  1276. (,(js--make-framework-matcher
  1277. 'dojo
  1278. "^\\s-*" js--dotted-name-re "\\s-*[],]")
  1279. ,(concat "\\(" js--dotted-name-re "\\)"
  1280. "\\s-*\\(?:\\].*$\\)?")
  1281. (if (save-excursion (backward-char)
  1282. (js--inside-dojo-class-list-p))
  1283. (forward-symbol -1)
  1284. (end-of-line))
  1285. (end-of-line)
  1286. (1 font-lock-type-face))
  1287. ;; variable declarations
  1288. ,(list
  1289. (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
  1290. (list #'js--variable-decl-matcher nil nil nil))
  1291. ;; class instantiation
  1292. ,(list
  1293. (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
  1294. (list 1 'font-lock-type-face))
  1295. ;; instanceof
  1296. ,(list
  1297. (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
  1298. (list 1 'font-lock-type-face))
  1299. ;; formal parameters
  1300. ,(list
  1301. (concat
  1302. "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
  1303. js--name-start-re)
  1304. (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
  1305. '(backward-char)
  1306. '(end-of-line)
  1307. '(1 font-lock-variable-name-face)))
  1308. ;; continued formal parameter list
  1309. ,(list
  1310. (concat
  1311. "^\\s-*" js--name-re "\\s-*[,)]")
  1312. (list js--name-re
  1313. '(if (save-excursion (backward-char)
  1314. (js--inside-param-list-p))
  1315. (forward-symbol -1)
  1316. (end-of-line))
  1317. '(end-of-line)
  1318. '(0 font-lock-variable-name-face))))
  1319. "Level three font lock for `js-mode'.")
  1320. (defun js--inside-pitem-p (pitem)
  1321. "Return whether point is inside the given pitem's header or body."
  1322. (js--ensure-cache)
  1323. (assert (js--pitem-h-begin pitem))
  1324. (assert (js--pitem-paren-depth pitem))
  1325. (and (> (point) (js--pitem-h-begin pitem))
  1326. (or (null (js--pitem-b-end pitem))
  1327. (> (js--pitem-b-end pitem) (point)))))
  1328. (defun js--parse-state-at-point ()
  1329. "Parse the JavaScript program state at point.
  1330. Return a list of `js--pitem' instances that apply to point, most
  1331. specific first. In the worst case, the current toplevel instance
  1332. will be returned."
  1333. (save-excursion
  1334. (save-restriction
  1335. (widen)
  1336. (js--ensure-cache)
  1337. (let ((pstate (or (save-excursion
  1338. (js--backward-pstate))
  1339. (list js--initial-pitem))))
  1340. ;; Loop until we either hit a pitem at BOB or pitem ends after
  1341. ;; point (or at point if we're at eob)
  1342. (loop for pitem = (car pstate)
  1343. until (or (eq (js--pitem-type pitem)
  1344. 'toplevel)
  1345. (js--inside-pitem-p pitem))
  1346. do (pop pstate))
  1347. pstate))))
  1348. (defun js--syntactic-context-from-pstate (pstate)
  1349. "Return the JavaScript syntactic context corresponding to PSTATE."
  1350. (let ((type (js--pitem-type (car pstate))))
  1351. (cond ((memq type '(function macro))
  1352. type)
  1353. ((consp type)
  1354. 'class)
  1355. (t 'toplevel))))
  1356. (defun js-syntactic-context ()
  1357. "Return the JavaScript syntactic context at point.
  1358. When called interactively, also display a message with that
  1359. context."
  1360. (interactive)
  1361. (let* ((syntactic-context (js--syntactic-context-from-pstate
  1362. (js--parse-state-at-point))))
  1363. (when (called-interactively-p 'interactive)
  1364. (message "Syntactic context: %s" syntactic-context))
  1365. syntactic-context))
  1366. (defun js--class-decl-matcher (limit)
  1367. "Font lock function used by `js-mode'.
  1368. This performs fontification according to `js--class-styles'."
  1369. (loop initially (js--ensure-cache limit)
  1370. while (re-search-forward js--quick-match-re limit t)
  1371. for orig-end = (match-end 0)
  1372. do (goto-char (match-beginning 0))
  1373. if (loop for style in js--class-styles
  1374. for decl-re = (plist-get style :class-decl)
  1375. if (and (memq (plist-get style :framework)
  1376. js-enabled-frameworks)
  1377. (memq (js-syntactic-context)
  1378. (plist-get style :contexts))
  1379. decl-re
  1380. (looking-at decl-re))
  1381. do (goto-char (match-end 0))
  1382. and return t)
  1383. return t
  1384. else do (goto-char orig-end)))
  1385. (defconst js--font-lock-keywords
  1386. '(js--font-lock-keywords-3 js--font-lock-keywords-1
  1387. js--font-lock-keywords-2
  1388. js--font-lock-keywords-3)
  1389. "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
  1390. (defun js-syntax-propertize-regexp (end)
  1391. (when (eq (nth 3 (syntax-ppss)) ?/)
  1392. ;; A /.../ regexp.
  1393. (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/" end 'move)
  1394. (put-text-property (1- (point)) (point)
  1395. 'syntax-table (string-to-syntax "\"/")))))
  1396. (defun js-syntax-propertize (start end)
  1397. ;; Javascript allows immediate regular expression objects, written /.../.
  1398. (goto-char start)
  1399. (js-syntax-propertize-regexp end)
  1400. (funcall
  1401. (syntax-propertize-rules
  1402. ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
  1403. ("\\(?:^\\|[=([{,:;]\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
  1404. (1 (ignore
  1405. (forward-char -1)
  1406. (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?\t)))
  1407. ;; If the / is at the beginning of line, we have to check
  1408. ;; the end of the previous text.
  1409. (save-excursion
  1410. (goto-char (match-beginning 0))
  1411. (forward-comment (- (point)))
  1412. (memq (char-before)
  1413. (eval-when-compile (append "=({[,:;" '(nil))))))
  1414. (put-text-property (match-beginning 1) (match-end 1)
  1415. 'syntax-table (string-to-syntax "\"/"))
  1416. (js-syntax-propertize-regexp end))))))
  1417. (point) end))
  1418. ;;; Indentation
  1419. (defconst js--possibly-braceless-keyword-re
  1420. (js--regexp-opt-symbol
  1421. '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
  1422. "each"))
  1423. "Regexp matching keywords optionally followed by an opening brace.")
  1424. (defconst js--indent-operator-re
  1425. (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
  1426. (js--regexp-opt-symbol '("in" "instanceof")))
  1427. "Regexp matching operators that affect indentation of continued expressions.")
  1428. (defun js--looking-at-operator-p ()
  1429. "Return non-nil if point is on a JavaScript operator, other than a comma."
  1430. (save-match-data
  1431. (and (looking-at js--indent-operator-re)
  1432. (or (not (looking-at ":"))
  1433. (save-excursion
  1434. (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
  1435. (looking-at "?")))))))
  1436. (defun js--continued-expression-p ()
  1437. "Return non-nil if the current line continues an expression."
  1438. (save-excursion
  1439. (back-to-indentation)
  1440. (or (js--looking-at-operator-p)
  1441. (and (js--re-search-backward "\n" nil t)
  1442. (progn
  1443. (skip-chars-backward " \t")
  1444. (or (bobp) (backward-char))
  1445. (and (> (point) (point-min))
  1446. (save-excursion (backward-char) (not (looking-at "[/*]/")))
  1447. (js--looking-at-operator-p)
  1448. (and (progn (backward-char)
  1449. (not (looking-at "++\\|--\\|/[/*]"))))))))))
  1450. (defun js--end-of-do-while-loop-p ()
  1451. "Return non-nil if point is on the \"while\" of a do-while statement.
  1452. Otherwise, return nil. A braceless do-while statement spanning
  1453. several lines requires that the start of the loop is indented to
  1454. the same column as the current line."
  1455. (interactive)
  1456. (save-excursion
  1457. (save-match-data
  1458. (when (looking-at "\\s-*\\_<while\\_>")
  1459. (if (save-excursion
  1460. (skip-chars-backward "[ \t\n]*}")
  1461. (looking-at "[ \t\n]*}"))
  1462. (save-excursion
  1463. (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
  1464. (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
  1465. (or (looking-at "\\_<do\\_>")
  1466. (let ((saved-indent (current-indentation)))
  1467. (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
  1468. (/= (current-indentation) saved-indent)))
  1469. (and (looking-at "\\s-*\\_<do\\_>")
  1470. (not (js--re-search-forward
  1471. "\\_<while\\_>" (point-at-eol) t))
  1472. (= (current-indentation) saved-indent)))))))))
  1473. (defun js--ctrl-statement-indentation ()
  1474. "Helper function for `js--proper-indentation'.
  1475. Return the proper indentation of the current line if it starts
  1476. the body of a control statement without braces; otherwise, return
  1477. nil."
  1478. (save-excursion
  1479. (back-to-indentation)
  1480. (when (save-excursion
  1481. (and (not (eq (point-at-bol) (point-min)))
  1482. (not (looking-at "[{]"))
  1483. (progn
  1484. (js--re-search-backward "[[:graph:]]" nil t)
  1485. (or (eobp) (forward-char))
  1486. (when (= (char-before) ?\)) (backward-list))
  1487. (skip-syntax-backward " ")
  1488. (skip-syntax-backward "w_")
  1489. (looking-at js--possibly-braceless-keyword-re))
  1490. (not (js--end-of-do-while-loop-p))))
  1491. (save-excursion
  1492. (goto-char (match-beginning 0))
  1493. (+ (current-indentation) js-indent-level)))))
  1494. (defun js--get-c-offset (symbol anchor)
  1495. (let ((c-offsets-alist
  1496. (list (cons 'c js-comment-lineup-func))))
  1497. (c-get-syntactic-indentation (list (cons symbol anchor)))))
  1498. (defun js--proper-indentation (parse-status)
  1499. "Return the proper indentation for the current line."
  1500. (save-excursion
  1501. (back-to-indentation)
  1502. (cond ((nth 4 parse-status)
  1503. (js--get-c-offset 'c (nth 8 parse-status)))
  1504. ((nth 8 parse-status) 0) ; inside string
  1505. ((js--ctrl-statement-indentation))
  1506. ((eq (char-after) ?#) 0)
  1507. ((save-excursion (js--beginning-of-macro)) 4)
  1508. ((nth 1 parse-status)
  1509. ;; A single closing paren/bracket should be indented at the
  1510. ;; same level as the opening statement. Same goes for
  1511. ;; "case" and "default".
  1512. (let ((same-indent-p (looking-at
  1513. "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
  1514. (continued-expr-p (js--continued-expression-p)))
  1515. (goto-char (nth 1 parse-status)) ; go to the opening char
  1516. (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
  1517. (progn ; nothing following the opening paren/bracket
  1518. (skip-syntax-backward " ")
  1519. (when (eq (char-before) ?\)) (backward-list))
  1520. (back-to-indentation)
  1521. (cond (same-indent-p
  1522. (current-column))
  1523. (continued-expr-p
  1524. (+ (current-column) (* 2 js-indent-level)
  1525. js-expr-indent-offset))
  1526. (t
  1527. (+ (current-column) js-indent-level
  1528. (case (char-after (nth 1 parse-status))
  1529. (?\( js-paren-indent-offset)
  1530. (?\[ js-square-indent-offset)
  1531. (?\{ js-curly-indent-offset))))))
  1532. ;; If there is something following the opening
  1533. ;; paren/bracket, everything else should be indented at
  1534. ;; the same level.
  1535. (unless same-indent-p
  1536. (forward-char)
  1537. (skip-chars-forward " \t"))
  1538. (current-column))))
  1539. ((js--continued-expression-p)
  1540. (+ js-indent-level js-expr-indent-offset))
  1541. (t 0))))
  1542. (defun js-indent-line ()
  1543. "Indent the current line as JavaScript."
  1544. (interactive)
  1545. (save-restriction
  1546. (widen)
  1547. (let* ((parse-status
  1548. (save-excursion (syntax-ppss (point-at-bol))))
  1549. (offset (- (current-column) (current-indentation))))
  1550. (indent-line-to (js--proper-indentation parse-status))
  1551. (when (> offset 0) (forward-char offset)))))
  1552. ;;; Filling
  1553. (defun js-c-fill-paragraph (&optional justify)
  1554. "Fill the paragraph with `c-fill-paragraph'."
  1555. (interactive "*P")
  1556. (flet ((c-forward-sws
  1557. (&optional limit)
  1558. (js--forward-syntactic-ws limit))
  1559. (c-backward-sws
  1560. (&optional limit)
  1561. (js--backward-syntactic-ws limit))
  1562. (c-beginning-of-macro
  1563. (&optional limit)
  1564. (js--beginning-of-macro limit)))
  1565. (let ((fill-paragraph-function 'c-fill-paragraph))
  1566. (c-fill-paragraph justify))))
  1567. ;;; Type database and Imenu
  1568. ;; We maintain a cache of semantic information, i.e., the classes and
  1569. ;; functions we've encountered so far. In order to avoid having to
  1570. ;; re-parse the buffer on every change, we cache the parse state at
  1571. ;; each interesting point in the buffer. Each parse state is a
  1572. ;; modified copy of the previous one, or in the case of the first
  1573. ;; parse state, the empty state.
  1574. ;;
  1575. ;; The parse state itself is just a stack of js--pitem
  1576. ;; instances. It starts off containing one element that is never
  1577. ;; closed, that is initially js--initial-pitem.
  1578. ;;
  1579. (defun js--pitem-format (pitem)
  1580. (let ((name (js--pitem-name pitem))
  1581. (type (js--pitem-type pitem)))
  1582. (format "name:%S type:%S"
  1583. name
  1584. (if (atom type)
  1585. type
  1586. (plist-get type :name)))))
  1587. (defun js--make-merged-item (item child name-parts)
  1588. "Helper function for `js--splice-into-items'.
  1589. Return a new item that is the result of merging CHILD into
  1590. ITEM. NAME-PARTS is a list of parts of the name of CHILD
  1591. that we haven't consumed yet."
  1592. (js--debug "js--make-merged-item: {%s} into {%s}"
  1593. (js--pitem-format child)
  1594. (js--pitem-format item))
  1595. ;; If the item we're merging into isn't a class, make it into one
  1596. (unless (consp (js--pitem-type item))
  1597. (js--debug "js--make-merged-item: changing dest into class")
  1598. (setq item (make-js--pitem
  1599. :children (list item)
  1600. ;; Use the child's class-style if it's available
  1601. :type (if (atom (js--pitem-type child))
  1602. js--dummy-class-style
  1603. (js--pitem-type child))
  1604. :name (js--pitem-strname item))))
  1605. ;; Now we can merge either a function or a class into a class
  1606. (cons (cond
  1607. ((cdr name-parts)
  1608. (js--debug "js--make-merged-item: recursing")
  1609. ;; if we have more name-parts to go before we get to the
  1610. ;; bottom of the class hierarchy, call the merger
  1611. ;; recursively
  1612. (js--splice-into-items (car item) child
  1613. (cdr name-parts)))
  1614. ((atom (js--pitem-type child))
  1615. (js--debug "js--make-merged-item: straight merge")
  1616. ;; Not merging a class, but something else, so just prepend
  1617. ;; it
  1618. (cons child (car item)))
  1619. (t
  1620. ;; Otherwise, merge the new child's items into those
  1621. ;; of the new class
  1622. (js--debug "js--make-merged-item: merging class contents")
  1623. (append (car child) (car item))))
  1624. (cdr item)))
  1625. (defun js--pitem-strname (pitem)
  1626. "Last part of the name of PITEM, as a string or symbol."
  1627. (let ((name (js--pitem-name pitem)))
  1628. (if (consp name)
  1629. (car (last name))
  1630. name)))
  1631. (defun js--splice-into-items (items child name-parts)
  1632. "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
  1633. If a class doesn't exist in the tree, create it. Return
  1634. the new items list. NAME-PARTS is a list of strings given
  1635. the broken-down class name of the item to insert."
  1636. (let ((top-name (car name-parts))
  1637. (item-ptr items)
  1638. new-items last-new-item new-cons)
  1639. (js--debug "js--splice-into-items: name-parts: %S items:%S"
  1640. name-parts
  1641. (mapcar #'js--pitem-name items))
  1642. (assert (stringp top-name))
  1643. (assert (> (length top-name) 0))
  1644. ;; If top-name isn't found in items, then we build a copy of items
  1645. ;; and throw it away. But that's okay, since most of the time, we
  1646. ;; *will* find an instance.
  1647. (while (and item-ptr
  1648. (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
  1649. ;; Okay, we found an entry with the right name. Splice
  1650. ;; the merged item into the list...
  1651. (setq new-cons (cons (js--make-merged-item
  1652. (car item-ptr) child
  1653. name-parts)
  1654. (cdr item-ptr)))
  1655. (if last-new-item
  1656. (setcdr last-new-item new-cons)
  1657. (setq new-items new-cons))
  1658. ;; ...and terminate the loop
  1659. nil)
  1660. (t
  1661. ;; Otherwise, copy the current cons and move onto the
  1662. ;; text. This is tricky; we keep track of the tail of
  1663. ;; the list that begins with new-items in
  1664. ;; last-new-item.
  1665. (setq new-cons (cons (car item-ptr) nil))
  1666. (if last-new-item
  1667. (setcdr last-new-item new-cons)
  1668. (setq new-items new-cons))
  1669. (setq last-new-item new-cons)
  1670. ;; Go to the next cell in items
  1671. (setq item-ptr (cdr item-ptr))))))
  1672. (if item-ptr
  1673. ;; Yay! We stopped because we found something, not because
  1674. ;; we ran out of items to search. Just return the new
  1675. ;; list.
  1676. (progn
  1677. (js--debug "search succeeded: %S" name-parts)
  1678. new-items)
  1679. ;; We didn't find anything. If the child is a class and we don't
  1680. ;; have any classes to drill down into, just push that class;
  1681. ;; otherwise, make a fake class and carry on.
  1682. (js--debug "search failed: %S" name-parts)
  1683. (cons (if (cdr name-parts)
  1684. ;; We have name-parts left to process. Make a fake
  1685. ;; class for this particular part...
  1686. (make-js--pitem
  1687. ;; ...and recursively digest the rest of the name
  1688. :children (js--splice-into-items
  1689. nil child (cdr name-parts))
  1690. :type js--dummy-class-style
  1691. :name top-name)
  1692. ;; Otherwise, this is the only name we have, so stick
  1693. ;; the item on the front of the list
  1694. child)
  1695. items))))
  1696. (defun js--pitem-add-child (pitem child)
  1697. "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
  1698. (assert (integerp (js--pitem-h-begin child)))
  1699. (assert (if (consp (js--pitem-name child))
  1700. (loop for part in (js--pitem-name child)
  1701. always (stringp part))
  1702. t))
  1703. ;; This trick works because we know (based on our defstructs) that
  1704. ;; the child list is always the first element, and so the second
  1705. ;; element and beyond can be shared when we make our "copy".
  1706. (cons
  1707. (let ((name (js--pitem-name child))
  1708. (type (js--pitem-type child)))
  1709. (cond ((cdr-safe name) ; true if a list of at least two elements
  1710. ;; Use slow path because we need class lookup
  1711. (js--splice-into-items (car pitem) child name))
  1712. ((and (consp type)
  1713. (plist-get type :prototype))
  1714. ;; Use slow path because we need class merging. We know
  1715. ;; name is a list here because down in
  1716. ;; `js--ensure-cache', we made sure to only add
  1717. ;; class entries with lists for :name
  1718. (assert (consp name))
  1719. (js--splice-into-items (car pitem) child name))
  1720. (t
  1721. ;; Fast path
  1722. (cons child (car pitem)))))
  1723. (cdr pitem)))
  1724. (defun js--maybe-make-marker (location)
  1725. "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
  1726. (if imenu-use-markers
  1727. (set-marker (make-marker) location)
  1728. location))
  1729. (defun js--pitems-to-imenu (pitems unknown-ctr)
  1730. "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
  1731. (let (imenu-items pitem pitem-type pitem-name subitems)
  1732. (while (setq pitem (pop pitems))
  1733. (setq pitem-type (js--pitem-type pitem))
  1734. (setq pitem-name (js--pitem-strname pitem))
  1735. (when (eq pitem-name t)
  1736. (setq pitem-name (format "[unknown %s]"
  1737. (incf (car unknown-ctr)))))
  1738. (cond
  1739. ((memq pitem-type '(function macro))
  1740. (assert (integerp (js--pitem-h-begin pitem)))
  1741. (push (cons pitem-name
  1742. (js--maybe-make-marker
  1743. (js--pitem-h-begin pitem)))
  1744. imenu-items))
  1745. ((consp pitem-type) ; class definition
  1746. (setq subitems (js--pitems-to-imenu
  1747. (js--pitem-children pitem)
  1748. unknown-ctr))
  1749. (cond (subitems
  1750. (push (cons pitem-name subitems)
  1751. imenu-items))
  1752. ((js--pitem-h-begin pitem)
  1753. (assert (integerp (js--pitem-h-begin pitem)))
  1754. (setq subitems (list
  1755. (cons "[empty]"
  1756. (js--maybe-make-marker
  1757. (js--pitem-h-begin pitem)))))
  1758. (push (cons pitem-name subitems)
  1759. imenu-items))))
  1760. (t (error "Unknown item type: %S" pitem-type))))
  1761. imenu-items))
  1762. (defun js--imenu-create-index ()
  1763. "Return an imenu index for the current buffer."
  1764. (save-excursion
  1765. (save-restriction
  1766. (widen)
  1767. (goto-char (point-max))
  1768. (js--ensure-cache)
  1769. (assert (or (= (point-min) (point-max))
  1770. (eq js--last-parse-pos (point))))
  1771. (when js--last-parse-pos
  1772. (let ((state js--state-at-last-parse-pos)
  1773. (unknown-ctr (cons -1 nil)))
  1774. ;; Make sure everything is closed
  1775. (while (cdr state)
  1776. (setq state
  1777. (cons (js--pitem-add-child (second state) (car state))
  1778. (cddr state))))
  1779. (assert (= (length state) 1))
  1780. ;; Convert the new-finalized state into what imenu expects
  1781. (js--pitems-to-imenu
  1782. (car (js--pitem-children state))
  1783. unknown-ctr))))))
  1784. ;; Silence the compiler.
  1785. (defvar which-func-imenu-joiner-function)
  1786. (defun js--which-func-joiner (parts)
  1787. (mapconcat #'identity parts "."))
  1788. (defun js--imenu-to-flat (items prefix symbols)
  1789. (loop for item in items
  1790. if (imenu--subalist-p item)
  1791. do (js--imenu-to-flat
  1792. (cdr item) (concat prefix (car item) ".")
  1793. symbols)
  1794. else
  1795. do (let* ((name (concat prefix (car item)))
  1796. (name2 name)
  1797. (ctr 0))
  1798. (while (gethash name2 symbols)
  1799. (setq name2 (format "%s<%d>" name (incf ctr))))
  1800. (puthash name2 (cdr item) symbols))))
  1801. (defun js--get-all-known-symbols ()
  1802. "Return a hash table of all JavaScript symbols.
  1803. This searches all existing `js-mode' buffers. Each key is the
  1804. name of a symbol (possibly disambiguated with <N>, where N > 1),
  1805. and each value is a marker giving the location of that symbol."
  1806. (loop with symbols = (make-hash-table :test 'equal)
  1807. with imenu-use-markers = t
  1808. for buffer being the buffers
  1809. for imenu-index = (with-current-buffer buffer
  1810. (when (derived-mode-p 'js-mode)
  1811. (js--imenu-create-index)))
  1812. do (js--imenu-to-flat imenu-index "" symbols)
  1813. finally return symbols))
  1814. (defvar js--symbol-history nil
  1815. "History of entered JavaScript symbols.")
  1816. (defun js--read-symbol (symbols-table prompt &optional initial-input)
  1817. "Helper function for `js-find-symbol'.
  1818. Read a symbol from SYMBOLS-TABLE, which is a hash table like the
  1819. one from `js--get-all-known-symbols', using prompt PROMPT and
  1820. initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
  1821. . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
  1822. marker."
  1823. (unless ido-mode
  1824. (ido-mode 1)
  1825. (ido-mode -1))
  1826. (let ((choice (ido-completing-read
  1827. prompt
  1828. (loop for key being the hash-keys of symbols-table
  1829. collect key)
  1830. nil t initial-input 'js--symbol-history)))
  1831. (cons choice (gethash choice symbols-table))))
  1832. (defun js--guess-symbol-at-point ()
  1833. (let ((bounds (bounds-of-thing-at-point 'symbol)))
  1834. (when bounds
  1835. (save-excursion
  1836. (goto-char (car bounds))
  1837. (when (eq (char-before) ?.)
  1838. (backward-char)
  1839. (setf (car bounds) (point))))
  1840. (buffer-substring (car bounds) (cdr bounds)))))
  1841. (defvar find-tag-marker-ring) ; etags
  1842. (defun js-find-symbol (&optional arg)
  1843. "Read a JavaScript symbol and jump to it.
  1844. With a prefix argument, restrict symbols to those from the
  1845. current buffer. Pushes a mark onto the tag ring just like
  1846. `find-tag'."
  1847. (interactive "P")
  1848. (require 'etags)
  1849. (let (symbols marker)
  1850. (if (not arg)
  1851. (setq symbols (js--get-all-known-symbols))
  1852. (setq symbols (make-hash-table :test 'equal))
  1853. (js--imenu-to-flat (js--imenu-create-index)
  1854. "" symbols))
  1855. (setq marker (cdr (js--read-symbol
  1856. symbols "Jump to: "
  1857. (js--guess-symbol-at-point))))
  1858. (ring-insert find-tag-marker-ring (point-marker))
  1859. (switch-to-buffer (marker-buffer marker))
  1860. (push-mark)
  1861. (goto-char marker)))
  1862. ;;; MozRepl integration
  1863. (put 'js-moz-bad-rpc 'error-conditions '(error timeout))
  1864. (put 'js-moz-bad-rpc 'error-message "Mozilla RPC Error")
  1865. (put 'js-js-error 'error-conditions '(error js-error))
  1866. (put 'js-js-error 'error-message "Javascript Error")
  1867. (defun js--wait-for-matching-output
  1868. (process regexp timeout &optional start)
  1869. "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
  1870. On timeout, return nil. On success, return t with match data
  1871. set. If START is non-nil, look for output starting from START.
  1872. Otherwise, use the current value of `process-mark'."
  1873. (with-current-buffer (process-buffer process)
  1874. (loop with start-pos = (or start
  1875. (marker-position (process-mark process)))
  1876. with end-time = (+ (float-time) timeout)
  1877. for time-left = (- end-time (float-time))
  1878. do (goto-char (point-max))
  1879. if (looking-back regexp start-pos) return t
  1880. while (> time-left 0)
  1881. do (accept-process-output process time-left nil t)
  1882. do (goto-char (process-mark process))
  1883. finally do (signal
  1884. 'js-moz-bad-rpc
  1885. (list (format "Timed out waiting for output matching %S" regexp))))))
  1886. (defstruct js--js-handle
  1887. ;; Integer, mirrors the value we see in JS
  1888. (id nil :read-only t)
  1889. ;; Process to which this thing belongs
  1890. (process nil :read-only t))
  1891. (defun js--js-handle-expired-p (x)
  1892. (not (eq (js--js-handle-process x)
  1893. (inferior-moz-process))))
  1894. (defvar js--js-references nil
  1895. "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
  1896. (defvar js--js-process nil
  1897. "The most recent MozRepl process object.")
  1898. (defvar js--js-gc-idle-timer nil
  1899. "Idle timer for cleaning up JS object references.")
  1900. (defvar js--js-last-gcs-done nil)
  1901. (defconst js--moz-interactor
  1902. (replace-regexp-in-string
  1903. "[ \n]+" " "
  1904. ; */" Make Emacs happy
  1905. "(function(repl) {
  1906. repl.defineInteractor('js', {
  1907. onStart: function onStart(repl) {
  1908. if(!repl._jsObjects) {
  1909. repl._jsObjects = {};
  1910. repl._jsLastID = 0;
  1911. repl._jsGC = this._jsGC;
  1912. }
  1913. this._input = '';
  1914. },
  1915. _jsGC: function _jsGC(ids_in_use) {
  1916. var objects = this._jsObjects;
  1917. var keys = [];
  1918. var num_freed = 0;
  1919. for(var pn in objects) {
  1920. keys.push(Number(pn));
  1921. }
  1922. keys.sort(function(x, y) x - y);
  1923. ids_in_use.sort(function(x, y) x - y);
  1924. var i = 0;
  1925. var j = 0;
  1926. while(i < ids_in_use.length && j < keys.length) {
  1927. var id = ids_in_use[i++];
  1928. while(j < keys.length && keys[j] !== id) {
  1929. var k_id = keys[j++];
  1930. delete objects[k_id];
  1931. ++num_freed;
  1932. }
  1933. ++j;
  1934. }
  1935. while(j < keys.length) {
  1936. var k_id = keys[j++];
  1937. delete objects[k_id];
  1938. ++num_freed;
  1939. }
  1940. return num_freed;
  1941. },
  1942. _mkArray: function _mkArray() {
  1943. var result = [];
  1944. for(var i = 0; i < arguments.length; ++i) {
  1945. result.push(arguments[i]);
  1946. }
  1947. return result;
  1948. },
  1949. _parsePropDescriptor: function _parsePropDescriptor(parts) {
  1950. if(typeof parts === 'string') {
  1951. parts = [ parts ];
  1952. }
  1953. var obj = parts[0];
  1954. var start = 1;
  1955. if(typeof obj === 'string') {
  1956. obj = window;
  1957. start = 0;
  1958. } else if(parts.length < 2) {
  1959. throw new Error('expected at least 2 arguments');
  1960. }
  1961. for(var i = start; i < parts.length - 1; ++i) {
  1962. obj = obj[parts[i]];
  1963. }
  1964. return [obj, parts[parts.length - 1]];
  1965. },
  1966. _getProp: function _getProp(/*...*/) {
  1967. if(arguments.length === 0) {
  1968. throw new Error('no arguments supplied to getprop');
  1969. }
  1970. if(arguments.length === 1 &&
  1971. (typeof arguments[0]) !== 'string')
  1972. {
  1973. return arguments[0];
  1974. }
  1975. var [obj, propname] = this._parsePropDescriptor(arguments);
  1976. return obj[propname];
  1977. },
  1978. _putProp: function _putProp(properties, value) {
  1979. var [obj, propname] = this._parsePropDescriptor(properties);
  1980. obj[propname] = value;
  1981. },
  1982. _delProp: function _delProp(propname) {
  1983. var [obj, propname] = this._parsePropDescriptor(arguments);
  1984. delete obj[propname];
  1985. },
  1986. _typeOf: function _typeOf(thing) {
  1987. return typeof thing;
  1988. },
  1989. _callNew: function(constructor) {
  1990. if(typeof constructor === 'string')
  1991. {
  1992. constructor = window[constructor];
  1993. } else if(constructor.length === 1 &&
  1994. typeof constructor[0] !== 'string')
  1995. {
  1996. constructor = constructor[0];
  1997. } else {
  1998. var [obj,propname] = this._parsePropDescriptor(constructor);
  1999. constructor = obj[propname];
  2000. }
  2001. /* Hacky, but should be robust */
  2002. var s = 'new constructor(';
  2003. for(var i = 1; i < arguments.length; ++i) {
  2004. if(i != 1) {
  2005. s += ',';
  2006. }
  2007. s += 'arguments[' + i + ']';
  2008. }
  2009. s += ')';
  2010. return eval(s);
  2011. },
  2012. _callEval: function(thisobj, js) {
  2013. return eval.call(thisobj, js);
  2014. },
  2015. getPrompt: function getPrompt(repl) {
  2016. return 'EVAL>'
  2017. },
  2018. _lookupObject: function _lookupObject(repl, id) {
  2019. if(typeof id === 'string') {
  2020. switch(id) {
  2021. case 'global':
  2022. return window;
  2023. case 'nil':
  2024. return null;
  2025. case 't':
  2026. return true;
  2027. case 'false':
  2028. return false;
  2029. case 'undefined':
  2030. return undefined;
  2031. case 'repl':
  2032. return repl;
  2033. case 'interactor':
  2034. return this;
  2035. case 'NaN':
  2036. return NaN;
  2037. case 'Infinity':
  2038. return Infinity;
  2039. case '-Infinity':
  2040. return -Infinity;
  2041. default:
  2042. throw new Error('No object with special id:' + id);
  2043. }
  2044. }
  2045. var ret = repl._jsObjects[id];
  2046. if(ret === undefined) {
  2047. throw new Error('No object with id:' + id + '(' + typeof id + ')');
  2048. }
  2049. return ret;
  2050. },
  2051. _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
  2052. if(typeof value !== 'object' && typeof value !== 'function') {
  2053. throw new Error('_findOrAllocateObject called on non-object('
  2054. + typeof(value) + '): '
  2055. + value)
  2056. }
  2057. for(var id in repl._jsObjects) {
  2058. id = Number(id);
  2059. var obj = repl._jsObjects[id];
  2060. if(obj === value) {
  2061. return id;
  2062. }
  2063. }
  2064. var id = ++repl._jsLastID;
  2065. repl._jsObjects[id] = value;
  2066. return id;
  2067. },
  2068. _fixupList: function _fixupList(repl, list) {
  2069. for(var i = 0; i < list.length; ++i) {
  2070. if(list[i] instanceof Array) {
  2071. this._fixupList(repl, list[i]);
  2072. } else if(typeof list[i] === 'object') {
  2073. var obj = list[i];
  2074. if(obj.funcall) {
  2075. var parts = obj.funcall;
  2076. this._fixupList(repl, parts);
  2077. var [thisobj, func] = this._parseFunc(parts[0]);
  2078. list[i] = func.apply(thisobj, parts.slice(1));
  2079. } else if(obj.objid) {
  2080. list[i] = this._lookupObject(repl, obj.objid);
  2081. } else {
  2082. throw new Error('Unknown object type: ' + obj.toSource());
  2083. }
  2084. }
  2085. }
  2086. },
  2087. _parseFunc: function(func) {
  2088. var thisobj = null;
  2089. if(typeof func === 'string') {
  2090. func = window[func];
  2091. } else if(func instanceof Array) {
  2092. if(func.length === 1 && typeof func[0] !== 'string') {
  2093. func = func[0];
  2094. } else {
  2095. [thisobj, func] = this._parsePropDescriptor(func);
  2096. func = thisobj[func];
  2097. }
  2098. }
  2099. return [thisobj,func];
  2100. },
  2101. _encodeReturn: function(value, array_as_mv) {
  2102. var ret;
  2103. if(value === null) {
  2104. ret = ['special', 'null'];
  2105. } else if(value === true) {
  2106. ret = ['special', 'true'];
  2107. } else if(value === false) {
  2108. ret = ['special', 'false'];
  2109. } else if(value === undefined) {
  2110. ret = ['special', 'undefined'];
  2111. } else if(typeof value === 'number') {
  2112. if(isNaN(value)) {
  2113. ret = ['special', 'NaN'];
  2114. } else if(value === Infinity) {
  2115. ret = ['special', 'Infinity'];
  2116. } else if(value === -Infinity) {
  2117. ret = ['special', '-Infinity'];
  2118. } else {
  2119. ret = ['atom', value];
  2120. }
  2121. } else if(typeof value === 'string') {
  2122. ret = ['atom', value];
  2123. } else if(array_as_mv && value instanceof Array) {
  2124. ret = ['array', value.map(this._encodeReturn, this)];
  2125. } else {
  2126. ret = ['objid', this._findOrAllocateObject(repl, value)];
  2127. }
  2128. return ret;
  2129. },
  2130. _handleInputLine: function _handleInputLine(repl, line) {
  2131. var ret;
  2132. var array_as_mv = false;
  2133. try {
  2134. if(line[0] === '*') {
  2135. array_as_mv = true;
  2136. line = line.substring(1);
  2137. }
  2138. var parts = eval(line);
  2139. this._fixupList(repl, parts);
  2140. var [thisobj, func] = this._parseFunc(parts[0]);
  2141. ret = this._encodeReturn(
  2142. func.apply(thisobj, parts.slice(1)),
  2143. array_as_mv);
  2144. } catch(x) {
  2145. ret = ['error', x.toString() ];
  2146. }
  2147. var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
  2148. repl.print(JSON.encode(ret));
  2149. repl._prompt();
  2150. },
  2151. handleInput: function handleInput(repl, chunk) {
  2152. this._input += chunk;
  2153. var match, line;
  2154. while(match = this._input.match(/.*\\n/)) {
  2155. line = match[0];
  2156. if(line === 'EXIT\\n') {
  2157. repl.popInteractor();
  2158. repl._prompt();
  2159. return;
  2160. }
  2161. this._input = this._input.substring(line.length);
  2162. this._handleInputLine(repl, line);
  2163. }
  2164. }
  2165. });
  2166. })
  2167. ")
  2168. "String to set MozRepl up into a simple-minded evaluation mode.")
  2169. (defun js--js-encode-value (x)
  2170. "Marshall the given value for JS.
  2171. Strings and numbers are JSON-encoded. Lists (including nil) are
  2172. made into JavaScript array literals and their contents encoded
  2173. with `js--js-encode-value'."
  2174. (cond ((stringp x) (json-encode-string x))
  2175. ((numberp x) (json-encode-number x))
  2176. ((symbolp x) (format "{objid:%S}" (symbol-name x)))
  2177. ((js--js-handle-p x)
  2178. (when (js--js-handle-expired-p x)
  2179. (error "Stale JS handle"))
  2180. (format "{objid:%s}" (js--js-handle-id x)))
  2181. ((sequencep x)
  2182. (if (eq (car-safe x) 'js--funcall)
  2183. (format "{funcall:[%s]}"
  2184. (mapconcat #'js--js-encode-value (cdr x) ","))
  2185. (concat
  2186. "[" (mapconcat #'js--js-encode-value x ",") "]")))
  2187. (t
  2188. (error "Unrecognized item: %S" x))))
  2189. (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
  2190. (defconst js--js-repl-prompt-regexp "^EVAL>$")
  2191. (defvar js--js-repl-depth 0)
  2192. (defun js--js-wait-for-eval-prompt ()
  2193. (js--wait-for-matching-output
  2194. (inferior-moz-process)
  2195. js--js-repl-prompt-regexp js-js-timeout
  2196. ;; start matching against the beginning of the line in
  2197. ;; order to catch a prompt that's only partially arrived
  2198. (save-excursion (forward-line 0) (point))))
  2199. (defun js--js-enter-repl ()
  2200. (inferior-moz-process) ; called for side-effect
  2201. (with-current-buffer inferior-moz-buffer
  2202. (goto-char (point-max))
  2203. ;; Do some initialization the first time we see a process
  2204. (unless (eq (inferior-moz-process) js--js-process)
  2205. (setq js--js-process (inferior-moz-process))
  2206. (setq js--js-references (make-hash-table :test 'eq :weakness t))
  2207. (setq js--js-repl-depth 0)
  2208. ;; Send interactor definition
  2209. (comint-send-string js--js-process js--moz-interactor)
  2210. (comint-send-string js--js-process
  2211. (concat "(" moz-repl-name ")\n"))
  2212. (js--wait-for-matching-output
  2213. (inferior-moz-process) js--js-prompt-regexp
  2214. js-js-timeout))
  2215. ;; Sanity check
  2216. (when (looking-back js--js-prompt-regexp
  2217. (save-excursion (forward-line 0) (point)))
  2218. (setq js--js-repl-depth 0))
  2219. (if (> js--js-repl-depth 0)
  2220. ;; If js--js-repl-depth > 0, we *should* be seeing an
  2221. ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
  2222. ;; up with us.
  2223. (js--js-wait-for-eval-prompt)
  2224. ;; Otherwise, tell Mozilla to enter the interactor mode
  2225. (insert (match-string-no-properties 1)
  2226. ".pushInteractor('js')")
  2227. (comint-send-input nil t)
  2228. (js--wait-for-matching-output
  2229. (inferior-moz-process) js--js-repl-prompt-regexp
  2230. js-js-timeout))
  2231. (incf js--js-repl-depth)))
  2232. (defun js--js-leave-repl ()
  2233. (assert (> js--js-repl-depth 0))
  2234. (when (= 0 (decf js--js-repl-depth))
  2235. (with-current-buffer inferior-moz-buffer
  2236. (goto-char (point-max))
  2237. (js--js-wait-for-eval-prompt)
  2238. (insert "EXIT")
  2239. (comint-send-input nil t)
  2240. (js--wait-for-matching-output
  2241. (inferior-moz-process) js--js-prompt-regexp
  2242. js-js-timeout))))
  2243. (defsubst js--js-not (value)
  2244. (memq value '(nil null false undefined)))
  2245. (defsubst js--js-true (value)
  2246. (not (js--js-not value)))
  2247. (eval-and-compile
  2248. (defun js--optimize-arglist (arglist)
  2249. "Convert immediate js< and js! references to deferred ones."
  2250. (loop for item in arglist
  2251. if (eq (car-safe item) 'js<)
  2252. collect (append (list 'list ''js--funcall
  2253. '(list 'interactor "_getProp"))
  2254. (js--optimize-arglist (cdr item)))
  2255. else if (eq (car-safe item) 'js>)
  2256. collect (append (list 'list ''js--funcall
  2257. '(list 'interactor "_putProp"))
  2258. (if (atom (cadr item))
  2259. (list (cadr item))
  2260. (list
  2261. (append
  2262. (list 'list ''js--funcall
  2263. '(list 'interactor "_mkArray"))
  2264. (js--optimize-arglist (cadr item)))))
  2265. (js--optimize-arglist (cddr item)))
  2266. else if (eq (car-safe item) 'js!)
  2267. collect (destructuring-bind (ignored function &rest body) item
  2268. (append (list 'list ''js--funcall
  2269. (if (consp function)
  2270. (cons 'list
  2271. (js--optimize-arglist function))
  2272. function))
  2273. (js--optimize-arglist body)))
  2274. else
  2275. collect item)))
  2276. (defmacro js--js-get-service (class-name interface-name)
  2277. `(js! ("Components" "classes" ,class-name "getService")
  2278. (js< "Components" "interfaces" ,interface-name)))
  2279. (defmacro js--js-create-instance (class-name interface-name)
  2280. `(js! ("Components" "classes" ,class-name "createInstance")
  2281. (js< "Components" "interfaces" ,interface-name)))
  2282. (defmacro js--js-qi (object interface-name)
  2283. `(js! (,object "QueryInterface")
  2284. (js< "Components" "interfaces" ,interface-name)))
  2285. (defmacro with-js (&rest forms)
  2286. "Run FORMS with the Mozilla repl set up for js commands.
  2287. Inside the lexical scope of `with-js', `js?', `js!',
  2288. `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
  2289. `js-create-instance', and `js-qi' are defined."
  2290. `(progn
  2291. (js--js-enter-repl)
  2292. (unwind-protect
  2293. (macrolet ((js? (&rest body) `(js--js-true ,@body))
  2294. (js! (function &rest body)
  2295. `(js--js-funcall
  2296. ,(if (consp function)
  2297. (cons 'list
  2298. (js--optimize-arglist function))
  2299. function)
  2300. ,@(js--optimize-arglist body)))
  2301. (js-new (function &rest body)
  2302. `(js--js-new
  2303. ,(if (consp function)
  2304. (cons 'list
  2305. (js--optimize-arglist function))
  2306. function)
  2307. ,@body))
  2308. (js-eval (thisobj js)
  2309. `(js--js-eval
  2310. ,@(js--optimize-arglist
  2311. (list thisobj js))))
  2312. (js-list (&rest args)
  2313. `(js--js-list
  2314. ,@(js--optimize-arglist args)))
  2315. (js-get-service (&rest args)
  2316. `(js--js-get-service
  2317. ,@(js--optimize-arglist args)))
  2318. (js-create-instance (&rest args)
  2319. `(js--js-create-instance
  2320. ,@(js--optimize-arglist args)))
  2321. (js-qi (&rest args)
  2322. `(js--js-qi
  2323. ,@(js--optimize-arglist args)))
  2324. (js< (&rest body) `(js--js-get
  2325. ,@(js--optimize-arglist body)))
  2326. (js> (props value)
  2327. `(js--js-funcall
  2328. '(interactor "_putProp")
  2329. ,(if (consp props)
  2330. (cons 'list
  2331. (js--optimize-arglist props))
  2332. props)
  2333. ,@(js--optimize-arglist (list value))
  2334. ))
  2335. (js-handle? (arg) `(js--js-handle-p ,arg)))
  2336. ,@forms)
  2337. (js--js-leave-repl))))
  2338. (defvar js--js-array-as-list nil
  2339. "Whether to listify any Array returned by a Mozilla function.
  2340. If nil, the whole Array is treated as a JS symbol.")
  2341. (defun js--js-decode-retval (result)
  2342. (ecase (intern (first result))
  2343. (atom (second result))
  2344. (special (intern (second result)))
  2345. (array
  2346. (mapcar #'js--js-decode-retval (second result)))
  2347. (objid
  2348. (or (gethash (second result)
  2349. js--js-references)
  2350. (puthash (second result)
  2351. (make-js--js-handle
  2352. :id (second result)
  2353. :process (inferior-moz-process))
  2354. js--js-references)))
  2355. (error (signal 'js-js-error (list (second result))))))
  2356. (defun js--js-funcall (function &rest arguments)
  2357. "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
  2358. If function is a string, look it up as a property on the global
  2359. object and use the global object for `this'.
  2360. If FUNCTION is a list with one element, use that element as the
  2361. function with the global object for `this', except that if that
  2362. single element is a string, look it up on the global object.
  2363. If FUNCTION is a list with more than one argument, use the list
  2364. up to the last value as a property descriptor and the last
  2365. argument as a function."
  2366. (with-js
  2367. (let ((argstr (js--js-encode-value
  2368. (cons function arguments))))
  2369. (with-current-buffer inferior-moz-buffer
  2370. ;; Actual funcall
  2371. (when js--js-array-as-list
  2372. (insert "*"))
  2373. (insert argstr)
  2374. (comint-send-input nil t)
  2375. (js--wait-for-matching-output
  2376. (inferior-moz-process) "EVAL>"
  2377. js-js-timeout)
  2378. (goto-char comint-last-input-end)
  2379. ;; Read the result
  2380. (let* ((json-array-type 'list)
  2381. (result (prog1 (json-read)
  2382. (goto-char (point-max)))))
  2383. (js--js-decode-retval result))))))
  2384. (defun js--js-new (constructor &rest arguments)
  2385. "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
  2386. CONSTRUCTOR is a JS handle, a string, or a list of these things."
  2387. (apply #'js--js-funcall
  2388. '(interactor "_callNew")
  2389. constructor arguments))
  2390. (defun js--js-eval (thisobj js)
  2391. (js--js-funcall '(interactor "_callEval") thisobj js))
  2392. (defun js--js-list (&rest arguments)
  2393. "Return a Lisp array resulting from evaluating each of ARGUMENTS."
  2394. (let ((js--js-array-as-list t))
  2395. (apply #'js--js-funcall '(interactor "_mkArray")
  2396. arguments)))
  2397. (defun js--js-get (&rest props)
  2398. (apply #'js--js-funcall '(interactor "_getProp") props))
  2399. (defun js--js-put (props value)
  2400. (js--js-funcall '(interactor "_putProp") props value))
  2401. (defun js-gc (&optional force)
  2402. "Tell the repl about any objects we don't reference anymore.
  2403. With argument, run even if no intervening GC has happened."
  2404. (interactive)
  2405. (when force
  2406. (setq js--js-last-gcs-done nil))
  2407. (let ((this-gcs-done gcs-done) keys num)
  2408. (when (and js--js-references
  2409. (boundp 'inferior-moz-buffer)
  2410. (buffer-live-p inferior-moz-buffer)
  2411. ;; Don't bother running unless we've had an intervening
  2412. ;; garbage collection; without a gc, nothing is deleted
  2413. ;; from the weak hash table, so it's pointless telling
  2414. ;; MozRepl about that references we still hold
  2415. (not (eq js--js-last-gcs-done this-gcs-done))
  2416. ;; Are we looking at a normal prompt? Make sure not to
  2417. ;; interrupt the user if he's doing something
  2418. (with-current-buffer inferior-moz-buffer
  2419. (save-excursion
  2420. (goto-char (point-max))
  2421. (looking-back js--js-prompt-regexp
  2422. (save-excursion (forward-line 0) (point))))))
  2423. (setq keys (loop for x being the hash-keys
  2424. of js--js-references
  2425. collect x))
  2426. (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
  2427. (setq js--js-last-gcs-done this-gcs-done)
  2428. (when (called-interactively-p 'interactive)
  2429. (message "Cleaned %s entries" num))
  2430. num)))
  2431. (run-with-idle-timer 30 t #'js-gc)
  2432. (defun js-eval (js)
  2433. "Evaluate the JavaScript in JS and return JSON-decoded result."
  2434. (interactive "MJavascript to evaluate: ")
  2435. (with-js
  2436. (let* ((content-window (js--js-content-window
  2437. (js--get-js-context)))
  2438. (result (js-eval content-window js)))
  2439. (when (called-interactively-p 'interactive)
  2440. (message "%s" (js! "String" result)))
  2441. result)))
  2442. (defun js--get-tabs ()
  2443. "Enumerate all JavaScript contexts available.
  2444. Each context is a list:
  2445. (TITLE URL BROWSER TAB TABBROWSER) for content documents
  2446. (TITLE URL WINDOW) for windows
  2447. All tabs of a given window are grouped together. The most recent
  2448. window is first. Within each window, the tabs are returned
  2449. left-to-right."
  2450. (with-js
  2451. (let (windows)
  2452. (loop with window-mediator = (js! ("Components" "classes"
  2453. "@mozilla.org/appshell/window-mediator;1"
  2454. "getService")
  2455. (js< "Components" "interfaces"
  2456. "nsIWindowMediator"))
  2457. with enumerator = (js! (window-mediator "getEnumerator") nil)
  2458. while (js? (js! (enumerator "hasMoreElements")))
  2459. for window = (js! (enumerator "getNext"))
  2460. for window-info = (js-list window
  2461. (js< window "document" "title")
  2462. (js! (window "location" "toString"))
  2463. (js< window "closed")
  2464. (js< window "windowState"))
  2465. unless (or (js? (fourth window-info))
  2466. (eq (fifth window-info) 2))
  2467. do (push window-info windows))
  2468. (loop for window-info in windows
  2469. for window = (first window-info)
  2470. collect (list (second window-info)
  2471. (third window-info)
  2472. window)
  2473. for gbrowser = (js< window "gBrowser")
  2474. if (js-handle? gbrowser)
  2475. nconc (loop
  2476. for x below (js< gbrowser "browsers" "length")
  2477. collect (js-list (js< gbrowser
  2478. "browsers"
  2479. x
  2480. "contentDocument"
  2481. "title")
  2482. (js! (gbrowser
  2483. "browsers"
  2484. x
  2485. "contentWindow"
  2486. "location"
  2487. "toString"))
  2488. (js< gbrowser
  2489. "browsers"
  2490. x)
  2491. (js! (gbrowser
  2492. "tabContainer"
  2493. "childNodes"
  2494. "item")
  2495. x)
  2496. gbrowser))))))
  2497. (defvar js-read-tab-history nil)
  2498. (defun js--read-tab (prompt)
  2499. "Read a Mozilla tab with prompt PROMPT.
  2500. Return a cons of (TYPE . OBJECT). TYPE is either 'window or
  2501. 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
  2502. browser, respectively."
  2503. ;; Prime IDO
  2504. (unless ido-mode
  2505. (ido-mode 1)
  2506. (ido-mode -1))
  2507. (with-js
  2508. (lexical-let ((tabs (js--get-tabs)) selected-tab-cname
  2509. selected-tab prev-hitab)
  2510. ;; Disambiguate names
  2511. (setq tabs (loop with tab-names = (make-hash-table :test 'equal)
  2512. for tab in tabs
  2513. for cname = (format "%s (%s)" (second tab) (first tab))
  2514. for num = (incf (gethash cname tab-names -1))
  2515. if (> num 0)
  2516. do (setq cname (format "%s <%d>" cname num))
  2517. collect (cons cname tab)))
  2518. (labels ((find-tab-by-cname
  2519. (cname)
  2520. (loop for tab in tabs
  2521. if (equal (car tab) cname)
  2522. return (cdr tab)))
  2523. (mogrify-highlighting
  2524. (hitab unhitab)
  2525. ;; Hack to reduce the number of
  2526. ;; round-trips to mozilla
  2527. (let (cmds)
  2528. (cond
  2529. ;; Highlighting tab
  2530. ((fourth hitab)
  2531. (push '(js! ((fourth hitab) "setAttribute")
  2532. "style"
  2533. "color: red; font-weight: bold")
  2534. cmds)
  2535. ;; Highlight window proper
  2536. (push '(js! ((third hitab)
  2537. "setAttribute")
  2538. "style"
  2539. "border: 8px solid red")
  2540. cmds)
  2541. ;; Select tab, when appropriate
  2542. (when js-js-switch-tabs
  2543. (push
  2544. '(js> ((fifth hitab) "selectedTab") (fourth hitab))
  2545. cmds)))
  2546. ;; Highlighting whole window
  2547. ((third hitab)
  2548. (push '(js! ((third hitab) "document"
  2549. "documentElement" "setAttribute")
  2550. "style"
  2551. (concat "-moz-appearance: none;"
  2552. "border: 8px solid red;"))
  2553. cmds)))
  2554. (cond
  2555. ;; Unhighlighting tab
  2556. ((fourth unhitab)
  2557. (push '(js! ((fourth unhitab) "setAttribute") "style" "")
  2558. cmds)
  2559. (push '(js! ((third unhitab) "setAttribute") "style" "")
  2560. cmds))
  2561. ;; Unhighlighting window
  2562. ((third unhitab)
  2563. (push '(js! ((third unhitab) "document"
  2564. "documentElement" "setAttribute")
  2565. "style" "")
  2566. cmds)))
  2567. (eval (list 'with-js
  2568. (cons 'js-list (nreverse cmds))))))
  2569. (command-hook
  2570. ()
  2571. (let* ((tab (find-tab-by-cname (car ido-matches))))
  2572. (mogrify-highlighting tab prev-hitab)
  2573. (setq prev-hitab tab)))
  2574. (setup-hook
  2575. ()
  2576. ;; Fiddle with the match list a bit: if our first match
  2577. ;; is a tabbrowser window, rotate the match list until
  2578. ;; the active tab comes up
  2579. (let ((matched-tab (find-tab-by-cname (car ido-matches))))
  2580. (when (and matched-tab
  2581. (null (fourth matched-tab))
  2582. (equal "navigator:browser"
  2583. (js! ((third matched-tab)
  2584. "document"
  2585. "documentElement"
  2586. "getAttribute")
  2587. "windowtype")))
  2588. (loop with tab-to-match = (js< (third matched-tab)
  2589. "gBrowser"
  2590. "selectedTab")
  2591. with index = 0
  2592. for match in ido-matches
  2593. for candidate-tab = (find-tab-by-cname match)
  2594. if (eq (fourth candidate-tab) tab-to-match)
  2595. do (setq ido-cur-list (ido-chop ido-cur-list match))
  2596. and return t)))
  2597. (add-hook 'post-command-hook #'command-hook t t)))
  2598. (unwind-protect
  2599. (setq selected-tab-cname
  2600. (let ((ido-minibuffer-setup-hook
  2601. (cons #'setup-hook ido-minibuffer-setup-hook)))
  2602. (ido-completing-read
  2603. prompt
  2604. (mapcar #'car tabs)
  2605. nil t nil
  2606. 'js-read-tab-history)))
  2607. (when prev-hitab
  2608. (mogrify-highlighting nil prev-hitab)
  2609. (setq prev-hitab nil)))
  2610. (add-to-history 'js-read-tab-history selected-tab-cname)
  2611. (setq selected-tab (loop for tab in tabs
  2612. if (equal (car tab) selected-tab-cname)
  2613. return (cdr tab)))
  2614. (if (fourth selected-tab)
  2615. (cons 'browser (third selected-tab))
  2616. (cons 'window (third selected-tab)))))))
  2617. (defun js--guess-eval-defun-info (pstate)
  2618. "Helper function for `js-eval-defun'.
  2619. Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
  2620. strings making up the class name and NAME is the name of the
  2621. function part."
  2622. (cond ((and (= (length pstate) 3)
  2623. (eq (js--pitem-type (first pstate)) 'function)
  2624. (= (length (js--pitem-name (first pstate))) 1)
  2625. (consp (js--pitem-type (second pstate))))
  2626. (append (js--pitem-name (second pstate))
  2627. (list (first (js--pitem-name (first pstate))))))
  2628. ((and (= (length pstate) 2)
  2629. (eq (js--pitem-type (first pstate)) 'function))
  2630. (append
  2631. (butlast (js--pitem-name (first pstate)))
  2632. (list (car (last (js--pitem-name (first pstate)))))))
  2633. (t (error "Function not a toplevel defun or class member"))))
  2634. (defvar js--js-context nil
  2635. "The current JavaScript context.
  2636. This is a cons like the one returned from `js--read-tab'.
  2637. Change with `js-set-js-context'.")
  2638. (defconst js--js-inserter
  2639. "(function(func_info,func) {
  2640. func_info.unshift('window');
  2641. var obj = window;
  2642. for(var i = 1; i < func_info.length - 1; ++i) {
  2643. var next = obj[func_info[i]];
  2644. if(typeof next !== 'object' && typeof next !== 'function') {
  2645. next = obj.prototype && obj.prototype[func_info[i]];
  2646. if(typeof next !== 'object' && typeof next !== 'function') {
  2647. alert('Could not find ' + func_info.slice(0, i+1).join('.') +
  2648. ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
  2649. return;
  2650. }
  2651. func_info.splice(i+1, 0, 'prototype');
  2652. ++i;
  2653. }
  2654. }
  2655. obj[func_info[i]] = func;
  2656. alert('Successfully updated '+func_info.join('.'));
  2657. })")
  2658. (defun js-set-js-context (context)
  2659. "Set the JavaScript context to CONTEXT.
  2660. When called interactively, prompt for CONTEXT."
  2661. (interactive (list (js--read-tab "Javascript Context: ")))
  2662. (setq js--js-context context))
  2663. (defun js--get-js-context ()
  2664. "Return a valid JavaScript context.
  2665. If one hasn't been set, or if it's stale, prompt for a new one."
  2666. (with-js
  2667. (when (or (null js--js-context)
  2668. (js--js-handle-expired-p (cdr js--js-context))
  2669. (ecase (car js--js-context)
  2670. (window (js? (js< (cdr js--js-context) "closed")))
  2671. (browser (not (js? (js< (cdr js--js-context)
  2672. "contentDocument"))))))
  2673. (setq js--js-context (js--read-tab "Javascript Context: ")))
  2674. js--js-context))
  2675. (defun js--js-content-window (context)
  2676. (with-js
  2677. (ecase (car context)
  2678. (window (cdr context))
  2679. (browser (js< (cdr context)
  2680. "contentWindow" "wrappedJSObject")))))
  2681. (defun js--make-nsilocalfile (path)
  2682. (with-js
  2683. (let ((file (js-create-instance "@mozilla.org/file/local;1"
  2684. "nsILocalFile")))
  2685. (js! (file "initWithPath") path)
  2686. file)))
  2687. (defun js--js-add-resource-alias (alias path)
  2688. (with-js
  2689. (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
  2690. "nsIIOService"))
  2691. (res-prot (js! (io-service "getProtocolHandler") "resource"))
  2692. (res-prot (js-qi res-prot "nsIResProtocolHandler"))
  2693. (path-file (js--make-nsilocalfile path))
  2694. (path-uri (js! (io-service "newFileURI") path-file)))
  2695. (js! (res-prot "setSubstitution") alias path-uri))))
  2696. (defun* js-eval-defun ()
  2697. "Update a Mozilla tab using the JavaScript defun at point."
  2698. (interactive)
  2699. ;; This function works by generating a temporary file that contains
  2700. ;; the function we'd like to insert. We then use the elisp-js bridge
  2701. ;; to command mozilla to load this file by inserting a script tag
  2702. ;; into the document we set. This way, debuggers and such will have
  2703. ;; a way to find the source of the just-inserted function.
  2704. ;;
  2705. ;; We delete the temporary file if there's an error, but otherwise
  2706. ;; we add an unload event listener on the Mozilla side to delete the
  2707. ;; file.
  2708. (save-excursion
  2709. (let (begin end pstate defun-info temp-name defun-body)
  2710. (js-end-of-defun)
  2711. (setq end (point))
  2712. (js--ensure-cache)
  2713. (js-beginning-of-defun)
  2714. (re-search-forward "\\_<function\\_>")
  2715. (setq begin (match-beginning 0))
  2716. (setq pstate (js--forward-pstate))
  2717. (when (or (null pstate)
  2718. (> (point) end))
  2719. (error "Could not locate function definition"))
  2720. (setq defun-info (js--guess-eval-defun-info pstate))
  2721. (let ((overlay (make-overlay begin end)))
  2722. (overlay-put overlay 'face 'highlight)
  2723. (unwind-protect
  2724. (unless (y-or-n-p (format "Send %s to Mozilla? "
  2725. (mapconcat #'identity defun-info ".")))
  2726. (message "") ; question message lingers until next command
  2727. (return-from js-eval-defun))
  2728. (delete-overlay overlay)))
  2729. (setq defun-body (buffer-substring-no-properties begin end))
  2730. (make-directory js-js-tmpdir t)
  2731. ;; (Re)register a Mozilla resource URL to point to the
  2732. ;; temporary directory
  2733. (js--js-add-resource-alias "js" js-js-tmpdir)
  2734. (setq temp-name (make-temp-file (concat js-js-tmpdir
  2735. "/js-")
  2736. nil ".js"))
  2737. (unwind-protect
  2738. (with-js
  2739. (with-temp-buffer
  2740. (insert js--js-inserter)
  2741. (insert "(")
  2742. (insert (json-encode-list defun-info))
  2743. (insert ",\n")
  2744. (insert defun-body)
  2745. (insert "\n)")
  2746. (write-region (point-min) (point-max) temp-name
  2747. nil 1))
  2748. ;; Give Mozilla responsibility for deleting this file
  2749. (let* ((content-window (js--js-content-window
  2750. (js--get-js-context)))
  2751. (content-document (js< content-window "document"))
  2752. (head (if (js? (js< content-document "body"))
  2753. ;; Regular content
  2754. (js< (js! (content-document "getElementsByTagName")
  2755. "head")
  2756. 0)
  2757. ;; Chrome
  2758. (js< content-document "documentElement")))
  2759. (elem (js! (content-document "createElementNS")
  2760. "http://www.w3.org/1999/xhtml" "script")))
  2761. (js! (elem "setAttribute") "type" "text/javascript")
  2762. (js! (elem "setAttribute") "src"
  2763. (format "resource://js/%s"
  2764. (file-name-nondirectory temp-name)))
  2765. (js! (head "appendChild") elem)
  2766. (js! (content-window "addEventListener") "unload"
  2767. (js! ((js-new
  2768. "Function" "file"
  2769. "return function() { file.remove(false) }"))
  2770. (js--make-nsilocalfile temp-name))
  2771. 'false)
  2772. (setq temp-name nil)
  2773. ))
  2774. ;; temp-name is set to nil on success
  2775. (when temp-name
  2776. (delete-file temp-name))))))
  2777. ;;; Main Function
  2778. ;;;###autoload
  2779. (define-derived-mode js-mode prog-mode "Javascript"
  2780. "Major mode for editing JavaScript."
  2781. :group 'js
  2782. (set (make-local-variable 'indent-line-function) 'js-indent-line)
  2783. (set (make-local-variable 'beginning-of-defun-function)
  2784. 'js-beginning-of-defun)
  2785. (set (make-local-variable 'end-of-defun-function)
  2786. 'js-end-of-defun)
  2787. (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
  2788. (set (make-local-variable 'font-lock-defaults)
  2789. (list js--font-lock-keywords))
  2790. (set (make-local-variable 'syntax-propertize-function)
  2791. #'js-syntax-propertize)
  2792. (set (make-local-variable 'parse-sexp-ignore-comments) t)
  2793. (set (make-local-variable 'parse-sexp-lookup-properties) t)
  2794. (set (make-local-variable 'which-func-imenu-joiner-function)
  2795. #'js--which-func-joiner)
  2796. ;; Comments
  2797. (set (make-local-variable 'comment-start) "// ")
  2798. (set (make-local-variable 'comment-end) "")
  2799. (set (make-local-variable 'fill-paragraph-function)
  2800. 'js-c-fill-paragraph)
  2801. ;; Parse cache
  2802. (add-hook 'before-change-functions #'js--flush-caches t t)
  2803. ;; Frameworks
  2804. (js--update-quick-match-re)
  2805. ;; Imenu
  2806. (setq imenu-case-fold-search nil)
  2807. (set (make-local-variable 'imenu-create-index-function)
  2808. #'js--imenu-create-index)
  2809. ;; for filling, pretend we're cc-mode
  2810. (setq c-comment-prefix-regexp "//+\\|\\**"
  2811. c-paragraph-start "$"
  2812. c-paragraph-separate "$"
  2813. c-block-comment-prefix "* "
  2814. c-line-comment-starter "//"
  2815. c-comment-start-regexp "/[*/]\\|\\s!"
  2816. comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
  2817. (set (make-local-variable 'electric-indent-chars)
  2818. (append "{}():;," electric-indent-chars))
  2819. (set (make-local-variable 'electric-layout-rules)
  2820. '((?\; . after) (?\{ . after) (?\} . before)))
  2821. (let ((c-buffer-is-cc-mode t))
  2822. ;; FIXME: These are normally set by `c-basic-common-init'. Should
  2823. ;; we call it instead? (Bug#6071)
  2824. (make-local-variable 'paragraph-start)
  2825. (make-local-variable 'paragraph-separate)
  2826. (make-local-variable 'paragraph-ignore-fill-prefix)
  2827. (make-local-variable 'adaptive-fill-mode)
  2828. (make-local-variable 'adaptive-fill-regexp)
  2829. (c-setup-paragraph-variables))
  2830. (set (make-local-variable 'syntax-begin-function)
  2831. #'js--syntax-begin-function)
  2832. ;; Important to fontify the whole buffer syntactically! If we don't,
  2833. ;; then we might have regular expression literals that aren't marked
  2834. ;; as strings, which will screw up parse-partial-sexp, scan-lists,
  2835. ;; etc. and produce maddening "unbalanced parenthesis" errors.
  2836. ;; When we attempt to find the error and scroll to the portion of
  2837. ;; the buffer containing the problem, JIT-lock will apply the
  2838. ;; correct syntax to the regular expression literal and the problem
  2839. ;; will mysteriously disappear.
  2840. ;; FIXME: We should actually do this fontification lazily by adding
  2841. ;; calls to syntax-propertize wherever it's really needed.
  2842. (syntax-propertize (point-max)))
  2843. ;;;###autoload
  2844. (defalias 'javascript-mode 'js-mode)
  2845. (eval-after-load 'folding
  2846. '(when (fboundp 'folding-add-to-marks-list)
  2847. (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
  2848. (provide 'js)
  2849. ;; js.el ends here