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))
73 (defvar comment-continue)
74 (declare-function comment-string-strip "newcomment" (str beforep afterp))
76 ;;; Building precedence level tables from BNF specs.
78 ;; We have 4 different representations of a "grammar":
79 ;; - a BNF table, which is a list of BNF rules of the form
80 ;; (NONTERM RHS1 ... RHSn) where each RHS is a list of terminals (tokens)
81 ;; or nonterminals. Any element in these lists which does not appear as
82 ;; the `car' of a BNF rule is taken to be a terminal.
83 ;; - A list of precedences (key word "precs"), is a list, sorted
84 ;; from lowest to highest precedence, of precedence classes that
85 ;; have the form (ASSOCIATIVITY TERMINAL1 .. TERMINALn), where
86 ;; ASSOCIATIVITY can be `assoc', `left', `right' or `nonassoc'.
87 ;; - a 2 dimensional precedence table (key word "prec2"), is a 2D
88 ;; table recording the precedence relation (can be `<', `=', `>', or
89 ;; nil) between each pair of tokens.
90 ;; - a precedence-level table (key word "levels"), while is a alist
91 ;; giving for each token its left and right precedence level (a
92 ;; number or nil). This is used in `smie-op-levels'.
93 ;; The prec2 tables are only intermediate data structures: the source
94 ;; code normally provides a mix of BNF and precs tables, and then
95 ;; turns them into a levels table, which is what's used by the rest of
98 (defun smie-set-prec2tab (table x y val &optional override)
100 (let* ((key (cons x y))
101 (old (gethash key table)))
102 (if (and old (not (eq old val)))
103 (if (and override (gethash key override))
104 ;; FIXME: The override is meant to resolve ambiguities,
105 ;; but it also hides real conflicts. It would be great to
106 ;; be able to distinguish the two cases so that overrides
107 ;; don't hide real conflicts.
108 (puthash key (gethash key override) table)
109 (display-warning 'smie (format "Conflict: %s %s/%s %s" x old val y)))
110 (puthash key val table))))
112 (put 'smie-precs-precedence-table 'pure t)
113 (defun smie-precs-precedence-table (precs)
114 "Compute a 2D precedence table from a list of precedences.
115 PRECS should be a list, sorted by precedence (e.g. \"+\" will
116 come before \"*\"), of elements of the form \(left OP ...)
117 or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
118 one of those elements share the same precedence level and associativity."
119 (let ((prec2-table (make-hash-table :test 'equal)))
121 (dolist (op (cdr prec))
122 (let ((selfrule (cdr (assq (car prec)
123 '((left . >) (right . <) (assoc . =))))))
125 (dolist (other-op (cdr prec))
126 (smie-set-prec2tab prec2-table op other-op selfrule))))
127 (let ((op1 '<) (op2 '>))
128 (dolist (other-prec precs)
129 (if (eq prec other-prec)
131 (dolist (other-op (cdr other-prec))
132 (smie-set-prec2tab prec2-table op other-op op2)
133 (smie-set-prec2tab prec2-table other-op op op1)))))))
136 (put 'smie-merge-prec2s 'pure t)
137 (defun smie-merge-prec2s (&rest tables)
138 (if (null (cdr tables))
140 (let ((prec2 (make-hash-table :test 'equal)))
141 (dolist (table tables)
142 (maphash (lambda (k v)
144 (smie-set-prec2tab prec2 (car k) (cdr k) v)
145 (if (and (gethash k prec2)
146 (not (equal (gethash k prec2) v)))
147 (error "Conflicting values for %s property" k)
148 (puthash k v prec2))))
152 (put 'smie-bnf-precedence-table 'pure t)
153 (defun smie-bnf-precedence-table (bnf &rest precs)
154 (let ((nts (mapcar 'car bnf)) ;Non-terminals
159 (prec2 (make-hash-table :test 'equal))
160 (override (apply 'smie-merge-prec2s
161 (mapcar 'smie-precs-precedence-table precs)))
164 (let ((nt (car rules))
169 (dolist (rhs (cdr rules))
171 (signal 'wrong-type-argument `(consp ,rhs)))
172 (if (not (member (car rhs) nts))
173 (pushnew (car rhs) first-ops)
174 (pushnew (car rhs) first-nts)
175 (when (consp (cdr rhs))
176 ;; If the first is not an OP we add the second (which
177 ;; should be an OP if BNF is an "operator grammar").
178 ;; Strictly speaking, this should only be done if the
179 ;; first is a non-terminal which can expand to a phrase
180 ;; without any OP in it, but checking doesn't seem worth
181 ;; the trouble, and it lets the writer of the BNF
182 ;; be a bit more sloppy by skipping uninteresting base
183 ;; cases which are terminals but not OPs.
184 (assert (not (member (cadr rhs) nts)))
185 (pushnew (cadr rhs) first-ops)))
186 (let ((shr (reverse rhs)))
187 (if (not (member (car shr) nts))
188 (pushnew (car shr) last-ops)
189 (pushnew (car shr) last-nts)
190 (when (consp (cdr shr))
191 (assert (not (member (cadr shr) nts)))
192 (pushnew (cadr shr) last-ops)))))
193 (push (cons nt first-ops) first-ops-table)
194 (push (cons nt last-ops) last-ops-table)
195 (push (cons nt first-nts) first-nts-table)
196 (push (cons nt last-nts) last-nts-table)))
197 ;; Compute all first-ops by propagating the initial ones we have
198 ;; now, according to first-nts.
200 (while (prog1 again (setq again nil))
201 (dolist (first-nts first-nts-table)
202 (let* ((nt (pop first-nts))
203 (first-ops (assoc nt first-ops-table)))
204 (dolist (first-nt first-nts)
205 (dolist (op (cdr (assoc first-nt first-ops-table)))
206 (unless (member op first-ops)
208 (push op (cdr first-ops))))))))
209 ;; Same thing for last-ops.
211 (while (prog1 again (setq again nil))
212 (dolist (last-nts last-nts-table)
213 (let* ((nt (pop last-nts))
214 (last-ops (assoc nt last-ops-table)))
215 (dolist (last-nt last-nts)
216 (dolist (op (cdr (assoc last-nt last-ops-table)))
217 (unless (member op last-ops)
219 (push op (cdr last-ops))))))))
220 ;; Now generate the 2D precedence table.
222 (dolist (rhs (cdr rules))
225 ((member (car rhs) nts)
226 (dolist (last (cdr (assoc (car rhs) last-ops-table)))
227 (smie-set-prec2tab prec2 last (cadr rhs) '> override)))
228 ((member (cadr rhs) nts)
229 (dolist (first (cdr (assoc (cadr rhs) first-ops-table)))
230 (smie-set-prec2tab prec2 (car rhs) first '< override))
231 (if (and (cddr rhs) (not (member (car (cddr rhs)) nts)))
232 (smie-set-prec2tab prec2 (car rhs) (car (cddr rhs))
234 (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
235 (setq rhs (cdr rhs)))))
236 ;; Keep track of which tokens are openers/closer, so they can get a nil
237 ;; precedence in smie-prec2-levels.
238 (puthash :smie-open/close-alist (smie-bnf-classify bnf) prec2)
239 (puthash :smie-closer-alist (smie-bnf-closer-alist bnf) prec2)
242 ;; (defun smie-prec2-closer-alist (prec2 include-inners)
243 ;; "Build a closer-alist from a PREC2 table.
244 ;; The return value is in the same form as `smie-closer-alist'.
245 ;; INCLUDE-INNERS if non-nil means that inner keywords will be included
246 ;; in the table, e.g. the table will include things like (\"if\" . \"else\")."
247 ;; (let* ((non-openers '())
249 ;; ;; For each keyword, this gives the matching openers, if any.
250 ;; (openers (make-hash-table :test 'equal))
253 ;; ;; First, find the non-openers and non-closers.
254 ;; (maphash (lambda (k v)
255 ;; (unless (or (eq v '<) (member (cdr k) non-openers))
256 ;; (push (cdr k) non-openers))
257 ;; (unless (or (eq v '>) (member (car k) non-closers))
258 ;; (push (car k) non-closers)))
260 ;; ;; Then find the openers and closers.
261 ;; (maphash (lambda (k _)
262 ;; (unless (member (car k) non-openers)
263 ;; (puthash (car k) (list (car k)) openers))
264 ;; (unless (or (member (cdr k) non-closers)
265 ;; (member (cdr k) closers))
266 ;; (push (cdr k) closers)))
268 ;; ;; Then collect the matching elements.
271 ;; (maphash (lambda (k v)
273 ;; (let ((aopeners (gethash (car k) openers))
274 ;; (dopeners (gethash (cdr k) openers))
276 ;; (dolist (o aopeners)
277 ;; (unless (member o dopeners)
279 ;; (push o dopeners)))
282 ;; (puthash (cdr k) dopeners openers)))))
284 ;; ;; Finally, dump the resulting table.
285 ;; (let ((alist '()))
286 ;; (maphash (lambda (k v)
287 ;; (when (or include-inners (member k closers))
288 ;; (dolist (opener v)
289 ;; (unless (equal opener k)
290 ;; (push (cons opener k) alist)))))
294 (defun smie-bnf-closer-alist (bnf &optional no-inners)
295 ;; We can also build this closer-alist table from a prec2 table,
296 ;; but it takes more work, and the order is unpredictable, which
297 ;; is a problem for smie-close-block.
298 ;; More convenient would be to build it from a levels table since we
299 ;; always have this table (contrary to the BNF), but it has all the
300 ;; disadvantages of the prec2 case plus the disadvantage that the levels
301 ;; table has lost some info which would result in extra invalid pairs.
302 "Build a closer-alist from a BNF table.
303 The return value is in the same form as `smie-closer-alist'.
304 NO-INNERS if non-nil means that inner keywords will be excluded
305 from the table, e.g. the table will not include things like (\"if\" . \"else\")."
306 (let ((nts (mapcar #'car bnf)) ;non terminals.
309 (dolist (rhs (cdr nt))
310 (unless (or (< (length rhs) 2) (member (car rhs) nts))
312 (let ((last (car (last rhs))))
313 (unless (member last nts)
314 (pushnew (cons (car rhs) last) alist :test #'equal)))
315 ;; Reverse so that the "real" closer gets there first,
316 ;; which is important for smie-close-block.
317 (dolist (term (reverse (cdr rhs)))
318 (unless (member term nts)
319 (pushnew (cons (car rhs) term) alist :test #'equal)))))))
322 (defun smie-bnf-classify (bnf)
323 "Return a table classifying terminals.
324 Each terminal can either be an `opener', a `closer', or neither."
325 (let ((table (make-hash-table :test #'equal))
327 (dolist (category bnf)
328 (puthash (car category) 'neither table) ;Remove non-terminals.
329 (dolist (rhs (cdr category))
331 (puthash (pop rhs) 'neither table)
332 (let ((first (pop rhs)))
334 (if (memq (gethash first table) '(nil opener))
338 (puthash (pop rhs) 'neither table)) ;Remove internals.
339 (let ((last (pop rhs)))
341 (if (memq (gethash last table) '(nil closer))
344 (maphash (lambda (tok v)
345 (when (memq v '(closer opener))
346 (push (cons tok v) alist)))
350 (defun smie-debug--prec2-cycle (csts)
351 "Return a cycle in CSTS, assuming there's one.
352 CSTS is a list of pairs representing arcs in a graph."
353 ;; A PATH is of the form (START . REST) where REST is a reverse
354 ;; list of nodes through which the path goes.
355 (let ((paths (mapcar (lambda (pair) (list (car pair) (cdr pair))) csts))
358 (dolist (path (prog1 paths (setq paths nil)))
360 (when (eq (car cst) (nth 1 path))
361 (if (eq (cdr cst) (car path))
363 (push (cons (car path) (cons (cdr cst) (cdr path)))
365 (cons (car cycle) (nreverse (cdr cycle)))))
367 (defun smie-debug--describe-cycle (table cycle)
369 (mapcar (lambda (val)
372 (if (eq (cdr elem) val)
373 (push (concat "." (car elem)) res))
374 (if (eq (cddr elem) val)
375 (push (concat (car elem) ".") res)))
380 (lambda (elems) (mapconcat 'identity elems "="))
381 (append names (list (car names)))
384 (put 'smie-prec2-levels 'pure t)
385 (defun smie-prec2-levels (prec2)
386 ;; FIXME: Rather than only return an alist of precedence levels, we should
387 ;; also extract other useful data from it:
388 ;; - better default indentation rules (i.e. non-zero indentation after inner
389 ;; keywords like the "in" of "let..in..end") for smie-indent-after-keyword.
390 ;; Of course, maybe those things would be even better handled in the
391 ;; bnf->prec function.
392 "Take a 2D precedence table and turn it into an alist of precedence levels.
393 PREC2 is a table as returned by `smie-precs-precedence-table' or
394 `smie-bnf-precedence-table'."
395 ;; For each operator, we create two "variables" (corresponding to
396 ;; the left and right precedence level), which are represented by
397 ;; cons cells. Those are the very cons cells that appear in the
398 ;; final `table'. The value of each "variable" is kept in the `car'.
403 ;; From `prec2' we construct a list of constraints between
404 ;; variables (aka "precedence levels"). These can be either
405 ;; equality constraints (in `eqs') or `<' constraints (in `csts').
406 (maphash (lambda (k v)
408 (if (setq tmp (assoc (car k) table))
410 (setq x (cons nil nil))
411 (push (cons (car k) (cons nil x)) table))
412 (if (setq tmp (assoc (cdr k) table))
414 (setq y (cons nil (cons nil nil)))
415 (push (cons (cdr k) y) table))
417 (= (push (cons x y) eqs))
418 (< (push (cons x y) csts))
419 (> (push (cons y x) csts)))))
421 ;; First process the equality constraints.
424 (let ((from (caar eqs))
429 (dolist (other-eq eqs)
430 (if (eq from (cdr other-eq)) (setcdr other-eq to))
431 (when (eq from (car other-eq))
432 ;; This can happen because of `assoc' settings in precs
433 ;; or because of a rhs like ("op" foo "op").
434 (setcar other-eq to)))
436 (if (eq from (cdr cst)) (setcdr cst to))
437 (if (eq from (car cst)) (setcar cst to)))))))
438 ;; Then eliminate trivial constraints iteratively.
441 (let ((rhvs (mapcar 'cdr csts))
444 (unless (memq (car cst) rhvs)
446 ;; We could give each var in a given iteration the same value,
447 ;; but we can also give them arbitrarily different values.
448 ;; Basically, these are vars between which there is no
449 ;; constraint (neither equality nor inequality), so
451 ;; We give them arbitrary values, which means that we
452 ;; replace the "no constraint" case with either > or <
453 ;; but not =. The reason we do that is so as to try and
454 ;; distinguish associative operators (which will have
459 (setq csts (delq cst csts))))
461 (error "Can't resolve the precedence cycle: %s"
462 (smie-debug--describe-cycle
463 table (smie-debug--prec2-cycle csts)))))
465 ;; Propagate equalities back to their source.
466 (dolist (eq (nreverse eqs))
467 (assert (or (null (caar eq)) (eq (car eq) (cdr eq))))
468 (setcar (car eq) (cadr eq)))
469 ;; Finally, fill in the remaining vars (which only appeared on the
470 ;; right side of the < constraints).
471 (let ((classification-table (gethash :smie-open/close-alist prec2)))
473 ;; When both sides are nil, it means this operator binds very
474 ;; very tight, but it's still just an operator, so we give it
475 ;; the highest precedence.
476 ;; OTOH if only one side is nil, it usually means it's like an
477 ;; open-paren, which is very important for indentation purposes,
478 ;; so we keep it nil if so, to make it easier to recognize.
479 (unless (or (nth 1 x)
480 (eq 'opener (cdr (assoc (car x) classification-table))))
482 (incf i)) ;See other (incf i) above.
483 (unless (or (nth 2 x)
484 (eq 'closer (cdr (assoc (car x) classification-table))))
486 (incf i))))) ;See other (incf i) above.
487 (let ((ca (gethash :smie-closer-alist prec2)))
488 (when ca (push (cons :smie-closer-alist ca) table)))
491 ;;; Parsing using a precedence level table.
493 (defvar smie-op-levels 'unset
494 "List of token parsing info.
495 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
496 Parsing is done using an operator precedence parser.
497 LEFT-LEVEL and RIGHT-LEVEL can be either numbers or nil, where nil
498 means that this operator does not bind on the corresponding side,
499 i.e. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
500 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
501 like a close-paren.")
503 (defvar smie-forward-token-function 'smie-default-forward-token
504 "Function to scan forward for the next token.
505 Called with no argument should return a token and move to its end.
506 If no token is found, return nil or the empty string.
507 It can return nil when bumping into a parenthesis, which lets SMIE
508 use syntax-tables to handle them in efficient C code.")
510 (defvar smie-backward-token-function 'smie-default-backward-token
511 "Function to scan backward the previous token.
512 Same calling convention as `smie-forward-token-function' except
513 it should move backward to the beginning of the previous token.")
515 (defalias 'smie-op-left 'car)
516 (defalias 'smie-op-right 'cadr)
518 (defun smie-default-backward-token ()
519 (forward-comment (- (point)))
520 (buffer-substring-no-properties
522 (progn (if (zerop (skip-syntax-backward "."))
523 (skip-syntax-backward "w_'"))
526 (defun smie-default-forward-token ()
527 (forward-comment (point-max))
528 (buffer-substring-no-properties
530 (progn (if (zerop (skip-syntax-forward "."))
531 (skip-syntax-forward "w_'"))
534 (defun smie--associative-p (toklevels)
535 ;; in "a + b + c" we want to stop at each +, but in
536 ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
537 ;; To distinguish the two cases, we made smie-prec2-levels choose
538 ;; different levels for each part of "if a then b else c", so that
539 ;; by checking if the left-level is equal to the right level, we can
540 ;; figure out that it's an associative operator.
541 ;; This is not 100% foolproof, tho, since the "elsif" will have to have
542 ;; equal left and right levels (since it's optional), so smie-next-sexp
543 ;; has to be careful to distinguish those different cases.
544 (eq (smie-op-left toklevels) (smie-op-right toklevels)))
546 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
548 NEXT-TOKEN is a function of no argument that moves forward by one
549 token (after skipping comments if needed) and returns it.
550 NEXT-SEXP is a lower-level function to skip one sexp.
551 OP-FORW is the accessor to the forward level of the level data.
552 OP-BACK is the accessor to the backward level of the level data.
553 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
554 first token we see is an operator, skip over its left-hand-side argument.
555 Possible return values:
556 (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
557 is too high. FORW-LEVEL is the forw-level of TOKEN,
558 POS is its start position in the buffer.
559 (t POS TOKEN): same thing when we bump on the wrong side of a paren.
560 (nil POS TOKEN): we skipped over a paren-like pair.
561 nil: we skipped over an identifier, matched parentheses, ..."
566 (token (funcall next-token))
567 (toklevels (cdr (assoc token smie-op-levels))))
570 (when (zerop (length token))
572 (progn (goto-char pos) (funcall next-sexp 1) nil)
573 (scan-error (throw 'return
575 (buffer-substring-no-properties
578 (if (< (point) (caddr err))
581 ;; We did not move, so let's abort the loop.
582 (throw 'return (list t (point))))))
583 ((null (funcall op-back toklevels))
584 ;; A token like a paren-close.
585 (assert (funcall op-forw toklevels)) ;Otherwise, why mention it?
586 (push toklevels levels))
588 (while (and levels (< (funcall op-back toklevels)
589 (funcall op-forw (car levels))))
590 (setq levels (cdr levels)))
593 (if (and halfsexp (funcall op-forw toklevels))
594 (push toklevels levels)
596 (prog1 (list (or (car toklevels) t) (point) token)
599 (let ((lastlevels levels))
600 (if (and levels (= (funcall op-back toklevels)
601 (funcall op-forw (car levels))))
602 (setq levels (cdr levels)))
603 ;; We may have found a match for the previously pending
604 ;; operator. Is this the end?
606 ;; Keep looking as long as we haven't matched the
609 (if (funcall op-forw toklevels)
610 (push toklevels levels)))
611 ;; We matched the topmost operator. If the new operator
612 ;; is the last in the corresponding BNF rule, we're done.
613 ((null (funcall op-forw toklevels))
614 ;; It is the last element, let's stop here.
615 (throw 'return (list nil (point) token)))
616 ;; If the new operator is not the last in the BNF rule,
617 ;; ans is not associative, it's one of the inner operators
618 ;; (like the "in" in "let .. in .. end"), so keep looking.
619 ((not (smie--associative-p toklevels))
620 (push toklevels levels))
621 ;; The new operator is associative. Two cases:
622 ;; - it's really just an associative operator (like + or ;)
623 ;; in which case we should have stopped right before.
625 (smie--associative-p (car lastlevels)))
627 (prog1 (list (or (car toklevels) t) (point) token)
629 ;; - it's an associative operator within a larger construct
630 ;; (e.g. an "elsif"), so we should just ignore it and keep
631 ;; looking for the closing element.
632 (t (setq levels lastlevels))))))))
634 (setq halfsexp nil)))))
636 (defun smie-backward-sexp (&optional halfsexp)
638 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
639 first token we see is an operator, skip over its left-hand-side argument.
640 Possible return values:
641 (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
642 is too high. LEFT-LEVEL is the left-level of TOKEN,
643 POS is its start position in the buffer.
644 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
645 (nil POS TOKEN): we skipped over a paren-like pair.
646 nil: we skipped over an identifier, matched parentheses, ..."
648 (indirect-function smie-backward-token-function)
649 (indirect-function 'backward-sexp)
650 (indirect-function 'smie-op-left)
651 (indirect-function 'smie-op-right)
654 (defun smie-forward-sexp (&optional halfsexp)
656 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
657 first token we see is an operator, skip over its left-hand-side argument.
658 Possible return values:
659 (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
660 is too high. RIGHT-LEVEL is the right-level of TOKEN,
661 POS is its end position in the buffer.
662 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
663 (nil POS TOKEN): we skipped over a paren-like pair.
664 nil: we skipped over an identifier, matched parentheses, ..."
666 (indirect-function smie-forward-token-function)
667 (indirect-function 'forward-sexp)
668 (indirect-function 'smie-op-right)
669 (indirect-function 'smie-op-left)
672 ;;; Miscellanous commands using the precedence parser.
674 (defun smie-backward-sexp-command (&optional n)
675 "Move backward through N logical elements."
677 (smie-forward-sexp-command (- n)))
679 (defun smie-forward-sexp-command (&optional n)
680 "Move forward through N logical elements."
683 (forward-sexp-function nil))
685 (setq n (- n (if forw 1 -1)))
688 (smie-forward-sexp 'halfsexp)
689 (smie-backward-sexp 'halfsexp))))
690 (if (and (car res) (= pos (point)) (not (if forw (eobp) (bobp))))
692 (list "Containing expression ends prematurely"
693 (cadr res) (cadr res)))
696 (defvar smie-closer-alist nil
697 "Alist giving the closer corresponding to an opener.")
699 (defun smie-close-block ()
700 "Close the closest surrounding block."
705 (if (looking-at "\\s(")
706 (string (cdr (syntax-after (point))))
707 (let* ((open (funcall smie-forward-token-function))
708 (closer (cdr (assoc open smie-closer-alist)))
709 (levels (list (assoc open smie-op-levels)))
713 ;; Even if we improve the auto-computation of closers,
714 ;; there are still cases where we need manual
715 ;; intervention, e.g. for Octave's use of `until'
716 ;; as a pseudo-closer of `do'.
718 ((or (equal levels '(nil)) (nth 1 (car levels)))
719 (error "Doesn't look like a block"))
721 ;; FIXME: With grammars like Octave's, every closer ("end",
722 ;; "endif", "endwhile", ...) has the same level, so we'd need
723 ;; to look at the BNF or at least at the 2D prec-table, in
724 ;; order to find the right closer for a given opener.
726 (let ((level (pop levels)))
727 (dolist (other smie-op-levels)
728 (when (and (eq (nth 2 level) (nth 1 other))
729 (not (memq other seen)))
733 (push (car other) found))))))
735 ((null found) (error "No known closer for opener %s" open))
736 ;; FIXME: what should we do if there are various closers?
737 (t (car found))))))))))
738 (unless (save-excursion (skip-chars-backward " \t") (bolp))
741 (if (save-excursion (skip-chars-forward " \t") (eolp))
742 (indent-according-to-mode)
743 (reindent-then-newline-and-indent))))
745 (defun smie-down-list (&optional arg)
746 "Move forward down one level paren-like blocks. Like `down-list'.
747 With argument ARG, do this that many times.
748 A negative argument means move backward but still go down a level.
749 This command assumes point is not in a string or comment."
751 (let ((start (point))
752 (inc (if (< arg 0) -1 1))
753 (offset (if (< arg 0) 1 0))
754 (next-token (if (< arg 0)
755 smie-backward-token-function
756 smie-forward-token-function)))
758 (setq arg (- arg inc))
761 (token (funcall next-token))
762 (levels (assoc token smie-op-levels)))
764 ((zerop (length token))
765 (if (if (< inc 0) (looking-back "\\s(\\|\\s)" (1- (point)))
766 (looking-at "\\s(\\|\\s)"))
767 ;; Go back to `start' in case of an error. This presumes
768 ;; none of the token we've found until now include a ( or ).
769 (progn (goto-char start) (down-list inc) nil)
772 ((and levels (null (nth (+ 1 offset) levels))) nil)
773 ((and levels (null (nth (- 2 offset) levels)))
777 (list "Containing expression ends prematurely"
781 (defvar smie-blink-matching-triggers '(?\s ?\n)
782 "Chars which might trigger `blink-matching-open'.
783 These can include the final chars of end-tokens, or chars that are
784 typically inserted right after an end token.
785 I.e. a good choice can be:
787 (mapcar (lambda (kw) (aref (cdr kw) (1- (length (cdr kw)))))
788 smie-closer-alist))")
790 (defcustom smie-blink-matching-inners t
791 "Whether SMIE should blink to matching opener for inner keywords.
792 If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
795 (defun smie-blink-matching-check (start end)
798 (let ((ender (funcall smie-backward-token-function)))
800 ((not (and ender (rassoc ender smie-closer-alist)))
801 ;; This not is one of the begin..end we know how to check.
802 (blink-matching-check-mismatch start end))
804 ((eq t (car (rassoc ender smie-closer-alist))) nil)
807 (let ((starter (funcall smie-forward-token-function)))
808 (not (member (cons starter ender) smie-closer-alist))))))))
810 (defun smie-blink-matching-open ()
811 "Blink the matching opener when applicable.
812 This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
813 (let ((pos (point)) ;Position after the close token.
815 (when (and blink-matching-paren
816 smie-closer-alist ; Optimization.
817 (or (eq (char-before) last-command-event) ;; Sanity check.
819 (or (progn (skip-chars-backward " \t")
821 (eq (char-before) last-command-event))
822 (progn (skip-chars-backward " \n\t")
824 (eq (char-before) last-command-event)))))
825 (memq last-command-event smie-blink-matching-triggers)
826 (not (nth 8 (syntax-ppss))))
828 (setq token (funcall smie-backward-token-function))
829 (when (and (eq (point) (1- pos))
831 (not (rassoc token smie-closer-alist)))
832 ;; The trigger char is itself a token but is not one of the
833 ;; closers (e.g. ?\; in Octave mode), so go back to the
836 (setq token (funcall smie-backward-token-function)))
837 (when (rassoc token smie-closer-alist)
838 ;; We're after a close token. Let's still make sure we
839 ;; didn't skip a comment to find that token.
840 (funcall smie-forward-token-function)
841 (when (and (save-excursion
842 ;; Skip the trigger char, if applicable.
843 (if (eq (char-after) last-command-event)
845 (if (eq ?\n last-command-event)
846 ;; Skip any auto-indentation, if applicable.
847 (skip-chars-forward " \t"))
849 ;; If token ends with a trigger char, don't blink for
850 ;; anything else than this trigger char, lest we'd blink
851 ;; both when inserting the trigger char and when
852 ;; inserting a subsequent trigger char like SPC.
854 (not (memq (char-before)
855 smie-blink-matching-triggers)))
856 (or smie-blink-matching-inners
857 (null (nth 2 (assoc token smie-op-levels)))))
858 ;; The major mode might set blink-matching-check-function
859 ;; buffer-locally so that interactive calls to
860 ;; blink-matching-open work right, but let's not presume
862 (let ((blink-matching-check-function #'smie-blink-matching-check))
863 (blink-matching-open))))))))
865 ;;; The indentation engine.
867 (defcustom smie-indent-basic 4
868 "Basic amount of indentation."
871 (defvar smie-rules-function 'ignore
872 "Function providing the indentation rules.
873 It takes two arguments METHOD and ARG where the meaning of ARG
874 and the expected return value depends on METHOD.
876 - :after, in which case ARG is a token and the function should return the
877 OFFSET to use for indentation after ARG.
878 - :before, in which case ARG is a token and the function should return the
879 OFFSET to use to indent ARG itself.
880 - :elem, in which case the function should return either:
881 - the offset to use to indent function arguments (ARG = `arg')
882 - the basic indentation step (ARG = `basic').
883 - :list-intro, in which case ARG is a token and the function should return
884 non-nil if TOKEN is followed by a list of expressions (not separated by any
885 token) rather than an expression.
887 When ARG is a token, the function is called with point just before that token.
888 A return value of nil always means to fallback on the default behavior, so the
889 function should return nil for arguments it does not expect.
891 OFFSET can be of the form:
892 `point' align with the token.
893 `parent' align with the parent.
894 NUMBER offset by NUMBER.
895 \(+ OFFSETS...) use the sum of OFFSETS.
896 VARIABLE use the value of VARIABLE as offset.
898 This function will often use some of the following functions designed
900 `smie-bolp', `smie-hanging-p', `smie-parent-p', `smie-next-p', `smie-prev-p'.")
902 (defun smie-hanging-p ()
903 "Return non-nil if the current token is \"hanging\".
904 A hanging keyword is one that's at the end of a line except it's not at
905 the beginning of a line."
906 (and (not (smie-bolp))
908 (when (zerop (length (funcall smie-forward-token-function)))
909 ;; Could be an open-paren.
911 (skip-chars-forward " \t")
915 "Return non-nil if the current token is the first on the line."
916 (save-excursion (skip-chars-backward " \t") (bolp)))
918 (defvar smie--parent) (defvar smie--after) ;Dynamically scoped.
920 (defun smie-parent-p (&rest parents)
921 "Return non-nil if the current token's parent is among PARENTS.
922 Only meaningful when called from within `smie-rules-function'."
923 (member (nth 2 (or smie--parent
926 (tok (funcall smie-forward-token-function)))
927 (unless (cadr (assoc tok smie-op-levels))
930 (smie-backward-sexp 'halfsexp))))))
933 (defun smie-next-p (&rest tokens)
934 "Return non-nil if the next token is among TOKENS.
935 Only meaningful when called from within `smie-rules-function'."
939 (smie-indent-forward-token) (setq smie--after (point)))
940 (goto-char smie--after)
941 (smie-indent-forward-token))))
942 (member (car next) tokens)))
944 (defun smie-prev-p (&rest tokens)
945 "Return non-nil if the previous token is among TOKENS."
946 (let ((prev (save-excursion
947 (smie-indent-backward-token))))
948 (member (car prev) tokens)))
951 (defun smie-indent--offset (elem)
952 (or (funcall smie-rules-function :elem elem)
953 (if (not (eq elem 'basic))
954 (funcall smie-rules-function :elem 'basic))
957 (defun smie-indent--rule (kind token &optional after parent)
958 (let ((smie--parent parent)
960 (funcall smie-rules-function kind token)))
962 (defun smie-indent--column (offset &optional base parent virtual-point)
963 "Compute the actual column to use for a given OFFSET.
964 BASE is the base position to use, and PARENT is the parent info, if any.
965 If VIRTUAL-POINT is non-nil, then `point' is virtual."
967 ((eq (car-safe offset) '+)
968 (apply '+ (mapcar (lambda (offset) (smie-indent--column offset nil parent))
974 (parent (goto-char (cadr parent))
975 (smie-indent-virtual))
978 ;; For indentation after "(let" in SML-mode, we end up accumulating
979 ;; the offset of "(" and the offset of "let", so we use `min' to try
980 ;; and get it right either way.
981 (min (smie-indent-virtual) (current-column))))))
983 ;; In indent-keyword, if we're indenting `then' wrt `if', we want to use
984 ;; indent-virtual rather than use just current-column, so that we can
985 ;; apply the (:before . "if") rule which does the "else if" dance in SML.
986 ;; But in other cases, we do not want to use indent-virtual
987 ;; (e.g. indentation of "*" w.r.t "+", or ";" wrt "("). We could just
988 ;; always use indent-virtual and then have indent-rules say explicitly
989 ;; to use `point' after things like "(" or "+" when they're not at EOL,
990 ;; but you'd end up with lots of those rules.
991 ;; So we use a heuristic here, which is that we only use virtual if
992 ;; the parent is tightly linked to the child token (they're part of
993 ;; the same BNF rule).
994 (if (and virtual-point (null (car parent))) ;Black magic :-(
995 (smie-indent-virtual) (current-column)))
998 (setq parent (or (smie-backward-sexp 'halfsexp) :notfound)))
999 (if (consp parent) (goto-char (cadr parent)))
1000 (smie-indent-virtual))
1001 ((eq offset nil) nil)
1002 ;; FIXME: would be good to get rid of this since smie-rules-function
1003 ;; can usually do the lookup trivially, but in cases where
1004 ;; smie-rules-function returns (+ point VAR) it's not nearly as trivial.
1005 ((and (symbolp offset) (boundp 'offset))
1006 (smie-indent--column (symbol-value offset) base parent virtual-point))
1007 (t (error "Unknown indentation offset %s" offset))))
1009 (defun smie-indent-forward-token ()
1010 "Skip token forward and return it, along with its levels."
1011 (let ((tok (funcall smie-forward-token-function)))
1013 ((< 0 (length tok)) (assoc tok smie-op-levels))
1014 ((looking-at "\\s(")
1016 (list (buffer-substring (1- (point)) (point)) nil 0)))))
1018 (defun smie-indent-backward-token ()
1019 "Skip token backward and return it, along with its levels."
1020 (let ((tok (funcall smie-backward-token-function)))
1022 ((< 0 (length tok)) (assoc tok smie-op-levels))
1023 ;; 4 == Open paren syntax.
1024 ((eq 4 (syntax-class (syntax-after (1- (point)))))
1026 (list (buffer-substring (point) (1+ (point))) nil 0)))))
1028 (defun smie-indent-virtual ()
1029 ;; We used to take an optional arg (with value :not-hanging) to specify that
1030 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
1031 ;; keyword. This was a bad idea, because the virtual indent of a position
1032 ;; should not depend on the caller, since it leads to situations where two
1033 ;; dependent indentations get indented differently.
1034 "Compute the virtual indentation to use for point.
1035 This is used when we're not trying to indent point but just
1036 need to compute the column at which point should be indented
1037 in order to figure out the indentation of some other (further down) point."
1038 ;; Trust pre-existing indentation on other lines.
1039 (if (smie-bolp) (current-column) (smie-indent-calculate)))
1041 (defun smie-indent-fixindent ()
1042 ;; Obey the `fixindent' special comment.
1045 (comment-normalize-vars)
1046 (re-search-forward (concat comment-start-skip
1049 ;; 1+ to account for the \n comment termination.
1050 (1+ (line-end-position)) t))
1053 (defun smie-indent-bob ()
1054 ;; Start the file at column 0.
1056 (forward-comment (- (point)))
1059 (defun smie-indent-close ()
1060 ;; Align close paren with opening paren.
1062 ;; (forward-comment (point-max))
1063 (when (looking-at "\\s)")
1064 (while (not (zerop (skip-syntax-forward ")")))
1065 (skip-chars-forward " \t"))
1069 (smie-indent-virtual)) ;:not-hanging
1070 (scan-error nil)))))
1072 (defun smie-indent-keyword ()
1073 ;; Align closing token with the corresponding opening one.
1074 ;; (e.g. "of" with "case", or "in" with "let").
1076 (let* ((pos (point))
1077 (toklevels (smie-indent-forward-token))
1078 (token (pop toklevels)))
1079 (if (null (car toklevels))
1083 ;; - smie-bolp: "indent according to others".
1084 ;; - common hanging: "indent according to others".
1085 ;; - SML-let hanging: "indent like parent".
1086 ;; - if-after-else: "indent-like parent".
1087 ;; - middle-of-line: "trust current position".
1089 ((null (cdr toklevels)) nil) ;Not a keyword.
1091 ;; For an open-paren-like thingy at BOL, always indent only
1092 ;; based on other rules (typically smie-indent-after-keyword).
1095 ;; We're only ever here for virtual-indent, which is why
1096 ;; we can use (current-column) as answer for `point'.
1097 (let* ((offset (or (smie-indent--rule :before token)
1098 ;; By default use point unless we're hanging.
1099 (unless (smie-hanging-p) 'point))))
1100 (smie-indent--column offset)))))
1102 ;; FIXME: This still looks too much like black magic!!
1103 (let* ((parent (smie-backward-sexp 'halfsexp))
1104 (offset (save-excursion
1106 (or (smie-indent--rule :before token nil parent)
1108 ;; Different behaviors:
1109 ;; - align with parent.
1110 ;; - parent + offset.
1111 ;; - after parent's column + offset (actually, after or before
1112 ;; depending on where backward-sexp stopped).
1113 ;; ? let it drop to some other indentation function (almost never).
1114 ;; ? parent + offset + parent's own offset.
1116 ;; - bump into a same-level operator.
1117 ;; - bump into a specific known parent.
1118 ;; - find a matching open-paren thingy.
1119 ;; - bump into some random parent.
1120 ;; ? borderline case (almost never).
1121 ;; ? bump immediately into a parent.
1123 ((not (or (< (point) pos)
1124 (and (cadr parent) (< (cadr parent) pos))))
1125 ;; If we didn't move at all, that means we didn't really skip
1126 ;; what we wanted. Should almost never happen, other than
1127 ;; maybe when an infix or close-paren is at the beginning
1130 ((eq (car parent) (car toklevels))
1131 ;; We bumped into a same-level operator. align with it.
1132 (if (and (smie-bolp) (/= (point) pos)
1134 (goto-char (goto-char (cadr parent)))
1136 ;; Check the offset of `token' rather then its parent
1137 ;; because its parent may have used a special rule. E.g.
1141 ;; The ; on the first line had a special rule, but when
1142 ;; indenting line3, we don't care about it and want to
1143 ;; align with line2.
1144 (memq offset '(point nil)))
1145 ;; If the parent is at EOL and its children are indented like
1146 ;; itself, then we can just obey the indentation chosen for the
1148 ;; This is important for operators like ";" which
1149 ;; are usually at EOL (and have an offset of 0): otherwise we'd
1150 ;; always go back over all the statements, which is
1151 ;; a performance problem and would also mean that fixindents
1152 ;; in the middle of such a sequence would be ignored.
1154 ;; This is a delicate point!
1155 ;; Even if the offset is not 0, we could follow the same logic
1156 ;; and subtract the offset from the child's indentation.
1157 ;; But that would more often be a bad idea: OT1H we generally
1158 ;; want to reuse the closest similar indentation point, so that
1159 ;; the user's choice (or the fixindents) are obeyed. But OTOH
1160 ;; we don't want this to affect "unrelated" parts of the code.
1161 ;; E.g. a fixindent in the body of a "begin..end" should not
1162 ;; affect the indentation of the "end".
1164 (goto-char (cadr parent))
1165 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
1166 ;; want to jump back over a sequence of same-level ops such as
1169 ;; So as to align with the earliest appropriate place.
1170 (smie-indent-virtual)))
1172 (if (and (= (point) pos) (smie-bolp)
1173 (or (eq offset 'point)
1174 (and (consp offset) (memq 'point offset))))
1175 ;; Since we started at BOL, we're not computing a virtual
1176 ;; indentation, and we're still at the starting point, so
1177 ;; we can't use `current-column' which would cause
1178 ;; indentation to depend on itself.
1180 (smie-indent--column offset 'parent parent
1181 ;; If we're still at pos, indent-virtual
1183 (unless (= (point) pos) 'virtual))))))))))
1185 (defun smie-indent-comment ()
1186 "Compute indentation of a comment."
1187 ;; Don't do it for virtual indentations. We should normally never be "in
1188 ;; front of a comment" when doing virtual-indentation anyway. And if we are
1189 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
1191 (let ((pos (point)))
1194 (and (re-search-forward comment-start-skip (line-end-position) t)
1195 (eq pos (or (match-end 1) (match-beginning 0))))))
1197 (forward-comment (point-max))
1198 (skip-chars-forward " \t\r\n")
1199 (smie-indent-calculate))))
1201 (defun smie-indent-comment-continue ()
1202 ;; indentation of comment-continue lines.
1203 (let ((continue (and comment-continue
1204 (comment-string-strip comment-continue t t))))
1205 (and (< 0 (length continue))
1206 (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
1207 (let ((ppss (syntax-ppss)))
1210 (if (<= (point) (nth 8 ppss))
1211 (progn (goto-char (1+ (nth 8 ppss))) (current-column))
1212 (skip-chars-forward " \t")
1213 (if (looking-at (regexp-quote continue))
1214 (current-column))))))))
1216 (defun smie-indent-comment-close ()
1217 (and (boundp 'comment-end-skip)
1219 (not (looking-at " \t*$")) ;Not just a \n comment-closer.
1220 (looking-at comment-end-skip)
1221 (nth 4 (syntax-ppss))
1223 (goto-char (nth 8 (syntax-ppss)))
1226 (defun smie-indent-comment-inside ()
1227 (and (nth 4 (syntax-ppss))
1230 (defun smie-indent-after-keyword ()
1231 ;; Indentation right after a special keyword.
1233 (let* ((pos (point))
1234 (toklevel (smie-indent-backward-token))
1235 (tok (car toklevel)))
1238 (or (smie-indent--rule :after tok pos)
1239 ;; The default indentation after a keyword/operator is
1240 ;; 0 for infix and t for prefix.
1241 (if (or (null (cadr toklevel))
1242 (rassoc tok smie-closer-alist))
1243 (smie-indent--offset 'basic) 0)))
1246 (smie-indent--column offset before))))))
1248 (defun smie-indent-exps ()
1249 ;; Indentation of sequences of simple expressions without
1250 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
1251 ;; Can be a list of expressions or a function call.
1252 ;; If it's a function call, the first element is special (it's the
1253 ;; function). We distinguish function calls from mere lists of
1254 ;; expressions based on whether the preceding token is listed in
1255 ;; the `list-intro' entry of smie-indent-rules.
1257 ;; TODO: to indent Lisp code, we should add a way to specify
1258 ;; particular indentation for particular args depending on the
1259 ;; function (which would require always skipping back until the
1261 ;; TODO: to indent C code, such as "if (...) {...}" we might need
1262 ;; to add similar indentation hooks for particular positions, but
1263 ;; based on the preceding token rather than based on the first exp.
1265 (let ((positions nil)
1267 (while (and (null (car (smie-backward-sexp)))
1268 (push (point) positions)
1271 ;; Figure out if the atom we just skipped is an argument rather
1274 (or (null (car (smie-backward-sexp)))
1275 (funcall smie-rules-function :list-intro
1276 (funcall smie-backward-token-function)))))
1279 ;; We're the first expression of the list. In that case, the
1280 ;; indentation should be (have been) determined by its context.
1283 ;; There's a previous element, and it's not special (it's not
1284 ;; the function), so let's just align with that one.
1285 (goto-char (car positions))
1288 ;; We skipped some args plus the function and bumped into something.
1289 ;; Align with the first arg.
1290 (goto-char (cadr positions))
1293 ;; We're the first arg.
1294 (goto-char (car positions))
1295 ;; FIXME: Use smie-indent--column.
1296 (+ (smie-indent--offset 'args)
1297 ;; We used to use (smie-indent-virtual), but that
1298 ;; doesn't seem right since it might then indent args less than
1299 ;; the function itself.
1300 (current-column)))))))
1302 (defvar smie-indent-functions
1303 '(smie-indent-fixindent smie-indent-bob smie-indent-close
1304 smie-indent-comment smie-indent-comment-continue smie-indent-comment-close
1305 smie-indent-comment-inside smie-indent-keyword smie-indent-after-keyword
1307 "Functions to compute the indentation.
1308 Each function is called with no argument, shouldn't move point, and should
1309 return either nil if it has no opinion, or an integer representing the column
1310 to which that point should be aligned, if we were to reindent it.")
1312 (defun smie-indent-calculate ()
1313 "Compute the indentation to use for point."
1314 (run-hook-with-args-until-success 'smie-indent-functions))
1316 (defun smie-indent-line ()
1317 "Indent current line using the SMIE indentation engine."
1319 (let* ((savep (point))
1320 (indent (condition-case-no-debug nil
1323 (skip-chars-forward " \t")
1324 (if (>= (point) savep) (setq savep nil))
1325 (or (smie-indent-calculate) 0))
1327 (if (not (numberp indent))
1328 ;; If something funny is used (e.g. `noindent'), return it.
1330 (if (< indent 0) (setq indent 0)) ;Just in case.
1332 (save-excursion (indent-line-to indent))
1333 (indent-line-to indent)))))
1335 (defun smie-setup (op-levels rules-function &rest keywords)
1336 "Setup SMIE navigation and indentation.
1337 OP-LEVELS is a grammar table generated by `smie-prec2-levels'.
1338 RULES-FUNCTION is a set of indentation rules for use on `smie-rules-function'.
1339 KEYWORDS are additional arguments, which can use the following keywords:
1340 - :forward-token FUN
1341 - :backward-token FUN"
1342 (set (make-local-variable 'smie-rules-function) rules-function)
1343 (set (make-local-variable 'smie-op-levels) op-levels)
1344 (set (make-local-variable 'indent-line-function) 'smie-indent-line)
1345 (set (make-local-variable 'forward-sexp-function)
1346 'smie-forward-sexp-command)
1348 (let ((k (pop keywords))
1352 (set (make-local-variable 'smie-forward-token-function) v))
1354 (set (make-local-variable 'smie-backward-token-function) v))
1355 (t (message "smie-setup: ignoring unknown keyword %s" k)))))
1356 (let ((ca (cdr (assq :smie-closer-alist op-levels))))
1358 (set (make-local-variable 'smie-closer-alist) ca)
1359 ;; Only needed for interactive calls to blink-matching-open.
1360 (set (make-local-variable 'blink-matching-check-function)
1361 #'smie-blink-matching-check)
1362 (add-hook 'post-self-insert-hook
1363 #'smie-blink-matching-open 'append 'local)
1364 (set (make-local-variable 'smie-blink-matching-triggers)
1365 (append smie-blink-matching-triggers
1366 ;; Rather than wait for SPC to blink, try to blink as
1367 ;; soon as we type the last char of a block ender.
1368 (let ((closers (sort (mapcar #'cdr smie-closer-alist)
1372 (while (setq closer (pop closers))
1373 (unless (and closers
1374 ;; FIXME: this eliminates prefixes of other
1375 ;; closers, but we should probably elimnate
1376 ;; prefixes of other keywords as well.
1377 (string-prefix-p closer (car closers)))
1378 (push (aref closer (1- (length closer))) triggers)))
1379 (delete-dups triggers)))))))
1383 ;;; smie.el ends here