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