smie.el 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234
  1. ;;; smie.el --- Simple Minded Indentation Engine -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2010-2015 Free Software Foundation, Inc.
  3. ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
  4. ;; Keywords: languages, lisp, internal, parsing, indentation
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; While working on the SML indentation code, the idea grew that maybe
  18. ;; I could write something generic to do the same thing, and at the
  19. ;; end of working on the SML code, I had a pretty good idea of what it
  20. ;; could look like. That idea grew stronger after working on
  21. ;; LaTeX indentation.
  22. ;;
  23. ;; So at some point I decided to try it out, by writing a new
  24. ;; indentation code for Coq while trying to keep most of the code
  25. ;; "table driven", where only the tables are Coq-specific. The result
  26. ;; (which was used for Beluga-mode as well) turned out to be based on
  27. ;; something pretty close to an operator precedence parser.
  28. ;; So here is another rewrite, this time following the actual principles of
  29. ;; operator precedence grammars. Why OPG? Even though they're among the
  30. ;; weakest kinds of parsers, these parsers have some very desirable properties
  31. ;; for Emacs:
  32. ;; - most importantly for indentation, they work equally well in either
  33. ;; direction, so you can use them to parse backward from the indentation
  34. ;; point to learn the syntactic context;
  35. ;; - they work locally, so there's no need to keep a cache of
  36. ;; the parser's state;
  37. ;; - because of that locality, indentation also works just fine when earlier
  38. ;; parts of the buffer are syntactically incorrect since the indentation
  39. ;; looks at "as little as possible" of the buffer to make an indentation
  40. ;; decision.
  41. ;; - they typically have no error handling and can't even detect a parsing
  42. ;; error, so we don't have to worry about what to do in case of a syntax
  43. ;; error because the parser just automatically does something. Better yet,
  44. ;; we can afford to use a sloppy grammar.
  45. ;; A good background to understand the development (especially the parts
  46. ;; building the 2D precedence tables and then computing the precedence levels
  47. ;; from it) can be found in pages 187-194 of "Parsing techniques" by Dick Grune
  48. ;; and Ceriel Jacobs (BookBody.pdf available at
  49. ;; http://dickgrune.com/Books/PTAPG_1st_Edition/).
  50. ;;
  51. ;; OTOH we had to kill many chickens, read many coffee grounds, and practice
  52. ;; untold numbers of black magic spells, to come up with the indentation code.
  53. ;; Since then, some of that code has been beaten into submission, but the
  54. ;; smie-indent-keyword is still pretty obscure.
  55. ;; Conflict resolution:
  56. ;;
  57. ;; - One source of conflicts is when you have:
  58. ;; (exp ("IF" exp "ELSE" exp "END") ("CASE" cases "END"))
  59. ;; (cases (cases "ELSE" insts) ...)
  60. ;; The IF-rule implies ELSE=END and the CASE-rule implies ELSE>END.
  61. ;; This can be resolved simply with:
  62. ;; (exp ("IF" expelseexp "END") ("CASE" cases "END"))
  63. ;; (expelseexp (exp) (exp "ELSE" exp))
  64. ;; (cases (cases "ELSE" insts) ...)
  65. ;; - Another source of conflict is when a terminator/separator is used to
  66. ;; terminate elements at different levels, as in:
  67. ;; (decls ("VAR" vars) (decls "," decls))
  68. ;; (vars (id) (vars "," vars))
  69. ;; often these can be resolved by making the lexer distinguish the two
  70. ;; kinds of commas, e.g. based on the following token.
  71. ;; TODO & BUGS:
  72. ;;
  73. ;; - We could try to resolve conflicts such as the IFexpELSEexpEND -vs-
  74. ;; CASE(casesELSEexp)END automatically by changing the way BNF rules such as
  75. ;; the IF-rule is handled. I.e. rather than IF=ELSE and ELSE=END, we could
  76. ;; turn them into IF<ELSE and ELSE>END and IF=END.
  77. ;; - Using the structural information SMIE gives us, it should be possible to
  78. ;; implement a `smie-align' command that would automatically figure out what
  79. ;; there is to align and how to do it (something like: align the token of
  80. ;; lowest precedence that appears the same number of times on all lines,
  81. ;; and then do the same on each side of that token).
  82. ;; - Maybe accept two juxtaposed non-terminals in the BNF under the condition
  83. ;; that the first always ends with a terminal, or that the second always
  84. ;; starts with a terminal.
  85. ;; - Permit EBNF-style notation.
  86. ;; - If the grammar has conflicts, the only way is to make the lexer return
  87. ;; different tokens for the different cases. This extra work performed by
  88. ;; the lexer can be costly and unnecessary: we perform this extra work every
  89. ;; time we find the conflicting token, regardless of whether or not the
  90. ;; difference between the various situations is relevant to the current
  91. ;; situation. E.g. we may try to determine whether a ";" is a ";-operator"
  92. ;; or a ";-separator" in a case where we're skipping over a "begin..end" pair
  93. ;; where the difference doesn't matter. For frequently occurring tokens and
  94. ;; rarely occurring conflicts, this can be a significant performance problem.
  95. ;; We could try and let the lexer return a "set of possible tokens
  96. ;; plus a refinement function" and then let parser call the refinement
  97. ;; function if needed.
  98. ;; - Make it possible to better specify the behavior in the face of
  99. ;; syntax errors. IOW provide some control over the choice of precedence
  100. ;; levels within the limits of the constraints. E.g. make it possible for
  101. ;; the grammar to specify that "begin..end" has lower precedence than
  102. ;; "Module..EndModule", so that if a "begin" is missing, scanning from the
  103. ;; "end" will stop at "Module" rather than going past it (and similarly,
  104. ;; scanning from "Module" should not stop at a spurious "end").
  105. ;;; Code:
  106. ;; FIXME:
  107. ;; - smie-indent-comment doesn't interact well with mis-indented lines (where
  108. ;; the indent rules don't do what the user wants). Not sure what to do.
  109. (eval-when-compile (require 'cl-lib))
  110. (defgroup smie nil
  111. "Simple Minded Indentation Engine."
  112. :group 'languages)
  113. (defvar comment-continue)
  114. (declare-function comment-string-strip "newcomment" (str beforep afterp))
  115. ;;; Building precedence level tables from BNF specs.
  116. ;; We have 4 different representations of a "grammar":
  117. ;; - a BNF table, which is a list of BNF rules of the form
  118. ;; (NONTERM RHS1 ... RHSn) where each RHS is a list of terminals (tokens)
  119. ;; or nonterminals. Any element in these lists which does not appear as
  120. ;; the `car' of a BNF rule is taken to be a terminal.
  121. ;; - A list of precedences (key word "precs"), is a list, sorted
  122. ;; from lowest to highest precedence, of precedence classes that
  123. ;; have the form (ASSOCIATIVITY TERMINAL1 .. TERMINALn), where
  124. ;; ASSOCIATIVITY can be `assoc', `left', `right' or `nonassoc'.
  125. ;; - a 2 dimensional precedence table (key word "prec2"), is a 2D
  126. ;; table recording the precedence relation (can be `<', `=', `>', or
  127. ;; nil) between each pair of tokens.
  128. ;; - a precedence-level table (key word "grammar"), which is an alist
  129. ;; giving for each token its left and right precedence level (a
  130. ;; number or nil). This is used in `smie-grammar'.
  131. ;; The prec2 tables are only intermediate data structures: the source
  132. ;; code normally provides a mix of BNF and precs tables, and then
  133. ;; turns them into a levels table, which is what's used by the rest of
  134. ;; the SMIE code.
  135. (defvar smie-warning-count 0)
  136. (defun smie-set-prec2tab (table x y val &optional override)
  137. (cl-assert (and x y))
  138. (let* ((key (cons x y))
  139. (old (gethash key table)))
  140. (if (and old (not (eq old val)))
  141. (if (and override (gethash key override))
  142. ;; FIXME: The override is meant to resolve ambiguities,
  143. ;; but it also hides real conflicts. It would be great to
  144. ;; be able to distinguish the two cases so that overrides
  145. ;; don't hide real conflicts.
  146. (puthash key (gethash key override) table)
  147. (display-warning 'smie (format "Conflict: %s %s/%s %s" x old val y))
  148. (cl-incf smie-warning-count))
  149. (puthash key val table))))
  150. (put 'smie-precs->prec2 'pure t)
  151. (defun smie-precs->prec2 (precs)
  152. "Compute a 2D precedence table from a list of precedences.
  153. PRECS should be a list, sorted by precedence (e.g. \"+\" will
  154. come before \"*\"), of elements of the form \(left OP ...)
  155. or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
  156. one of those elements share the same precedence level and associativity."
  157. (let ((prec2-table (make-hash-table :test 'equal)))
  158. (dolist (prec precs)
  159. (dolist (op (cdr prec))
  160. (let ((selfrule (cdr (assq (car prec)
  161. '((left . >) (right . <) (assoc . =))))))
  162. (when selfrule
  163. (dolist (other-op (cdr prec))
  164. (smie-set-prec2tab prec2-table op other-op selfrule))))
  165. (let ((op1 '<) (op2 '>))
  166. (dolist (other-prec precs)
  167. (if (eq prec other-prec)
  168. (setq op1 '> op2 '<)
  169. (dolist (other-op (cdr other-prec))
  170. (smie-set-prec2tab prec2-table op other-op op2)
  171. (smie-set-prec2tab prec2-table other-op op op1)))))))
  172. prec2-table))
  173. (put 'smie-merge-prec2s 'pure t)
  174. (defun smie-merge-prec2s (&rest tables)
  175. (if (null (cdr tables))
  176. (car tables)
  177. (let ((prec2 (make-hash-table :test 'equal)))
  178. (dolist (table tables)
  179. (maphash (lambda (k v)
  180. (if (consp k)
  181. (smie-set-prec2tab prec2 (car k) (cdr k) v)
  182. (if (and (gethash k prec2)
  183. (not (equal (gethash k prec2) v)))
  184. (error "Conflicting values for %s property" k)
  185. (puthash k v prec2))))
  186. table))
  187. prec2)))
  188. (put 'smie-bnf->prec2 'pure t)
  189. (defun smie-bnf->prec2 (bnf &rest resolvers)
  190. "Convert the BNF grammar into a prec2 table.
  191. BNF is a list of nonterminal definitions of the form:
  192. \(NONTERM RHS1 RHS2 ...)
  193. where each RHS is a (non-empty) list of terminals (aka tokens) or non-terminals.
  194. Not all grammars are accepted:
  195. - an RHS cannot be an empty list (this is not needed, since SMIE allows all
  196. non-terminals to match the empty string anyway).
  197. - an RHS cannot have 2 consecutive non-terminals: between each non-terminal
  198. needs to be a terminal (aka token). This is a fundamental limitation of
  199. the parsing technology used (operator precedence grammar).
  200. Additionally, conflicts can occur:
  201. - The returned prec2 table holds constraints between pairs of
  202. token, and for any given pair only one constraint can be
  203. present, either: T1 < T2, T1 = T2, or T1 > T2.
  204. - A token can either be an `opener' (something similar to an open-paren),
  205. a `closer' (like a close-paren), or `neither' of the two (e.g. an infix
  206. operator, or an inner token like \"else\").
  207. Conflicts can be resolved via RESOLVERS, which is a list of elements that can
  208. be either:
  209. - a precs table (see `smie-precs->prec2') to resolve conflicting constraints,
  210. - a constraint (T1 REL T2) where REL is one of = < or >."
  211. ;; FIXME: Add repetition operator like (repeat <separator> <elems>).
  212. ;; Maybe also add (or <elem1> <elem2>...) for things like
  213. ;; (exp (exp (or "+" "*" "=" ..) exp)).
  214. ;; Basically, make it EBNF (except for the specification of a separator in
  215. ;; the repetition, maybe).
  216. (let* ((nts (mapcar 'car bnf)) ;Non-terminals.
  217. (first-ops-table ())
  218. (last-ops-table ())
  219. (first-nts-table ())
  220. (last-nts-table ())
  221. (smie-warning-count 0)
  222. (prec2 (make-hash-table :test 'equal))
  223. (override
  224. (let ((precs ())
  225. (over (make-hash-table :test 'equal)))
  226. (dolist (resolver resolvers)
  227. (cond
  228. ((and (= 3 (length resolver)) (memq (nth 1 resolver) '(= < >)))
  229. (smie-set-prec2tab
  230. over (nth 0 resolver) (nth 2 resolver) (nth 1 resolver)))
  231. ((memq (caar resolver) '(left right assoc nonassoc))
  232. (push resolver precs))
  233. (t (error "Unknown resolver %S" resolver))))
  234. (apply #'smie-merge-prec2s over
  235. (mapcar 'smie-precs->prec2 precs))))
  236. again)
  237. (dolist (rules bnf)
  238. (let ((nt (car rules))
  239. (last-ops ())
  240. (first-ops ())
  241. (last-nts ())
  242. (first-nts ()))
  243. (dolist (rhs (cdr rules))
  244. (unless (consp rhs)
  245. (signal 'wrong-type-argument `(consp ,rhs)))
  246. (if (not (member (car rhs) nts))
  247. (cl-pushnew (car rhs) first-ops)
  248. (cl-pushnew (car rhs) first-nts)
  249. (when (consp (cdr rhs))
  250. ;; If the first is not an OP we add the second (which
  251. ;; should be an OP if BNF is an "operator grammar").
  252. ;; Strictly speaking, this should only be done if the
  253. ;; first is a non-terminal which can expand to a phrase
  254. ;; without any OP in it, but checking doesn't seem worth
  255. ;; the trouble, and it lets the writer of the BNF
  256. ;; be a bit more sloppy by skipping uninteresting base
  257. ;; cases which are terminals but not OPs.
  258. (when (member (cadr rhs) nts)
  259. (error "Adjacent non-terminals: %s %s"
  260. (car rhs) (cadr rhs)))
  261. (cl-pushnew (cadr rhs) first-ops)))
  262. (let ((shr (reverse rhs)))
  263. (if (not (member (car shr) nts))
  264. (cl-pushnew (car shr) last-ops)
  265. (cl-pushnew (car shr) last-nts)
  266. (when (consp (cdr shr))
  267. (when (member (cadr shr) nts)
  268. (error "Adjacent non-terminals: %s %s"
  269. (cadr shr) (car shr)))
  270. (cl-pushnew (cadr shr) last-ops)))))
  271. (push (cons nt first-ops) first-ops-table)
  272. (push (cons nt last-ops) last-ops-table)
  273. (push (cons nt first-nts) first-nts-table)
  274. (push (cons nt last-nts) last-nts-table)))
  275. ;; Compute all first-ops by propagating the initial ones we have
  276. ;; now, according to first-nts.
  277. (setq again t)
  278. (while (prog1 again (setq again nil))
  279. (dolist (first-nts first-nts-table)
  280. (let* ((nt (pop first-nts))
  281. (first-ops (assoc nt first-ops-table)))
  282. (dolist (first-nt first-nts)
  283. (dolist (op (cdr (assoc first-nt first-ops-table)))
  284. (unless (member op first-ops)
  285. (setq again t)
  286. (push op (cdr first-ops))))))))
  287. ;; Same thing for last-ops.
  288. (setq again t)
  289. (while (prog1 again (setq again nil))
  290. (dolist (last-nts last-nts-table)
  291. (let* ((nt (pop last-nts))
  292. (last-ops (assoc nt last-ops-table)))
  293. (dolist (last-nt last-nts)
  294. (dolist (op (cdr (assoc last-nt last-ops-table)))
  295. (unless (member op last-ops)
  296. (setq again t)
  297. (push op (cdr last-ops))))))))
  298. ;; Now generate the 2D precedence table.
  299. (dolist (rules bnf)
  300. (dolist (rhs (cdr rules))
  301. (while (cdr rhs)
  302. (cond
  303. ((member (car rhs) nts)
  304. (dolist (last (cdr (assoc (car rhs) last-ops-table)))
  305. (smie-set-prec2tab prec2 last (cadr rhs) '> override)))
  306. ((member (cadr rhs) nts)
  307. (dolist (first (cdr (assoc (cadr rhs) first-ops-table)))
  308. (smie-set-prec2tab prec2 (car rhs) first '< override))
  309. (if (and (cddr rhs) (not (member (car (cddr rhs)) nts)))
  310. (smie-set-prec2tab prec2 (car rhs) (car (cddr rhs))
  311. '= override)))
  312. (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
  313. (setq rhs (cdr rhs)))))
  314. ;; Keep track of which tokens are openers/closer, so they can get a nil
  315. ;; precedence in smie-prec2->grammar.
  316. (puthash :smie-open/close-alist (smie-bnf--classify bnf) prec2)
  317. (puthash :smie-closer-alist (smie-bnf--closer-alist bnf) prec2)
  318. (if (> smie-warning-count 0)
  319. (display-warning
  320. 'smie (format "Total: %d warnings" smie-warning-count)))
  321. prec2))
  322. ;; (defun smie-prec2-closer-alist (prec2 include-inners)
  323. ;; "Build a closer-alist from a PREC2 table.
  324. ;; The return value is in the same form as `smie-closer-alist'.
  325. ;; INCLUDE-INNERS if non-nil means that inner keywords will be included
  326. ;; in the table, e.g. the table will include things like (\"if\" . \"else\")."
  327. ;; (let* ((non-openers '())
  328. ;; (non-closers '())
  329. ;; ;; For each keyword, this gives the matching openers, if any.
  330. ;; (openers (make-hash-table :test 'equal))
  331. ;; (closers '())
  332. ;; (done nil))
  333. ;; ;; First, find the non-openers and non-closers.
  334. ;; (maphash (lambda (k v)
  335. ;; (unless (or (eq v '<) (member (cdr k) non-openers))
  336. ;; (push (cdr k) non-openers))
  337. ;; (unless (or (eq v '>) (member (car k) non-closers))
  338. ;; (push (car k) non-closers)))
  339. ;; prec2)
  340. ;; ;; Then find the openers and closers.
  341. ;; (maphash (lambda (k _)
  342. ;; (unless (member (car k) non-openers)
  343. ;; (puthash (car k) (list (car k)) openers))
  344. ;; (unless (or (member (cdr k) non-closers)
  345. ;; (member (cdr k) closers))
  346. ;; (push (cdr k) closers)))
  347. ;; prec2)
  348. ;; ;; Then collect the matching elements.
  349. ;; (while (not done)
  350. ;; (setq done t)
  351. ;; (maphash (lambda (k v)
  352. ;; (when (eq v '=)
  353. ;; (let ((aopeners (gethash (car k) openers))
  354. ;; (dopeners (gethash (cdr k) openers))
  355. ;; (new nil))
  356. ;; (dolist (o aopeners)
  357. ;; (unless (member o dopeners)
  358. ;; (setq new t)
  359. ;; (push o dopeners)))
  360. ;; (when new
  361. ;; (setq done nil)
  362. ;; (puthash (cdr k) dopeners openers)))))
  363. ;; prec2))
  364. ;; ;; Finally, dump the resulting table.
  365. ;; (let ((alist '()))
  366. ;; (maphash (lambda (k v)
  367. ;; (when (or include-inners (member k closers))
  368. ;; (dolist (opener v)
  369. ;; (unless (equal opener k)
  370. ;; (push (cons opener k) alist)))))
  371. ;; openers)
  372. ;; alist)))
  373. (defun smie-bnf--closer-alist (bnf &optional no-inners)
  374. ;; We can also build this closer-alist table from a prec2 table,
  375. ;; but it takes more work, and the order is unpredictable, which
  376. ;; is a problem for smie-close-block.
  377. ;; More convenient would be to build it from a levels table since we
  378. ;; always have this table (contrary to the BNF), but it has all the
  379. ;; disadvantages of the prec2 case plus the disadvantage that the levels
  380. ;; table has lost some info which would result in extra invalid pairs.
  381. "Build a closer-alist from a BNF table.
  382. The return value is in the same form as `smie-closer-alist'.
  383. NO-INNERS if non-nil means that inner keywords will be excluded
  384. from the table, e.g. the table will not include things like (\"if\" . \"else\")."
  385. (let ((nts (mapcar #'car bnf)) ;non terminals.
  386. (alist '()))
  387. (dolist (nt bnf)
  388. (dolist (rhs (cdr nt))
  389. (unless (or (< (length rhs) 2) (member (car rhs) nts))
  390. (if no-inners
  391. (let ((last (car (last rhs))))
  392. (unless (member last nts)
  393. (cl-pushnew (cons (car rhs) last) alist :test #'equal)))
  394. ;; Reverse so that the "real" closer gets there first,
  395. ;; which is important for smie-close-block.
  396. (dolist (term (reverse (cdr rhs)))
  397. (unless (member term nts)
  398. (cl-pushnew (cons (car rhs) term) alist :test #'equal)))))))
  399. (nreverse alist)))
  400. (defun smie-bnf--set-class (table token class)
  401. (let ((prev (gethash token table class)))
  402. (puthash token
  403. (cond
  404. ((eq prev class) class)
  405. ((eq prev t) t) ;Non-terminal.
  406. (t (display-warning
  407. 'smie
  408. (format "token %s is both %s and %s" token class prev))
  409. 'neither))
  410. table)))
  411. (defun smie-bnf--classify (bnf)
  412. "Return a table classifying terminals.
  413. Each terminal can either be an `opener', a `closer', or `neither'."
  414. (let ((table (make-hash-table :test #'equal))
  415. (alist '()))
  416. (dolist (category bnf)
  417. (puthash (car category) t table)) ;Mark non-terminals.
  418. (dolist (category bnf)
  419. (dolist (rhs (cdr category))
  420. (if (null (cdr rhs))
  421. (smie-bnf--set-class table (pop rhs) 'neither)
  422. (smie-bnf--set-class table (pop rhs) 'opener)
  423. (while (cdr rhs) ;Remove internals.
  424. (smie-bnf--set-class table (pop rhs) 'neither))
  425. (smie-bnf--set-class table (pop rhs) 'closer))))
  426. (maphash (lambda (tok v)
  427. (when (memq v '(closer opener))
  428. (push (cons tok v) alist)))
  429. table)
  430. alist))
  431. (defun smie-debug--prec2-cycle (csts)
  432. "Return a cycle in CSTS, assuming there's one.
  433. CSTS is a list of pairs representing arcs in a graph."
  434. ;; A PATH is of the form (START . REST) where REST is a reverse
  435. ;; list of nodes through which the path goes.
  436. (let ((paths (mapcar (lambda (pair) (list (car pair) (cdr pair))) csts))
  437. (cycle nil))
  438. (while (null cycle)
  439. (dolist (path (prog1 paths (setq paths nil)))
  440. (dolist (cst csts)
  441. (when (eq (car cst) (nth 1 path))
  442. (if (eq (cdr cst) (car path))
  443. (setq cycle path)
  444. (push (cons (car path) (cons (cdr cst) (cdr path)))
  445. paths))))))
  446. (cons (car cycle) (nreverse (cdr cycle)))))
  447. (defun smie-debug--describe-cycle (table cycle)
  448. (let ((names
  449. (mapcar (lambda (val)
  450. (let ((res nil))
  451. (dolist (elem table)
  452. (if (eq (cdr elem) val)
  453. (push (concat "." (car elem)) res))
  454. (if (eq (cddr elem) val)
  455. (push (concat (car elem) ".") res)))
  456. (cl-assert res)
  457. res))
  458. cycle)))
  459. (mapconcat
  460. (lambda (elems) (mapconcat 'identity elems "="))
  461. (append names (list (car names)))
  462. " < ")))
  463. ;; (defun smie-check-grammar (grammar prec2 &optional dummy)
  464. ;; (maphash (lambda (k v)
  465. ;; (when (consp k)
  466. ;; (let ((left (nth 2 (assoc (car k) grammar)))
  467. ;; (right (nth 1 (assoc (cdr k) grammar))))
  468. ;; (when (and left right)
  469. ;; (cond
  470. ;; ((< left right) (cl-assert (eq v '<)))
  471. ;; ((> left right) (cl-assert (eq v '>)))
  472. ;; (t (cl-assert (eq v '=))))))))
  473. ;; prec2))
  474. (put 'smie-prec2->grammar 'pure t)
  475. (defun smie-prec2->grammar (prec2)
  476. "Take a 2D precedence table and turn it into an alist of precedence levels.
  477. PREC2 is a table as returned by `smie-precs->prec2' or
  478. `smie-bnf->prec2'."
  479. ;; For each operator, we create two "variables" (corresponding to
  480. ;; the left and right precedence level), which are represented by
  481. ;; cons cells. Those are the very cons cells that appear in the
  482. ;; final `table'. The value of each "variable" is kept in the `car'.
  483. (let ((table ())
  484. (csts ())
  485. (eqs ()))
  486. ;; From `prec2' we construct a list of constraints between
  487. ;; variables (aka "precedence levels"). These can be either
  488. ;; equality constraints (in `eqs') or `<' constraints (in `csts').
  489. (maphash (lambda (k v)
  490. (when (consp k)
  491. (let ((tmp (assoc (car k) table))
  492. x y)
  493. (if tmp
  494. (setq x (cddr tmp))
  495. (setq x (cons nil nil))
  496. (push (cons (car k) (cons nil x)) table))
  497. (if (setq tmp (assoc (cdr k) table))
  498. (setq y (cdr tmp))
  499. (setq y (cons nil (cons nil nil)))
  500. (push (cons (cdr k) y) table))
  501. (pcase v
  502. (`= (push (cons x y) eqs))
  503. (`< (push (cons x y) csts))
  504. (`> (push (cons y x) csts))
  505. (_ (error "SMIE error: prec2 has %S↦%S which ∉ {<,+,>}"
  506. k v))))))
  507. prec2)
  508. ;; First process the equality constraints.
  509. (let ((eqs eqs))
  510. (while eqs
  511. (let ((from (caar eqs))
  512. (to (cdar eqs)))
  513. (setq eqs (cdr eqs))
  514. (if (eq to from)
  515. nil ;Nothing to do.
  516. (dolist (other-eq eqs)
  517. (if (eq from (cdr other-eq)) (setcdr other-eq to))
  518. (when (eq from (car other-eq))
  519. ;; This can happen because of `assoc' settings in precs
  520. ;; or because of a rhs like ("op" foo "op").
  521. (setcar other-eq to)))
  522. (dolist (cst csts)
  523. (if (eq from (cdr cst)) (setcdr cst to))
  524. (if (eq from (car cst)) (setcar cst to)))))))
  525. ;; Then eliminate trivial constraints iteratively.
  526. (let ((i 0))
  527. (while csts
  528. (let ((rhvs (mapcar 'cdr csts))
  529. (progress nil))
  530. (dolist (cst csts)
  531. (unless (memq (car cst) rhvs)
  532. (setq progress t)
  533. ;; We could give each var in a given iteration the same value,
  534. ;; but we can also give them arbitrarily different values.
  535. ;; Basically, these are vars between which there is no
  536. ;; constraint (neither equality nor inequality), so
  537. ;; anything will do.
  538. ;; We give them arbitrary values, which means that we
  539. ;; replace the "no constraint" case with either > or <
  540. ;; but not =. The reason we do that is so as to try and
  541. ;; distinguish associative operators (which will have
  542. ;; left = right).
  543. (unless (caar cst)
  544. (setcar (car cst) i)
  545. ;; (smie-check-grammar table prec2 'step1)
  546. (cl-incf i))
  547. (setq csts (delq cst csts))))
  548. (unless progress
  549. (error "Can't resolve the precedence cycle: %s"
  550. (smie-debug--describe-cycle
  551. table (smie-debug--prec2-cycle csts)))))
  552. (cl-incf i 10))
  553. ;; Propagate equality constraints back to their sources.
  554. (dolist (eq (nreverse eqs))
  555. (when (null (cadr eq))
  556. ;; There's an equality constraint, but we still haven't given
  557. ;; it a value: that means it binds tighter than anything else,
  558. ;; and it can't be an opener/closer (those don't have equality
  559. ;; constraints).
  560. ;; So set it here rather than below since doing it below
  561. ;; makes it more difficult to obey the equality constraints.
  562. (setcar (cdr eq) i)
  563. (cl-incf i))
  564. (cl-assert (or (null (caar eq)) (eq (caar eq) (cadr eq))))
  565. (setcar (car eq) (cadr eq))
  566. ;; (smie-check-grammar table prec2 'step2)
  567. )
  568. ;; Finally, fill in the remaining vars (which did not appear on the
  569. ;; left side of any < constraint).
  570. (dolist (x table)
  571. (unless (nth 1 x)
  572. (setf (nth 1 x) i)
  573. (cl-incf i)) ;See other (cl-incf i) above.
  574. (unless (nth 2 x)
  575. (setf (nth 2 x) i)
  576. (cl-incf i)))) ;See other (cl-incf i) above.
  577. ;; Mark closers and openers.
  578. (dolist (x (gethash :smie-open/close-alist prec2))
  579. (let* ((token (car x))
  580. (cons (pcase (cdr x)
  581. (`closer (cddr (assoc token table)))
  582. (`opener (cdr (assoc token table))))))
  583. ;; `cons' can be nil for openers/closers which only contain
  584. ;; "atomic" elements.
  585. (when cons
  586. (cl-assert (numberp (car cons)))
  587. (setf (car cons) (list (car cons))))))
  588. (let ((ca (gethash :smie-closer-alist prec2)))
  589. (when ca (push (cons :smie-closer-alist ca) table)))
  590. ;; (smie-check-grammar table prec2 'step3)
  591. table))
  592. ;;; Parsing using a precedence level table.
  593. (defvar smie-grammar 'unset
  594. "List of token parsing info.
  595. This list is normally built by `smie-prec2->grammar'.
  596. Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
  597. Parsing is done using an operator precedence parser.
  598. LEFT-LEVEL and RIGHT-LEVEL can be either numbers or a list, where a list
  599. means that this operator does not bind on the corresponding side,
  600. e.g. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
  601. an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
  602. like a close-paren.")
  603. (defvar smie-forward-token-function #'smie-default-forward-token
  604. "Function to scan forward for the next token.
  605. Called with no argument should return a token and move to its end.
  606. If no token is found, return nil or the empty string.
  607. It can return nil when bumping into a parenthesis, which lets SMIE
  608. use syntax-tables to handle them in efficient C code.")
  609. (defvar smie-backward-token-function #'smie-default-backward-token
  610. "Function to scan backward the previous token.
  611. Same calling convention as `smie-forward-token-function' except
  612. it should move backward to the beginning of the previous token.")
  613. (defalias 'smie-op-left 'car)
  614. (defalias 'smie-op-right 'cadr)
  615. (defun smie-default-backward-token ()
  616. (forward-comment (- (point)))
  617. (buffer-substring-no-properties
  618. (point)
  619. (progn (if (zerop (skip-syntax-backward "."))
  620. (skip-syntax-backward "w_'"))
  621. (point))))
  622. (defun smie-default-forward-token ()
  623. (forward-comment (point-max))
  624. (buffer-substring-no-properties
  625. (point)
  626. (progn (if (zerop (skip-syntax-forward "."))
  627. (skip-syntax-forward "w_'"))
  628. (point))))
  629. (defun smie--associative-p (toklevels)
  630. ;; in "a + b + c" we want to stop at each +, but in
  631. ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
  632. ;; To distinguish the two cases, we made smie-prec2->grammar choose
  633. ;; different levels for each part of "if a then b else c", so that
  634. ;; by checking if the left-level is equal to the right level, we can
  635. ;; figure out that it's an associative operator.
  636. ;; This is not 100% foolproof, tho, since the "elsif" will have to have
  637. ;; equal left and right levels (since it's optional), so smie-next-sexp
  638. ;; has to be careful to distinguish those different cases.
  639. (eq (smie-op-left toklevels) (smie-op-right toklevels)))
  640. (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
  641. "Skip over one sexp.
  642. NEXT-TOKEN is a function of no argument that moves forward by one
  643. token (after skipping comments if needed) and returns it.
  644. NEXT-SEXP is a lower-level function to skip one sexp.
  645. OP-FORW is the accessor to the forward level of the level data.
  646. OP-BACK is the accessor to the backward level of the level data.
  647. HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
  648. first token we see is an operator, skip over its left-hand-side argument.
  649. HALFSEXP can also be a token, in which case it means to parse as if
  650. we had just successfully passed this token.
  651. Possible return values:
  652. (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
  653. is too high. FORW-LEVEL is the forw-level of TOKEN,
  654. POS is its start position in the buffer.
  655. (t POS TOKEN): same thing when we bump on the wrong side of a paren.
  656. Instead of t, the `car' can also be some other non-nil non-number value.
  657. (nil POS TOKEN): we skipped over a paren-like pair.
  658. nil: we skipped over an identifier, matched parentheses, ..."
  659. (catch 'return
  660. (let ((levels
  661. (if (stringp halfsexp)
  662. (prog1 (list (cdr (assoc halfsexp smie-grammar)))
  663. (setq halfsexp nil)))))
  664. (while
  665. (let* ((pos (point))
  666. (token (funcall next-token))
  667. (toklevels (cdr (assoc token smie-grammar))))
  668. (cond
  669. ((null toklevels)
  670. (when (zerop (length token))
  671. (condition-case err
  672. (progn (funcall next-sexp 1) nil)
  673. (scan-error
  674. (let* ((epos1 (nth 2 err))
  675. (epos (if (<= (point) epos1) (nth 3 err) epos1)))
  676. (goto-char pos)
  677. (throw 'return
  678. (list t epos
  679. (buffer-substring-no-properties
  680. epos
  681. (+ epos (if (< (point) epos) -1 1))))))))
  682. (if (eq pos (point))
  683. ;; We did not move, so let's abort the loop.
  684. (throw 'return (list t (point))))))
  685. ((not (numberp (funcall op-back toklevels)))
  686. ;; A token like a paren-close.
  687. (cl-assert (numberp ; Otherwise, why mention it in smie-grammar.
  688. (funcall op-forw toklevels)))
  689. (push toklevels levels))
  690. (t
  691. (while (and levels (< (funcall op-back toklevels)
  692. (funcall op-forw (car levels))))
  693. (setq levels (cdr levels)))
  694. (cond
  695. ((null levels)
  696. (if (and halfsexp (numberp (funcall op-forw toklevels)))
  697. (push toklevels levels)
  698. (throw 'return
  699. (prog1 (list (or (funcall op-forw toklevels) t)
  700. (point) token)
  701. (goto-char pos)))))
  702. (t
  703. (let ((lastlevels levels))
  704. (if (and levels (= (funcall op-back toklevels)
  705. (funcall op-forw (car levels))))
  706. (setq levels (cdr levels)))
  707. ;; We may have found a match for the previously pending
  708. ;; operator. Is this the end?
  709. (cond
  710. ;; Keep looking as long as we haven't matched the
  711. ;; topmost operator.
  712. (levels
  713. (cond
  714. ((numberp (funcall op-forw toklevels))
  715. (push toklevels levels))
  716. ;; FIXME: For some languages, we can express the grammar
  717. ;; OK, but next-sexp doesn't stop where we'd want it to.
  718. ;; E.g. in SML, we'd want to stop right in front of
  719. ;; "local" if we're scanning (both forward and backward)
  720. ;; from a "val/fun/..." at the same level.
  721. ;; Same for Pascal/Modula2's "procedure" w.r.t
  722. ;; "type/var/const".
  723. ;;
  724. ;; ((and (functionp (cadr (funcall op-forw toklevels)))
  725. ;; (funcall (cadr (funcall op-forw toklevels))
  726. ;; levels))
  727. ;; (setq levels nil))
  728. ))
  729. ;; We matched the topmost operator. If the new operator
  730. ;; is the last in the corresponding BNF rule, we're done.
  731. ((not (numberp (funcall op-forw toklevels)))
  732. ;; It is the last element, let's stop here.
  733. (throw 'return (list nil (point) token)))
  734. ;; If the new operator is not the last in the BNF rule,
  735. ;; and is not associative, it's one of the inner operators
  736. ;; (like the "in" in "let .. in .. end"), so keep looking.
  737. ((not (smie--associative-p toklevels))
  738. (push toklevels levels))
  739. ;; The new operator is associative. Two cases:
  740. ;; - it's really just an associative operator (like + or ;)
  741. ;; in which case we should have stopped right before.
  742. ((and lastlevels
  743. (smie--associative-p (car lastlevels)))
  744. (throw 'return
  745. (prog1 (list (or (funcall op-forw toklevels) t)
  746. (point) token)
  747. (goto-char pos))))
  748. ;; - it's an associative operator within a larger construct
  749. ;; (e.g. an "elsif"), so we should just ignore it and keep
  750. ;; looking for the closing element.
  751. (t (setq levels lastlevels))))))))
  752. levels)
  753. (setq halfsexp nil)))))
  754. (defun smie-backward-sexp (&optional halfsexp)
  755. "Skip over one sexp.
  756. HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
  757. first token we see is an operator, skip over its left-hand-side argument.
  758. HALFSEXP can also be a token, in which case we should skip the text
  759. assuming it is the left-hand-side argument of that token.
  760. Possible return values:
  761. (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
  762. is too high. LEFT-LEVEL is the left-level of TOKEN,
  763. POS is its start position in the buffer.
  764. (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
  765. Instead of t, the `car' can also be some other non-nil non-number value.
  766. (nil POS TOKEN): we skipped over a paren-like pair.
  767. nil: we skipped over an identifier, matched parentheses, ..."
  768. (smie-next-sexp
  769. (indirect-function smie-backward-token-function)
  770. (indirect-function #'backward-sexp)
  771. (indirect-function #'smie-op-left)
  772. (indirect-function #'smie-op-right)
  773. halfsexp))
  774. (defun smie-forward-sexp (&optional halfsexp)
  775. "Skip over one sexp.
  776. HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
  777. first token we see is an operator, skip over its right-hand-side argument.
  778. HALFSEXP can also be a token, in which case we should skip the text
  779. assuming it is the right-hand-side argument of that token.
  780. Possible return values:
  781. (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
  782. is too high. RIGHT-LEVEL is the right-level of TOKEN,
  783. POS is its end position in the buffer.
  784. (t POS TOKEN): same thing but for a close-paren or the end of buffer.
  785. Instead of t, the `car' can also be some other non-nil non-number value.
  786. (nil POS TOKEN): we skipped over a paren-like pair.
  787. nil: we skipped over an identifier, matched parentheses, ..."
  788. (smie-next-sexp
  789. (indirect-function smie-forward-token-function)
  790. (indirect-function #'forward-sexp)
  791. (indirect-function #'smie-op-right)
  792. (indirect-function #'smie-op-left)
  793. halfsexp))
  794. ;;; Miscellaneous commands using the precedence parser.
  795. (defun smie-backward-sexp-command (n)
  796. "Move backward through N logical elements."
  797. (interactive "^p")
  798. (smie-forward-sexp-command (- n)))
  799. (defun smie-forward-sexp-command (n)
  800. "Move forward through N logical elements."
  801. (interactive "^p")
  802. (let ((forw (> n 0))
  803. (forward-sexp-function nil))
  804. (while (/= n 0)
  805. (setq n (- n (if forw 1 -1)))
  806. (let ((pos (point))
  807. (res (if forw
  808. (smie-forward-sexp 'halfsexp)
  809. (smie-backward-sexp 'halfsexp))))
  810. (if (and (car res) (= pos (point)) (not (if forw (eobp) (bobp))))
  811. (signal 'scan-error
  812. (list "Containing expression ends prematurely"
  813. (cadr res) (cadr res)))
  814. nil)))))
  815. (defvar smie-closer-alist nil
  816. "Alist giving the closer corresponding to an opener.")
  817. (defun smie-close-block ()
  818. "Close the closest surrounding block."
  819. (interactive)
  820. (let ((closer
  821. (save-excursion
  822. (backward-up-list 1)
  823. (if (looking-at "\\s(")
  824. (string (cdr (syntax-after (point))))
  825. (let* ((open (funcall smie-forward-token-function))
  826. (closer (cdr (assoc open smie-closer-alist)))
  827. (levels (list (assoc open smie-grammar)))
  828. (seen '())
  829. (found '()))
  830. (cond
  831. ;; Even if we improve the auto-computation of closers,
  832. ;; there are still cases where we need manual
  833. ;; intervention, e.g. for Octave's use of `until'
  834. ;; as a pseudo-closer of `do'.
  835. (closer)
  836. ((or (equal levels '(nil)) (numberp (nth 1 (car levels))))
  837. (error "Doesn't look like a block"))
  838. (t
  839. ;; Now that smie-setup automatically sets smie-closer-alist
  840. ;; from the BNF, this is not really needed any more.
  841. (while levels
  842. (let ((level (pop levels)))
  843. (dolist (other smie-grammar)
  844. (when (and (eq (nth 2 level) (nth 1 other))
  845. (not (memq other seen)))
  846. (push other seen)
  847. (if (numberp (nth 2 other))
  848. (push other levels)
  849. (push (car other) found))))))
  850. (cond
  851. ((null found) (error "No known closer for opener %s" open))
  852. ;; What should we do if there are various closers?
  853. (t (car found))))))))))
  854. (unless (save-excursion (skip-chars-backward " \t") (bolp))
  855. (newline))
  856. (insert closer)
  857. (if (save-excursion (skip-chars-forward " \t") (eolp))
  858. (indent-according-to-mode)
  859. (reindent-then-newline-and-indent))))
  860. (defun smie-down-list (&optional arg)
  861. "Move forward down one level paren-like blocks. Like `down-list'.
  862. With argument ARG, do this that many times.
  863. A negative argument means move backward but still go down a level.
  864. This command assumes point is not in a string or comment."
  865. (interactive "p")
  866. (let ((start (point))
  867. (inc (if (< arg 0) -1 1))
  868. (offset (if (< arg 0) 1 0))
  869. (next-token (if (< arg 0)
  870. smie-backward-token-function
  871. smie-forward-token-function)))
  872. (while (/= arg 0)
  873. (setq arg (- arg inc))
  874. (while
  875. (let* ((pos (point))
  876. (token (funcall next-token))
  877. (levels (assoc token smie-grammar)))
  878. (cond
  879. ((zerop (length token))
  880. (if (if (< inc 0) (looking-back "\\s(\\|\\s)" (1- (point)))
  881. (looking-at "\\s(\\|\\s)"))
  882. ;; Go back to `start' in case of an error. This presumes
  883. ;; none of the token we've found until now include a ( or ).
  884. (progn (goto-char start) (down-list inc) nil)
  885. (forward-sexp inc)
  886. (/= (point) pos)))
  887. ((and levels (not (numberp (nth (+ 1 offset) levels)))) nil)
  888. ((and levels (not (numberp (nth (- 2 offset) levels))))
  889. (let ((end (point)))
  890. (goto-char start)
  891. (signal 'scan-error
  892. (list "Containing expression ends prematurely"
  893. pos end))))
  894. (t)))))))
  895. (defvar smie-blink-matching-triggers '(?\s ?\n)
  896. "Chars which might trigger `blink-matching-open'.
  897. These can include the final chars of end-tokens, or chars that are
  898. typically inserted right after an end token.
  899. I.e. a good choice can be:
  900. (delete-dups
  901. (mapcar (lambda (kw) (aref (cdr kw) (1- (length (cdr kw)))))
  902. smie-closer-alist))")
  903. (defcustom smie-blink-matching-inners t
  904. "Whether SMIE should blink to matching opener for inner keywords.
  905. If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
  906. :type 'boolean
  907. :group 'smie)
  908. (defun smie-blink-matching-check (start end)
  909. (save-excursion
  910. (goto-char end)
  911. (let ((ender (funcall smie-backward-token-function)))
  912. (cond
  913. ((not (and ender (rassoc ender smie-closer-alist)))
  914. ;; This is not one of the begin..end we know how to check.
  915. (blink-matching-check-mismatch start end))
  916. ((not start) t)
  917. ((eq t (car (rassoc ender smie-closer-alist))) nil)
  918. (t
  919. (goto-char start)
  920. (let ((starter (funcall smie-forward-token-function)))
  921. (not (member (cons starter ender) smie-closer-alist))))))))
  922. (defun smie-blink-matching-open ()
  923. "Blink the matching opener when applicable.
  924. This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
  925. (let ((pos (point)) ;Position after the close token.
  926. token)
  927. (when (and blink-matching-paren
  928. smie-closer-alist ; Optimization.
  929. (or (eq (char-before) last-command-event) ;; Sanity check.
  930. (save-excursion
  931. (or (progn (skip-chars-backward " \t")
  932. (setq pos (point))
  933. (eq (char-before) last-command-event))
  934. (progn (skip-chars-backward " \n\t")
  935. (setq pos (point))
  936. (eq (char-before) last-command-event)))))
  937. (memq last-command-event smie-blink-matching-triggers)
  938. (not (nth 8 (syntax-ppss))))
  939. (save-excursion
  940. (setq token (funcall smie-backward-token-function))
  941. (when (and (eq (point) (1- pos))
  942. (= 1 (length token))
  943. (not (rassoc token smie-closer-alist)))
  944. ;; The trigger char is itself a token but is not one of the
  945. ;; closers (e.g. ?\; in Octave mode), so go back to the
  946. ;; previous token.
  947. (setq pos (point))
  948. (setq token (funcall smie-backward-token-function)))
  949. (when (rassoc token smie-closer-alist)
  950. ;; We're after a close token. Let's still make sure we
  951. ;; didn't skip a comment to find that token.
  952. (funcall smie-forward-token-function)
  953. (when (and (save-excursion
  954. ;; Skip the trigger char, if applicable.
  955. (if (eq (char-after) last-command-event)
  956. (forward-char 1))
  957. (if (eq ?\n last-command-event)
  958. ;; Skip any auto-indentation, if applicable.
  959. (skip-chars-forward " \t"))
  960. (>= (point) pos))
  961. ;; If token ends with a trigger char, don't blink for
  962. ;; anything else than this trigger char, lest we'd blink
  963. ;; both when inserting the trigger char and when
  964. ;; inserting a subsequent trigger char like SPC.
  965. (or (eq (char-before) last-command-event)
  966. (not (memq (char-before)
  967. smie-blink-matching-triggers)))
  968. ;; FIXME: For octave's "switch ... case ... case" we flash
  969. ;; `switch' at the end of the first `case' and we burp
  970. ;; "mismatch" at the end of the second `case'.
  971. (or smie-blink-matching-inners
  972. (not (numberp (nth 2 (assoc token smie-grammar))))))
  973. ;; The major mode might set blink-matching-check-function
  974. ;; buffer-locally so that interactive calls to
  975. ;; blink-matching-open work right, but let's not presume
  976. ;; that's the case.
  977. (let ((blink-matching-check-function #'smie-blink-matching-check))
  978. (blink-matching-open))))))))
  979. (defvar-local smie--matching-block-data-cache nil)
  980. (defun smie--opener/closer-at-point ()
  981. "Return (OPENER TOKEN START END) or nil.
  982. OPENER is non-nil if TOKEN is an opener and nil if it's a closer."
  983. (let* ((start (point))
  984. ;; Move to a previous position outside of a token.
  985. (_ (funcall smie-backward-token-function))
  986. ;; Move to the end of the token before point.
  987. (btok (funcall smie-forward-token-function))
  988. (bend (point)))
  989. (cond
  990. ;; Token before point is a closer?
  991. ((and (>= bend start) (rassoc btok smie-closer-alist))
  992. (funcall smie-backward-token-function)
  993. (when (< (point) start)
  994. (prog1 (list nil btok (point) bend)
  995. (goto-char bend))))
  996. ;; Token around point is an opener?
  997. ((and (> bend start) (assoc btok smie-closer-alist))
  998. (funcall smie-backward-token-function)
  999. (when (<= (point) start) (list t btok (point) bend)))
  1000. ((<= bend start)
  1001. (let ((atok (funcall smie-forward-token-function))
  1002. (aend (point)))
  1003. (cond
  1004. ((< aend start) nil) ;Hopefully shouldn't happen.
  1005. ;; Token after point is a closer?
  1006. ((assoc atok smie-closer-alist)
  1007. (funcall smie-backward-token-function)
  1008. (when (<= (point) start)
  1009. (list t atok (point) aend)))))))))
  1010. (defun smie--matching-block-data (orig &rest args)
  1011. "A function suitable for `show-paren-data-function' (which see)."
  1012. (if (or (null smie-closer-alist)
  1013. (equal (cons (point) (buffer-chars-modified-tick))
  1014. (car smie--matching-block-data-cache)))
  1015. (or (cdr smie--matching-block-data-cache)
  1016. (apply orig args))
  1017. (setq smie--matching-block-data-cache
  1018. (list (cons (point) (buffer-chars-modified-tick))))
  1019. (unless (nth 8 (syntax-ppss))
  1020. (condition-case nil
  1021. (let ((here (smie--opener/closer-at-point)))
  1022. (when (and here
  1023. (or smie-blink-matching-inners
  1024. (not (numberp
  1025. (nth (if (nth 0 here) 1 2)
  1026. (assoc (nth 1 here) smie-grammar))))))
  1027. (let ((there
  1028. (cond
  1029. ((car here) ; Opener.
  1030. (let ((data (smie-forward-sexp 'halfsexp))
  1031. (tend (point)))
  1032. (unless (car data)
  1033. (funcall smie-backward-token-function)
  1034. (list (member (cons (nth 1 here) (nth 2 data))
  1035. smie-closer-alist)
  1036. (point) tend))))
  1037. (t ;Closer.
  1038. (let ((data (smie-backward-sexp 'halfsexp))
  1039. (htok (nth 1 here)))
  1040. (if (car data)
  1041. (let* ((hprec (nth 2 (assoc htok smie-grammar)))
  1042. (ttok (nth 2 data))
  1043. (tprec (nth 1 (assoc ttok smie-grammar))))
  1044. (when (and (numberp hprec) ;Here is an inner.
  1045. (eq hprec tprec))
  1046. (goto-char (nth 1 data))
  1047. (let ((tbeg (point)))
  1048. (funcall smie-forward-token-function)
  1049. (list t tbeg (point)))))
  1050. (let ((tbeg (point)))
  1051. (funcall smie-forward-token-function)
  1052. (list (member (cons (nth 2 data) htok)
  1053. smie-closer-alist)
  1054. tbeg (point)))))))))
  1055. ;; Update the cache.
  1056. (setcdr smie--matching-block-data-cache
  1057. (list (nth 2 here) (nth 3 here)
  1058. (nth 1 there) (nth 2 there)
  1059. (not (nth 0 there)))))))
  1060. (scan-error nil))
  1061. (goto-char (caar smie--matching-block-data-cache)))
  1062. (apply #'smie--matching-block-data orig args)))
  1063. ;;; The indentation engine.
  1064. (defcustom smie-indent-basic 4
  1065. "Basic amount of indentation."
  1066. :type 'integer
  1067. :group 'smie)
  1068. (defvar smie-rules-function #'ignore
  1069. "Function providing the indentation rules.
  1070. It takes two arguments METHOD and ARG where the meaning of ARG
  1071. and the expected return value depends on METHOD.
  1072. METHOD can be:
  1073. - :after, in which case ARG is a token and the function should return the
  1074. OFFSET to use for indentation after ARG.
  1075. - :before, in which case ARG is a token and the function should return the
  1076. OFFSET to use to indent ARG itself.
  1077. - :elem, in which case the function should return either:
  1078. - the offset to use to indent function arguments (ARG = `arg')
  1079. - the basic indentation step (ARG = `basic').
  1080. - :list-intro, in which case ARG is a token and the function should return
  1081. non-nil if TOKEN is followed by a list of expressions (not separated by any
  1082. token) rather than an expression.
  1083. - :close-all, in which case ARG is a close-paren token at indentation and
  1084. the function should return non-nil if it should be aligned with the opener
  1085. of the last close-paren token on the same line, if there are multiple.
  1086. Otherwise, it will be aligned with its own opener.
  1087. When ARG is a token, the function is called with point just before that token.
  1088. A return value of nil always means to fallback on the default behavior, so the
  1089. function should return nil for arguments it does not expect.
  1090. OFFSET can be:
  1091. nil use the default indentation rule.
  1092. \(column . COLUMN) indent to column COLUMN.
  1093. NUMBER offset by NUMBER, relative to a base token
  1094. which is the current token for :after and
  1095. its parent for :before.
  1096. The functions whose name starts with \"smie-rule-\" are helper functions
  1097. designed specifically for use in this function.")
  1098. (defvar smie--hanging-eolp-function
  1099. ;; FIXME: This is a quick hack for 24.4. Don't document it and replace with
  1100. ;; a well-defined function with a cleaner interface instead!
  1101. (lambda ()
  1102. (skip-chars-forward " \t")
  1103. (or (eolp)
  1104. (and ;; (looking-at comment-start-skip) ;(bug#16041).
  1105. (forward-comment (point-max))))))
  1106. (defalias 'smie-rule-hanging-p 'smie-indent--hanging-p)
  1107. (defun smie-indent--hanging-p ()
  1108. "Return non-nil if the current token is \"hanging\".
  1109. A hanging keyword is one that's at the end of a line except it's not at
  1110. the beginning of a line."
  1111. (and (not (smie-indent--bolp))
  1112. (save-excursion
  1113. (<= (line-end-position)
  1114. (progn
  1115. (and (zerop (length (funcall smie-forward-token-function)))
  1116. (not (eobp))
  1117. ;; Could be an open-paren.
  1118. (forward-char 1))
  1119. (funcall smie--hanging-eolp-function)
  1120. (point))))))
  1121. (defalias 'smie-rule-bolp 'smie-indent--bolp)
  1122. (defun smie-indent--bolp ()
  1123. "Return non-nil if the current token is the first on the line."
  1124. (save-excursion (skip-chars-backward " \t") (bolp)))
  1125. (defun smie-indent--bolp-1 ()
  1126. ;; Like smie-indent--bolp but also returns non-nil if it's the first
  1127. ;; non-comment token. Maybe we should simply always use this?
  1128. "Return non-nil if the current token is the first on the line.
  1129. Comments are treated as spaces."
  1130. (let ((bol (line-beginning-position)))
  1131. (save-excursion
  1132. (forward-comment (- (point)))
  1133. (<= (point) bol))))
  1134. (defun smie-indent--current-column ()
  1135. "Like `current-column', but if there's a comment before us, use that."
  1136. ;; This is used, so that when we align elements, we don't get
  1137. ;; toto = { /* foo, */ a,
  1138. ;; b }
  1139. ;; but
  1140. ;; toto = { /* foo, */ a,
  1141. ;; b }
  1142. (let ((pos (point))
  1143. (lbp (line-beginning-position)))
  1144. (save-excursion
  1145. (unless (and (forward-comment -1) (>= (point) lbp))
  1146. (goto-char pos))
  1147. (current-column))))
  1148. ;; Dynamically scoped.
  1149. (defvar smie--parent) (defvar smie--after) (defvar smie--token)
  1150. (defun smie-indent--parent ()
  1151. (or smie--parent
  1152. (save-excursion
  1153. (let* ((pos (point))
  1154. (tok (funcall smie-forward-token-function)))
  1155. (unless (numberp (cadr (assoc tok smie-grammar)))
  1156. (goto-char pos))
  1157. (setq smie--parent
  1158. (or (smie-backward-sexp 'halfsexp)
  1159. (let (res)
  1160. (while (null (setq res (smie-backward-sexp))))
  1161. (list nil (point) (nth 2 res)))))))))
  1162. (defun smie-rule-parent-p (&rest parents)
  1163. "Return non-nil if the current token's parent is among PARENTS.
  1164. Only meaningful when called from within `smie-rules-function'."
  1165. (member (nth 2 (smie-indent--parent)) parents))
  1166. (defun smie-rule-next-p (&rest tokens)
  1167. "Return non-nil if the next token is among TOKENS.
  1168. Only meaningful when called from within `smie-rules-function'."
  1169. (let ((next
  1170. (save-excursion
  1171. (unless smie--after
  1172. (smie-indent-forward-token) (setq smie--after (point)))
  1173. (goto-char smie--after)
  1174. (smie-indent-forward-token))))
  1175. (member (car next) tokens)))
  1176. (defun smie-rule-prev-p (&rest tokens)
  1177. "Return non-nil if the previous token is among TOKENS."
  1178. (let ((prev (save-excursion
  1179. (smie-indent-backward-token))))
  1180. (member (car prev) tokens)))
  1181. (defun smie-rule-sibling-p ()
  1182. "Return non-nil if the parent is actually a sibling.
  1183. Only meaningful when called from within `smie-rules-function'."
  1184. (eq (car (smie-indent--parent))
  1185. (cadr (assoc smie--token smie-grammar))))
  1186. (defun smie-rule-parent (&optional offset)
  1187. "Align with parent.
  1188. If non-nil, OFFSET should be an integer giving an additional offset to apply.
  1189. Only meaningful when called from within `smie-rules-function'."
  1190. (save-excursion
  1191. (goto-char (cadr (smie-indent--parent)))
  1192. (cons 'column
  1193. (+ (or offset 0)
  1194. (smie-indent-virtual)))))
  1195. (defvar smie-rule-separator-outdent 2)
  1196. (defun smie-indent--separator-outdent ()
  1197. ;; FIXME: Here we actually have several reasonable behaviors.
  1198. ;; E.g. for a parent token of "FOO" and a separator ";" we may want to:
  1199. ;; 1- left-align ; with FOO.
  1200. ;; 2- right-align ; with FOO.
  1201. ;; 3- align content after ; with content after FOO.
  1202. ;; 4- align content plus add/remove spaces so as to align ; with FOO.
  1203. ;; Currently, we try to align the contents (option 3) which actually behaves
  1204. ;; just like option 2 (if the number of spaces after FOO and ; is equal).
  1205. (let ((afterpos (save-excursion
  1206. (let ((tok (funcall smie-forward-token-function)))
  1207. (unless tok
  1208. (with-demoted-errors
  1209. (error "smie-rule-separator: can't skip token %s"
  1210. smie--token))))
  1211. (skip-chars-forward " ")
  1212. (unless (eolp) (point)))))
  1213. (or (and afterpos
  1214. ;; This should always be true, unless
  1215. ;; smie-forward-token-function skipped a \n.
  1216. (< afterpos (line-end-position))
  1217. (- afterpos (point)))
  1218. smie-rule-separator-outdent)))
  1219. (defun smie-rule-separator (method)
  1220. "Indent current token as a \"separator\".
  1221. By \"separator\", we mean here a token whose sole purpose is to separate
  1222. various elements within some enclosing syntactic construct, and which does
  1223. not have any semantic significance in itself (i.e. it would typically no exist
  1224. as a node in an abstract syntax tree).
  1225. Such a token is expected to have an associative syntax and be closely tied
  1226. to its syntactic parent. Typical examples are \",\" in lists of arguments
  1227. \(enclosed inside parentheses), or \";\" in sequences of instructions (enclosed
  1228. in a {..} or begin..end block).
  1229. METHOD should be the method name that was passed to `smie-rules-function'.
  1230. Only meaningful when called from within `smie-rules-function'."
  1231. ;; FIXME: The code below works OK for cases where the separators
  1232. ;; are placed consistently always at beginning or always at the end,
  1233. ;; but not if some are at the beginning and others are at the end.
  1234. ;; I.e. it gets confused in cases such as:
  1235. ;; ( a
  1236. ;; , a,
  1237. ;; b
  1238. ;; , c,
  1239. ;; d
  1240. ;; )
  1241. ;;
  1242. ;; Assuming token is associative, the default rule for associative
  1243. ;; tokens (which assumes an infix operator) works fine for many cases.
  1244. ;; We mostly need to take care of the case where token is at beginning of
  1245. ;; line, in which case we want to align it with its enclosing parent.
  1246. (cond
  1247. ((and (eq method :before) (smie-rule-bolp) (not (smie-rule-sibling-p)))
  1248. (let ((parent-col (cdr (smie-rule-parent)))
  1249. (parent-pos-col ;FIXME: we knew this when computing smie--parent.
  1250. (save-excursion
  1251. (goto-char (cadr smie--parent))
  1252. (smie-indent-forward-token)
  1253. (forward-comment (point-max))
  1254. (current-column))))
  1255. (cons 'column
  1256. (max parent-col
  1257. (min parent-pos-col
  1258. (- parent-pos-col (smie-indent--separator-outdent)))))))
  1259. ((and (eq method :after) (smie-indent--bolp))
  1260. (smie-indent--separator-outdent))))
  1261. (defun smie-indent--offset (elem)
  1262. (or (funcall smie-rules-function :elem elem)
  1263. (if (not (eq elem 'basic))
  1264. (funcall smie-rules-function :elem 'basic))
  1265. smie-indent-basic))
  1266. (defun smie-indent--rule (method token
  1267. ;; FIXME: Too many parameters.
  1268. &optional after parent base-pos)
  1269. "Compute indentation column according to `smie-rules-function'.
  1270. METHOD and TOKEN are passed to `smie-rules-function'.
  1271. AFTER is the position after TOKEN, if known.
  1272. PARENT is the parent info returned by `smie-backward-sexp', if known.
  1273. BASE-POS is the position relative to which offsets should be applied."
  1274. ;; This is currently called in 3 cases:
  1275. ;; - :before opener, where rest=nil but base-pos could as well be parent.
  1276. ;; - :before other, where
  1277. ;; ; after=nil
  1278. ;; ; parent is set
  1279. ;; ; base-pos=parent
  1280. ;; - :after tok, where
  1281. ;; ; after is set; parent=nil; base-pos=point;
  1282. (save-excursion
  1283. (let ((offset (smie-indent--rule-1 method token after parent)))
  1284. (cond
  1285. ((not offset) nil)
  1286. ((eq (car-safe offset) 'column) (cdr offset))
  1287. ((integerp offset)
  1288. (+ offset
  1289. (if (null base-pos) 0
  1290. (goto-char base-pos)
  1291. ;; Use smie-indent-virtual when indenting relative to an opener:
  1292. ;; this will also by default use current-column unless
  1293. ;; that opener is hanging, but will additionally consult
  1294. ;; rules-function, so it gives it a chance to tweak indentation
  1295. ;; (e.g. by forcing indentation relative to its own parent, as in
  1296. ;; fn a => fn b => fn c =>).
  1297. ;; When parent==nil it doesn't matter because the only case
  1298. ;; where it's really used is when the base-pos is hanging anyway.
  1299. (if (or (and parent (null (car parent)))
  1300. (smie-indent--hanging-p))
  1301. (smie-indent-virtual) (current-column)))))
  1302. (t (error "Unknown indentation offset %s" offset))))))
  1303. (defun smie-indent--rule-1 (method token &optional after parent)
  1304. (let ((smie--parent parent)
  1305. (smie--token token)
  1306. (smie--after after))
  1307. (funcall smie-rules-function method token)))
  1308. (defun smie-indent-forward-token ()
  1309. "Skip token forward and return it, along with its levels."
  1310. (let ((tok (funcall smie-forward-token-function)))
  1311. (cond
  1312. ((< 0 (length tok)) (assoc tok smie-grammar))
  1313. ((looking-at "\\s(\\|\\s)\\(\\)")
  1314. (forward-char 1)
  1315. (cons (buffer-substring-no-properties (1- (point)) (point))
  1316. (if (match-end 1) '(0 nil) '(nil 0))))
  1317. ((looking-at "\\s\"\\|\\s|")
  1318. (forward-sexp 1)
  1319. nil)
  1320. ((eobp) nil)
  1321. (t (error "Bumped into unknown token")))))
  1322. (defun smie-indent-backward-token ()
  1323. "Skip token backward and return it, along with its levels."
  1324. (let ((tok (funcall smie-backward-token-function))
  1325. class)
  1326. (cond
  1327. ((< 0 (length tok)) (assoc tok smie-grammar))
  1328. ;; 4 == open paren syntax, 5 == close.
  1329. ((memq (setq class (syntax-class (syntax-after (1- (point))))) '(4 5))
  1330. (forward-char -1)
  1331. (cons (buffer-substring-no-properties (point) (1+ (point)))
  1332. (if (eq class 4) '(nil 0) '(0 nil))))
  1333. ((memq class '(7 15))
  1334. (backward-sexp 1)
  1335. nil)
  1336. ((bobp) nil)
  1337. (t (error "Bumped into unknown token")))))
  1338. (defun smie-indent-virtual ()
  1339. ;; We used to take an optional arg (with value :not-hanging) to specify that
  1340. ;; we should only use (smie-indent-calculate) if we're looking at a hanging
  1341. ;; keyword. This was a bad idea, because the virtual indent of a position
  1342. ;; should not depend on the caller, since it leads to situations where two
  1343. ;; dependent indentations get indented differently.
  1344. "Compute the virtual indentation to use for point.
  1345. This is used when we're not trying to indent point but just
  1346. need to compute the column at which point should be indented
  1347. in order to figure out the indentation of some other (further down) point."
  1348. ;; Trust pre-existing indentation on other lines.
  1349. (if (smie-indent--bolp) (current-column) (smie-indent-calculate)))
  1350. (defun smie-indent-fixindent ()
  1351. ;; Obey the `fixindent' special comment.
  1352. (and (smie-indent--bolp)
  1353. (save-excursion
  1354. (comment-normalize-vars)
  1355. (re-search-forward (concat comment-start-skip
  1356. "fixindent"
  1357. comment-end-skip)
  1358. ;; 1+ to account for the \n comment termination.
  1359. (1+ (line-end-position)) t))
  1360. (current-column)))
  1361. (defun smie-indent-bob ()
  1362. ;; Start the file at column 0.
  1363. (save-excursion
  1364. (forward-comment (- (point)))
  1365. (if (bobp) 0)))
  1366. (defun smie-indent-close ()
  1367. ;; Align close paren with opening paren.
  1368. (save-excursion
  1369. ;; (forward-comment (point-max))
  1370. (when (looking-at "\\s)")
  1371. (if (smie-indent--rule-1 :close-all
  1372. (buffer-substring-no-properties
  1373. (point) (1+ (point)))
  1374. (1+ (point)))
  1375. (while (not (zerop (skip-syntax-forward ")")))
  1376. (skip-chars-forward " \t"))
  1377. (forward-char 1))
  1378. (condition-case nil
  1379. (progn
  1380. (backward-sexp 1)
  1381. (smie-indent-virtual)) ;:not-hanging
  1382. (scan-error nil)))))
  1383. (defun smie-indent-keyword (&optional token)
  1384. "Indent point based on the token that follows it immediately.
  1385. If TOKEN is non-nil, assume that that is the token that follows point.
  1386. Returns either a column number or nil if it considers that indentation
  1387. should not be computed on the basis of the following token."
  1388. (save-excursion
  1389. (let* ((pos (point))
  1390. (toklevels
  1391. (if token
  1392. (assoc token smie-grammar)
  1393. (let* ((res (smie-indent-forward-token)))
  1394. ;; Ignore tokens on subsequent lines.
  1395. (if (and (< pos (line-beginning-position))
  1396. ;; Make sure `token' also *starts* on another line.
  1397. (save-excursion
  1398. (let ((endpos (point)))
  1399. (goto-char pos)
  1400. (forward-line 1)
  1401. (and (equal res (smie-indent-forward-token))
  1402. (eq (point) endpos)))))
  1403. nil
  1404. (goto-char pos)
  1405. res)))))
  1406. (setq token (pop toklevels))
  1407. (cond
  1408. ((null (cdr toklevels)) nil) ;Not a keyword.
  1409. ((not (numberp (car toklevels)))
  1410. ;; Different cases:
  1411. ;; - smie-indent--bolp: "indent according to others".
  1412. ;; - common hanging: "indent according to others".
  1413. ;; - SML-let hanging: "indent like parent".
  1414. ;; - if-after-else: "indent-like parent".
  1415. ;; - middle-of-line: "trust current position".
  1416. (cond
  1417. ((smie-indent--rule :before token))
  1418. ((smie-indent--bolp-1) ;I.e. non-virtual indent.
  1419. ;; For an open-paren-like thingy at BOL, always indent only
  1420. ;; based on other rules (typically smie-indent-after-keyword).
  1421. ;; FIXME: we do the same if after a comment, since we may be trying
  1422. ;; to compute the indentation of this comment and we shouldn't indent
  1423. ;; based on the indentation of subsequent code.
  1424. nil)
  1425. (t
  1426. ;; By default use point unless we're hanging.
  1427. (unless (smie-indent--hanging-p) (current-column)))))
  1428. (t
  1429. ;; FIXME: This still looks too much like black magic!!
  1430. (let* ((parent (smie-backward-sexp token)))
  1431. ;; Different behaviors:
  1432. ;; - align with parent.
  1433. ;; - parent + offset.
  1434. ;; - after parent's column + offset (actually, after or before
  1435. ;; depending on where backward-sexp stopped).
  1436. ;; ? let it drop to some other indentation function (almost never).
  1437. ;; ? parent + offset + parent's own offset.
  1438. ;; Different cases:
  1439. ;; - bump into a same-level operator.
  1440. ;; - bump into a specific known parent.
  1441. ;; - find a matching open-paren thingy.
  1442. ;; - bump into some random parent.
  1443. ;; ? borderline case (almost never).
  1444. ;; ? bump immediately into a parent.
  1445. (cond
  1446. ((not (or (< (point) pos)
  1447. (and (cadr parent) (< (cadr parent) pos))))
  1448. ;; If we didn't move at all, that means we didn't really skip
  1449. ;; what we wanted. Should almost never happen, other than
  1450. ;; maybe when an infix or close-paren is at the beginning
  1451. ;; of a buffer.
  1452. nil)
  1453. ((save-excursion
  1454. (goto-char pos)
  1455. (smie-indent--rule :before token nil parent (cadr parent))))
  1456. ((eq (car parent) (car toklevels))
  1457. ;; We bumped into a same-level operator; align with it.
  1458. (if (and (smie-indent--bolp) (/= (point) pos)
  1459. (save-excursion
  1460. (goto-char (goto-char (cadr parent)))
  1461. (not (smie-indent--bolp))))
  1462. ;; If the parent is at EOL and its children are indented like
  1463. ;; itself, then we can just obey the indentation chosen for the
  1464. ;; child.
  1465. ;; This is important for operators like ";" which
  1466. ;; are usually at EOL (and have an offset of 0): otherwise we'd
  1467. ;; always go back over all the statements, which is
  1468. ;; a performance problem and would also mean that fixindents
  1469. ;; in the middle of such a sequence would be ignored.
  1470. ;;
  1471. ;; This is a delicate point!
  1472. ;; Even if the offset is not 0, we could follow the same logic
  1473. ;; and subtract the offset from the child's indentation.
  1474. ;; But that would more often be a bad idea: OT1H we generally
  1475. ;; want to reuse the closest similar indentation point, so that
  1476. ;; the user's choice (or the fixindents) are obeyed. But OTOH
  1477. ;; we don't want this to affect "unrelated" parts of the code.
  1478. ;; E.g. a fixindent in the body of a "begin..end" should not
  1479. ;; affect the indentation of the "end".
  1480. (current-column)
  1481. (goto-char (cadr parent))
  1482. ;; Don't use (smie-indent-virtual :not-hanging) here, because we
  1483. ;; want to jump back over a sequence of same-level ops such as
  1484. ;; a -> b -> c
  1485. ;; -> d
  1486. ;; So as to align with the earliest appropriate place.
  1487. (smie-indent-virtual)))
  1488. (t
  1489. (if (and (= (point) pos) (smie-indent--bolp))
  1490. ;; Since we started at BOL, we're not computing a virtual
  1491. ;; indentation, and we're still at the starting point, so
  1492. ;; we can't use `current-column' which would cause
  1493. ;; indentation to depend on itself and we can't use
  1494. ;; smie-indent-virtual since that would be an inf-loop.
  1495. nil
  1496. ;; In indent-keyword, if we're indenting `then' wrt `if', we
  1497. ;; want to use indent-virtual rather than use just
  1498. ;; current-column, so that we can apply the (:before . "if")
  1499. ;; rule which does the "else if" dance in SML. But in other
  1500. ;; cases, we do not want to use indent-virtual (e.g. indentation
  1501. ;; of "*" w.r.t "+", or ";" wrt "("). We could just always use
  1502. ;; indent-virtual and then have indent-rules say explicitly to
  1503. ;; use `point' after things like "(" or "+" when they're not at
  1504. ;; EOL, but you'd end up with lots of those rules.
  1505. ;; So we use a heuristic here, which is that we only use virtual
  1506. ;; if the parent is tightly linked to the child token (they're
  1507. ;; part of the same BNF rule).
  1508. (if (car parent)
  1509. (smie-indent--current-column)
  1510. (smie-indent-virtual)))))))))))
  1511. (defun smie-indent-comment ()
  1512. "Compute indentation of a comment."
  1513. ;; Don't do it for virtual indentations. We should normally never be "in
  1514. ;; front of a comment" when doing virtual-indentation anyway. And if we are
  1515. ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
  1516. (and (smie-indent--bolp)
  1517. (let ((pos (point)))
  1518. (save-excursion
  1519. (beginning-of-line)
  1520. (and (re-search-forward comment-start-skip (line-end-position) t)
  1521. (eq pos (or (match-end 1) (match-beginning 0))))))
  1522. (save-excursion
  1523. (forward-comment (point-max))
  1524. (skip-chars-forward " \t\r\n")
  1525. (unless
  1526. ;; Don't align with a closer, since the comment is "within" the
  1527. ;; closed element. Don't align with EOB either.
  1528. (save-excursion
  1529. (let ((next (funcall smie-forward-token-function)))
  1530. (or (if (zerop (length next))
  1531. (or (eobp) (eq (car (syntax-after (point))) 5)))
  1532. (rassoc next smie-closer-alist))))
  1533. ;; FIXME: We assume here that smie-indent-calculate will compute the
  1534. ;; indentation of the next token based on text before the comment,
  1535. ;; but this is not guaranteed, so maybe we should let
  1536. ;; smie-indent-calculate return some info about which buffer
  1537. ;; position was used as the "indentation base" and check that this
  1538. ;; base is before `pos'.
  1539. (smie-indent-calculate)))))
  1540. (defun smie-indent-comment-continue ()
  1541. ;; indentation of comment-continue lines.
  1542. (let ((continue (and comment-continue
  1543. (comment-string-strip comment-continue t t))))
  1544. (and (< 0 (length continue))
  1545. (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
  1546. (let ((ppss (syntax-ppss)))
  1547. (save-excursion
  1548. (forward-line -1)
  1549. (if (<= (point) (nth 8 ppss))
  1550. (progn (goto-char (1+ (nth 8 ppss))) (current-column))
  1551. (skip-chars-forward " \t")
  1552. (if (looking-at (regexp-quote continue))
  1553. (current-column))))))))
  1554. (defun smie-indent-comment-close ()
  1555. (and (boundp 'comment-end-skip)
  1556. comment-end-skip
  1557. (not (looking-at " \t*$")) ;Not just a \n comment-closer.
  1558. (looking-at comment-end-skip)
  1559. (let ((end (match-string 0)))
  1560. (and (nth 4 (syntax-ppss))
  1561. (save-excursion
  1562. (goto-char (nth 8 (syntax-ppss)))
  1563. (and (looking-at comment-start-skip)
  1564. (let ((start (match-string 0)))
  1565. ;; Align the common substring between starter
  1566. ;; and ender, if possible.
  1567. (if (string-match "\\(.+\\).*\n\\(.*?\\)\\1"
  1568. (concat start "\n" end))
  1569. (+ (current-column) (match-beginning 0)
  1570. (- (match-beginning 2) (match-end 2)))
  1571. (current-column)))))))))
  1572. (defun smie-indent-comment-inside ()
  1573. (and (nth 4 (syntax-ppss))
  1574. 'noindent))
  1575. (defun smie-indent-inside-string ()
  1576. (and (nth 3 (syntax-ppss))
  1577. 'noindent))
  1578. (defun smie-indent-after-keyword ()
  1579. ;; Indentation right after a special keyword.
  1580. (save-excursion
  1581. (let* ((pos (point))
  1582. (toklevel (smie-indent-backward-token))
  1583. (tok (car toklevel)))
  1584. (cond
  1585. ((null toklevel) nil)
  1586. ((smie-indent--rule :after tok pos nil (point)))
  1587. ;; The default indentation after a keyword/operator is
  1588. ;; 0 for infix, t for prefix, and use another rule
  1589. ;; for postfix.
  1590. ((not (numberp (nth 2 toklevel))) nil) ;A closer.
  1591. ((or (not (numberp (nth 1 toklevel))) ;An opener.
  1592. (rassoc tok smie-closer-alist)) ;An inner.
  1593. (+ (smie-indent-virtual) (smie-indent--offset 'basic))) ;
  1594. (t (smie-indent-virtual)))))) ;An infix.
  1595. (defun smie-indent-exps ()
  1596. ;; Indentation of sequences of simple expressions without
  1597. ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
  1598. ;; Can be a list of expressions or a function call.
  1599. ;; If it's a function call, the first element is special (it's the
  1600. ;; function). We distinguish function calls from mere lists of
  1601. ;; expressions based on whether the preceding token is listed in
  1602. ;; the `list-intro' entry of smie-indent-rules.
  1603. ;;
  1604. ;; TODO: to indent Lisp code, we should add a way to specify
  1605. ;; particular indentation for particular args depending on the
  1606. ;; function (which would require always skipping back until the
  1607. ;; function).
  1608. ;; TODO: to indent C code, such as "if (...) {...}" we might need
  1609. ;; to add similar indentation hooks for particular positions, but
  1610. ;; based on the preceding token rather than based on the first exp.
  1611. (save-excursion
  1612. (let ((positions nil)
  1613. arg)
  1614. (while (and (null (car (smie-backward-sexp)))
  1615. (push (point) positions)
  1616. (not (smie-indent--bolp))))
  1617. (save-excursion
  1618. ;; Figure out if the atom we just skipped is an argument rather
  1619. ;; than a function.
  1620. (setq arg
  1621. (or (null (car (smie-backward-sexp)))
  1622. (funcall smie-rules-function :list-intro
  1623. (funcall smie-backward-token-function)))))
  1624. (cond
  1625. ((null positions)
  1626. ;; We're the first expression of the list. In that case, the
  1627. ;; indentation should be (have been) determined by its context.
  1628. nil)
  1629. (arg
  1630. ;; There's a previous element, and it's not special (it's not
  1631. ;; the function), so let's just align with that one.
  1632. (goto-char (car positions))
  1633. (smie-indent--current-column))
  1634. ((cdr positions)
  1635. ;; We skipped some args plus the function and bumped into something.
  1636. ;; Align with the first arg.
  1637. (goto-char (cadr positions))
  1638. (smie-indent--current-column))
  1639. (positions
  1640. ;; We're the first arg.
  1641. (goto-char (car positions))
  1642. (+ (smie-indent--offset 'args)
  1643. ;; We used to use (smie-indent-virtual), but that
  1644. ;; doesn't seem right since it might then indent args less than
  1645. ;; the function itself.
  1646. (smie-indent--current-column)))))))
  1647. (defvar smie-indent-functions
  1648. '(smie-indent-fixindent smie-indent-bob smie-indent-close
  1649. smie-indent-comment smie-indent-comment-continue smie-indent-comment-close
  1650. smie-indent-comment-inside smie-indent-inside-string
  1651. smie-indent-keyword smie-indent-after-keyword
  1652. smie-indent-exps)
  1653. "Functions to compute the indentation.
  1654. Each function is called with no argument, shouldn't move point, and should
  1655. return either nil if it has no opinion, or an integer representing the column
  1656. to which that point should be aligned, if we were to reindent it.")
  1657. (defun smie-indent-calculate ()
  1658. "Compute the indentation to use for point."
  1659. (run-hook-with-args-until-success 'smie-indent-functions))
  1660. (defun smie-indent-line ()
  1661. "Indent current line using the SMIE indentation engine."
  1662. (interactive)
  1663. (let* ((savep (point))
  1664. (indent (or (with-demoted-errors
  1665. (save-excursion
  1666. (forward-line 0)
  1667. (skip-chars-forward " \t")
  1668. (if (>= (point) savep) (setq savep nil))
  1669. (or (smie-indent-calculate) 0)))
  1670. 0)))
  1671. (if (not (numberp indent))
  1672. ;; If something funny is used (e.g. `noindent'), return it.
  1673. indent
  1674. (if (< indent 0) (setq indent 0)) ;Just in case.
  1675. (if savep
  1676. (save-excursion (indent-line-to indent))
  1677. (indent-line-to indent)))))
  1678. (defun smie-auto-fill (do-auto-fill)
  1679. (let ((fc (current-fill-column)))
  1680. (when (and fc (> (current-column) fc))
  1681. ;; The loop below presumes BOL is outside of strings or comments. Also,
  1682. ;; sometimes we prefer to fill the comment than the code around it.
  1683. (unless (or (nth 8 (save-excursion
  1684. (syntax-ppss (line-beginning-position))))
  1685. (nth 4 (save-excursion
  1686. (move-to-column fc)
  1687. (syntax-ppss))))
  1688. (while
  1689. (and (with-demoted-errors
  1690. (save-excursion
  1691. (let ((end (point))
  1692. (bsf nil) ;Best-so-far.
  1693. (gain 0))
  1694. (beginning-of-line)
  1695. (while (progn
  1696. (smie-indent-forward-token)
  1697. (and (<= (point) end)
  1698. (<= (current-column) fc)))
  1699. ;; FIXME? `smie-indent-calculate' can (and often
  1700. ;; does) return a result that actually depends on the
  1701. ;; presence/absence of a newline, so the gain computed
  1702. ;; here may not be accurate, but in practice it seems
  1703. ;; to work well enough.
  1704. (skip-chars-forward " \t")
  1705. (let* ((newcol (smie-indent-calculate))
  1706. (newgain (- (current-column) newcol)))
  1707. (when (> newgain gain)
  1708. (setq gain newgain)
  1709. (setq bsf (point)))))
  1710. (when (> gain 0)
  1711. (goto-char bsf)
  1712. (newline-and-indent)
  1713. 'done))))
  1714. (> (current-column) fc))))
  1715. (when (> (current-column) fc)
  1716. (funcall do-auto-fill)))))
  1717. (defun smie-setup (grammar rules-function &rest keywords)
  1718. "Setup SMIE navigation and indentation.
  1719. GRAMMAR is a grammar table generated by `smie-prec2->grammar'.
  1720. RULES-FUNCTION is a set of indentation rules for use on `smie-rules-function'.
  1721. KEYWORDS are additional arguments, which can use the following keywords:
  1722. - :forward-token FUN
  1723. - :backward-token FUN"
  1724. (setq-local smie-rules-function rules-function)
  1725. (setq-local smie-grammar grammar)
  1726. (setq-local indent-line-function #'smie-indent-line)
  1727. (add-function :around (local 'normal-auto-fill-function) #'smie-auto-fill)
  1728. (setq-local forward-sexp-function #'smie-forward-sexp-command)
  1729. (while keywords
  1730. (let ((k (pop keywords))
  1731. (v (pop keywords)))
  1732. (pcase k
  1733. (`:forward-token
  1734. (set (make-local-variable 'smie-forward-token-function) v))
  1735. (`:backward-token
  1736. (set (make-local-variable 'smie-backward-token-function) v))
  1737. (_ (message "smie-setup: ignoring unknown keyword %s" k)))))
  1738. (let ((ca (cdr (assq :smie-closer-alist grammar))))
  1739. (when ca
  1740. (setq-local smie-closer-alist ca)
  1741. ;; Only needed for interactive calls to blink-matching-open.
  1742. (setq-local blink-matching-check-function #'smie-blink-matching-check)
  1743. (add-hook 'post-self-insert-hook
  1744. #'smie-blink-matching-open 'append 'local)
  1745. (add-function :around (local 'show-paren-data-function)
  1746. #'smie--matching-block-data)
  1747. ;; Setup smie-blink-matching-triggers. Rather than wait for SPC to
  1748. ;; blink, try to blink as soon as we type the last char of a block ender.
  1749. (let ((closers (sort (mapcar #'cdr smie-closer-alist) #'string-lessp))
  1750. (triggers ())
  1751. closer)
  1752. (while (setq closer (pop closers))
  1753. (unless
  1754. ;; FIXME: this eliminates prefixes of other closers, but we
  1755. ;; should probably eliminate prefixes of other keywords as well.
  1756. (and closers (string-prefix-p closer (car closers)))
  1757. (push (aref closer (1- (length closer))) triggers)))
  1758. (setq-local smie-blink-matching-triggers
  1759. (append smie-blink-matching-triggers
  1760. (delete-dups triggers)))))))
  1761. (declare-function edebug-instrument-function "edebug" (func))
  1762. (defun smie-edebug ()
  1763. "Instrument the `smie-rules-function' for Edebug."
  1764. (interactive)
  1765. (require 'edebug)
  1766. (if (symbolp smie-rules-function)
  1767. (edebug-instrument-function smie-rules-function)
  1768. (error "Sorry, don't know how to instrument a lambda expression")))
  1769. (defun smie--next-indent-change ()
  1770. "Go to the next line that needs to be reindented (and reindent it)."
  1771. (interactive)
  1772. (while
  1773. (let ((tick (buffer-chars-modified-tick)))
  1774. (indent-according-to-mode)
  1775. (eq tick (buffer-chars-modified-tick)))
  1776. (forward-line 1)))
  1777. ;;; User configuration
  1778. ;; This is designed to be a completely independent "module", so we can play
  1779. ;; with various kinds of smie-config modules without having to change the core.
  1780. ;; This smie-config module is fairly primitive and suffers from serious
  1781. ;; restrictions:
  1782. ;; - You can only change a returned offset, so you can't change the offset
  1783. ;; passed to smie-rule-parent, nor can you change the object with which
  1784. ;; to align (in general).
  1785. ;; - The rewrite rule can only distinguish cases based on the kind+token arg
  1786. ;; and smie-rules-function's return value, so you can't distinguish cases
  1787. ;; where smie-rules-function returns the same value.
  1788. ;; - Since config-rules depend on the return value of smie-rules-function, any
  1789. ;; config change that modifies this return value (e.g. changing
  1790. ;; foo-indent-basic) ends up invalidating config-rules.
  1791. ;; This last one is a serious problem since it means that file-local
  1792. ;; config-rules will only work if the user hasn't changed foo-indent-basic.
  1793. ;; One possible way to change it is to modify smie-rules-functions so they can
  1794. ;; return special symbols like +, ++, -, etc. Or make them use a new
  1795. ;; smie-rule-basic function which can then be used to know when a returned
  1796. ;; offset was computed based on foo-indent-basic.
  1797. (defvar-local smie-config--mode-local nil
  1798. "Indentation config rules installed for this major mode.
  1799. Typically manipulated from the major-mode's hook.")
  1800. (defvar-local smie-config--buffer-local nil
  1801. "Indentation config rules installed for this very buffer.
  1802. E.g. provided via a file-local call to `smie-config-local'.")
  1803. (defvar smie-config--trace nil
  1804. "Variable used to trace calls to `smie-rules-function'.")
  1805. (defun smie-config--advice (orig kind token)
  1806. (let* ((ret (funcall orig kind token))
  1807. (sig (list kind token ret))
  1808. (brule (rassoc sig smie-config--buffer-local))
  1809. (mrule (rassoc sig smie-config--mode-local)))
  1810. (when smie-config--trace
  1811. (setq smie-config--trace (or brule mrule)))
  1812. (cond
  1813. (brule (car brule))
  1814. (mrule (car mrule))
  1815. (t ret))))
  1816. (defun smie-config--mode-hook (rules)
  1817. (setq smie-config--mode-local
  1818. (append rules smie-config--mode-local))
  1819. (add-function :around (local 'smie-rules-function) #'smie-config--advice))
  1820. (defvar smie-config--modefuns nil)
  1821. (defun smie-config--setter (var value)
  1822. (setq-default var value)
  1823. (let ((old-modefuns smie-config--modefuns))
  1824. (setq smie-config--modefuns nil)
  1825. (pcase-dolist (`(,mode . ,rules) value)
  1826. (let ((modefunname (intern (format "smie-config--modefun-%s" mode))))
  1827. (fset modefunname (lambda () (smie-config--mode-hook rules)))
  1828. (push modefunname smie-config--modefuns)
  1829. (add-hook (intern (format "%s-hook" mode)) modefunname)))
  1830. ;; Neuter any left-over previously installed hook.
  1831. (dolist (modefun old-modefuns)
  1832. (unless (memq modefun smie-config--modefuns)
  1833. (fset modefun #'ignore)))))
  1834. (defcustom smie-config nil
  1835. ;; FIXME: there should be a file-local equivalent.
  1836. "User configuration of SMIE indentation.
  1837. This is a list of elements (MODE . RULES), where RULES is a list
  1838. of elements describing when and how to change the indentation rules.
  1839. Each RULE element should be of the form (NEW KIND TOKEN NORMAL),
  1840. where KIND and TOKEN are the elements passed to `smie-rules-function',
  1841. NORMAL is the value returned by `smie-rules-function' and NEW is the
  1842. value with which to replace it."
  1843. :version "24.4"
  1844. ;; FIXME improve value-type.
  1845. :type '(choice (const nil)
  1846. (alist :key-type symbol))
  1847. :initialize 'custom-initialize-default
  1848. :set #'smie-config--setter)
  1849. (defun smie-config-local (rules)
  1850. "Add RULES as local indentation rules to use in this buffer.
  1851. These replace any previous local rules, but supplement the rules
  1852. specified in `smie-config'."
  1853. (setq smie-config--buffer-local rules)
  1854. (add-function :around (local 'smie-rules-function) #'smie-config--advice))
  1855. ;; Make it so we can set those in the file-local block.
  1856. ;; FIXME: Better would be to be able to write "smie-config-local: (...)" rather
  1857. ;; than "eval: (smie-config-local '(...))".
  1858. (put 'smie-config-local 'safe-local-eval-function t)
  1859. (defun smie-config--get-trace ()
  1860. (save-excursion
  1861. (forward-line 0)
  1862. (skip-chars-forward " \t")
  1863. (let* ((trace ())
  1864. (srf-fun (lambda (orig kind token)
  1865. (let* ((pos (point))
  1866. (smie-config--trace t)
  1867. (res (funcall orig kind token)))
  1868. (push (if (consp smie-config--trace)
  1869. (list pos kind token res smie-config--trace)
  1870. (list pos kind token res))
  1871. trace)
  1872. res))))
  1873. (unwind-protect
  1874. (progn
  1875. (add-function :around (local 'smie-rules-function) srf-fun)
  1876. (cons (smie-indent-calculate)
  1877. trace))
  1878. (remove-function (local 'smie-rules-function) srf-fun)))))
  1879. (defun smie-config-show-indent (&optional arg)
  1880. "Display the SMIE rules that are used to indent the current line.
  1881. If prefix ARG is given, then move briefly point to the buffer
  1882. position corresponding to each rule."
  1883. (interactive "P")
  1884. (let ((trace (cdr (smie-config--get-trace))))
  1885. (cond
  1886. ((null trace) (message "No SMIE rules involved"))
  1887. ((not arg)
  1888. (message "Rules used: %s"
  1889. (mapconcat (lambda (elem)
  1890. (pcase-let ((`(,_pos ,kind ,token ,res ,rewrite)
  1891. elem))
  1892. (format "%S %S -> %S%s" kind token res
  1893. (if (null rewrite) ""
  1894. (format "(via %S)" (nth 3 rewrite))))))
  1895. trace
  1896. ", ")))
  1897. (t
  1898. (save-excursion
  1899. (pcase-dolist (`(,pos ,kind ,token ,res ,rewrite) trace)
  1900. (message "%S %S -> %S%s" kind token res
  1901. (if (null rewrite) ""
  1902. (format "(via %S)" (nth 3 rewrite))))
  1903. (goto-char pos)
  1904. (sit-for blink-matching-delay)))))))
  1905. (defun smie-config--guess-value (sig)
  1906. (add-function :around (local 'smie-rules-function) #'smie-config--advice)
  1907. (let* ((rule (cons 0 sig))
  1908. (smie-config--buffer-local (cons rule smie-config--buffer-local))
  1909. (goal (current-indentation))
  1910. (cur (smie-indent-calculate)))
  1911. (cond
  1912. ((and (eq goal
  1913. (progn (setf (car rule) (- goal cur))
  1914. (smie-indent-calculate))))
  1915. (- goal cur)))))
  1916. (defun smie-config-set-indent ()
  1917. "Add a rule to adjust the indentation of current line."
  1918. (interactive)
  1919. (let* ((trace (cdr (smie-config--get-trace)))
  1920. (_ (unless trace (error "No SMIE rules involved")))
  1921. (sig (if (null (cdr trace))
  1922. (pcase-let* ((elem (car trace))
  1923. (`(,_pos ,kind ,token ,res ,rewrite) elem))
  1924. (list kind token (or (nth 3 rewrite) res)))
  1925. (let* ((choicestr
  1926. (completing-read
  1927. "Adjust rule: "
  1928. (mapcar (lambda (elem)
  1929. (format "%s %S"
  1930. (substring (symbol-name (cadr elem))
  1931. 1)
  1932. (nth 2 elem)))
  1933. trace)
  1934. nil t nil nil
  1935. nil)) ;FIXME: Provide good default!
  1936. (choicelst (car (read-from-string
  1937. (concat "(:" choicestr ")")))))
  1938. (catch 'found
  1939. (pcase-dolist (`(,_pos ,kind ,token ,res ,rewrite) trace)
  1940. (when (and (eq kind (car choicelst))
  1941. (equal token (nth 1 choicelst)))
  1942. (throw 'found (list kind token
  1943. (or (nth 3 rewrite) res)))))))))
  1944. (default-new (smie-config--guess-value sig))
  1945. (newstr (read-string (format "Adjust rule (%S %S -> %S) to%s: "
  1946. (nth 0 sig) (nth 1 sig) (nth 2 sig)
  1947. (if (not default-new) ""
  1948. (format " (default %S)" default-new)))
  1949. nil nil (format "%S" default-new)))
  1950. (new (car (read-from-string newstr))))
  1951. (let ((old (rassoc sig smie-config--buffer-local)))
  1952. (when old
  1953. (setq smie-config--buffer-local
  1954. (remove old smie-config--buffer-local))))
  1955. (push (cons new sig) smie-config--buffer-local)
  1956. (message "Added rule %S %S -> %S (via %S)"
  1957. (nth 0 sig) (nth 1 sig) new (nth 2 sig))
  1958. (add-function :around (local 'smie-rules-function) #'smie-config--advice)))
  1959. (defun smie-config--guess (beg end)
  1960. (let ((otraces (make-hash-table :test #'equal))
  1961. (smie-config--buffer-local nil)
  1962. (smie-config--mode-local nil)
  1963. (pr (make-progress-reporter "Analyzing the buffer" beg end)))
  1964. ;; First, lets get the indentation traces and offsets for the region.
  1965. (save-excursion
  1966. (goto-char beg)
  1967. (forward-line 0)
  1968. (while (< (point) end)
  1969. (skip-chars-forward " \t")
  1970. (unless (eolp) ;Skip empty lines.
  1971. (progress-reporter-update pr (point))
  1972. (let* ((itrace (smie-config--get-trace))
  1973. (nindent (car itrace))
  1974. (trace (mapcar #'cdr (cdr itrace)))
  1975. (cur (current-indentation)))
  1976. (when (numberp nindent) ;Skip `noindent' and friends.
  1977. (cl-incf (gethash (cons (- cur nindent) trace) otraces 0)))))
  1978. (forward-line 1)))
  1979. (progress-reporter-done pr)
  1980. ;; Second, compile the data. Our algorithm only knows how to adjust rules
  1981. ;; where the smie-rules-function returns an integer. We call those
  1982. ;; "adjustable sigs". We build a table mapping each adjustable sig
  1983. ;; to its data, describing the total number of times we encountered it,
  1984. ;; the offsets found, and the traces in which it was found.
  1985. (message "Guessing...")
  1986. (let ((sigs (make-hash-table :test #'equal)))
  1987. (maphash (lambda (otrace count)
  1988. (let ((offset (car otrace))
  1989. (trace (cdr otrace))
  1990. (double nil))
  1991. (let ((sigs trace))
  1992. (while sigs
  1993. (let ((sig (pop sigs)))
  1994. (if (and (integerp (nth 2 sig)) (member sig sigs))
  1995. (setq double t)))))
  1996. (if double
  1997. ;; Disregard those traces where an adjustable sig
  1998. ;; appears twice, because the rest of the code assumes
  1999. ;; that adding a rule to add an offset N will change the
  2000. ;; end result by N rather than 2*N or more.
  2001. nil
  2002. (dolist (sig trace)
  2003. (if (not (integerp (nth 2 sig)))
  2004. ;; Disregard those sigs that return nil or a column,
  2005. ;; because our algorithm doesn't know how to adjust
  2006. ;; them anyway.
  2007. nil
  2008. (let ((sig-data (or (gethash sig sigs)
  2009. (let ((data (list 0 nil nil)))
  2010. (puthash sig data sigs)
  2011. data))))
  2012. (cl-incf (nth 0 sig-data) count)
  2013. (push (cons count otrace) (nth 2 sig-data))
  2014. (let ((sig-off-data
  2015. (or (assq offset (nth 1 sig-data))
  2016. (let ((off-data (cons offset 0)))
  2017. (push off-data (nth 1 sig-data))
  2018. off-data))))
  2019. (cl-incf (cdr sig-off-data) count))))))))
  2020. otraces)
  2021. ;; Finally, guess the indentation rules.
  2022. (prog1
  2023. (smie-config--guess-1 sigs)
  2024. (message "Guessing...done")))))
  2025. (defun smie-config--guess-1 (sigs)
  2026. (let ((ssigs nil)
  2027. (rules nil))
  2028. ;; Sort the sigs by frequency of occurrence.
  2029. (maphash (lambda (sig sig-data) (push (cons sig sig-data) ssigs)) sigs)
  2030. (setq ssigs (sort ssigs (lambda (sd1 sd2) (> (cadr sd1) (cadr sd2)))))
  2031. (while ssigs
  2032. (pcase-let ((`(,sig ,total ,off-alist ,cotraces) (pop ssigs)))
  2033. (cl-assert (= total (apply #'+ (mapcar #'cdr off-alist))))
  2034. (let* ((sorted-off-alist
  2035. (sort off-alist (lambda (x y) (> (cdr x) (cdr y)))))
  2036. (offset (caar sorted-off-alist)))
  2037. (if (zerop offset)
  2038. ;; Nothing to do with this sig; indentation is
  2039. ;; correct already.
  2040. nil
  2041. (push (cons (+ offset (nth 2 sig)) sig) rules)
  2042. ;; Adjust the rest of the data.
  2043. (pcase-dolist ((and cotrace `(,count ,toffset . ,trace))
  2044. cotraces)
  2045. (setf (nth 1 cotrace) (- toffset offset))
  2046. (dolist (sig trace)
  2047. (let ((sig-data (cdr (assq sig ssigs))))
  2048. (when sig-data
  2049. (let* ((ooff-data (assq toffset (nth 1 sig-data)))
  2050. (noffset (- toffset offset))
  2051. (noff-data
  2052. (or (assq noffset (nth 1 sig-data))
  2053. (let ((off-data (cons noffset 0)))
  2054. (push off-data (nth 1 sig-data))
  2055. off-data))))
  2056. (cl-assert (>= (cdr ooff-data) count))
  2057. (cl-decf (cdr ooff-data) count)
  2058. (cl-incf (cdr noff-data) count))))))))))
  2059. rules))
  2060. (defun smie-config-guess ()
  2061. "Try and figure out this buffer's indentation settings.
  2062. To save the result for future sessions, use `smie-config-save'."
  2063. (interactive)
  2064. (if (eq smie-grammar 'unset)
  2065. (user-error "This buffer does not seem to be using SMIE"))
  2066. (let ((config (smie-config--guess (point-min) (point-max))))
  2067. (cond
  2068. ((null config) (message "Nothing to change"))
  2069. ((null smie-config--buffer-local)
  2070. (smie-config-local config)
  2071. (message "Local rules set"))
  2072. ((y-or-n-p "Replace existing local config? ")
  2073. (message "Local rules replaced")
  2074. (smie-config-local config))
  2075. ((y-or-n-p "Merge with existing local config? ")
  2076. (message "Local rules adjusted")
  2077. (smie-config-local (append config smie-config--buffer-local)))
  2078. (t
  2079. (message "Rules guessed: %S" config)))))
  2080. (defun smie-config-save ()
  2081. "Save local rules for use with this major mode.
  2082. One way to generate local rules is the command `smie-config-guess'."
  2083. (interactive)
  2084. (cond
  2085. ((null smie-config--buffer-local)
  2086. (message "No local rules to save"))
  2087. (t
  2088. (let* ((existing (assq major-mode smie-config))
  2089. (config
  2090. (cond ((null existing)
  2091. (message "Local rules saved in ‘smie-config’")
  2092. smie-config--buffer-local)
  2093. ((y-or-n-p "Replace the existing mode's config? ")
  2094. (message "Mode rules replaced in ‘smie-config’")
  2095. smie-config--buffer-local)
  2096. ((y-or-n-p "Merge with existing mode's config? ")
  2097. (message "Mode rules adjusted in ‘smie-config’")
  2098. (append smie-config--buffer-local (cdr existing)))
  2099. (t (error "Abort")))))
  2100. (if existing
  2101. (setcdr existing config)
  2102. (push (cons major-mode config) smie-config))
  2103. (setq smie-config--mode-local config)
  2104. (kill-local-variable 'smie-config--buffer-local)
  2105. (customize-mark-as-set 'smie-config)))))
  2106. (provide 'smie)
  2107. ;;; smie.el ends here