1 ;;; smie.el --- Simple Minded Indentation Engine
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: languages, lisp, internal, parsing, indentation
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
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
31 ;; So at some point I decided to try it out, by writing a new
32 ;; indentation code for Coq while trying to keep most of the code
33 ;; "table driven", where only the tables are Coq-specific. The result
34 ;; (which was used for Beluga-mode as well) turned out to be based on
35 ;; something pretty close to an operator precedence parser.
37 ;; So here is another rewrite, this time following the actual principles of
38 ;; operator precedence grammars. Why OPG? Even though they're among the
39 ;; weakest kinds of parsers, these parsers have some very desirable properties
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
50 ;; - they typically have no error handling and can't even detect a parsing
51 ;; error, so we don't have to worry about what to do in case of a syntax
52 ;; error because the parser just automatically does something. Better yet,
53 ;; we can afford to use a sloppy grammar.
55 ;; The development (especially the parts building the 2D precedence
56 ;; tables and then computing the precedence levels from it) is largely
57 ;; inspired from page 187-194 of "Parsing techniques" by Dick Grune
58 ;; and Ceriel Jacobs (BookBody.pdf available at
59 ;; http://www.cs.vu.nl/~dick/PTAPG.html).
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.
68 ;; FIXME: I think the behavior on empty lines is wrong. It shouldn't
69 ;; look at the next token on subsequent lines.
71 (eval-when-compile (require 'cl))
74 "Simple Minded Indentation Engine."
77 (defvar comment-continue)
78 (declare-function comment-string-strip "newcomment" (str beforep afterp))
80 ;;; Building precedence level tables from BNF specs.
82 ;; We have 4 different representations of a "grammar":
83 ;; - a BNF table, which is a list of BNF rules of the form
84 ;; (NONTERM RHS1 ... RHSn) where each RHS is a list of terminals (tokens)
85 ;; or nonterminals. Any element in these lists which does not appear as
86 ;; the `car' of a BNF rule is taken to be a terminal.
87 ;; - A list of precedences (key word "precs"), is a list, sorted
88 ;; from lowest to highest precedence, of precedence classes that
89 ;; have the form (ASSOCIATIVITY TERMINAL1 .. TERMINALn), where
90 ;; ASSOCIATIVITY can be `assoc', `left', `right' or `nonassoc'.
91 ;; - a 2 dimensional precedence table (key word "prec2"), is a 2D
92 ;; table recording the precedence relation (can be `<', `=', `>', or
93 ;; nil) between each pair of tokens.
94 ;; - a precedence-level table (key word "levels"), while is a alist
95 ;; giving for each token its left and right precedence level (a
96 ;; number or nil). This is used in `smie-op-levels'.
97 ;; The prec2 tables are only intermediate data structures: the source
98 ;; code normally provides a mix of BNF and precs tables, and then
99 ;; turns them into a levels table, which is what's used by the rest of
102 (defun smie-set-prec2tab (table x y val &optional override)
104 (let* ((key (cons x y))
105 (old (gethash key table)))
106 (if (and old (not (eq old val)))
107 (if (and override (gethash key override))
108 ;; FIXME: The override is meant to resolve ambiguities,
109 ;; but it also hides real conflicts. It would be great to
110 ;; be able to distinguish the two cases so that overrides
111 ;; don't hide real conflicts.
112 (puthash key (gethash key override) table)
113 (display-warning 'smie (format "Conflict: %s %s/%s %s" x old val y)))
114 (puthash key val table))))
116 (put 'smie-precs-precedence-table 'pure t)
117 (defun smie-precs-precedence-table (precs)
118 "Compute a 2D precedence table from a list of precedences.
119 PRECS should be a list, sorted by precedence (e.g. \"+\" will
120 come before \"*\"), of elements of the form \(left OP ...)
121 or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
122 one of those elements share the same precedence level and associativity."
123 (let ((prec2-table (make-hash-table :test 'equal)))
125 (dolist (op (cdr prec))
126 (let ((selfrule (cdr (assq (car prec)
127 '((left . >) (right . <) (assoc . =))))))
129 (dolist (other-op (cdr prec))
130 (smie-set-prec2tab prec2-table op other-op selfrule))))
131 (let ((op1 '<) (op2 '>))
132 (dolist (other-prec precs)
133 (if (eq prec other-prec)
135 (dolist (other-op (cdr other-prec))
136 (smie-set-prec2tab prec2-table op other-op op2)
137 (smie-set-prec2tab prec2-table other-op op op1)))))))
140 (put 'smie-merge-prec2s 'pure t)
141 (defun smie-merge-prec2s (&rest tables)
142 (if (null (cdr tables))
144 (let ((prec2 (make-hash-table :test 'equal)))
145 (dolist (table tables)
146 (maphash (lambda (k v)
148 (smie-set-prec2tab prec2 (car k) (cdr k) v)
149 (if (and (gethash k prec2)
150 (not (equal (gethash k prec2) v)))
151 (error "Conflicting values for %s property" k)
152 (puthash k v prec2))))
156 (put 'smie-bnf-precedence-table 'pure t)
157 (defun smie-bnf-precedence-table (bnf &rest precs)
158 (let ((nts (mapcar 'car bnf)) ;Non-terminals
163 (prec2 (make-hash-table :test 'equal))
164 (override (apply 'smie-merge-prec2s
165 (mapcar 'smie-precs-precedence-table precs)))
168 (let ((nt (car rules))
173 (dolist (rhs (cdr rules))
175 (signal 'wrong-type-argument `(consp ,rhs)))
176 (if (not (member (car rhs) nts))
177 (pushnew (car rhs) first-ops)
178 (pushnew (car rhs) first-nts)
179 (when (consp (cdr rhs))
180 ;; If the first is not an OP we add the second (which
181 ;; should be an OP if BNF is an "operator grammar").
182 ;; Strictly speaking, this should only be done if the
183 ;; first is a non-terminal which can expand to a phrase
184 ;; without any OP in it, but checking doesn't seem worth
185 ;; the trouble, and it lets the writer of the BNF
186 ;; be a bit more sloppy by skipping uninteresting base
187 ;; cases which are terminals but not OPs.
188 (assert (not (member (cadr rhs) nts)))
189 (pushnew (cadr rhs) first-ops)))
190 (let ((shr (reverse rhs)))
191 (if (not (member (car shr) nts))
192 (pushnew (car shr) last-ops)
193 (pushnew (car shr) last-nts)
194 (when (consp (cdr shr))
195 (assert (not (member (cadr shr) nts)))
196 (pushnew (cadr shr) last-ops)))))
197 (push (cons nt first-ops) first-ops-table)
198 (push (cons nt last-ops) last-ops-table)
199 (push (cons nt first-nts) first-nts-table)
200 (push (cons nt last-nts) last-nts-table)))
201 ;; Compute all first-ops by propagating the initial ones we have
202 ;; now, according to first-nts.
204 (while (prog1 again (setq again nil))
205 (dolist (first-nts first-nts-table)
206 (let* ((nt (pop first-nts))
207 (first-ops (assoc nt first-ops-table)))
208 (dolist (first-nt first-nts)
209 (dolist (op (cdr (assoc first-nt first-ops-table)))
210 (unless (member op first-ops)
212 (push op (cdr first-ops))))))))
213 ;; Same thing for last-ops.
215 (while (prog1 again (setq again nil))
216 (dolist (last-nts last-nts-table)
217 (let* ((nt (pop last-nts))
218 (last-ops (assoc nt last-ops-table)))
219 (dolist (last-nt last-nts)
220 (dolist (op (cdr (assoc last-nt last-ops-table)))
221 (unless (member op last-ops)
223 (push op (cdr last-ops))))))))
224 ;; Now generate the 2D precedence table.
226 (dolist (rhs (cdr rules))
229 ((member (car rhs) nts)
230 (dolist (last (cdr (assoc (car rhs) last-ops-table)))
231 (smie-set-prec2tab prec2 last (cadr rhs) '> override)))
232 ((member (cadr rhs) nts)
233 (dolist (first (cdr (assoc (cadr rhs) first-ops-table)))
234 (smie-set-prec2tab prec2 (car rhs) first '< override))
235 (if (and (cddr rhs) (not (member (car (cddr rhs)) nts)))
236 (smie-set-prec2tab prec2 (car rhs) (car (cddr rhs))
238 (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
239 (setq rhs (cdr rhs)))))
240 ;; Keep track of which tokens are openers/closer, so they can get a nil
241 ;; precedence in smie-prec2-levels.
242 (puthash :smie-open/close-alist (smie-bnf-classify bnf) prec2)
243 (puthash :smie-closer-alist (smie-bnf-closer-alist bnf) prec2)
246 ;; (defun smie-prec2-closer-alist (prec2 include-inners)
247 ;; "Build a closer-alist from a PREC2 table.
248 ;; The return value is in the same form as `smie-closer-alist'.
249 ;; INCLUDE-INNERS if non-nil means that inner keywords will be included
250 ;; in the table, e.g. the table will include things like (\"if\" . \"else\")."
251 ;; (let* ((non-openers '())
253 ;; ;; For each keyword, this gives the matching openers, if any.
254 ;; (openers (make-hash-table :test 'equal))
257 ;; ;; First, find the non-openers and non-closers.
258 ;; (maphash (lambda (k v)
259 ;; (unless (or (eq v '<) (member (cdr k) non-openers))
260 ;; (push (cdr k) non-openers))
261 ;; (unless (or (eq v '>) (member (car k) non-closers))
262 ;; (push (car k) non-closers)))
264 ;; ;; Then find the openers and closers.
265 ;; (maphash (lambda (k _)
266 ;; (unless (member (car k) non-openers)
267 ;; (puthash (car k) (list (car k)) openers))
268 ;; (unless (or (member (cdr k) non-closers)
269 ;; (member (cdr k) closers))
270 ;; (push (cdr k) closers)))
272 ;; ;; Then collect the matching elements.
275 ;; (maphash (lambda (k v)
277 ;; (let ((aopeners (gethash (car k) openers))
278 ;; (dopeners (gethash (cdr k) openers))
280 ;; (dolist (o aopeners)
281 ;; (unless (member o dopeners)
283 ;; (push o dopeners)))
286 ;; (puthash (cdr k) dopeners openers)))))
288 ;; ;; Finally, dump the resulting table.
289 ;; (let ((alist '()))
290 ;; (maphash (lambda (k v)
291 ;; (when (or include-inners (member k closers))
292 ;; (dolist (opener v)
293 ;; (unless (equal opener k)
294 ;; (push (cons opener k) alist)))))
298 (defun smie-bnf-closer-alist (bnf &optional no-inners)
299 ;; We can also build this closer-alist table from a prec2 table,
300 ;; but it takes more work, and the order is unpredictable, which
301 ;; is a problem for smie-close-block.
302 ;; More convenient would be to build it from a levels table since we
303 ;; always have this table (contrary to the BNF), but it has all the
304 ;; disadvantages of the prec2 case plus the disadvantage that the levels
305 ;; table has lost some info which would result in extra invalid pairs.
306 "Build a closer-alist from a BNF table.
307 The return value is in the same form as `smie-closer-alist'.
308 NO-INNERS if non-nil means that inner keywords will be excluded
309 from the table, e.g. the table will not include things like (\"if\" . \"else\")."
310 (let ((nts (mapcar #'car bnf)) ;non terminals.
313 (dolist (rhs (cdr nt))
314 (unless (or (< (length rhs) 2) (member (car rhs) nts))
316 (let ((last (car (last rhs))))
317 (unless (member last nts)
318 (pushnew (cons (car rhs) last) alist :test #'equal)))
319 ;; Reverse so that the "real" closer gets there first,
320 ;; which is important for smie-close-block.
321 (dolist (term (reverse (cdr rhs)))
322 (unless (member term nts)
323 (pushnew (cons (car rhs) term) alist :test #'equal)))))))
326 (defun smie-bnf-classify (bnf)
327 "Return a table classifying terminals.
328 Each terminal can either be an `opener', a `closer', or neither."
329 (let ((table (make-hash-table :test #'equal))
331 (dolist (category bnf)
332 (puthash (car category) 'neither table) ;Remove non-terminals.
333 (dolist (rhs (cdr category))
335 (puthash (pop rhs) 'neither table)
336 (let ((first (pop rhs)))
338 (if (memq (gethash first table) '(nil opener))
342 (puthash (pop rhs) 'neither table)) ;Remove internals.
343 (let ((last (pop rhs)))
345 (if (memq (gethash last table) '(nil closer))
348 (maphash (lambda (tok v)
349 (when (memq v '(closer opener))
350 (push (cons tok v) alist)))
354 (defun smie-debug--prec2-cycle (csts)
355 "Return a cycle in CSTS, assuming there's one.
356 CSTS is a list of pairs representing arcs in a graph."
357 ;; A PATH is of the form (START . REST) where REST is a reverse
358 ;; list of nodes through which the path goes.
359 (let ((paths (mapcar (lambda (pair) (list (car pair) (cdr pair))) csts))
362 (dolist (path (prog1 paths (setq paths nil)))
364 (when (eq (car cst) (nth 1 path))
365 (if (eq (cdr cst) (car path))
367 (push (cons (car path) (cons (cdr cst) (cdr path)))
369 (cons (car cycle) (nreverse (cdr cycle)))))
371 (defun smie-debug--describe-cycle (table cycle)
373 (mapcar (lambda (val)
376 (if (eq (cdr elem) val)
377 (push (concat "." (car elem)) res))
378 (if (eq (cddr elem) val)
379 (push (concat (car elem) ".") res)))
384 (lambda (elems) (mapconcat 'identity elems "="))
385 (append names (list (car names)))
388 (put 'smie-prec2-levels 'pure t)
389 (defun smie-prec2-levels (prec2)
390 ;; FIXME: Rather than only return an alist of precedence levels, we should
391 ;; also extract other useful data from it:
392 ;; - better default indentation rules (i.e. non-zero indentation after inner
393 ;; keywords like the "in" of "let..in..end") for smie-indent-after-keyword.
394 ;; Of course, maybe those things would be even better handled in the
395 ;; bnf->prec function.
396 "Take a 2D precedence table and turn it into an alist of precedence levels.
397 PREC2 is a table as returned by `smie-precs-precedence-table' or
398 `smie-bnf-precedence-table'."
399 ;; For each operator, we create two "variables" (corresponding to
400 ;; the left and right precedence level), which are represented by
401 ;; cons cells. Those are the very cons cells that appear in the
402 ;; final `table'. The value of each "variable" is kept in the `car'.
407 ;; From `prec2' we construct a list of constraints between
408 ;; variables (aka "precedence levels"). These can be either
409 ;; equality constraints (in `eqs') or `<' constraints (in `csts').
410 (maphash (lambda (k v)
412 (if (setq tmp (assoc (car k) table))
414 (setq x (cons nil nil))
415 (push (cons (car k) (cons nil x)) table))
416 (if (setq tmp (assoc (cdr k) table))
418 (setq y (cons nil (cons nil nil)))
419 (push (cons (cdr k) y) table))
421 (= (push (cons x y) eqs))
422 (< (push (cons x y) csts))
423 (> (push (cons y x) csts)))))
425 ;; First process the equality constraints.
428 (let ((from (caar eqs))
433 (dolist (other-eq eqs)
434 (if (eq from (cdr other-eq)) (setcdr other-eq to))
435 (when (eq from (car other-eq))
436 ;; This can happen because of `assoc' settings in precs
437 ;; or because of a rhs like ("op" foo "op").
438 (setcar other-eq to)))
440 (if (eq from (cdr cst)) (setcdr cst to))
441 (if (eq from (car cst)) (setcar cst to)))))))
442 ;; Then eliminate trivial constraints iteratively.
445 (let ((rhvs (mapcar 'cdr csts))
448 (unless (memq (car cst) rhvs)
450 ;; We could give each var in a given iteration the same value,
451 ;; but we can also give them arbitrarily different values.
452 ;; Basically, these are vars between which there is no
453 ;; constraint (neither equality nor inequality), so
455 ;; We give them arbitrary values, which means that we
456 ;; replace the "no constraint" case with either > or <
457 ;; but not =. The reason we do that is so as to try and
458 ;; distinguish associative operators (which will have
463 (setq csts (delq cst csts))))
465 (error "Can't resolve the precedence cycle: %s"
466 (smie-debug--describe-cycle
467 table (smie-debug--prec2-cycle csts)))))
469 ;; Propagate equalities back to their source.
470 (dolist (eq (nreverse eqs))
471 (assert (or (null (caar eq)) (eq (car eq) (cdr eq))))
472 (setcar (car eq) (cadr eq)))
473 ;; Finally, fill in the remaining vars (which only appeared on the
474 ;; right side of the < constraints).
475 (let ((classification-table (gethash :smie-open/close-alist prec2)))
477 ;; When both sides are nil, it means this operator binds very
478 ;; very tight, but it's still just an operator, so we give it
479 ;; the highest precedence.
480 ;; OTOH if only one side is nil, it usually means it's like an
481 ;; open-paren, which is very important for indentation purposes,
482 ;; so we keep it nil if so, to make it easier to recognize.
483 (unless (or (nth 1 x)
484 (eq 'opener (cdr (assoc (car x) classification-table))))
486 (incf i)) ;See other (incf i) above.
487 (unless (or (nth 2 x)
488 (eq 'closer (cdr (assoc (car x) classification-table))))
490 (incf i))))) ;See other (incf i) above.
491 (let ((ca (gethash :smie-closer-alist prec2)))
492 (when ca (push (cons :smie-closer-alist ca) table)))
495 ;;; Parsing using a precedence level table.
497 (defvar smie-op-levels 'unset
498 "List of token parsing info.
499 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
500 Parsing is done using an operator precedence parser.
501 LEFT-LEVEL and RIGHT-LEVEL can be either numbers or nil, where nil
502 means that this operator does not bind on the corresponding side,
503 i.e. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
504 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
505 like a close-paren.")
507 (defvar smie-forward-token-function 'smie-default-forward-token
508 "Function to scan forward for the next token.
509 Called with no argument should return a token and move to its end.
510 If no token is found, return nil or the empty string.
511 It can return nil when bumping into a parenthesis, which lets SMIE
512 use syntax-tables to handle them in efficient C code.")
514 (defvar smie-backward-token-function 'smie-default-backward-token
515 "Function to scan backward the previous token.
516 Same calling convention as `smie-forward-token-function' except
517 it should move backward to the beginning of the previous token.")
519 (defalias 'smie-op-left 'car)
520 (defalias 'smie-op-right 'cadr)
522 (defun smie-default-backward-token ()
523 (forward-comment (- (point)))
524 (buffer-substring-no-properties
526 (progn (if (zerop (skip-syntax-backward "."))
527 (skip-syntax-backward "w_'"))
530 (defun smie-default-forward-token ()
531 (forward-comment (point-max))
532 (buffer-substring-no-properties
534 (progn (if (zerop (skip-syntax-forward "."))
535 (skip-syntax-forward "w_'"))
538 (defun smie--associative-p (toklevels)
539 ;; in "a + b + c" we want to stop at each +, but in
540 ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
541 ;; To distinguish the two cases, we made smie-prec2-levels choose
542 ;; different levels for each part of "if a then b else c", so that
543 ;; by checking if the left-level is equal to the right level, we can
544 ;; figure out that it's an associative operator.
545 ;; This is not 100% foolproof, tho, since the "elsif" will have to have
546 ;; equal left and right levels (since it's optional), so smie-next-sexp
547 ;; has to be careful to distinguish those different cases.
548 (eq (smie-op-left toklevels) (smie-op-right toklevels)))
550 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
552 NEXT-TOKEN is a function of no argument that moves forward by one
553 token (after skipping comments if needed) and returns it.
554 NEXT-SEXP is a lower-level function to skip one sexp.
555 OP-FORW is the accessor to the forward level of the level data.
556 OP-BACK is the accessor to the backward level of the level data.
557 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
558 first token we see is an operator, skip over its left-hand-side argument.
559 Possible return values:
560 (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
561 is too high. FORW-LEVEL is the forw-level of TOKEN,
562 POS is its start position in the buffer.
563 (t POS TOKEN): same thing when we bump on the wrong side of a paren.
564 (nil POS TOKEN): we skipped over a paren-like pair.
565 nil: we skipped over an identifier, matched parentheses, ..."
570 (token (funcall next-token))
571 (toklevels (cdr (assoc token smie-op-levels))))
574 (when (zerop (length token))
576 (progn (goto-char pos) (funcall next-sexp 1) nil)
577 (scan-error (throw 'return
579 (buffer-substring-no-properties
582 (if (< (point) (caddr err))
585 ;; We did not move, so let's abort the loop.
586 (throw 'return (list t (point))))))
587 ((null (funcall op-back toklevels))
588 ;; A token like a paren-close.
589 (assert (funcall op-forw toklevels)) ;Otherwise, why mention it?
590 (push toklevels levels))
592 (while (and levels (< (funcall op-back toklevels)
593 (funcall op-forw (car levels))))
594 (setq levels (cdr levels)))
597 (if (and halfsexp (funcall op-forw toklevels))
598 (push toklevels levels)
600 (prog1 (list (or (car toklevels) t) (point) token)
603 (let ((lastlevels levels))
604 (if (and levels (= (funcall op-back toklevels)
605 (funcall op-forw (car levels))))
606 (setq levels (cdr levels)))
607 ;; We may have found a match for the previously pending
608 ;; operator. Is this the end?
610 ;; Keep looking as long as we haven't matched the
613 (if (funcall op-forw toklevels)
614 (push toklevels levels)))
615 ;; We matched the topmost operator. If the new operator
616 ;; is the last in the corresponding BNF rule, we're done.
617 ((null (funcall op-forw toklevels))
618 ;; It is the last element, let's stop here.
619 (throw 'return (list nil (point) token)))
620 ;; If the new operator is not the last in the BNF rule,
621 ;; ans is not associative, it's one of the inner operators
622 ;; (like the "in" in "let .. in .. end"), so keep looking.
623 ((not (smie--associative-p toklevels))
624 (push toklevels levels))
625 ;; The new operator is associative. Two cases:
626 ;; - it's really just an associative operator (like + or ;)
627 ;; in which case we should have stopped right before.
629 (smie--associative-p (car lastlevels)))
631 (prog1 (list (or (car toklevels) t) (point) token)
633 ;; - it's an associative operator within a larger construct
634 ;; (e.g. an "elsif"), so we should just ignore it and keep
635 ;; looking for the closing element.
636 (t (setq levels lastlevels))))))))
638 (setq halfsexp nil)))))
640 (defun smie-backward-sexp (&optional halfsexp)
642 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
643 first token we see is an operator, skip over its left-hand-side argument.
644 Possible return values:
645 (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
646 is too high. LEFT-LEVEL is the left-level of TOKEN,
647 POS is its start position in the buffer.
648 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
649 (nil POS TOKEN): we skipped over a paren-like pair.
650 nil: we skipped over an identifier, matched parentheses, ..."
652 (indirect-function smie-backward-token-function)
653 (indirect-function 'backward-sexp)
654 (indirect-function 'smie-op-left)
655 (indirect-function 'smie-op-right)
658 (defun smie-forward-sexp (&optional halfsexp)
660 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
661 first token we see is an operator, skip over its left-hand-side argument.
662 Possible return values:
663 (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
664 is too high. RIGHT-LEVEL is the right-level of TOKEN,
665 POS is its end position in the buffer.
666 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
667 (nil POS TOKEN): we skipped over a paren-like pair.
668 nil: we skipped over an identifier, matched parentheses, ..."
670 (indirect-function smie-forward-token-function)
671 (indirect-function 'forward-sexp)
672 (indirect-function 'smie-op-right)
673 (indirect-function 'smie-op-left)
676 ;;; Miscellanous commands using the precedence parser.
678 (defun smie-backward-sexp-command (&optional n)
679 "Move backward through N logical elements."
681 (smie-forward-sexp-command (- n)))
683 (defun smie-forward-sexp-command (&optional n)
684 "Move forward through N logical elements."
687 (forward-sexp-function nil))
689 (setq n (- n (if forw 1 -1)))
692 (smie-forward-sexp 'halfsexp)
693 (smie-backward-sexp 'halfsexp))))
694 (if (and (car res) (= pos (point)) (not (if forw (eobp) (bobp))))
696 (list "Containing expression ends prematurely"
697 (cadr res) (cadr res)))
700 (defvar smie-closer-alist nil
701 "Alist giving the closer corresponding to an opener.")
703 (defun smie-close-block ()
704 "Close the closest surrounding block."
709 (if (looking-at "\\s(")
710 (string (cdr (syntax-after (point))))
711 (let* ((open (funcall smie-forward-token-function))
712 (closer (cdr (assoc open smie-closer-alist)))
713 (levels (list (assoc open smie-op-levels)))
717 ;; Even if we improve the auto-computation of closers,
718 ;; there are still cases where we need manual
719 ;; intervention, e.g. for Octave's use of `until'
720 ;; as a pseudo-closer of `do'.
722 ((or (equal levels '(nil)) (nth 1 (car levels)))
723 (error "Doesn't look like a block"))
725 ;; FIXME: With grammars like Octave's, every closer ("end",
726 ;; "endif", "endwhile", ...) has the same level, so we'd need
727 ;; to look at the BNF or at least at the 2D prec-table, in
728 ;; order to find the right closer for a given opener.
730 (let ((level (pop levels)))
731 (dolist (other smie-op-levels)
732 (when (and (eq (nth 2 level) (nth 1 other))
733 (not (memq other seen)))
737 (push (car other) found))))))
739 ((null found) (error "No known closer for opener %s" open))
740 ;; FIXME: what should we do if there are various closers?
741 (t (car found))))))))))
742 (unless (save-excursion (skip-chars-backward " \t") (bolp))
745 (if (save-excursion (skip-chars-forward " \t") (eolp))
746 (indent-according-to-mode)
747 (reindent-then-newline-and-indent))))
749 (defun smie-down-list (&optional arg)
750 "Move forward down one level paren-like blocks. Like `down-list'.
751 With argument ARG, do this that many times.
752 A negative argument means move backward but still go down a level.
753 This command assumes point is not in a string or comment."
755 (let ((start (point))
756 (inc (if (< arg 0) -1 1))
757 (offset (if (< arg 0) 1 0))
758 (next-token (if (< arg 0)
759 smie-backward-token-function
760 smie-forward-token-function)))
762 (setq arg (- arg inc))
765 (token (funcall next-token))
766 (levels (assoc token smie-op-levels)))
768 ((zerop (length token))
769 (if (if (< inc 0) (looking-back "\\s(\\|\\s)" (1- (point)))
770 (looking-at "\\s(\\|\\s)"))
771 ;; Go back to `start' in case of an error. This presumes
772 ;; none of the token we've found until now include a ( or ).
773 (progn (goto-char start) (down-list inc) nil)
776 ((and levels (null (nth (+ 1 offset) levels))) nil)
777 ((and levels (null (nth (- 2 offset) levels)))
781 (list "Containing expression ends prematurely"
785 (defvar smie-blink-matching-triggers '(?\s ?\n)
786 "Chars which might trigger `blink-matching-open'.
787 These can include the final chars of end-tokens, or chars that are
788 typically inserted right after an end token.
789 I.e. a good choice can be:
791 (mapcar (lambda (kw) (aref (cdr kw) (1- (length (cdr kw)))))
792 smie-closer-alist))")
794 (defcustom smie-blink-matching-inners t
795 "Whether SMIE should blink to matching opener for inner keywords.
796 If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
800 (defun smie-blink-matching-check (start end)
803 (let ((ender (funcall smie-backward-token-function)))
805 ((not (and ender (rassoc ender smie-closer-alist)))
806 ;; This not is one of the begin..end we know how to check.
807 (blink-matching-check-mismatch start end))
809 ((eq t (car (rassoc ender smie-closer-alist))) nil)
812 (let ((starter (funcall smie-forward-token-function)))
813 (not (member (cons starter ender) smie-closer-alist))))))))
815 (defun smie-blink-matching-open ()
816 "Blink the matching opener when applicable.
817 This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
818 (let ((pos (point)) ;Position after the close token.
820 (when (and blink-matching-paren
821 smie-closer-alist ; Optimization.
822 (or (eq (char-before) last-command-event) ;; Sanity check.
824 (or (progn (skip-chars-backward " \t")
826 (eq (char-before) last-command-event))
827 (progn (skip-chars-backward " \n\t")
829 (eq (char-before) last-command-event)))))
830 (memq last-command-event smie-blink-matching-triggers)
831 (not (nth 8 (syntax-ppss))))
833 (setq token (funcall smie-backward-token-function))
834 (when (and (eq (point) (1- pos))
836 (not (rassoc token smie-closer-alist)))
837 ;; The trigger char is itself a token but is not one of the
838 ;; closers (e.g. ?\; in Octave mode), so go back to the
841 (setq token (funcall smie-backward-token-function)))
842 (when (rassoc token smie-closer-alist)
843 ;; We're after a close token. Let's still make sure we
844 ;; didn't skip a comment to find that token.
845 (funcall smie-forward-token-function)
846 (when (and (save-excursion
847 ;; Skip the trigger char, if applicable.
848 (if (eq (char-after) last-command-event)
850 (if (eq ?\n last-command-event)
851 ;; Skip any auto-indentation, if applicable.
852 (skip-chars-forward " \t"))
854 ;; If token ends with a trigger char, don't blink for
855 ;; anything else than this trigger char, lest we'd blink
856 ;; both when inserting the trigger char and when
857 ;; inserting a subsequent trigger char like SPC.
859 (not (memq (char-before)
860 smie-blink-matching-triggers)))
861 (or smie-blink-matching-inners
862 (null (nth 2 (assoc token smie-op-levels)))))
863 ;; The major mode might set blink-matching-check-function
864 ;; buffer-locally so that interactive calls to
865 ;; blink-matching-open work right, but let's not presume
867 (let ((blink-matching-check-function #'smie-blink-matching-check))
868 (blink-matching-open))))))))
870 ;;; The indentation engine.
872 (defcustom smie-indent-basic 4
873 "Basic amount of indentation."
877 (defvar smie-rules-function 'ignore
878 "Function providing the indentation rules.
879 It takes two arguments METHOD and ARG where the meaning of ARG
880 and the expected return value depends on METHOD.
882 - :after, in which case ARG is a token and the function should return the
883 OFFSET to use for indentation after ARG.
884 - :before, in which case ARG is a token and the function should return the
885 OFFSET to use to indent ARG itself.
886 - :elem, in which case the function should return either:
887 - the offset to use to indent function arguments (ARG = `arg')
888 - the basic indentation step (ARG = `basic').
889 - :list-intro, in which case ARG is a token and the function should return
890 non-nil if TOKEN is followed by a list of expressions (not separated by any
891 token) rather than an expression.
893 When ARG is a token, the function is called with point just before that token.
894 A return value of nil always means to fallback on the default behavior, so the
895 function should return nil for arguments it does not expect.
897 OFFSET can be of the form:
898 `point' align with the token.
899 `parent' align with the parent.
900 NUMBER offset by NUMBER.
901 \(+ OFFSETS...) use the sum of OFFSETS.
902 VARIABLE use the value of VARIABLE as offset.
904 This function will often use some of the following functions designed
906 `smie-bolp', `smie-hanging-p', `smie-parent-p', `smie-next-p', `smie-prev-p'.")
908 (defun smie-hanging-p ()
909 "Return non-nil if the current token is \"hanging\".
910 A hanging keyword is one that's at the end of a line except it's not at
911 the beginning of a line."
912 (and (not (smie-bolp))
914 (when (zerop (length (funcall smie-forward-token-function)))
915 ;; Could be an open-paren.
917 (skip-chars-forward " \t")
921 "Return non-nil if the current token is the first on the line."
922 (save-excursion (skip-chars-backward " \t") (bolp)))
924 (defvar smie--parent) (defvar smie--after) ;Dynamically scoped.
926 (defun smie-parent-p (&rest parents)
927 "Return non-nil if the current token's parent is among PARENTS.
928 Only meaningful when called from within `smie-rules-function'."
929 (member (nth 2 (or smie--parent
932 (tok (funcall smie-forward-token-function)))
933 (unless (cadr (assoc tok smie-op-levels))
936 (smie-backward-sexp 'halfsexp))))))
939 (defun smie-next-p (&rest tokens)
940 "Return non-nil if the next token is among TOKENS.
941 Only meaningful when called from within `smie-rules-function'."
945 (smie-indent-forward-token) (setq smie--after (point)))
946 (goto-char smie--after)
947 (smie-indent-forward-token))))
948 (member (car next) tokens)))
950 (defun smie-prev-p (&rest tokens)
951 "Return non-nil if the previous token is among TOKENS."
952 (let ((prev (save-excursion
953 (smie-indent-backward-token))))
954 (member (car prev) tokens)))
957 (defun smie-indent--offset (elem)
958 (or (funcall smie-rules-function :elem elem)
959 (if (not (eq elem 'basic))
960 (funcall smie-rules-function :elem 'basic))
963 (defun smie-indent--rule (kind token &optional after parent)
964 (let ((smie--parent parent)
966 (funcall smie-rules-function kind token)))
968 (defun smie-indent--column (offset &optional base parent virtual-point)
969 "Compute the actual column to use for a given OFFSET.
970 BASE is the base position to use, and PARENT is the parent info, if any.
971 If VIRTUAL-POINT is non-nil, then `point' is virtual."
973 ((eq (car-safe offset) '+)
974 (apply '+ (mapcar (lambda (offset) (smie-indent--column offset nil parent))
980 (parent (goto-char (cadr parent))
981 (smie-indent-virtual))
984 ;; For indentation after "(let" in SML-mode, we end up accumulating
985 ;; the offset of "(" and the offset of "let", so we use `min' to try
986 ;; and get it right either way.
987 (min (smie-indent-virtual) (current-column))))))
989 ;; In indent-keyword, if we're indenting `then' wrt `if', we want to use
990 ;; indent-virtual rather than use just current-column, so that we can
991 ;; apply the (:before . "if") rule which does the "else if" dance in SML.
992 ;; But in other cases, we do not want to use indent-virtual
993 ;; (e.g. indentation of "*" w.r.t "+", or ";" wrt "("). We could just
994 ;; always use indent-virtual and then have indent-rules say explicitly
995 ;; to use `point' after things like "(" or "+" when they're not at EOL,
996 ;; but you'd end up with lots of those rules.
997 ;; So we use a heuristic here, which is that we only use virtual if
998 ;; the parent is tightly linked to the child token (they're part of
999 ;; the same BNF rule).
1000 (if (and virtual-point (null (car parent))) ;Black magic :-(
1001 (smie-indent-virtual) (current-column)))
1002 ((eq offset 'parent)
1004 (setq parent (or (smie-backward-sexp 'halfsexp) :notfound)))
1005 (if (consp parent) (goto-char (cadr parent)))
1006 (smie-indent-virtual))
1007 ((eq offset nil) nil)
1008 ;; FIXME: would be good to get rid of this since smie-rules-function
1009 ;; can usually do the lookup trivially, but in cases where
1010 ;; smie-rules-function returns (+ point VAR) it's not nearly as trivial.
1011 ((and (symbolp offset) (boundp 'offset))
1012 (smie-indent--column (symbol-value offset) base parent virtual-point))
1013 (t (error "Unknown indentation offset %s" offset))))
1015 (defun smie-indent-forward-token ()
1016 "Skip token forward and return it, along with its levels."
1017 (let ((tok (funcall smie-forward-token-function)))
1019 ((< 0 (length tok)) (assoc tok smie-op-levels))
1020 ((looking-at "\\s(")
1022 (list (buffer-substring (1- (point)) (point)) nil 0)))))
1024 (defun smie-indent-backward-token ()
1025 "Skip token backward and return it, along with its levels."
1026 (let ((tok (funcall smie-backward-token-function)))
1028 ((< 0 (length tok)) (assoc tok smie-op-levels))
1029 ;; 4 == Open paren syntax.
1030 ((eq 4 (syntax-class (syntax-after (1- (point)))))
1032 (list (buffer-substring (point) (1+ (point))) nil 0)))))
1034 (defun smie-indent-virtual ()
1035 ;; We used to take an optional arg (with value :not-hanging) to specify that
1036 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
1037 ;; keyword. This was a bad idea, because the virtual indent of a position
1038 ;; should not depend on the caller, since it leads to situations where two
1039 ;; dependent indentations get indented differently.
1040 "Compute the virtual indentation to use for point.
1041 This is used when we're not trying to indent point but just
1042 need to compute the column at which point should be indented
1043 in order to figure out the indentation of some other (further down) point."
1044 ;; Trust pre-existing indentation on other lines.
1045 (if (smie-bolp) (current-column) (smie-indent-calculate)))
1047 (defun smie-indent-fixindent ()
1048 ;; Obey the `fixindent' special comment.
1051 (comment-normalize-vars)
1052 (re-search-forward (concat comment-start-skip
1055 ;; 1+ to account for the \n comment termination.
1056 (1+ (line-end-position)) t))
1059 (defun smie-indent-bob ()
1060 ;; Start the file at column 0.
1062 (forward-comment (- (point)))
1065 (defun smie-indent-close ()
1066 ;; Align close paren with opening paren.
1068 ;; (forward-comment (point-max))
1069 (when (looking-at "\\s)")
1070 (while (not (zerop (skip-syntax-forward ")")))
1071 (skip-chars-forward " \t"))
1075 (smie-indent-virtual)) ;:not-hanging
1076 (scan-error nil)))))
1078 (defun smie-indent-keyword ()
1079 ;; Align closing token with the corresponding opening one.
1080 ;; (e.g. "of" with "case", or "in" with "let").
1082 (let* ((pos (point))
1083 (toklevels (smie-indent-forward-token))
1084 (token (pop toklevels)))
1085 (if (null (car toklevels))
1089 ;; - smie-bolp: "indent according to others".
1090 ;; - common hanging: "indent according to others".
1091 ;; - SML-let hanging: "indent like parent".
1092 ;; - if-after-else: "indent-like parent".
1093 ;; - middle-of-line: "trust current position".
1095 ((null (cdr toklevels)) nil) ;Not a keyword.
1097 ;; For an open-paren-like thingy at BOL, always indent only
1098 ;; based on other rules (typically smie-indent-after-keyword).
1101 ;; We're only ever here for virtual-indent, which is why
1102 ;; we can use (current-column) as answer for `point'.
1103 (let* ((offset (or (smie-indent--rule :before token)
1104 ;; By default use point unless we're hanging.
1105 (unless (smie-hanging-p) 'point))))
1106 (smie-indent--column offset)))))
1108 ;; FIXME: This still looks too much like black magic!!
1109 (let* ((parent (smie-backward-sexp 'halfsexp))
1110 (offset (save-excursion
1112 (or (smie-indent--rule :before token nil parent)
1114 ;; Different behaviors:
1115 ;; - align with parent.
1116 ;; - parent + offset.
1117 ;; - after parent's column + offset (actually, after or before
1118 ;; depending on where backward-sexp stopped).
1119 ;; ? let it drop to some other indentation function (almost never).
1120 ;; ? parent + offset + parent's own offset.
1122 ;; - bump into a same-level operator.
1123 ;; - bump into a specific known parent.
1124 ;; - find a matching open-paren thingy.
1125 ;; - bump into some random parent.
1126 ;; ? borderline case (almost never).
1127 ;; ? bump immediately into a parent.
1129 ((not (or (< (point) pos)
1130 (and (cadr parent) (< (cadr parent) pos))))
1131 ;; If we didn't move at all, that means we didn't really skip
1132 ;; what we wanted. Should almost never happen, other than
1133 ;; maybe when an infix or close-paren is at the beginning
1136 ((eq (car parent) (car toklevels))
1137 ;; We bumped into a same-level operator. align with it.
1138 (if (and (smie-bolp) (/= (point) pos)
1140 (goto-char (goto-char (cadr parent)))
1142 ;; Check the offset of `token' rather then its parent
1143 ;; because its parent may have used a special rule. E.g.
1147 ;; The ; on the first line had a special rule, but when
1148 ;; indenting line3, we don't care about it and want to
1149 ;; align with line2.
1150 (memq offset '(point nil)))
1151 ;; If the parent is at EOL and its children are indented like
1152 ;; itself, then we can just obey the indentation chosen for the
1154 ;; This is important for operators like ";" which
1155 ;; are usually at EOL (and have an offset of 0): otherwise we'd
1156 ;; always go back over all the statements, which is
1157 ;; a performance problem and would also mean that fixindents
1158 ;; in the middle of such a sequence would be ignored.
1160 ;; This is a delicate point!
1161 ;; Even if the offset is not 0, we could follow the same logic
1162 ;; and subtract the offset from the child's indentation.
1163 ;; But that would more often be a bad idea: OT1H we generally
1164 ;; want to reuse the closest similar indentation point, so that
1165 ;; the user's choice (or the fixindents) are obeyed. But OTOH
1166 ;; we don't want this to affect "unrelated" parts of the code.
1167 ;; E.g. a fixindent in the body of a "begin..end" should not
1168 ;; affect the indentation of the "end".
1170 (goto-char (cadr parent))
1171 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
1172 ;; want to jump back over a sequence of same-level ops such as
1175 ;; So as to align with the earliest appropriate place.
1176 (smie-indent-virtual)))
1178 (if (and (= (point) pos) (smie-bolp)
1179 (or (eq offset 'point)
1180 (and (consp offset) (memq 'point offset))))
1181 ;; Since we started at BOL, we're not computing a virtual
1182 ;; indentation, and we're still at the starting point, so
1183 ;; we can't use `current-column' which would cause
1184 ;; indentation to depend on itself.
1186 (smie-indent--column offset 'parent parent
1187 ;; If we're still at pos, indent-virtual
1189 (unless (= (point) pos) 'virtual))))))))))
1191 (defun smie-indent-comment ()
1192 "Compute indentation of a comment."
1193 ;; Don't do it for virtual indentations. We should normally never be "in
1194 ;; front of a comment" when doing virtual-indentation anyway. And if we are
1195 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
1197 (let ((pos (point)))
1200 (and (re-search-forward comment-start-skip (line-end-position) t)
1201 (eq pos (or (match-end 1) (match-beginning 0))))))
1203 (forward-comment (point-max))
1204 (skip-chars-forward " \t\r\n")
1205 (smie-indent-calculate))))
1207 (defun smie-indent-comment-continue ()
1208 ;; indentation of comment-continue lines.
1209 (let ((continue (and comment-continue
1210 (comment-string-strip comment-continue t t))))
1211 (and (< 0 (length continue))
1212 (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
1213 (let ((ppss (syntax-ppss)))
1216 (if (<= (point) (nth 8 ppss))
1217 (progn (goto-char (1+ (nth 8 ppss))) (current-column))
1218 (skip-chars-forward " \t")
1219 (if (looking-at (regexp-quote continue))
1220 (current-column))))))))
1222 (defun smie-indent-comment-close ()
1223 (and (boundp 'comment-end-skip)
1225 (not (looking-at " \t*$")) ;Not just a \n comment-closer.
1226 (looking-at comment-end-skip)
1227 (nth 4 (syntax-ppss))
1229 (goto-char (nth 8 (syntax-ppss)))
1232 (defun smie-indent-comment-inside ()
1233 (and (nth 4 (syntax-ppss))
1236 (defun smie-indent-after-keyword ()
1237 ;; Indentation right after a special keyword.
1239 (let* ((pos (point))
1240 (toklevel (smie-indent-backward-token))
1241 (tok (car toklevel)))
1244 (or (smie-indent--rule :after tok pos)
1245 ;; The default indentation after a keyword/operator is
1246 ;; 0 for infix and t for prefix.
1247 (if (or (null (cadr toklevel))
1248 (rassoc tok smie-closer-alist))
1249 (smie-indent--offset 'basic) 0)))
1252 (smie-indent--column offset before))))))
1254 (defun smie-indent-exps ()
1255 ;; Indentation of sequences of simple expressions without
1256 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
1257 ;; Can be a list of expressions or a function call.
1258 ;; If it's a function call, the first element is special (it's the
1259 ;; function). We distinguish function calls from mere lists of
1260 ;; expressions based on whether the preceding token is listed in
1261 ;; the `list-intro' entry of smie-indent-rules.
1263 ;; TODO: to indent Lisp code, we should add a way to specify
1264 ;; particular indentation for particular args depending on the
1265 ;; function (which would require always skipping back until the
1267 ;; TODO: to indent C code, such as "if (...) {...}" we might need
1268 ;; to add similar indentation hooks for particular positions, but
1269 ;; based on the preceding token rather than based on the first exp.
1271 (let ((positions nil)
1273 (while (and (null (car (smie-backward-sexp)))
1274 (push (point) positions)
1277 ;; Figure out if the atom we just skipped is an argument rather
1280 (or (null (car (smie-backward-sexp)))
1281 (funcall smie-rules-function :list-intro
1282 (funcall smie-backward-token-function)))))
1285 ;; We're the first expression of the list. In that case, the
1286 ;; indentation should be (have been) determined by its context.
1289 ;; There's a previous element, and it's not special (it's not
1290 ;; the function), so let's just align with that one.
1291 (goto-char (car positions))
1294 ;; We skipped some args plus the function and bumped into something.
1295 ;; Align with the first arg.
1296 (goto-char (cadr positions))
1299 ;; We're the first arg.
1300 (goto-char (car positions))
1301 ;; FIXME: Use smie-indent--column.
1302 (+ (smie-indent--offset 'args)
1303 ;; We used to use (smie-indent-virtual), but that
1304 ;; doesn't seem right since it might then indent args less than
1305 ;; the function itself.
1306 (current-column)))))))
1308 (defvar smie-indent-functions
1309 '(smie-indent-fixindent smie-indent-bob smie-indent-close
1310 smie-indent-comment smie-indent-comment-continue smie-indent-comment-close
1311 smie-indent-comment-inside smie-indent-keyword smie-indent-after-keyword
1313 "Functions to compute the indentation.
1314 Each function is called with no argument, shouldn't move point, and should
1315 return either nil if it has no opinion, or an integer representing the column
1316 to which that point should be aligned, if we were to reindent it.")
1318 (defun smie-indent-calculate ()
1319 "Compute the indentation to use for point."
1320 (run-hook-with-args-until-success 'smie-indent-functions))
1322 (defun smie-indent-line ()
1323 "Indent current line using the SMIE indentation engine."
1325 (let* ((savep (point))
1326 (indent (condition-case-no-debug nil
1329 (skip-chars-forward " \t")
1330 (if (>= (point) savep) (setq savep nil))
1331 (or (smie-indent-calculate) 0))
1333 (if (not (numberp indent))
1334 ;; If something funny is used (e.g. `noindent'), return it.
1336 (if (< indent 0) (setq indent 0)) ;Just in case.
1338 (save-excursion (indent-line-to indent))
1339 (indent-line-to indent)))))
1341 (defun smie-setup (op-levels rules-function &rest keywords)
1342 "Setup SMIE navigation and indentation.
1343 OP-LEVELS is a grammar table generated by `smie-prec2-levels'.
1344 RULES-FUNCTION is a set of indentation rules for use on `smie-rules-function'.
1345 KEYWORDS are additional arguments, which can use the following keywords:
1346 - :forward-token FUN
1347 - :backward-token FUN"
1348 (set (make-local-variable 'smie-rules-function) rules-function)
1349 (set (make-local-variable 'smie-op-levels) op-levels)
1350 (set (make-local-variable 'indent-line-function) 'smie-indent-line)
1351 (set (make-local-variable 'forward-sexp-function)
1352 'smie-forward-sexp-command)
1354 (let ((k (pop keywords))
1358 (set (make-local-variable 'smie-forward-token-function) v))
1360 (set (make-local-variable 'smie-backward-token-function) v))
1361 (t (message "smie-setup: ignoring unknown keyword %s" k)))))
1362 (let ((ca (cdr (assq :smie-closer-alist op-levels))))
1364 (set (make-local-variable 'smie-closer-alist) ca)
1365 ;; Only needed for interactive calls to blink-matching-open.
1366 (set (make-local-variable 'blink-matching-check-function)
1367 #'smie-blink-matching-check)
1368 (add-hook 'post-self-insert-hook
1369 #'smie-blink-matching-open 'append 'local)
1370 (set (make-local-variable 'smie-blink-matching-triggers)
1371 (append smie-blink-matching-triggers
1372 ;; Rather than wait for SPC to blink, try to blink as
1373 ;; soon as we type the last char of a block ender.
1374 (let ((closers (sort (mapcar #'cdr smie-closer-alist)
1378 (while (setq closer (pop closers))
1379 (unless (and closers
1380 ;; FIXME: this eliminates prefixes of other
1381 ;; closers, but we should probably elimnate
1382 ;; prefixes of other keywords as well.
1383 (string-prefix-p closer (car closers)))
1384 (push (aref closer (1- (length closer))) triggers)))
1385 (delete-dups triggers)))))))
1389 ;;; smie.el ends here