smie.el 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  1. ;;; smie.el --- Simple Minded Indentation Engine -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2010-2012 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))
  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. (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. (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. (pushnew (car rhs) first-ops)
  248. (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. (pushnew (cadr rhs) first-ops)))
  262. (let ((shr (reverse rhs)))
  263. (if (not (member (car shr) nts))
  264. (pushnew (car shr) last-ops)
  265. (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. (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. (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. (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. (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) (assert (eq v '<)))
  471. ;; ((> left right) (assert (eq v '>)))
  472. ;; (t (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. tmp x y)
  487. ;; From `prec2' we construct a list of constraints between
  488. ;; variables (aka "precedence levels"). These can be either
  489. ;; equality constraints (in `eqs') or `<' constraints (in `csts').
  490. (maphash (lambda (k v)
  491. (when (consp k)
  492. (if (setq tmp (assoc (car k) table))
  493. (setq x (cddr tmp))
  494. (setq x (cons nil nil))
  495. (push (cons (car k) (cons nil x)) table))
  496. (if (setq tmp (assoc (cdr k) table))
  497. (setq y (cdr tmp))
  498. (setq y (cons nil (cons nil nil)))
  499. (push (cons (cdr k) y) table))
  500. (ecase v
  501. (= (push (cons x y) eqs))
  502. (< (push (cons x y) csts))
  503. (> (push (cons y x) csts)))))
  504. prec2)
  505. ;; First process the equality constraints.
  506. (let ((eqs eqs))
  507. (while eqs
  508. (let ((from (caar eqs))
  509. (to (cdar eqs)))
  510. (setq eqs (cdr eqs))
  511. (if (eq to from)
  512. nil ;Nothing to do.
  513. (dolist (other-eq eqs)
  514. (if (eq from (cdr other-eq)) (setcdr other-eq to))
  515. (when (eq from (car other-eq))
  516. ;; This can happen because of `assoc' settings in precs
  517. ;; or because of a rhs like ("op" foo "op").
  518. (setcar other-eq to)))
  519. (dolist (cst csts)
  520. (if (eq from (cdr cst)) (setcdr cst to))
  521. (if (eq from (car cst)) (setcar cst to)))))))
  522. ;; Then eliminate trivial constraints iteratively.
  523. (let ((i 0))
  524. (while csts
  525. (let ((rhvs (mapcar 'cdr csts))
  526. (progress nil))
  527. (dolist (cst csts)
  528. (unless (memq (car cst) rhvs)
  529. (setq progress t)
  530. ;; We could give each var in a given iteration the same value,
  531. ;; but we can also give them arbitrarily different values.
  532. ;; Basically, these are vars between which there is no
  533. ;; constraint (neither equality nor inequality), so
  534. ;; anything will do.
  535. ;; We give them arbitrary values, which means that we
  536. ;; replace the "no constraint" case with either > or <
  537. ;; but not =. The reason we do that is so as to try and
  538. ;; distinguish associative operators (which will have
  539. ;; left = right).
  540. (unless (caar cst)
  541. (setcar (car cst) i)
  542. ;; (smie-check-grammar table prec2 'step1)
  543. (incf i))
  544. (setq csts (delq cst csts))))
  545. (unless progress
  546. (error "Can't resolve the precedence cycle: %s"
  547. (smie-debug--describe-cycle
  548. table (smie-debug--prec2-cycle csts)))))
  549. (incf i 10))
  550. ;; Propagate equality constraints back to their sources.
  551. (dolist (eq (nreverse eqs))
  552. (when (null (cadr eq))
  553. ;; There's an equality constraint, but we still haven't given
  554. ;; it a value: that means it binds tighter than anything else,
  555. ;; and it can't be an opener/closer (those don't have equality
  556. ;; constraints).
  557. ;; So set it here rather than below since doing it below
  558. ;; makes it more difficult to obey the equality constraints.
  559. (setcar (cdr eq) i)
  560. (incf i))
  561. (assert (or (null (caar eq)) (eq (caar eq) (cadr eq))))
  562. (setcar (car eq) (cadr eq))
  563. ;; (smie-check-grammar table prec2 'step2)
  564. )
  565. ;; Finally, fill in the remaining vars (which did not appear on the
  566. ;; left side of any < constraint).
  567. (dolist (x table)
  568. (unless (nth 1 x)
  569. (setf (nth 1 x) i)
  570. (incf i)) ;See other (incf i) above.
  571. (unless (nth 2 x)
  572. (setf (nth 2 x) i)
  573. (incf i)))) ;See other (incf i) above.
  574. ;; Mark closers and openers.
  575. (dolist (x (gethash :smie-open/close-alist prec2))
  576. (let* ((token (car x))
  577. (cons (case (cdr x)
  578. (closer (cddr (assoc token table)))
  579. (opener (cdr (assoc token table))))))
  580. (assert (numberp (car cons)))
  581. (setf (car cons) (list (car cons)))))
  582. (let ((ca (gethash :smie-closer-alist prec2)))
  583. (when ca (push (cons :smie-closer-alist ca) table)))
  584. ;; (smie-check-grammar table prec2 'step3)
  585. table))
  586. ;;; Parsing using a precedence level table.
  587. (defvar smie-grammar 'unset
  588. "List of token parsing info.
  589. This list is normally built by `smie-prec2->grammar'.
  590. Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
  591. Parsing is done using an operator precedence parser.
  592. LEFT-LEVEL and RIGHT-LEVEL can be either numbers or a list, where a list
  593. means that this operator does not bind on the corresponding side,
  594. e.g. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
  595. an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
  596. like a close-paren.")
  597. (defvar smie-forward-token-function 'smie-default-forward-token
  598. "Function to scan forward for the next token.
  599. Called with no argument should return a token and move to its end.
  600. If no token is found, return nil or the empty string.
  601. It can return nil when bumping into a parenthesis, which lets SMIE
  602. use syntax-tables to handle them in efficient C code.")
  603. (defvar smie-backward-token-function 'smie-default-backward-token
  604. "Function to scan backward the previous token.
  605. Same calling convention as `smie-forward-token-function' except
  606. it should move backward to the beginning of the previous token.")
  607. (defalias 'smie-op-left 'car)
  608. (defalias 'smie-op-right 'cadr)
  609. (defun smie-default-backward-token ()
  610. (forward-comment (- (point)))
  611. (buffer-substring-no-properties
  612. (point)
  613. (progn (if (zerop (skip-syntax-backward "."))
  614. (skip-syntax-backward "w_'"))
  615. (point))))
  616. (defun smie-default-forward-token ()
  617. (forward-comment (point-max))
  618. (buffer-substring-no-properties
  619. (point)
  620. (progn (if (zerop (skip-syntax-forward "."))
  621. (skip-syntax-forward "w_'"))
  622. (point))))
  623. (defun smie--associative-p (toklevels)
  624. ;; in "a + b + c" we want to stop at each +, but in
  625. ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
  626. ;; To distinguish the two cases, we made smie-prec2->grammar choose
  627. ;; different levels for each part of "if a then b else c", so that
  628. ;; by checking if the left-level is equal to the right level, we can
  629. ;; figure out that it's an associative operator.
  630. ;; This is not 100% foolproof, tho, since the "elsif" will have to have
  631. ;; equal left and right levels (since it's optional), so smie-next-sexp
  632. ;; has to be careful to distinguish those different cases.
  633. (eq (smie-op-left toklevels) (smie-op-right toklevels)))
  634. (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
  635. "Skip over one sexp.
  636. NEXT-TOKEN is a function of no argument that moves forward by one
  637. token (after skipping comments if needed) and returns it.
  638. NEXT-SEXP is a lower-level function to skip one sexp.
  639. OP-FORW is the accessor to the forward level of the level data.
  640. OP-BACK is the accessor to the backward level of the level data.
  641. HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
  642. first token we see is an operator, skip over its left-hand-side argument.
  643. HALFSEXP can also be a token, in which case it means to parse as if
  644. we had just successfully passed this token.
  645. Possible return values:
  646. (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
  647. is too high. FORW-LEVEL is the forw-level of TOKEN,
  648. POS is its start position in the buffer.
  649. (t POS TOKEN): same thing when we bump on the wrong side of a paren.
  650. (nil POS TOKEN): we skipped over a paren-like pair.
  651. nil: we skipped over an identifier, matched parentheses, ..."
  652. (catch 'return
  653. (let ((levels
  654. (if (stringp halfsexp)
  655. (prog1 (list (cdr (assoc halfsexp smie-grammar)))
  656. (setq halfsexp nil)))))
  657. (while
  658. (let* ((pos (point))
  659. (token (funcall next-token))
  660. (toklevels (cdr (assoc token smie-grammar))))
  661. (cond
  662. ((null toklevels)
  663. (when (zerop (length token))
  664. (condition-case err
  665. (progn (goto-char pos) (funcall next-sexp 1) nil)
  666. (scan-error (throw 'return
  667. (list t (caddr err)
  668. (buffer-substring-no-properties
  669. (caddr err)
  670. (+ (caddr err)
  671. (if (< (point) (caddr err))
  672. -1 1)))))))
  673. (if (eq pos (point))
  674. ;; We did not move, so let's abort the loop.
  675. (throw 'return (list t (point))))))
  676. ((not (numberp (funcall op-back toklevels)))
  677. ;; A token like a paren-close.
  678. (assert (numberp ; Otherwise, why mention it in smie-grammar.
  679. (funcall op-forw toklevels)))
  680. (push toklevels levels))
  681. (t
  682. (while (and levels (< (funcall op-back toklevels)
  683. (funcall op-forw (car levels))))
  684. (setq levels (cdr levels)))
  685. (cond
  686. ((null levels)
  687. (if (and halfsexp (numberp (funcall op-forw toklevels)))
  688. (push toklevels levels)
  689. (throw 'return
  690. (prog1 (list (or (car toklevels) t) (point) token)
  691. (goto-char pos)))))
  692. (t
  693. (let ((lastlevels levels))
  694. (if (and levels (= (funcall op-back toklevels)
  695. (funcall op-forw (car levels))))
  696. (setq levels (cdr levels)))
  697. ;; We may have found a match for the previously pending
  698. ;; operator. Is this the end?
  699. (cond
  700. ;; Keep looking as long as we haven't matched the
  701. ;; topmost operator.
  702. (levels
  703. (cond
  704. ((numberp (funcall op-forw toklevels))
  705. (push toklevels levels))
  706. ;; FIXME: For some languages, we can express the grammar
  707. ;; OK, but next-sexp doesn't stop where we'd want it to.
  708. ;; E.g. in SML, we'd want to stop right in front of
  709. ;; "local" if we're scanning (both forward and backward)
  710. ;; from a "val/fun/..." at the same level.
  711. ;; Same for Pascal/Modula2's "procedure" w.r.t
  712. ;; "type/var/const".
  713. ;;
  714. ;; ((and (functionp (cadr (funcall op-forw toklevels)))
  715. ;; (funcall (cadr (funcall op-forw toklevels))
  716. ;; levels))
  717. ;; (setq levels nil))
  718. ))
  719. ;; We matched the topmost operator. If the new operator
  720. ;; is the last in the corresponding BNF rule, we're done.
  721. ((not (numberp (funcall op-forw toklevels)))
  722. ;; It is the last element, let's stop here.
  723. (throw 'return (list nil (point) token)))
  724. ;; If the new operator is not the last in the BNF rule,
  725. ;; and is not associative, it's one of the inner operators
  726. ;; (like the "in" in "let .. in .. end"), so keep looking.
  727. ((not (smie--associative-p toklevels))
  728. (push toklevels levels))
  729. ;; The new operator is associative. Two cases:
  730. ;; - it's really just an associative operator (like + or ;)
  731. ;; in which case we should have stopped right before.
  732. ((and lastlevels
  733. (smie--associative-p (car lastlevels)))
  734. (throw 'return
  735. (prog1 (list (or (car toklevels) t) (point) token)
  736. (goto-char pos))))
  737. ;; - it's an associative operator within a larger construct
  738. ;; (e.g. an "elsif"), so we should just ignore it and keep
  739. ;; looking for the closing element.
  740. (t (setq levels lastlevels))))))))
  741. levels)
  742. (setq halfsexp nil)))))
  743. (defun smie-backward-sexp (&optional halfsexp)
  744. "Skip over one sexp.
  745. HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
  746. first token we see is an operator, skip over its left-hand-side argument.
  747. HALFSEXP can also be a token, in which case we should skip the text
  748. assuming it is the left-hand-side argument of that token.
  749. Possible return values:
  750. (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
  751. is too high. LEFT-LEVEL is the left-level of TOKEN,
  752. POS is its start position in the buffer.
  753. (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
  754. (nil POS TOKEN): we skipped over a paren-like pair.
  755. nil: we skipped over an identifier, matched parentheses, ..."
  756. (smie-next-sexp
  757. (indirect-function smie-backward-token-function)
  758. (indirect-function 'backward-sexp)
  759. (indirect-function 'smie-op-left)
  760. (indirect-function 'smie-op-right)
  761. halfsexp))
  762. (defun smie-forward-sexp (&optional halfsexp)
  763. "Skip over one sexp.
  764. HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
  765. first token we see is an operator, skip over its right-hand-side argument.
  766. HALFSEXP can also be a token, in which case we should skip the text
  767. assuming it is the right-hand-side argument of that token.
  768. Possible return values:
  769. (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
  770. is too high. RIGHT-LEVEL is the right-level of TOKEN,
  771. POS is its end position in the buffer.
  772. (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
  773. (nil POS TOKEN): we skipped over a paren-like pair.
  774. nil: we skipped over an identifier, matched parentheses, ..."
  775. (smie-next-sexp
  776. (indirect-function smie-forward-token-function)
  777. (indirect-function 'forward-sexp)
  778. (indirect-function 'smie-op-right)
  779. (indirect-function 'smie-op-left)
  780. halfsexp))
  781. ;;; Miscellaneous commands using the precedence parser.
  782. (defun smie-backward-sexp-command (&optional n)
  783. "Move backward through N logical elements."
  784. (interactive "^p")
  785. (smie-forward-sexp-command (- n)))
  786. (defun smie-forward-sexp-command (&optional n)
  787. "Move forward through N logical elements."
  788. (interactive "^p")
  789. (let ((forw (> n 0))
  790. (forward-sexp-function nil))
  791. (while (/= n 0)
  792. (setq n (- n (if forw 1 -1)))
  793. (let ((pos (point))
  794. (res (if forw
  795. (smie-forward-sexp 'halfsexp)
  796. (smie-backward-sexp 'halfsexp))))
  797. (if (and (car res) (= pos (point)) (not (if forw (eobp) (bobp))))
  798. (signal 'scan-error
  799. (list "Containing expression ends prematurely"
  800. (cadr res) (cadr res)))
  801. nil)))))
  802. (defvar smie-closer-alist nil
  803. "Alist giving the closer corresponding to an opener.")
  804. (defun smie-close-block ()
  805. "Close the closest surrounding block."
  806. (interactive)
  807. (let ((closer
  808. (save-excursion
  809. (backward-up-list 1)
  810. (if (looking-at "\\s(")
  811. (string (cdr (syntax-after (point))))
  812. (let* ((open (funcall smie-forward-token-function))
  813. (closer (cdr (assoc open smie-closer-alist)))
  814. (levels (list (assoc open smie-grammar)))
  815. (seen '())
  816. (found '()))
  817. (cond
  818. ;; Even if we improve the auto-computation of closers,
  819. ;; there are still cases where we need manual
  820. ;; intervention, e.g. for Octave's use of `until'
  821. ;; as a pseudo-closer of `do'.
  822. (closer)
  823. ((or (equal levels '(nil)) (numberp (nth 1 (car levels))))
  824. (error "Doesn't look like a block"))
  825. (t
  826. ;; Now that smie-setup automatically sets smie-closer-alist
  827. ;; from the BNF, this is not really needed any more.
  828. (while levels
  829. (let ((level (pop levels)))
  830. (dolist (other smie-grammar)
  831. (when (and (eq (nth 2 level) (nth 1 other))
  832. (not (memq other seen)))
  833. (push other seen)
  834. (if (numberp (nth 2 other))
  835. (push other levels)
  836. (push (car other) found))))))
  837. (cond
  838. ((null found) (error "No known closer for opener %s" open))
  839. ;; What should we do if there are various closers?
  840. (t (car found))))))))))
  841. (unless (save-excursion (skip-chars-backward " \t") (bolp))
  842. (newline))
  843. (insert closer)
  844. (if (save-excursion (skip-chars-forward " \t") (eolp))
  845. (indent-according-to-mode)
  846. (reindent-then-newline-and-indent))))
  847. (defun smie-down-list (&optional arg)
  848. "Move forward down one level paren-like blocks. Like `down-list'.
  849. With argument ARG, do this that many times.
  850. A negative argument means move backward but still go down a level.
  851. This command assumes point is not in a string or comment."
  852. (interactive "p")
  853. (let ((start (point))
  854. (inc (if (< arg 0) -1 1))
  855. (offset (if (< arg 0) 1 0))
  856. (next-token (if (< arg 0)
  857. smie-backward-token-function
  858. smie-forward-token-function)))
  859. (while (/= arg 0)
  860. (setq arg (- arg inc))
  861. (while
  862. (let* ((pos (point))
  863. (token (funcall next-token))
  864. (levels (assoc token smie-grammar)))
  865. (cond
  866. ((zerop (length token))
  867. (if (if (< inc 0) (looking-back "\\s(\\|\\s)" (1- (point)))
  868. (looking-at "\\s(\\|\\s)"))
  869. ;; Go back to `start' in case of an error. This presumes
  870. ;; none of the token we've found until now include a ( or ).
  871. (progn (goto-char start) (down-list inc) nil)
  872. (forward-sexp inc)
  873. (/= (point) pos)))
  874. ((and levels (not (numberp (nth (+ 1 offset) levels)))) nil)
  875. ((and levels (not (numberp (nth (- 2 offset) levels))))
  876. (let ((end (point)))
  877. (goto-char start)
  878. (signal 'scan-error
  879. (list "Containing expression ends prematurely"
  880. pos end))))
  881. (t)))))))
  882. (defvar smie-blink-matching-triggers '(?\s ?\n)
  883. "Chars which might trigger `blink-matching-open'.
  884. These can include the final chars of end-tokens, or chars that are
  885. typically inserted right after an end token.
  886. I.e. a good choice can be:
  887. (delete-dups
  888. (mapcar (lambda (kw) (aref (cdr kw) (1- (length (cdr kw)))))
  889. smie-closer-alist))")
  890. (defcustom smie-blink-matching-inners t
  891. "Whether SMIE should blink to matching opener for inner keywords.
  892. If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
  893. :type 'boolean
  894. :group 'smie)
  895. (defun smie-blink-matching-check (start end)
  896. (save-excursion
  897. (goto-char end)
  898. (let ((ender (funcall smie-backward-token-function)))
  899. (cond
  900. ((not (and ender (rassoc ender smie-closer-alist)))
  901. ;; This not is one of the begin..end we know how to check.
  902. (blink-matching-check-mismatch start end))
  903. ((not start) t)
  904. ((eq t (car (rassoc ender smie-closer-alist))) nil)
  905. (t
  906. (goto-char start)
  907. (let ((starter (funcall smie-forward-token-function)))
  908. (not (member (cons starter ender) smie-closer-alist))))))))
  909. (defun smie-blink-matching-open ()
  910. "Blink the matching opener when applicable.
  911. This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
  912. (let ((pos (point)) ;Position after the close token.
  913. token)
  914. (when (and blink-matching-paren
  915. smie-closer-alist ; Optimization.
  916. (or (eq (char-before) last-command-event) ;; Sanity check.
  917. (save-excursion
  918. (or (progn (skip-chars-backward " \t")
  919. (setq pos (point))
  920. (eq (char-before) last-command-event))
  921. (progn (skip-chars-backward " \n\t")
  922. (setq pos (point))
  923. (eq (char-before) last-command-event)))))
  924. (memq last-command-event smie-blink-matching-triggers)
  925. (not (nth 8 (syntax-ppss))))
  926. (save-excursion
  927. (setq token (funcall smie-backward-token-function))
  928. (when (and (eq (point) (1- pos))
  929. (= 1 (length token))
  930. (not (rassoc token smie-closer-alist)))
  931. ;; The trigger char is itself a token but is not one of the
  932. ;; closers (e.g. ?\; in Octave mode), so go back to the
  933. ;; previous token.
  934. (setq pos (point))
  935. (setq token (funcall smie-backward-token-function)))
  936. (when (rassoc token smie-closer-alist)
  937. ;; We're after a close token. Let's still make sure we
  938. ;; didn't skip a comment to find that token.
  939. (funcall smie-forward-token-function)
  940. (when (and (save-excursion
  941. ;; Skip the trigger char, if applicable.
  942. (if (eq (char-after) last-command-event)
  943. (forward-char 1))
  944. (if (eq ?\n last-command-event)
  945. ;; Skip any auto-indentation, if applicable.
  946. (skip-chars-forward " \t"))
  947. (>= (point) pos))
  948. ;; If token ends with a trigger char, don't blink for
  949. ;; anything else than this trigger char, lest we'd blink
  950. ;; both when inserting the trigger char and when
  951. ;; inserting a subsequent trigger char like SPC.
  952. (or (eq (char-before) last-command-event)
  953. (not (memq (char-before)
  954. smie-blink-matching-triggers)))
  955. (or smie-blink-matching-inners
  956. (not (numberp (nth 2 (assoc token smie-grammar))))))
  957. ;; The major mode might set blink-matching-check-function
  958. ;; buffer-locally so that interactive calls to
  959. ;; blink-matching-open work right, but let's not presume
  960. ;; that's the case.
  961. (let ((blink-matching-check-function #'smie-blink-matching-check))
  962. (blink-matching-open))))))))
  963. ;;; The indentation engine.
  964. (defcustom smie-indent-basic 4
  965. "Basic amount of indentation."
  966. :type 'integer
  967. :group 'smie)
  968. (defvar smie-rules-function 'ignore
  969. "Function providing the indentation rules.
  970. It takes two arguments METHOD and ARG where the meaning of ARG
  971. and the expected return value depends on METHOD.
  972. METHOD can be:
  973. - :after, in which case ARG is a token and the function should return the
  974. OFFSET to use for indentation after ARG.
  975. - :before, in which case ARG is a token and the function should return the
  976. OFFSET to use to indent ARG itself.
  977. - :elem, in which case the function should return either:
  978. - the offset to use to indent function arguments (ARG = `arg')
  979. - the basic indentation step (ARG = `basic').
  980. - :list-intro, in which case ARG is a token and the function should return
  981. non-nil if TOKEN is followed by a list of expressions (not separated by any
  982. token) rather than an expression.
  983. When ARG is a token, the function is called with point just before that token.
  984. A return value of nil always means to fallback on the default behavior, so the
  985. function should return nil for arguments it does not expect.
  986. OFFSET can be:
  987. nil use the default indentation rule.
  988. \(column . COLUMN) indent to column COLUMN.
  989. NUMBER offset by NUMBER, relative to a base token
  990. which is the current token for :after and
  991. its parent for :before.
  992. The functions whose name starts with \"smie-rule-\" are helper functions
  993. designed specifically for use in this function.")
  994. (defalias 'smie-rule-hanging-p 'smie-indent--hanging-p)
  995. (defun smie-indent--hanging-p ()
  996. "Return non-nil if the current token is \"hanging\".
  997. A hanging keyword is one that's at the end of a line except it's not at
  998. the beginning of a line."
  999. (and (not (smie-indent--bolp))
  1000. (save-excursion
  1001. (<= (line-end-position)
  1002. (progn
  1003. (when (zerop (length (funcall smie-forward-token-function)))
  1004. ;; Could be an open-paren.
  1005. (forward-char 1))
  1006. (skip-chars-forward " \t")
  1007. (or (eolp)
  1008. (and (looking-at comment-start-skip)
  1009. (forward-comment (point-max))))
  1010. (point))))))
  1011. (defalias 'smie-rule-bolp 'smie-indent--bolp)
  1012. (defun smie-indent--bolp ()
  1013. "Return non-nil if the current token is the first on the line."
  1014. (save-excursion (skip-chars-backward " \t") (bolp)))
  1015. ;; Dynamically scoped.
  1016. (defvar smie--parent) (defvar smie--after) (defvar smie--token)
  1017. (defun smie-indent--parent ()
  1018. (or smie--parent
  1019. (save-excursion
  1020. (let* ((pos (point))
  1021. (tok (funcall smie-forward-token-function)))
  1022. (unless (numberp (cadr (assoc tok smie-grammar)))
  1023. (goto-char pos))
  1024. (setq smie--parent
  1025. (or (smie-backward-sexp 'halfsexp)
  1026. (let (res)
  1027. (while (null (setq res (smie-backward-sexp))))
  1028. (list nil (point) (nth 2 res)))))))))
  1029. (defun smie-rule-parent-p (&rest parents)
  1030. "Return non-nil if the current token's parent is among PARENTS.
  1031. Only meaningful when called from within `smie-rules-function'."
  1032. (member (nth 2 (smie-indent--parent)) parents))
  1033. (defun smie-rule-next-p (&rest tokens)
  1034. "Return non-nil if the next token is among TOKENS.
  1035. Only meaningful when called from within `smie-rules-function'."
  1036. (let ((next
  1037. (save-excursion
  1038. (unless smie--after
  1039. (smie-indent-forward-token) (setq smie--after (point)))
  1040. (goto-char smie--after)
  1041. (smie-indent-forward-token))))
  1042. (member (car next) tokens)))
  1043. (defun smie-rule-prev-p (&rest tokens)
  1044. "Return non-nil if the previous token is among TOKENS."
  1045. (let ((prev (save-excursion
  1046. (smie-indent-backward-token))))
  1047. (member (car prev) tokens)))
  1048. (defun smie-rule-sibling-p ()
  1049. "Return non-nil if the parent is actually a sibling.
  1050. Only meaningful when called from within `smie-rules-function'."
  1051. (eq (car (smie-indent--parent))
  1052. (cadr (assoc smie--token smie-grammar))))
  1053. (defun smie-rule-parent (&optional offset)
  1054. "Align with parent.
  1055. If non-nil, OFFSET should be an integer giving an additional offset to apply.
  1056. Only meaningful when called from within `smie-rules-function'."
  1057. (save-excursion
  1058. (goto-char (cadr (smie-indent--parent)))
  1059. (cons 'column
  1060. (+ (or offset 0)
  1061. ;; Use smie-indent-virtual when indenting relative to an opener:
  1062. ;; this will also by default use current-column unless
  1063. ;; that opener is hanging, but will additionally consult
  1064. ;; rules-function, so it gives it a chance to tweak
  1065. ;; indentation (e.g. by forcing indentation relative to
  1066. ;; its own parent, as in fn a => fn b => fn c =>).
  1067. (if (or (listp (car smie--parent)) (smie-indent--hanging-p))
  1068. (smie-indent-virtual) (current-column))))))
  1069. (defvar smie-rule-separator-outdent 2)
  1070. (defun smie-indent--separator-outdent ()
  1071. ;; FIXME: Here we actually have several reasonable behaviors.
  1072. ;; E.g. for a parent token of "FOO" and a separator ";" we may want to:
  1073. ;; 1- left-align ; with FOO.
  1074. ;; 2- right-align ; with FOO.
  1075. ;; 3- align content after ; with content after FOO.
  1076. ;; 4- align content plus add/remove spaces so as to align ; with FOO.
  1077. ;; Currently, we try to align the contents (option 3) which actually behaves
  1078. ;; just like option 2 (if the number of spaces after FOO and ; is equal).
  1079. (let ((afterpos (save-excursion
  1080. (let ((tok (funcall smie-forward-token-function)))
  1081. (unless tok
  1082. (with-demoted-errors
  1083. (error "smie-rule-separator: can't skip token %s"
  1084. smie--token))))
  1085. (skip-chars-forward " ")
  1086. (unless (eolp) (point)))))
  1087. (or (and afterpos
  1088. ;; This should always be true, unless
  1089. ;; smie-forward-token-function skipped a \n.
  1090. (< afterpos (line-end-position))
  1091. (- afterpos (point)))
  1092. smie-rule-separator-outdent)))
  1093. (defun smie-rule-separator (method)
  1094. "Indent current token as a \"separator\".
  1095. By \"separator\", we mean here a token whose sole purpose is to separate
  1096. various elements within some enclosing syntactic construct, and which does
  1097. not have any semantic significance in itself (i.e. it would typically no exist
  1098. as a node in an abstract syntax tree).
  1099. Such a token is expected to have an associative syntax and be closely tied
  1100. to its syntactic parent. Typical examples are \",\" in lists of arguments
  1101. \(enclosed inside parentheses), or \";\" in sequences of instructions (enclosed
  1102. in a {..} or begin..end block).
  1103. METHOD should be the method name that was passed to `smie-rules-function'.
  1104. Only meaningful when called from within `smie-rules-function'."
  1105. ;; FIXME: The code below works OK for cases where the separators
  1106. ;; are placed consistently always at beginning or always at the end,
  1107. ;; but not if some are at the beginning and others are at the end.
  1108. ;; I.e. it gets confused in cases such as:
  1109. ;; ( a
  1110. ;; , a,
  1111. ;; b
  1112. ;; , c,
  1113. ;; d
  1114. ;; )
  1115. ;;
  1116. ;; Assuming token is associative, the default rule for associative
  1117. ;; tokens (which assumes an infix operator) works fine for many cases.
  1118. ;; We mostly need to take care of the case where token is at beginning of
  1119. ;; line, in which case we want to align it with its enclosing parent.
  1120. (cond
  1121. ((and (eq method :before) (smie-rule-bolp) (not (smie-rule-sibling-p)))
  1122. (let ((parent-col (cdr (smie-rule-parent)))
  1123. (parent-pos-col ;FIXME: we knew this when computing smie--parent.
  1124. (save-excursion
  1125. (goto-char (cadr smie--parent))
  1126. (smie-indent-forward-token)
  1127. (forward-comment (point-max))
  1128. (current-column))))
  1129. (cons 'column
  1130. (max parent-col
  1131. (min parent-pos-col
  1132. (- parent-pos-col (smie-indent--separator-outdent)))))))
  1133. ((and (eq method :after) (smie-indent--bolp))
  1134. (smie-indent--separator-outdent))))
  1135. (defun smie-indent--offset (elem)
  1136. (or (funcall smie-rules-function :elem elem)
  1137. (if (not (eq elem 'basic))
  1138. (funcall smie-rules-function :elem 'basic))
  1139. smie-indent-basic))
  1140. (defun smie-indent--rule (method token
  1141. ;; FIXME: Too many parameters.
  1142. &optional after parent base-pos)
  1143. "Compute indentation column according to `indent-rule-functions'.
  1144. METHOD and TOKEN are passed to `indent-rule-functions'.
  1145. AFTER is the position after TOKEN, if known.
  1146. PARENT is the parent info returned by `smie-backward-sexp', if known.
  1147. BASE-POS is the position relative to which offsets should be applied."
  1148. ;; This is currently called in 3 cases:
  1149. ;; - :before opener, where rest=nil but base-pos could as well be parent.
  1150. ;; - :before other, where
  1151. ;; ; after=nil
  1152. ;; ; parent is set
  1153. ;; ; base-pos=parent
  1154. ;; - :after tok, where
  1155. ;; ; after is set; parent=nil; base-pos=point;
  1156. (save-excursion
  1157. (let ((offset
  1158. (let ((smie--parent parent)
  1159. (smie--token token)
  1160. (smie--after after))
  1161. (funcall smie-rules-function method token))))
  1162. (cond
  1163. ((not offset) nil)
  1164. ((eq (car-safe offset) 'column) (cdr offset))
  1165. ((integerp offset)
  1166. (+ offset
  1167. (if (null base-pos) 0
  1168. (goto-char base-pos)
  1169. ;; Use smie-indent-virtual when indenting relative to an opener:
  1170. ;; this will also by default use current-column unless
  1171. ;; that opener is hanging, but will additionally consult
  1172. ;; rules-function, so it gives it a chance to tweak indentation
  1173. ;; (e.g. by forcing indentation relative to its own parent, as in
  1174. ;; fn a => fn b => fn c =>).
  1175. ;; When parent==nil it doesn't matter because the only case
  1176. ;; where it's really used is when the base-pos is hanging anyway.
  1177. (if (or (and parent (null (car parent)))
  1178. (smie-indent--hanging-p))
  1179. (smie-indent-virtual) (current-column)))))
  1180. (t (error "Unknown indentation offset %s" offset))))))
  1181. (defun smie-indent-forward-token ()
  1182. "Skip token forward and return it, along with its levels."
  1183. (let ((tok (funcall smie-forward-token-function)))
  1184. (cond
  1185. ((< 0 (length tok)) (assoc tok smie-grammar))
  1186. ((looking-at "\\s(\\|\\s)\\(\\)")
  1187. (forward-char 1)
  1188. (cons (buffer-substring (1- (point)) (point))
  1189. (if (match-end 1) '(0 nil) '(nil 0)))))))
  1190. (defun smie-indent-backward-token ()
  1191. "Skip token backward and return it, along with its levels."
  1192. (let ((tok (funcall smie-backward-token-function))
  1193. class)
  1194. (cond
  1195. ((< 0 (length tok)) (assoc tok smie-grammar))
  1196. ;; 4 == open paren syntax, 5 == close.
  1197. ((memq (setq class (syntax-class (syntax-after (1- (point))))) '(4 5))
  1198. (forward-char -1)
  1199. (cons (buffer-substring (point) (1+ (point)))
  1200. (if (eq class 4) '(nil 0) '(0 nil)))))))
  1201. (defun smie-indent-virtual ()
  1202. ;; We used to take an optional arg (with value :not-hanging) to specify that
  1203. ;; we should only use (smie-indent-calculate) if we're looking at a hanging
  1204. ;; keyword. This was a bad idea, because the virtual indent of a position
  1205. ;; should not depend on the caller, since it leads to situations where two
  1206. ;; dependent indentations get indented differently.
  1207. "Compute the virtual indentation to use for point.
  1208. This is used when we're not trying to indent point but just
  1209. need to compute the column at which point should be indented
  1210. in order to figure out the indentation of some other (further down) point."
  1211. ;; Trust pre-existing indentation on other lines.
  1212. (if (smie-indent--bolp) (current-column) (smie-indent-calculate)))
  1213. (defun smie-indent-fixindent ()
  1214. ;; Obey the `fixindent' special comment.
  1215. (and (smie-indent--bolp)
  1216. (save-excursion
  1217. (comment-normalize-vars)
  1218. (re-search-forward (concat comment-start-skip
  1219. "fixindent"
  1220. comment-end-skip)
  1221. ;; 1+ to account for the \n comment termination.
  1222. (1+ (line-end-position)) t))
  1223. (current-column)))
  1224. (defun smie-indent-bob ()
  1225. ;; Start the file at column 0.
  1226. (save-excursion
  1227. (forward-comment (- (point)))
  1228. (if (bobp) 0)))
  1229. (defun smie-indent-close ()
  1230. ;; Align close paren with opening paren.
  1231. (save-excursion
  1232. ;; (forward-comment (point-max))
  1233. (when (looking-at "\\s)")
  1234. (while (not (zerop (skip-syntax-forward ")")))
  1235. (skip-chars-forward " \t"))
  1236. (condition-case nil
  1237. (progn
  1238. (backward-sexp 1)
  1239. (smie-indent-virtual)) ;:not-hanging
  1240. (scan-error nil)))))
  1241. (defun smie-indent-keyword (&optional token)
  1242. "Indent point based on the token that follows it immediately.
  1243. If TOKEN is non-nil, assume that that is the token that follows point.
  1244. Returns either a column number or nil if it considers that indentation
  1245. should not be computed on the basis of the following token."
  1246. (save-excursion
  1247. (let* ((pos (point))
  1248. (toklevels
  1249. (if token
  1250. (assoc token smie-grammar)
  1251. (let* ((res (smie-indent-forward-token)))
  1252. ;; Ignore tokens on subsequent lines.
  1253. (if (and (< pos (line-beginning-position))
  1254. ;; Make sure `token' also *starts* on another line.
  1255. (save-excursion
  1256. (smie-indent-backward-token)
  1257. (< pos (line-beginning-position))))
  1258. nil
  1259. (goto-char pos)
  1260. res)))))
  1261. (setq token (pop toklevels))
  1262. (cond
  1263. ((null (cdr toklevels)) nil) ;Not a keyword.
  1264. ((not (numberp (car toklevels)))
  1265. ;; Different cases:
  1266. ;; - smie-indent--bolp: "indent according to others".
  1267. ;; - common hanging: "indent according to others".
  1268. ;; - SML-let hanging: "indent like parent".
  1269. ;; - if-after-else: "indent-like parent".
  1270. ;; - middle-of-line: "trust current position".
  1271. (cond
  1272. ((smie-indent--rule :before token))
  1273. ((smie-indent--bolp) ;I.e. non-virtual indent.
  1274. ;; For an open-paren-like thingy at BOL, always indent only
  1275. ;; based on other rules (typically smie-indent-after-keyword).
  1276. nil)
  1277. (t
  1278. ;; By default use point unless we're hanging.
  1279. (unless (smie-indent--hanging-p) (current-column)))))
  1280. (t
  1281. ;; FIXME: This still looks too much like black magic!!
  1282. (let* ((parent (smie-backward-sexp token)))
  1283. ;; Different behaviors:
  1284. ;; - align with parent.
  1285. ;; - parent + offset.
  1286. ;; - after parent's column + offset (actually, after or before
  1287. ;; depending on where backward-sexp stopped).
  1288. ;; ? let it drop to some other indentation function (almost never).
  1289. ;; ? parent + offset + parent's own offset.
  1290. ;; Different cases:
  1291. ;; - bump into a same-level operator.
  1292. ;; - bump into a specific known parent.
  1293. ;; - find a matching open-paren thingy.
  1294. ;; - bump into some random parent.
  1295. ;; ? borderline case (almost never).
  1296. ;; ? bump immediately into a parent.
  1297. (cond
  1298. ((not (or (< (point) pos)
  1299. (and (cadr parent) (< (cadr parent) pos))))
  1300. ;; If we didn't move at all, that means we didn't really skip
  1301. ;; what we wanted. Should almost never happen, other than
  1302. ;; maybe when an infix or close-paren is at the beginning
  1303. ;; of a buffer.
  1304. nil)
  1305. ((save-excursion
  1306. (goto-char pos)
  1307. (smie-indent--rule :before token nil parent (cadr parent))))
  1308. ((eq (car parent) (car toklevels))
  1309. ;; We bumped into a same-level operator; align with it.
  1310. (if (and (smie-indent--bolp) (/= (point) pos)
  1311. (save-excursion
  1312. (goto-char (goto-char (cadr parent)))
  1313. (not (smie-indent--bolp))))
  1314. ;; If the parent is at EOL and its children are indented like
  1315. ;; itself, then we can just obey the indentation chosen for the
  1316. ;; child.
  1317. ;; This is important for operators like ";" which
  1318. ;; are usually at EOL (and have an offset of 0): otherwise we'd
  1319. ;; always go back over all the statements, which is
  1320. ;; a performance problem and would also mean that fixindents
  1321. ;; in the middle of such a sequence would be ignored.
  1322. ;;
  1323. ;; This is a delicate point!
  1324. ;; Even if the offset is not 0, we could follow the same logic
  1325. ;; and subtract the offset from the child's indentation.
  1326. ;; But that would more often be a bad idea: OT1H we generally
  1327. ;; want to reuse the closest similar indentation point, so that
  1328. ;; the user's choice (or the fixindents) are obeyed. But OTOH
  1329. ;; we don't want this to affect "unrelated" parts of the code.
  1330. ;; E.g. a fixindent in the body of a "begin..end" should not
  1331. ;; affect the indentation of the "end".
  1332. (current-column)
  1333. (goto-char (cadr parent))
  1334. ;; Don't use (smie-indent-virtual :not-hanging) here, because we
  1335. ;; want to jump back over a sequence of same-level ops such as
  1336. ;; a -> b -> c
  1337. ;; -> d
  1338. ;; So as to align with the earliest appropriate place.
  1339. (smie-indent-virtual)))
  1340. (t
  1341. (if (and (= (point) pos) (smie-indent--bolp))
  1342. ;; Since we started at BOL, we're not computing a virtual
  1343. ;; indentation, and we're still at the starting point, so
  1344. ;; we can't use `current-column' which would cause
  1345. ;; indentation to depend on itself and we can't use
  1346. ;; smie-indent-virtual since that would be an inf-loop.
  1347. nil
  1348. ;; In indent-keyword, if we're indenting `then' wrt `if', we
  1349. ;; want to use indent-virtual rather than use just
  1350. ;; current-column, so that we can apply the (:before . "if")
  1351. ;; rule which does the "else if" dance in SML. But in other
  1352. ;; cases, we do not want to use indent-virtual (e.g. indentation
  1353. ;; of "*" w.r.t "+", or ";" wrt "("). We could just always use
  1354. ;; indent-virtual and then have indent-rules say explicitly to
  1355. ;; use `point' after things like "(" or "+" when they're not at
  1356. ;; EOL, but you'd end up with lots of those rules.
  1357. ;; So we use a heuristic here, which is that we only use virtual
  1358. ;; if the parent is tightly linked to the child token (they're
  1359. ;; part of the same BNF rule).
  1360. (if (car parent) (current-column) (smie-indent-virtual)))))))))))
  1361. (defun smie-indent-comment ()
  1362. "Compute indentation of a comment."
  1363. ;; Don't do it for virtual indentations. We should normally never be "in
  1364. ;; front of a comment" when doing virtual-indentation anyway. And if we are
  1365. ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
  1366. (and (smie-indent--bolp)
  1367. (let ((pos (point)))
  1368. (save-excursion
  1369. (beginning-of-line)
  1370. (and (re-search-forward comment-start-skip (line-end-position) t)
  1371. (eq pos (or (match-end 1) (match-beginning 0))))))
  1372. (save-excursion
  1373. (forward-comment (point-max))
  1374. (skip-chars-forward " \t\r\n")
  1375. (smie-indent-calculate))))
  1376. (defun smie-indent-comment-continue ()
  1377. ;; indentation of comment-continue lines.
  1378. (let ((continue (and comment-continue
  1379. (comment-string-strip comment-continue t t))))
  1380. (and (< 0 (length continue))
  1381. (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
  1382. (let ((ppss (syntax-ppss)))
  1383. (save-excursion
  1384. (forward-line -1)
  1385. (if (<= (point) (nth 8 ppss))
  1386. (progn (goto-char (1+ (nth 8 ppss))) (current-column))
  1387. (skip-chars-forward " \t")
  1388. (if (looking-at (regexp-quote continue))
  1389. (current-column))))))))
  1390. (defun smie-indent-comment-close ()
  1391. (and (boundp 'comment-end-skip)
  1392. comment-end-skip
  1393. (not (looking-at " \t*$")) ;Not just a \n comment-closer.
  1394. (looking-at comment-end-skip)
  1395. (let ((end (match-string 0)))
  1396. (and (nth 4 (syntax-ppss))
  1397. (save-excursion
  1398. (goto-char (nth 8 (syntax-ppss)))
  1399. (and (looking-at comment-start-skip)
  1400. (let ((start (match-string 0)))
  1401. ;; Align the common substring between starter
  1402. ;; and ender, if possible.
  1403. (if (string-match "\\(.+\\).*\n\\(.*?\\)\\1"
  1404. (concat start "\n" end))
  1405. (+ (current-column) (match-beginning 0)
  1406. (- (match-beginning 2) (match-end 2)))
  1407. (current-column)))))))))
  1408. (defun smie-indent-comment-inside ()
  1409. (and (nth 4 (syntax-ppss))
  1410. 'noindent))
  1411. (defun smie-indent-inside-string ()
  1412. (and (nth 3 (syntax-ppss))
  1413. 'noindent))
  1414. (defun smie-indent-after-keyword ()
  1415. ;; Indentation right after a special keyword.
  1416. (save-excursion
  1417. (let* ((pos (point))
  1418. (toklevel (smie-indent-backward-token))
  1419. (tok (car toklevel)))
  1420. (cond
  1421. ((null toklevel) nil)
  1422. ((smie-indent--rule :after tok pos nil (point)))
  1423. ;; The default indentation after a keyword/operator is
  1424. ;; 0 for infix, t for prefix, and use another rule
  1425. ;; for postfix.
  1426. ((not (numberp (nth 2 toklevel))) nil) ;A closer.
  1427. ((or (not (numberp (nth 1 toklevel))) ;An opener.
  1428. (rassoc tok smie-closer-alist)) ;An inner.
  1429. (+ (smie-indent-virtual) (smie-indent--offset 'basic))) ;
  1430. (t (smie-indent-virtual)))))) ;An infix.
  1431. (defun smie-indent-exps ()
  1432. ;; Indentation of sequences of simple expressions without
  1433. ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
  1434. ;; Can be a list of expressions or a function call.
  1435. ;; If it's a function call, the first element is special (it's the
  1436. ;; function). We distinguish function calls from mere lists of
  1437. ;; expressions based on whether the preceding token is listed in
  1438. ;; the `list-intro' entry of smie-indent-rules.
  1439. ;;
  1440. ;; TODO: to indent Lisp code, we should add a way to specify
  1441. ;; particular indentation for particular args depending on the
  1442. ;; function (which would require always skipping back until the
  1443. ;; function).
  1444. ;; TODO: to indent C code, such as "if (...) {...}" we might need
  1445. ;; to add similar indentation hooks for particular positions, but
  1446. ;; based on the preceding token rather than based on the first exp.
  1447. (save-excursion
  1448. (let ((positions nil)
  1449. arg)
  1450. (while (and (null (car (smie-backward-sexp)))
  1451. (push (point) positions)
  1452. (not (smie-indent--bolp))))
  1453. (save-excursion
  1454. ;; Figure out if the atom we just skipped is an argument rather
  1455. ;; than a function.
  1456. (setq arg
  1457. (or (null (car (smie-backward-sexp)))
  1458. (funcall smie-rules-function :list-intro
  1459. (funcall smie-backward-token-function)))))
  1460. (cond
  1461. ((null positions)
  1462. ;; We're the first expression of the list. In that case, the
  1463. ;; indentation should be (have been) determined by its context.
  1464. nil)
  1465. (arg
  1466. ;; There's a previous element, and it's not special (it's not
  1467. ;; the function), so let's just align with that one.
  1468. (goto-char (car positions))
  1469. (current-column))
  1470. ((cdr positions)
  1471. ;; We skipped some args plus the function and bumped into something.
  1472. ;; Align with the first arg.
  1473. (goto-char (cadr positions))
  1474. (current-column))
  1475. (positions
  1476. ;; We're the first arg.
  1477. (goto-char (car positions))
  1478. (+ (smie-indent--offset 'args)
  1479. ;; We used to use (smie-indent-virtual), but that
  1480. ;; doesn't seem right since it might then indent args less than
  1481. ;; the function itself.
  1482. (current-column)))))))
  1483. (defvar smie-indent-functions
  1484. '(smie-indent-fixindent smie-indent-bob smie-indent-close
  1485. smie-indent-comment smie-indent-comment-continue smie-indent-comment-close
  1486. smie-indent-comment-inside smie-indent-inside-string
  1487. smie-indent-keyword smie-indent-after-keyword
  1488. smie-indent-exps)
  1489. "Functions to compute the indentation.
  1490. Each function is called with no argument, shouldn't move point, and should
  1491. return either nil if it has no opinion, or an integer representing the column
  1492. to which that point should be aligned, if we were to reindent it.")
  1493. (defun smie-indent-calculate ()
  1494. "Compute the indentation to use for point."
  1495. (run-hook-with-args-until-success 'smie-indent-functions))
  1496. (defun smie-indent-line ()
  1497. "Indent current line using the SMIE indentation engine."
  1498. (interactive)
  1499. (let* ((savep (point))
  1500. (indent (or (with-demoted-errors
  1501. (save-excursion
  1502. (forward-line 0)
  1503. (skip-chars-forward " \t")
  1504. (if (>= (point) savep) (setq savep nil))
  1505. (or (smie-indent-calculate) 0)))
  1506. 0)))
  1507. (if (not (numberp indent))
  1508. ;; If something funny is used (e.g. `noindent'), return it.
  1509. indent
  1510. (if (< indent 0) (setq indent 0)) ;Just in case.
  1511. (if savep
  1512. (save-excursion (indent-line-to indent))
  1513. (indent-line-to indent)))))
  1514. (defun smie-setup (grammar rules-function &rest keywords)
  1515. "Setup SMIE navigation and indentation.
  1516. GRAMMAR is a grammar table generated by `smie-prec2->grammar'.
  1517. RULES-FUNCTION is a set of indentation rules for use on `smie-rules-function'.
  1518. KEYWORDS are additional arguments, which can use the following keywords:
  1519. - :forward-token FUN
  1520. - :backward-token FUN"
  1521. (set (make-local-variable 'smie-rules-function) rules-function)
  1522. (set (make-local-variable 'smie-grammar) grammar)
  1523. (set (make-local-variable 'indent-line-function) 'smie-indent-line)
  1524. (set (make-local-variable 'forward-sexp-function)
  1525. 'smie-forward-sexp-command)
  1526. (while keywords
  1527. (let ((k (pop keywords))
  1528. (v (pop keywords)))
  1529. (case k
  1530. (:forward-token
  1531. (set (make-local-variable 'smie-forward-token-function) v))
  1532. (:backward-token
  1533. (set (make-local-variable 'smie-backward-token-function) v))
  1534. (t (message "smie-setup: ignoring unknown keyword %s" k)))))
  1535. (let ((ca (cdr (assq :smie-closer-alist grammar))))
  1536. (when ca
  1537. (set (make-local-variable 'smie-closer-alist) ca)
  1538. ;; Only needed for interactive calls to blink-matching-open.
  1539. (set (make-local-variable 'blink-matching-check-function)
  1540. #'smie-blink-matching-check)
  1541. (add-hook 'post-self-insert-hook
  1542. #'smie-blink-matching-open 'append 'local)
  1543. (set (make-local-variable 'smie-blink-matching-triggers)
  1544. (append smie-blink-matching-triggers
  1545. ;; Rather than wait for SPC to blink, try to blink as
  1546. ;; soon as we type the last char of a block ender.
  1547. (let ((closers (sort (mapcar #'cdr smie-closer-alist)
  1548. #'string-lessp))
  1549. (triggers ())
  1550. closer)
  1551. (while (setq closer (pop closers))
  1552. (unless (and closers
  1553. ;; FIXME: this eliminates prefixes of other
  1554. ;; closers, but we should probably
  1555. ;; eliminate prefixes of other keywords
  1556. ;; as well.
  1557. (string-prefix-p closer (car closers)))
  1558. (push (aref closer (1- (length closer))) triggers)))
  1559. (delete-dups triggers)))))))
  1560. (provide 'smie)
  1561. ;;; smie.el ends here