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 (defun smie-precs-precedence-table (precs)
113 "Compute a 2D precedence table from a list of precedences.
114 PRECS should be a list, sorted by precedence (e.g. \"+\" will
115 come before \"*\"), of elements of the form \(left OP ...)
116 or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
117 one of those elements share the same precedence level and associativity."
118 (let ((prec2-table (make-hash-table :test 'equal)))
120 (dolist (op (cdr prec))
121 (let ((selfrule (cdr (assq (car prec)
122 '((left . >) (right . <) (assoc . =))))))
124 (dolist (other-op (cdr prec))
125 (smie-set-prec2tab prec2-table op other-op selfrule))))
126 (let ((op1 '<) (op2 '>))
127 (dolist (other-prec precs)
128 (if (eq prec other-prec)
130 (dolist (other-op (cdr other-prec))
131 (smie-set-prec2tab prec2-table op other-op op2)
132 (smie-set-prec2tab prec2-table other-op op op1)))))))
135 (defun smie-merge-prec2s (&rest tables)
136 (if (null (cdr tables))
138 (let ((prec2 (make-hash-table :test 'equal)))
139 (dolist (table tables)
140 (maphash (lambda (k v)
142 (smie-set-prec2tab prec2 (car k) (cdr k) v)
143 (if (and (gethash k prec2)
144 (not (equal (gethash k prec2) v)))
145 (error "Conflicting values for %s property" k)
146 (puthash k v prec2))))
150 (defun smie-bnf-precedence-table (bnf &rest precs)
151 (let ((nts (mapcar 'car bnf)) ;Non-terminals
156 (prec2 (make-hash-table :test 'equal))
157 (override (apply 'smie-merge-prec2s
158 (mapcar 'smie-precs-precedence-table precs)))
161 (let ((nt (car rules))
166 (dolist (rhs (cdr rules))
168 (signal 'wrong-type-argument `(consp ,rhs)))
169 (if (not (member (car rhs) nts))
170 (pushnew (car rhs) first-ops)
171 (pushnew (car rhs) first-nts)
172 (when (consp (cdr rhs))
173 ;; If the first is not an OP we add the second (which
174 ;; should be an OP if BNF is an "operator grammar").
175 ;; Strictly speaking, this should only be done if the
176 ;; first is a non-terminal which can expand to a phrase
177 ;; without any OP in it, but checking doesn't seem worth
178 ;; the trouble, and it lets the writer of the BNF
179 ;; be a bit more sloppy by skipping uninteresting base
180 ;; cases which are terminals but not OPs.
181 (assert (not (member (cadr rhs) nts)))
182 (pushnew (cadr rhs) first-ops)))
183 (let ((shr (reverse rhs)))
184 (if (not (member (car shr) nts))
185 (pushnew (car shr) last-ops)
186 (pushnew (car shr) last-nts)
187 (when (consp (cdr shr))
188 (assert (not (member (cadr shr) nts)))
189 (pushnew (cadr shr) last-ops)))))
190 (push (cons nt first-ops) first-ops-table)
191 (push (cons nt last-ops) last-ops-table)
192 (push (cons nt first-nts) first-nts-table)
193 (push (cons nt last-nts) last-nts-table)))
194 ;; Compute all first-ops by propagating the initial ones we have
195 ;; now, according to first-nts.
197 (while (prog1 again (setq again nil))
198 (dolist (first-nts first-nts-table)
199 (let* ((nt (pop first-nts))
200 (first-ops (assoc nt first-ops-table)))
201 (dolist (first-nt first-nts)
202 (dolist (op (cdr (assoc first-nt first-ops-table)))
203 (unless (member op first-ops)
205 (push op (cdr first-ops))))))))
206 ;; Same thing for last-ops.
208 (while (prog1 again (setq again nil))
209 (dolist (last-nts last-nts-table)
210 (let* ((nt (pop last-nts))
211 (last-ops (assoc nt last-ops-table)))
212 (dolist (last-nt last-nts)
213 (dolist (op (cdr (assoc last-nt last-ops-table)))
214 (unless (member op last-ops)
216 (push op (cdr last-ops))))))))
217 ;; Now generate the 2D precedence table.
219 (dolist (rhs (cdr rules))
222 ((member (car rhs) nts)
223 (dolist (last (cdr (assoc (car rhs) last-ops-table)))
224 (smie-set-prec2tab prec2 last (cadr rhs) '> override)))
225 ((member (cadr rhs) nts)
226 (dolist (first (cdr (assoc (cadr rhs) first-ops-table)))
227 (smie-set-prec2tab prec2 (car rhs) first '< override))
228 (if (and (cddr rhs) (not (member (car (cddr rhs)) nts)))
229 (smie-set-prec2tab prec2 (car rhs) (car (cddr rhs))
231 (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
232 (setq rhs (cdr rhs)))))
233 ;; Keep track of which tokens are openers/closer, so they can get a nil
234 ;; precedence in smie-prec2-levels.
235 (puthash :smie-open/close-alist (smie-bnf-classify bnf) prec2)
238 ;; (defun smie-prec2-closer-alist (prec2 include-inners)
239 ;; "Build a closer-alist from a PREC2 table.
240 ;; The return value is in the same form as `smie-closer-alist'.
241 ;; INCLUDE-INNERS if non-nil means that inner keywords will be included
242 ;; in the table, e.g. the table will include things like (\"if\" . \"else\")."
243 ;; (let* ((non-openers '())
245 ;; ;; For each keyword, this gives the matching openers, if any.
246 ;; (openers (make-hash-table :test 'equal))
249 ;; ;; First, find the non-openers and non-closers.
250 ;; (maphash (lambda (k v)
251 ;; (unless (or (eq v '<) (member (cdr k) non-openers))
252 ;; (push (cdr k) non-openers))
253 ;; (unless (or (eq v '>) (member (car k) non-closers))
254 ;; (push (car k) non-closers)))
256 ;; ;; Then find the openers and closers.
257 ;; (maphash (lambda (k _)
258 ;; (unless (member (car k) non-openers)
259 ;; (puthash (car k) (list (car k)) openers))
260 ;; (unless (or (member (cdr k) non-closers)
261 ;; (member (cdr k) closers))
262 ;; (push (cdr k) closers)))
264 ;; ;; Then collect the matching elements.
267 ;; (maphash (lambda (k v)
269 ;; (let ((aopeners (gethash (car k) openers))
270 ;; (dopeners (gethash (cdr k) openers))
272 ;; (dolist (o aopeners)
273 ;; (unless (member o dopeners)
275 ;; (push o dopeners)))
278 ;; (puthash (cdr k) dopeners openers)))))
280 ;; ;; Finally, dump the resulting table.
281 ;; (let ((alist '()))
282 ;; (maphash (lambda (k v)
283 ;; (when (or include-inners (member k closers))
284 ;; (dolist (opener v)
285 ;; (unless (equal opener k)
286 ;; (push (cons opener k) alist)))))
290 (defun smie-bnf-closer-alist (bnf &optional no-inners)
291 ;; We can also build this closer-alist table from a prec2 table,
292 ;; but it takes more work, and the order is unpredictable, which
293 ;; is a problem for smie-close-block.
294 ;; More convenient would be to build it from a levels table since we
295 ;; always have this table (contrary to the BNF), but it has all the
296 ;; disadvantages of the prec2 case plus the disadvantage that the levels
297 ;; table has lost some info which would result in extra invalid pairs.
298 "Build a closer-alist from a BNF table.
299 The return value is in the same form as `smie-closer-alist'.
300 NO-INNERS if non-nil means that inner keywords will be excluded
301 from the table, e.g. the table will not include things like (\"if\" . \"else\")."
302 (let ((nts (mapcar #'car bnf)) ;non terminals.
305 (dolist (rhs (cdr nt))
306 (unless (or (< (length rhs) 2) (member (car rhs) nts))
308 (let ((last (car (last rhs))))
309 (unless (member last nts)
310 (pushnew (cons (car rhs) last) alist :test #'equal)))
311 ;; Reverse so that the "real" closer gets there first,
312 ;; which is important for smie-close-block.
313 (dolist (term (reverse (cdr rhs)))
314 (unless (member term nts)
315 (pushnew (cons (car rhs) term) alist :test #'equal)))))))
318 (defun smie-bnf-classify (bnf)
319 "Return a table classifying terminals.
320 Each terminal can either be an `opener', a `closer', or neither."
321 (let ((table (make-hash-table :test #'equal))
323 (dolist (category bnf)
324 (puthash (car category) 'neither table) ;Remove non-terminals.
325 (dolist (rhs (cdr category))
327 (puthash (pop rhs) 'neither table)
328 (let ((first (pop rhs)))
330 (if (memq (gethash first table) '(nil opener))
334 (puthash (pop rhs) 'neither table)) ;Remove internals.
335 (let ((last (pop rhs)))
337 (if (memq (gethash last table) '(nil closer))
340 (maphash (lambda (tok v)
341 (when (memq v '(closer opener))
342 (push (cons tok v) alist)))
346 (defun smie-debug--prec2-cycle (csts)
347 "Return a cycle in CSTS, assuming there's one.
348 CSTS is a list of pairs representing arcs in a graph."
349 ;; A PATH is of the form (START . REST) where REST is a reverse
350 ;; list of nodes through which the path goes.
351 (let ((paths (mapcar (lambda (pair) (list (car pair) (cdr pair))) csts))
354 (dolist (path (prog1 paths (setq paths nil)))
356 (when (eq (car cst) (nth 1 path))
357 (if (eq (cdr cst) (car path))
359 (push (cons (car path) (cons (cdr cst) (cdr path)))
361 (cons (car cycle) (nreverse (cdr cycle)))))
363 (defun smie-debug--describe-cycle (table cycle)
365 (mapcar (lambda (val)
368 (if (eq (cdr elem) val)
369 (push (concat "." (car elem)) res))
370 (if (eq (cddr elem) val)
371 (push (concat (car elem) ".") res)))
376 (lambda (elems) (mapconcat 'identity elems "="))
377 (append names (list (car names)))
380 (defun smie-prec2-levels (prec2)
381 ;; FIXME: Rather than only return an alist of precedence levels, we should
382 ;; also extract other useful data from it:
383 ;; - better default indentation rules (i.e. non-zero indentation after inner
384 ;; keywords like the "in" of "let..in..end") for smie-indent-after-keyword.
385 ;; Of course, maybe those things would be even better handled in the
386 ;; bnf->prec function.
387 "Take a 2D precedence table and turn it into an alist of precedence levels.
388 PREC2 is a table as returned by `smie-precs-precedence-table' or
389 `smie-bnf-precedence-table'."
390 ;; For each operator, we create two "variables" (corresponding to
391 ;; the left and right precedence level), which are represented by
392 ;; cons cells. Those are the very cons cells that appear in the
393 ;; final `table'. The value of each "variable" is kept in the `car'.
398 ;; From `prec2' we construct a list of constraints between
399 ;; variables (aka "precedence levels"). These can be either
400 ;; equality constraints (in `eqs') or `<' constraints (in `csts').
401 (maphash (lambda (k v)
403 (if (setq tmp (assoc (car k) table))
405 (setq x (cons nil nil))
406 (push (cons (car k) (cons nil x)) table))
407 (if (setq tmp (assoc (cdr k) table))
409 (setq y (cons nil (cons nil nil)))
410 (push (cons (cdr k) y) table))
412 (= (push (cons x y) eqs))
413 (< (push (cons x y) csts))
414 (> (push (cons y x) csts)))))
416 ;; First process the equality constraints.
419 (let ((from (caar eqs))
424 (dolist (other-eq eqs)
425 (if (eq from (cdr other-eq)) (setcdr other-eq to))
426 (when (eq from (car other-eq))
427 ;; This can happen because of `assoc' settings in precs
428 ;; or because of a rhs like ("op" foo "op").
429 (setcar other-eq to)))
431 (if (eq from (cdr cst)) (setcdr cst to))
432 (if (eq from (car cst)) (setcar cst to)))))))
433 ;; Then eliminate trivial constraints iteratively.
436 (let ((rhvs (mapcar 'cdr csts))
439 (unless (memq (car cst) rhvs)
441 ;; We could give each var in a given iteration the same value,
442 ;; but we can also give them arbitrarily different values.
443 ;; Basically, these are vars between which there is no
444 ;; constraint (neither equality nor inequality), so
446 ;; We give them arbitrary values, which means that we
447 ;; replace the "no constraint" case with either > or <
448 ;; but not =. The reason we do that is so as to try and
449 ;; distinguish associative operators (which will have
454 (setq csts (delq cst csts))))
456 (error "Can't resolve the precedence cycle: %s"
457 (smie-debug--describe-cycle
458 table (smie-debug--prec2-cycle csts)))))
460 ;; Propagate equalities back to their source.
461 (dolist (eq (nreverse eqs))
462 (assert (or (null (caar eq)) (eq (car eq) (cdr eq))))
463 (setcar (car eq) (cadr eq)))
464 ;; Finally, fill in the remaining vars (which only appeared on the
465 ;; right side of the < constraints).
466 (let ((classification-table (gethash :smie-open/close-alist prec2)))
468 ;; When both sides are nil, it means this operator binds very
469 ;; very tight, but it's still just an operator, so we give it
470 ;; the highest precedence.
471 ;; OTOH if only one side is nil, it usually means it's like an
472 ;; open-paren, which is very important for indentation purposes,
473 ;; so we keep it nil if so, to make it easier to recognize.
474 (unless (or (nth 1 x)
475 (eq 'opener (cdr (assoc (car x) classification-table))))
477 (incf i)) ;See other (incf i) above.
478 (unless (or (nth 2 x)
479 (eq 'closer (cdr (assoc (car x) classification-table))))
481 (incf i))))) ;See other (incf i) above.
484 ;;; Parsing using a precedence level table.
486 (defvar smie-op-levels 'unset
487 "List of token parsing info.
488 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
489 Parsing is done using an operator precedence parser.
490 LEFT-LEVEL and RIGHT-LEVEL can be either numbers or nil, where nil
491 means that this operator does not bind on the corresponding side,
492 i.e. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
493 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
494 like a close-paren.")
496 (defvar smie-forward-token-function 'smie-default-forward-token
497 "Function to scan forward for the next token.
498 Called with no argument should return a token and move to its end.
499 If no token is found, return nil or the empty string.
500 It can return nil when bumping into a parenthesis, which lets SMIE
501 use syntax-tables to handle them in efficient C code.")
503 (defvar smie-backward-token-function 'smie-default-backward-token
504 "Function to scan backward the previous token.
505 Same calling convention as `smie-forward-token-function' except
506 it should move backward to the beginning of the previous token.")
508 (defalias 'smie-op-left 'car)
509 (defalias 'smie-op-right 'cadr)
511 (defun smie-default-backward-token ()
512 (forward-comment (- (point)))
513 (buffer-substring-no-properties
515 (progn (if (zerop (skip-syntax-backward "."))
516 (skip-syntax-backward "w_'"))
519 (defun smie-default-forward-token ()
520 (forward-comment (point-max))
521 (buffer-substring-no-properties
523 (progn (if (zerop (skip-syntax-forward "."))
524 (skip-syntax-forward "w_'"))
527 (defun smie--associative-p (toklevels)
528 ;; in "a + b + c" we want to stop at each +, but in
529 ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
530 ;; To distinguish the two cases, we made smie-prec2-levels choose
531 ;; different levels for each part of "if a then b else c", so that
532 ;; by checking if the left-level is equal to the right level, we can
533 ;; figure out that it's an associative operator.
534 ;; This is not 100% foolproof, tho, since the "elsif" will have to have
535 ;; equal left and right levels (since it's optional), so smie-next-sexp
536 ;; has to be careful to distinguish those different cases.
537 (eq (smie-op-left toklevels) (smie-op-right toklevels)))
539 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
541 NEXT-TOKEN is a function of no argument that moves forward by one
542 token (after skipping comments if needed) and returns it.
543 NEXT-SEXP is a lower-level function to skip one sexp.
544 OP-FORW is the accessor to the forward level of the level data.
545 OP-BACK is the accessor to the backward level of the level data.
546 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
547 first token we see is an operator, skip over its left-hand-side argument.
548 Possible return values:
549 (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
550 is too high. FORW-LEVEL is the forw-level of TOKEN,
551 POS is its start position in the buffer.
552 (t POS TOKEN): same thing when we bump on the wrong side of a paren.
553 (nil POS TOKEN): we skipped over a paren-like pair.
554 nil: we skipped over an identifier, matched parentheses, ..."
559 (token (funcall next-token))
560 (toklevels (cdr (assoc token smie-op-levels))))
563 (when (zerop (length token))
565 (progn (goto-char pos) (funcall next-sexp 1) nil)
566 (scan-error (throw 'return
568 (buffer-substring-no-properties
571 (if (< (point) (caddr err))
574 ;; We did not move, so let's abort the loop.
575 (throw 'return (list t (point))))))
576 ((null (funcall op-back toklevels))
577 ;; A token like a paren-close.
578 (assert (funcall op-forw toklevels)) ;Otherwise, why mention it?
579 (push toklevels levels))
581 (while (and levels (< (funcall op-back toklevels)
582 (funcall op-forw (car levels))))
583 (setq levels (cdr levels)))
586 (if (and halfsexp (funcall op-forw toklevels))
587 (push toklevels levels)
589 (prog1 (list (or (car toklevels) t) (point) token)
592 (let ((lastlevels levels))
593 (if (and levels (= (funcall op-back toklevels)
594 (funcall op-forw (car levels))))
595 (setq levels (cdr levels)))
596 ;; We may have found a match for the previously pending
597 ;; operator. Is this the end?
599 ;; Keep looking as long as we haven't matched the
602 (if (funcall op-forw toklevels)
603 (push toklevels levels)))
604 ;; We matched the topmost operator. If the new operator
605 ;; is the last in the corresponding BNF rule, we're done.
606 ((null (funcall op-forw toklevels))
607 ;; It is the last element, let's stop here.
608 (throw 'return (list nil (point) token)))
609 ;; If the new operator is not the last in the BNF rule,
610 ;; ans is not associative, it's one of the inner operators
611 ;; (like the "in" in "let .. in .. end"), so keep looking.
612 ((not (smie--associative-p toklevels))
613 (push toklevels levels))
614 ;; The new operator is associative. Two cases:
615 ;; - it's really just an associative operator (like + or ;)
616 ;; in which case we should have stopped right before.
618 (smie--associative-p (car lastlevels)))
620 (prog1 (list (or (car toklevels) t) (point) token)
622 ;; - it's an associative operator within a larger construct
623 ;; (e.g. an "elsif"), so we should just ignore it and keep
624 ;; looking for the closing element.
625 (t (setq levels lastlevels))))))))
627 (setq halfsexp nil)))))
629 (defun smie-backward-sexp (&optional halfsexp)
631 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
632 first token we see is an operator, skip over its left-hand-side argument.
633 Possible return values:
634 (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
635 is too high. LEFT-LEVEL is the left-level of TOKEN,
636 POS is its start position in the buffer.
637 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
638 (nil POS TOKEN): we skipped over a paren-like pair.
639 nil: we skipped over an identifier, matched parentheses, ..."
641 (indirect-function smie-backward-token-function)
642 (indirect-function 'backward-sexp)
643 (indirect-function 'smie-op-left)
644 (indirect-function 'smie-op-right)
647 (defun smie-forward-sexp (&optional halfsexp)
649 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
650 first token we see is an operator, skip over its left-hand-side argument.
651 Possible return values:
652 (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
653 is too high. RIGHT-LEVEL is the right-level of TOKEN,
654 POS is its end position in the buffer.
655 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
656 (nil POS TOKEN): we skipped over a paren-like pair.
657 nil: we skipped over an identifier, matched parentheses, ..."
659 (indirect-function smie-forward-token-function)
660 (indirect-function 'forward-sexp)
661 (indirect-function 'smie-op-right)
662 (indirect-function 'smie-op-left)
665 ;;; Miscellanous commands using the precedence parser.
667 (defun smie-backward-sexp-command (&optional n)
668 "Move backward through N logical elements."
670 (smie-forward-sexp-command (- n)))
672 (defun smie-forward-sexp-command (&optional n)
673 "Move forward through N logical elements."
676 (forward-sexp-function nil))
678 (setq n (- n (if forw 1 -1)))
681 (smie-forward-sexp 'halfsexp)
682 (smie-backward-sexp 'halfsexp))))
683 (if (and (car res) (= pos (point)) (not (if forw (eobp) (bobp))))
685 (list "Containing expression ends prematurely"
686 (cadr res) (cadr res)))
689 (defvar smie-closer-alist nil
690 "Alist giving the closer corresponding to an opener.")
692 (defun smie-close-block ()
693 "Close the closest surrounding block."
698 (if (looking-at "\\s(")
699 (string (cdr (syntax-after (point))))
700 (let* ((open (funcall smie-forward-token-function))
701 (closer (cdr (assoc open smie-closer-alist)))
702 (levels (list (assoc open smie-op-levels)))
706 ;; Even if we improve the auto-computation of closers,
707 ;; there are still cases where we need manual
708 ;; intervention, e.g. for Octave's use of `until'
709 ;; as a pseudo-closer of `do'.
711 ((or (equal levels '(nil)) (nth 1 (car levels)))
712 (error "Doesn't look like a block"))
714 ;; FIXME: With grammars like Octave's, every closer ("end",
715 ;; "endif", "endwhile", ...) has the same level, so we'd need
716 ;; to look at the BNF or at least at the 2D prec-table, in
717 ;; order to find the right closer for a given opener.
719 (let ((level (pop levels)))
720 (dolist (other smie-op-levels)
721 (when (and (eq (nth 2 level) (nth 1 other))
722 (not (memq other seen)))
726 (push (car other) found))))))
728 ((null found) (error "No known closer for opener %s" open))
729 ;; FIXME: what should we do if there are various closers?
730 (t (car found))))))))))
731 (unless (save-excursion (skip-chars-backward " \t") (bolp))
734 (if (save-excursion (skip-chars-forward " \t") (eolp))
735 (indent-according-to-mode)
736 (reindent-then-newline-and-indent))))
738 (defun smie-down-list (&optional arg)
739 "Move forward down one level paren-like blocks. Like `down-list'.
740 With argument ARG, do this that many times.
741 A negative argument means move backward but still go down a level.
742 This command assumes point is not in a string or comment."
744 (let ((start (point))
745 (inc (if (< arg 0) -1 1))
746 (offset (if (< arg 0) 1 0))
747 (next-token (if (< arg 0)
748 smie-backward-token-function
749 smie-forward-token-function)))
751 (setq arg (- arg inc))
754 (token (funcall next-token))
755 (levels (assoc token smie-op-levels)))
757 ((zerop (length token))
758 (if (if (< inc 0) (looking-back "\\s(\\|\\s)" (1- (point)))
759 (looking-at "\\s(\\|\\s)"))
760 ;; Go back to `start' in case of an error. This presumes
761 ;; none of the token we've found until now include a ( or ).
762 (progn (goto-char start) (down-list inc) nil)
765 ((and levels (null (nth (+ 1 offset) levels))) nil)
766 ((and levels (null (nth (- 2 offset) levels)))
770 (list "Containing expression ends prematurely"
774 (defvar smie-blink-matching-triggers '(?\s ?\n)
775 "Chars which might trigger `blink-matching-open'.
776 These can include the final chars of end-tokens, or chars that are
777 typically inserted right after an end token.
778 I.e. a good choice can be:
780 (mapcar (lambda (kw) (aref (cdr kw) (1- (length (cdr kw)))))
781 smie-closer-alist))")
783 (defcustom smie-blink-matching-inners t
784 "Whether SMIE should blink to matching opener for inner keywords.
785 If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
788 (defun smie-blink-matching-check (start end)
791 (let ((ender (funcall smie-backward-token-function)))
793 ((not (and ender (rassoc ender smie-closer-alist)))
794 ;; This not is one of the begin..end we know how to check.
795 (blink-matching-check-mismatch start end))
797 ((eq t (car (rassoc ender smie-closer-alist))) nil)
800 (let ((starter (funcall smie-forward-token-function)))
801 (not (member (cons starter ender) smie-closer-alist))))))))
803 (defun smie-blink-matching-open ()
804 "Blink the matching opener when applicable.
805 This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
806 (when (and blink-matching-paren
807 smie-closer-alist ; Optimization.
808 (eq (char-before) last-command-event) ; Sanity check.
809 (memq last-command-event smie-blink-matching-triggers)
810 (not (nth 8 (syntax-ppss))))
813 (token (funcall smie-backward-token-function)))
814 (when (and (eq (point) (1- pos))
816 (not (rassoc token smie-closer-alist)))
817 ;; The trigger char is itself a token but is not one of the
818 ;; closers (e.g. ?\; in Octave mode), so go back to the
821 (setq token (save-excursion
822 (funcall smie-backward-token-function))))
823 (when (rassoc token smie-closer-alist)
824 ;; We're after a close token. Let's still make sure we
825 ;; didn't skip a comment to find that token.
826 (funcall smie-forward-token-function)
827 (when (and (save-excursion
828 ;; Trigger can be SPC, or reindent.
829 (skip-chars-forward " \n\t")
831 ;; If token ends with a trigger char, so don't blink for
832 ;; anything else than this trigger char, lest we'd blink
833 ;; both when inserting the trigger char and when
834 ;; inserting a subsequent trigger char like SPC.
836 (not (memq (char-before)
837 smie-blink-matching-triggers)))
838 (or smie-blink-matching-inners
839 (null (nth 2 (assoc token smie-op-levels)))))
840 ;; The major mode might set blink-matching-check-function
841 ;; buffer-locally so that interactive calls to
842 ;; blink-matching-open work right, but let's not presume
844 (let ((blink-matching-check-function #'smie-blink-matching-check))
845 (blink-matching-open))))))))
847 ;;; The indentation engine.
849 (defcustom smie-indent-basic 4
850 "Basic amount of indentation."
853 (defvar smie-indent-rules 'unset
854 ;; TODO: For SML, we need more rule formats, so as to handle
860 ;; I.e. the indentation after "=" depends on the parent ("structure")
861 ;; as well as on the following token ("struct").
862 "Rules of the following form.
863 \((:before . TOK) . OFFSET-RULES) how to indent TOK itself.
864 \(TOK . OFFSET-RULES) how to indent right after TOK.
865 \(list-intro . TOKENS) declare TOKENS as being followed by what may look like
866 a funcall but is just a sequence of expressions.
867 \(t . OFFSET) basic indentation step.
868 \(args . OFFSET) indentation of arguments.
869 \((T1 . T2) OFFSET) like ((:before . T2) (:parent T1 OFFSET)).
871 OFFSET-RULES is a list of elements which can each either be:
873 \(:hanging . OFFSET-RULES) if TOK is hanging, use OFFSET-RULES.
874 \(:parent PARENT . OFFSET-RULES) if TOK's parent is PARENT, use OFFSET-RULES.
875 \(:next TOKEN . OFFSET-RULES) if TOK is followed by TOKEN, use OFFSET-RULES.
876 \(:prev TOKEN . OFFSET-RULES) if TOK is preceded by TOKEN, use
877 \(:bolp . OFFSET-RULES) If TOK is first on a line, use OFFSET-RULES.
878 OFFSET the offset to use.
880 PARENT can be either the name of the parent or a list of such names.
882 OFFSET can be of the form:
883 `point' align with the token.
884 `parent' align with the parent.
885 NUMBER offset by NUMBER.
886 \(+ OFFSETS...) use the sum of OFFSETS.
887 VARIABLE use the value of VARIABLE as offset.
889 The precise meaning of `point' depends on various details: it can
890 either mean the position of the token we're indenting, or the
891 position of its parent, or the position right after its parent.
893 A nil offset for indentation after an opening token defaults
894 to `smie-indent-basic'.")
896 (defun smie-indent--hanging-p ()
897 ;; A hanging keyword is one that's at the end of a line except it's not at
898 ;; the beginning of a line.
900 (when (zerop (length (funcall smie-forward-token-function)))
901 ;; Could be an open-paren.
903 (skip-chars-forward " \t")
905 (not (smie-indent--bolp))))
907 (defun smie-indent--bolp ()
908 (save-excursion (skip-chars-backward " \t") (bolp)))
910 (defun smie-indent--offset (elem)
911 (or (cdr (assq elem smie-indent-rules))
912 (cdr (assq t smie-indent-rules))
915 (defvar smie-indent-debug-log)
917 (defun smie-indent--offset-rule (tokinfo &optional after parent)
918 "Apply the OFFSET-RULES in TOKINFO.
919 Point is expected to be right in front of the token corresponding to TOKINFO.
920 If computing the indentation after the token, then AFTER is the position
921 after the token, otherwise it should be nil.
922 PARENT if non-nil should be the parent info returned by `smie-backward-sexp'."
923 (let ((rules (cdr tokinfo))
927 (let ((rule (pop rules)))
929 ((not (consp rule)) (setq offset rule))
930 ((eq (car rule) '+) (setq offset rule))
931 ((eq (car rule) :hanging)
932 (when (smie-indent--hanging-p)
933 (setq rules (cdr rule))))
934 ((eq (car rule) :bolp)
935 (when (smie-indent--bolp)
936 (setq rules (cdr rule))))
937 ((eq (car rule) :eolp)
939 (error "Can't use :eolp in :before indentation rules"))
940 (when (> after (line-end-position))
941 (setq rules (cdr rule))))
942 ((eq (car rule) :prev)
945 (setq prev (smie-indent-backward-token))))
946 (when (equal (car prev) (cadr rule))
947 (setq rules (cddr rule))))
948 ((eq (car rule) :next)
951 (error "Can't use :next in :before indentation rules"))
954 (setq next (smie-indent-forward-token))))
955 (when (equal (car next) (cadr rule))
956 (setq rules (cddr rule))))
957 ((eq (car rule) :parent)
960 (if after (goto-char after))
961 (setq parent (smie-backward-sexp 'halfsexp))))
962 (when (if (listp (cadr rule))
963 (member (nth 2 parent) (cadr rule))
964 (equal (nth 2 parent) (cadr rule)))
965 (setq rules (cddr rule))))
966 (t (error "Unknown rule %s for indentation of %s"
967 rule (car tokinfo))))))
968 ;; If `offset' is not set yet, use `rules' to handle the case where
969 ;; the tokinfo uses the old-style ((PARENT . TOK). OFFSET).
970 (unless offset (setq offset rules))
971 (when (boundp 'smie-indent-debug-log)
972 (push (list (point) offset tokinfo) smie-indent-debug-log))
975 (defun smie-indent--column (offset &optional base parent virtual-point)
976 "Compute the actual column to use for a given OFFSET.
977 BASE is the base position to use, and PARENT is the parent info, if any.
978 If VIRTUAL-POINT is non-nil, then `point' is virtual."
980 ((eq (car-safe offset) '+)
981 (apply '+ (mapcar (lambda (offset) (smie-indent--column offset nil parent))
987 (parent (goto-char (cadr parent))
988 (smie-indent-virtual))
991 ;; For indentation after "(let" in SML-mode, we end up accumulating
992 ;; the offset of "(" and the offset of "let", so we use `min' to try
993 ;; and get it right either way.
994 (min (smie-indent-virtual) (current-column))))))
996 ;; In indent-keyword, if we're indenting `then' wrt `if', we want to use
997 ;; indent-virtual rather than use just current-column, so that we can
998 ;; apply the (:before . "if") rule which does the "else if" dance in SML.
999 ;; But in other cases, we do not want to use indent-virtual
1000 ;; (e.g. indentation of "*" w.r.t "+", or ";" wrt "("). We could just
1001 ;; always use indent-virtual and then have indent-rules say explicitly
1002 ;; to use `point' after things like "(" or "+" when they're not at EOL,
1003 ;; but you'd end up with lots of those rules.
1004 ;; So we use a heuristic here, which is that we only use virtual if
1005 ;; the parent is tightly linked to the child token (they're part of
1006 ;; the same BNF rule).
1007 (if (and virtual-point (null (car parent))) ;Black magic :-(
1008 (smie-indent-virtual) (current-column)))
1009 ((eq offset 'parent)
1011 (setq parent (or (smie-backward-sexp 'halfsexp) :notfound)))
1012 (if (consp parent) (goto-char (cadr parent)))
1013 (smie-indent-virtual))
1014 ((eq offset nil) nil)
1015 ((and (symbolp offset) (boundp 'offset))
1016 (smie-indent--column (symbol-value offset) base parent virtual-point))
1017 (t (error "Unknown indentation offset %s" offset))))
1019 (defun smie-indent-forward-token ()
1020 "Skip token forward and return it, along with its levels."
1021 (let ((tok (funcall smie-forward-token-function)))
1023 ((< 0 (length tok)) (assoc tok smie-op-levels))
1024 ((looking-at "\\s(")
1026 (list (buffer-substring (1- (point)) (point)) nil 0)))))
1028 (defun smie-indent-backward-token ()
1029 "Skip token backward and return it, along with its levels."
1030 (let ((tok (funcall smie-backward-token-function)))
1032 ((< 0 (length tok)) (assoc tok smie-op-levels))
1033 ;; 4 == Open paren syntax.
1034 ((eq 4 (syntax-class (syntax-after (1- (point)))))
1036 (list (buffer-substring (point) (1+ (point))) nil 0)))))
1038 (defun smie-indent-virtual ()
1039 ;; We used to take an optional arg (with value :not-hanging) to specify that
1040 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
1041 ;; keyword. This was a bad idea, because the virtual indent of a position
1042 ;; should not depend on the caller, since it leads to situations where two
1043 ;; dependent indentations get indented differently.
1044 "Compute the virtual indentation to use for point.
1045 This is used when we're not trying to indent point but just
1046 need to compute the column at which point should be indented
1047 in order to figure out the indentation of some other (further down) point."
1048 ;; Trust pre-existing indentation on other lines.
1049 (if (smie-indent--bolp) (current-column) (smie-indent-calculate)))
1051 (defun smie-indent-fixindent ()
1052 ;; Obey the `fixindent' special comment.
1053 (and (smie-indent--bolp)
1055 (comment-normalize-vars)
1056 (re-search-forward (concat comment-start-skip
1059 ;; 1+ to account for the \n comment termination.
1060 (1+ (line-end-position)) t))
1063 (defun smie-indent-bob ()
1064 ;; Start the file at column 0.
1066 (forward-comment (- (point)))
1069 (defun smie-indent-close ()
1070 ;; Align close paren with opening paren.
1072 ;; (forward-comment (point-max))
1073 (when (looking-at "\\s)")
1074 (while (not (zerop (skip-syntax-forward ")")))
1075 (skip-chars-forward " \t"))
1079 (smie-indent-virtual)) ;:not-hanging
1080 (scan-error nil)))))
1082 (defun smie-indent-keyword ()
1083 ;; Align closing token with the corresponding opening one.
1084 ;; (e.g. "of" with "case", or "in" with "let").
1086 (let* ((pos (point))
1087 (toklevels (smie-indent-forward-token))
1088 (token (pop toklevels)))
1089 (if (null (car toklevels))
1093 ;; - smie-indent--bolp: "indent according to others".
1094 ;; - common hanging: "indent according to others".
1095 ;; - SML-let hanging: "indent like parent".
1096 ;; - if-after-else: "indent-like parent".
1097 ;; - middle-of-line: "trust current position".
1099 ((null (cdr toklevels)) nil) ;Not a keyword.
1100 ((smie-indent--bolp)
1101 ;; For an open-paren-like thingy at BOL, always indent only
1102 ;; based on other rules (typically smie-indent-after-keyword).
1105 ;; We're only ever here for virtual-indent, which is why
1106 ;; we can use (current-column) as answer for `point'.
1107 (let* ((tokinfo (or (assoc (cons :before token)
1109 ;; By default use point unless we're hanging.
1110 `((:before . ,token) (:hanging nil) point)))
1111 ;; (after (prog1 (point) (goto-char pos)))
1112 (offset (smie-indent--offset-rule tokinfo)))
1113 (smie-indent--column offset)))))
1115 ;; FIXME: This still looks too much like black magic!!
1116 ;; FIXME: Rather than a bunch of rules like (PARENT . TOKEN), we
1117 ;; want a single rule for TOKEN with different cases for each PARENT.
1118 (let* ((parent (smie-backward-sexp 'halfsexp))
1120 (or (assoc (cons (caddr parent) token)
1122 (assoc (cons :before token) smie-indent-rules)
1124 `((:before . ,token)
1127 (offset (save-excursion
1129 (smie-indent--offset-rule tokinfo nil parent))))
1130 ;; Different behaviors:
1131 ;; - align with parent.
1132 ;; - parent + offset.
1133 ;; - after parent's column + offset (actually, after or before
1134 ;; depending on where backward-sexp stopped).
1135 ;; ? let it drop to some other indentation function (almost never).
1136 ;; ? parent + offset + parent's own offset.
1138 ;; - bump into a same-level operator.
1139 ;; - bump into a specific known parent.
1140 ;; - find a matching open-paren thingy.
1141 ;; - bump into some random parent.
1142 ;; ? borderline case (almost never).
1143 ;; ? bump immediately into a parent.
1145 ((not (or (< (point) pos)
1146 (and (cadr parent) (< (cadr parent) pos))))
1147 ;; If we didn't move at all, that means we didn't really skip
1148 ;; what we wanted. Should almost never happen, other than
1149 ;; maybe when an infix or close-paren is at the beginning
1152 ((eq (car parent) (car toklevels))
1153 ;; We bumped into a same-level operator. align with it.
1154 (if (and (smie-indent--bolp) (/= (point) pos)
1156 (goto-char (goto-char (cadr parent)))
1157 (not (smie-indent--bolp)))
1158 ;; Check the offset of `token' rather then its parent
1159 ;; because its parent may have used a special rule. E.g.
1163 ;; The ; on the first line had a special rule, but when
1164 ;; indenting line3, we don't care about it and want to
1165 ;; align with line2.
1166 (memq offset '(point nil)))
1167 ;; If the parent is at EOL and its children are indented like
1168 ;; itself, then we can just obey the indentation chosen for the
1170 ;; This is important for operators like ";" which
1171 ;; are usually at EOL (and have an offset of 0): otherwise we'd
1172 ;; always go back over all the statements, which is
1173 ;; a performance problem and would also mean that fixindents
1174 ;; in the middle of such a sequence would be ignored.
1176 ;; This is a delicate point!
1177 ;; Even if the offset is not 0, we could follow the same logic
1178 ;; and subtract the offset from the child's indentation.
1179 ;; But that would more often be a bad idea: OT1H we generally
1180 ;; want to reuse the closest similar indentation point, so that
1181 ;; the user's choice (or the fixindents) are obeyed. But OTOH
1182 ;; we don't want this to affect "unrelated" parts of the code.
1183 ;; E.g. a fixindent in the body of a "begin..end" should not
1184 ;; affect the indentation of the "end".
1186 (goto-char (cadr parent))
1187 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
1188 ;; want to jump back over a sequence of same-level ops such as
1191 ;; So as to align with the earliest appropriate place.
1192 (smie-indent-virtual)))
1194 (if (and (= (point) pos) (smie-indent--bolp)
1195 (or (eq offset 'point)
1196 (and (consp offset) (memq 'point offset))))
1197 ;; Since we started at BOL, we're not computing a virtual
1198 ;; indentation, and we're still at the starting point, so
1199 ;; we can't use `current-column' which would cause
1200 ;; indentation to depend on itself.
1202 (smie-indent--column offset 'parent parent
1203 ;; If we're still at pos, indent-virtual
1205 (unless (= (point) pos) 'virtual))))))))))
1207 (defun smie-indent-comment ()
1208 "Compute indentation of a comment."
1209 ;; Don't do it for virtual indentations. We should normally never be "in
1210 ;; front of a comment" when doing virtual-indentation anyway. And if we are
1211 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
1212 (and (smie-indent--bolp)
1213 (let ((pos (point)))
1216 (and (re-search-forward comment-start-skip (line-end-position) t)
1217 (eq pos (or (match-end 1) (match-beginning 0))))))
1219 (forward-comment (point-max))
1220 (skip-chars-forward " \t\r\n")
1221 (smie-indent-calculate))))
1223 (defun smie-indent-comment-continue ()
1224 ;; indentation of comment-continue lines.
1225 (let ((continue (and comment-continue
1226 (comment-string-strip comment-continue t t))))
1227 (and (< 0 (length continue))
1228 (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
1229 (let ((ppss (syntax-ppss)))
1232 (if (<= (point) (nth 8 ppss))
1233 (progn (goto-char (1+ (nth 8 ppss))) (current-column))
1234 (skip-chars-forward " \t")
1235 (if (looking-at (regexp-quote continue))
1236 (current-column))))))))
1238 (defun smie-indent-comment-close ()
1239 (and (boundp 'comment-end-skip)
1241 (not (looking-at " \t*$")) ;Not just a \n comment-closer.
1242 (looking-at comment-end-skip)
1243 (nth 4 (syntax-ppss))
1245 (goto-char (nth 8 (syntax-ppss)))
1248 (defun smie-indent-comment-inside ()
1249 (and (nth 4 (syntax-ppss))
1252 (defun smie-indent-after-keyword ()
1253 ;; Indentation right after a special keyword.
1255 (let* ((pos (point))
1256 (toklevel (smie-indent-backward-token))
1257 (tok (car toklevel))
1258 (tokinfo (assoc tok smie-indent-rules)))
1259 ;; Set some default indent rules.
1260 (if (and toklevel (null (cadr toklevel)) (null tokinfo))
1261 (setq tokinfo (list (car toklevel))))
1262 ;; (if (and tokinfo (null toklevel))
1263 ;; (error "Token %S has indent rule but has no parsing info" tok))
1266 ;; The default indentation after a keyword/operator is 0 for
1267 ;; infix and t for prefix.
1268 ;; Using the BNF syntax, we could come up with better
1269 ;; defaults, but we only have the precedence levels here.
1270 (setq tokinfo (list tok 'default-rule
1271 (if (cadr toklevel) 0 (smie-indent--offset t)))))
1273 (or (smie-indent--offset-rule tokinfo pos)
1274 (smie-indent--offset t))))
1275 (let ((before (point)))
1277 (smie-indent--column offset before)))))))
1279 (defun smie-indent-exps ()
1280 ;; Indentation of sequences of simple expressions without
1281 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
1282 ;; Can be a list of expressions or a function call.
1283 ;; If it's a function call, the first element is special (it's the
1284 ;; function). We distinguish function calls from mere lists of
1285 ;; expressions based on whether the preceding token is listed in
1286 ;; the `list-intro' entry of smie-indent-rules.
1288 ;; TODO: to indent Lisp code, we should add a way to specify
1289 ;; particular indentation for particular args depending on the
1290 ;; function (which would require always skipping back until the
1292 ;; TODO: to indent C code, such as "if (...) {...}" we might need
1293 ;; to add similar indentation hooks for particular positions, but
1294 ;; based on the preceding token rather than based on the first exp.
1296 (let ((positions nil)
1298 (while (and (null (car (smie-backward-sexp)))
1299 (push (point) positions)
1300 (not (smie-indent--bolp))))
1302 ;; Figure out if the atom we just skipped is an argument rather
1304 (setq arg (or (null (car (smie-backward-sexp)))
1305 (member (funcall smie-backward-token-function)
1306 (cdr (assoc 'list-intro smie-indent-rules))))))
1309 ;; We're the first expression of the list. In that case, the
1310 ;; indentation should be (have been) determined by its context.
1313 ;; There's a previous element, and it's not special (it's not
1314 ;; the function), so let's just align with that one.
1315 (goto-char (car positions))
1318 ;; We skipped some args plus the function and bumped into something.
1319 ;; Align with the first arg.
1320 (goto-char (cadr positions))
1323 ;; We're the first arg.
1324 (goto-char (car positions))
1325 ;; FIXME: Use smie-indent--column.
1326 (+ (smie-indent--offset 'args)
1327 ;; We used to use (smie-indent-virtual), but that
1328 ;; doesn't seem right since it might then indent args less than
1329 ;; the function itself.
1330 (current-column)))))))
1332 (defvar smie-indent-functions
1333 '(smie-indent-fixindent smie-indent-bob smie-indent-close
1334 smie-indent-comment smie-indent-comment-continue smie-indent-comment-close
1335 smie-indent-comment-inside smie-indent-keyword smie-indent-after-keyword
1337 "Functions to compute the indentation.
1338 Each function is called with no argument, shouldn't move point, and should
1339 return either nil if it has no opinion, or an integer representing the column
1340 to which that point should be aligned, if we were to reindent it.")
1342 (defun smie-indent-calculate ()
1343 "Compute the indentation to use for point."
1344 (run-hook-with-args-until-success 'smie-indent-functions))
1346 (defun smie-indent-line ()
1347 "Indent current line using the SMIE indentation engine."
1349 (let* ((savep (point))
1350 (indent (condition-case-no-debug nil
1353 (skip-chars-forward " \t")
1354 (if (>= (point) savep) (setq savep nil))
1355 (or (smie-indent-calculate) 0))
1357 (if (not (numberp indent))
1358 ;; If something funny is used (e.g. `noindent'), return it.
1360 (if (< indent 0) (setq indent 0)) ;Just in case.
1362 (save-excursion (indent-line-to indent))
1363 (indent-line-to indent)))))
1365 (defun smie-indent-debug ()
1366 "Show the rules used to compute indentation of current line."
1368 (let ((smie-indent-debug-log '()))
1369 (smie-indent-calculate)
1370 ;; FIXME: please improve!
1371 (message "%S" smie-indent-debug-log)))
1373 (defun smie-setup (op-levels indent-rules)
1374 (set (make-local-variable 'smie-indent-rules) indent-rules)
1375 (set (make-local-variable 'smie-op-levels) op-levels)
1376 (set (make-local-variable 'indent-line-function) 'smie-indent-line))
1380 ;;; smie.el ends here