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