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 ;; A good background to understand the development (especially the parts
56 ;; building the 2D precedence tables and then computing the precedence levels
57 ;; from it) can be found in pages 187-194 of "Parsing techniques" by Dick Grune
58 ;; and Ceriel Jacobs (BookBody.pdf available at
59 ;; http://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.
66 ;; Conflict resolution:
68 ;; - One source of conflicts is when you have:
69 ;; (exp ("IF" exp "ELSE" exp "END") ("CASE" cases "END"))
70 ;; (cases (cases "ELSE" insts) ...)
71 ;; The IF-rule implies ELSE=END and the CASE-rule implies ELSE>END.
72 ;; FIXME: we could try to resolve such conflicts automatically by changing
73 ;; the way BNF rules such as the IF-rule is handled. I.e. rather than
74 ;; IF=ELSE and ELSE=END, we could turn them into IF<ELSE and ELSE>END
79 ;; FIXME: I think the behavior on empty lines is wrong. It shouldn't
80 ;; look at the next token on subsequent lines.
82 (eval-when-compile (require 'cl
))
85 "Simple Minded Indentation Engine."
88 (defvar comment-continue
)
89 (declare-function comment-string-strip
"newcomment" (str beforep afterp
))
91 ;;; Building precedence level tables from BNF specs.
93 ;; We have 4 different representations of a "grammar":
94 ;; - a BNF table, which is a list of BNF rules of the form
95 ;; (NONTERM RHS1 ... RHSn) where each RHS is a list of terminals (tokens)
96 ;; or nonterminals. Any element in these lists which does not appear as
97 ;; the `car' of a BNF rule is taken to be a terminal.
98 ;; - A list of precedences (key word "precs"), is a list, sorted
99 ;; from lowest to highest precedence, of precedence classes that
100 ;; have the form (ASSOCIATIVITY TERMINAL1 .. TERMINALn), where
101 ;; ASSOCIATIVITY can be `assoc', `left', `right' or `nonassoc'.
102 ;; - a 2 dimensional precedence table (key word "prec2"), is a 2D
103 ;; table recording the precedence relation (can be `<', `=', `>', or
104 ;; nil) between each pair of tokens.
105 ;; - a precedence-level table (key word "grammar"), which is a alist
106 ;; giving for each token its left and right precedence level (a
107 ;; number or nil). This is used in `smie-grammar'.
108 ;; The prec2 tables are only intermediate data structures: the source
109 ;; code normally provides a mix of BNF and precs tables, and then
110 ;; turns them into a levels table, which is what's used by the rest of
113 (defun smie-set-prec2tab (table x y val
&optional override
)
115 (let* ((key (cons x y
))
116 (old (gethash key table
)))
117 (if (and old
(not (eq old val
)))
118 (if (and override
(gethash key override
))
119 ;; FIXME: The override is meant to resolve ambiguities,
120 ;; but it also hides real conflicts. It would be great to
121 ;; be able to distinguish the two cases so that overrides
122 ;; don't hide real conflicts.
123 (puthash key
(gethash key override
) table
)
124 (display-warning 'smie
(format "Conflict: %s %s/%s %s" x old val y
)))
125 (puthash key val table
))))
127 (put 'smie-precs-
>prec2
'pure t
)
128 (defun smie-precs->prec2
(precs)
129 "Compute a 2D precedence table from a list of precedences.
130 PRECS should be a list, sorted by precedence (e.g. \"+\" will
131 come before \"*\"), of elements of the form \(left OP ...)
132 or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
133 one of those elements share the same precedence level and associativity."
134 (let ((prec2-table (make-hash-table :test
'equal
)))
136 (dolist (op (cdr prec
))
137 (let ((selfrule (cdr (assq (car prec
)
138 '((left .
>) (right .
<) (assoc .
=))))))
140 (dolist (other-op (cdr prec
))
141 (smie-set-prec2tab prec2-table op other-op selfrule
))))
142 (let ((op1 '<) (op2 '>))
143 (dolist (other-prec precs
)
144 (if (eq prec other-prec
)
146 (dolist (other-op (cdr other-prec
))
147 (smie-set-prec2tab prec2-table op other-op op2
)
148 (smie-set-prec2tab prec2-table other-op op op1
)))))))
151 (put 'smie-merge-prec2s
'pure t
)
152 (defun smie-merge-prec2s (&rest tables
)
153 (if (null (cdr tables
))
155 (let ((prec2 (make-hash-table :test
'equal
)))
156 (dolist (table tables
)
157 (maphash (lambda (k v
)
159 (smie-set-prec2tab prec2
(car k
) (cdr k
) v
)
160 (if (and (gethash k prec2
)
161 (not (equal (gethash k prec2
) v
)))
162 (error "Conflicting values for %s property" k
)
163 (puthash k v prec2
))))
167 (put 'smie-bnf-
>prec2
'pure t
)
168 (defun smie-bnf->prec2
(bnf &rest precs
)
169 ;; FIXME: Add repetition operator like (repeat <separator> <elems>).
170 ;; Maybe also add (or <elem1> <elem2>...) for things like
171 ;; (exp (exp (or "+" "*" "=" ..) exp)).
172 ;; Basically, make it EBNF (except for the specification of a separator in
174 (let ((nts (mapcar 'car bnf
)) ;Non-terminals
179 (prec2 (make-hash-table :test
'equal
))
180 (override (apply 'smie-merge-prec2s
181 (mapcar 'smie-precs-
>prec2 precs
)))
184 (let ((nt (car rules
))
189 (dolist (rhs (cdr rules
))
191 (signal 'wrong-type-argument
`(consp ,rhs
)))
192 (if (not (member (car rhs
) nts
))
193 (pushnew (car rhs
) first-ops
)
194 (pushnew (car rhs
) first-nts
)
195 (when (consp (cdr rhs
))
196 ;; If the first is not an OP we add the second (which
197 ;; should be an OP if BNF is an "operator grammar").
198 ;; Strictly speaking, this should only be done if the
199 ;; first is a non-terminal which can expand to a phrase
200 ;; without any OP in it, but checking doesn't seem worth
201 ;; the trouble, and it lets the writer of the BNF
202 ;; be a bit more sloppy by skipping uninteresting base
203 ;; cases which are terminals but not OPs.
204 (assert (not (member (cadr rhs
) nts
)))
205 (pushnew (cadr rhs
) first-ops
)))
206 (let ((shr (reverse rhs
)))
207 (if (not (member (car shr
) nts
))
208 (pushnew (car shr
) last-ops
)
209 (pushnew (car shr
) last-nts
)
210 (when (consp (cdr shr
))
211 (assert (not (member (cadr shr
) nts
)))
212 (pushnew (cadr shr
) last-ops
)))))
213 (push (cons nt first-ops
) first-ops-table
)
214 (push (cons nt last-ops
) last-ops-table
)
215 (push (cons nt first-nts
) first-nts-table
)
216 (push (cons nt last-nts
) last-nts-table
)))
217 ;; Compute all first-ops by propagating the initial ones we have
218 ;; now, according to first-nts.
220 (while (prog1 again
(setq again nil
))
221 (dolist (first-nts first-nts-table
)
222 (let* ((nt (pop first-nts
))
223 (first-ops (assoc nt first-ops-table
)))
224 (dolist (first-nt first-nts
)
225 (dolist (op (cdr (assoc first-nt first-ops-table
)))
226 (unless (member op first-ops
)
228 (push op
(cdr first-ops
))))))))
229 ;; Same thing for last-ops.
231 (while (prog1 again
(setq again nil
))
232 (dolist (last-nts last-nts-table
)
233 (let* ((nt (pop last-nts
))
234 (last-ops (assoc nt last-ops-table
)))
235 (dolist (last-nt last-nts
)
236 (dolist (op (cdr (assoc last-nt last-ops-table
)))
237 (unless (member op last-ops
)
239 (push op
(cdr last-ops
))))))))
240 ;; Now generate the 2D precedence table.
242 (dolist (rhs (cdr rules
))
245 ((member (car rhs
) nts
)
246 (dolist (last (cdr (assoc (car rhs
) last-ops-table
)))
247 (smie-set-prec2tab prec2 last
(cadr rhs
) '> override
)))
248 ((member (cadr rhs
) nts
)
249 (dolist (first (cdr (assoc (cadr rhs
) first-ops-table
)))
250 (smie-set-prec2tab prec2
(car rhs
) first
'< override
))
251 (if (and (cddr rhs
) (not (member (car (cddr rhs
)) nts
)))
252 (smie-set-prec2tab prec2
(car rhs
) (car (cddr rhs
))
254 (t (smie-set-prec2tab prec2
(car rhs
) (cadr rhs
) '= override
)))
255 (setq rhs
(cdr rhs
)))))
256 ;; Keep track of which tokens are openers/closer, so they can get a nil
257 ;; precedence in smie-prec2->grammar.
258 (puthash :smie-open
/close-alist
(smie-bnf-classify bnf
) prec2
)
259 (puthash :smie-closer-alist
(smie-bnf-closer-alist bnf
) prec2
)
262 ;; (defun smie-prec2-closer-alist (prec2 include-inners)
263 ;; "Build a closer-alist from a PREC2 table.
264 ;; The return value is in the same form as `smie-closer-alist'.
265 ;; INCLUDE-INNERS if non-nil means that inner keywords will be included
266 ;; in the table, e.g. the table will include things like (\"if\" . \"else\")."
267 ;; (let* ((non-openers '())
269 ;; ;; For each keyword, this gives the matching openers, if any.
270 ;; (openers (make-hash-table :test 'equal))
273 ;; ;; First, find the non-openers and non-closers.
274 ;; (maphash (lambda (k v)
275 ;; (unless (or (eq v '<) (member (cdr k) non-openers))
276 ;; (push (cdr k) non-openers))
277 ;; (unless (or (eq v '>) (member (car k) non-closers))
278 ;; (push (car k) non-closers)))
280 ;; ;; Then find the openers and closers.
281 ;; (maphash (lambda (k _)
282 ;; (unless (member (car k) non-openers)
283 ;; (puthash (car k) (list (car k)) openers))
284 ;; (unless (or (member (cdr k) non-closers)
285 ;; (member (cdr k) closers))
286 ;; (push (cdr k) closers)))
288 ;; ;; Then collect the matching elements.
291 ;; (maphash (lambda (k v)
293 ;; (let ((aopeners (gethash (car k) openers))
294 ;; (dopeners (gethash (cdr k) openers))
296 ;; (dolist (o aopeners)
297 ;; (unless (member o dopeners)
299 ;; (push o dopeners)))
302 ;; (puthash (cdr k) dopeners openers)))))
304 ;; ;; Finally, dump the resulting table.
305 ;; (let ((alist '()))
306 ;; (maphash (lambda (k v)
307 ;; (when (or include-inners (member k closers))
308 ;; (dolist (opener v)
309 ;; (unless (equal opener k)
310 ;; (push (cons opener k) alist)))))
314 (defun smie-bnf-closer-alist (bnf &optional no-inners
)
315 ;; We can also build this closer-alist table from a prec2 table,
316 ;; but it takes more work, and the order is unpredictable, which
317 ;; is a problem for smie-close-block.
318 ;; More convenient would be to build it from a levels table since we
319 ;; always have this table (contrary to the BNF), but it has all the
320 ;; disadvantages of the prec2 case plus the disadvantage that the levels
321 ;; table has lost some info which would result in extra invalid pairs.
322 "Build a closer-alist from a BNF table.
323 The return value is in the same form as `smie-closer-alist'.
324 NO-INNERS if non-nil means that inner keywords will be excluded
325 from the table, e.g. the table will not include things like (\"if\" . \"else\")."
326 (let ((nts (mapcar #'car bnf
)) ;non terminals.
329 (dolist (rhs (cdr nt
))
330 (unless (or (< (length rhs
) 2) (member (car rhs
) nts
))
332 (let ((last (car (last rhs
))))
333 (unless (member last nts
)
334 (pushnew (cons (car rhs
) last
) alist
:test
#'equal
)))
335 ;; Reverse so that the "real" closer gets there first,
336 ;; which is important for smie-close-block.
337 (dolist (term (reverse (cdr rhs
)))
338 (unless (member term nts
)
339 (pushnew (cons (car rhs
) term
) alist
:test
#'equal
)))))))
342 (defun smie-bnf-classify (bnf)
343 "Return a table classifying terminals.
344 Each terminal can either be an `opener', a `closer', or neither."
345 (let ((table (make-hash-table :test
#'equal
))
347 (dolist (category bnf
)
348 (puthash (car category
) 'neither table
) ;Remove non-terminals.
349 (dolist (rhs (cdr category
))
351 (puthash (pop rhs
) 'neither table
)
352 (let ((first (pop rhs
)))
354 (if (memq (gethash first table
) '(nil opener
))
358 (puthash (pop rhs
) 'neither table
)) ;Remove internals.
359 (let ((last (pop rhs
)))
361 (if (memq (gethash last table
) '(nil closer
))
364 (maphash (lambda (tok v
)
365 (when (memq v
'(closer opener
))
366 (push (cons tok v
) alist
)))
370 (defun smie-debug--prec2-cycle (csts)
371 "Return a cycle in CSTS, assuming there's one.
372 CSTS is a list of pairs representing arcs in a graph."
373 ;; A PATH is of the form (START . REST) where REST is a reverse
374 ;; list of nodes through which the path goes.
375 (let ((paths (mapcar (lambda (pair) (list (car pair
) (cdr pair
))) csts
))
378 (dolist (path (prog1 paths
(setq paths nil
)))
380 (when (eq (car cst
) (nth 1 path
))
381 (if (eq (cdr cst
) (car path
))
383 (push (cons (car path
) (cons (cdr cst
) (cdr path
)))
385 (cons (car cycle
) (nreverse (cdr cycle
)))))
387 (defun smie-debug--describe-cycle (table cycle
)
389 (mapcar (lambda (val)
392 (if (eq (cdr elem
) val
)
393 (push (concat "." (car elem
)) res
))
394 (if (eq (cddr elem
) val
)
395 (push (concat (car elem
) ".") res
)))
400 (lambda (elems) (mapconcat 'identity elems
"="))
401 (append names
(list (car names
)))
404 (put 'smie-prec2-
>grammar
'pure t
)
405 (defun smie-prec2->grammar
(prec2)
406 "Take a 2D precedence table and turn it into an alist of precedence levels.
407 PREC2 is a table as returned by `smie-precs->prec2' or
409 ;; For each operator, we create two "variables" (corresponding to
410 ;; the left and right precedence level), which are represented by
411 ;; cons cells. Those are the very cons cells that appear in the
412 ;; final `table'. The value of each "variable" is kept in the `car'.
417 ;; From `prec2' we construct a list of constraints between
418 ;; variables (aka "precedence levels"). These can be either
419 ;; equality constraints (in `eqs') or `<' constraints (in `csts').
420 (maphash (lambda (k v
)
422 (if (setq tmp
(assoc (car k
) table
))
424 (setq x
(cons nil nil
))
425 (push (cons (car k
) (cons nil x
)) table
))
426 (if (setq tmp
(assoc (cdr k
) table
))
428 (setq y
(cons nil
(cons nil nil
)))
429 (push (cons (cdr k
) y
) table
))
431 (= (push (cons x y
) eqs
))
432 (< (push (cons x y
) csts
))
433 (> (push (cons y x
) csts
)))))
435 ;; First process the equality constraints.
438 (let ((from (caar eqs
))
443 (dolist (other-eq eqs
)
444 (if (eq from
(cdr other-eq
)) (setcdr other-eq to
))
445 (when (eq from
(car other-eq
))
446 ;; This can happen because of `assoc' settings in precs
447 ;; or because of a rhs like ("op" foo "op").
448 (setcar other-eq to
)))
450 (if (eq from
(cdr cst
)) (setcdr cst to
))
451 (if (eq from
(car cst
)) (setcar cst to
)))))))
452 ;; Then eliminate trivial constraints iteratively.
455 (let ((rhvs (mapcar 'cdr csts
))
458 (unless (memq (car cst
) rhvs
)
460 ;; We could give each var in a given iteration the same value,
461 ;; but we can also give them arbitrarily different values.
462 ;; Basically, these are vars between which there is no
463 ;; constraint (neither equality nor inequality), so
465 ;; We give them arbitrary values, which means that we
466 ;; replace the "no constraint" case with either > or <
467 ;; but not =. The reason we do that is so as to try and
468 ;; distinguish associative operators (which will have
473 (setq csts
(delq cst csts
))))
475 (error "Can't resolve the precedence cycle: %s"
476 (smie-debug--describe-cycle
477 table
(smie-debug--prec2-cycle csts
)))))
479 ;; Propagate equalities back to their source.
480 (dolist (eq (nreverse eqs
))
481 (assert (or (null (caar eq
)) (eq (car eq
) (cdr eq
))))
482 (setcar (car eq
) (cadr eq
)))
483 ;; Finally, fill in the remaining vars (which only appeared on the
484 ;; right side of the < constraints).
485 (let ((classification-table (gethash :smie-open
/close-alist prec2
)))
487 ;; When both sides are nil, it means this operator binds very
488 ;; very tight, but it's still just an operator, so we give it
489 ;; the highest precedence.
490 ;; OTOH if only one side is nil, it usually means it's like an
491 ;; open-paren, which is very important for indentation purposes,
492 ;; so we keep it nil if so, to make it easier to recognize.
493 (unless (or (nth 1 x
)
494 (eq 'opener
(cdr (assoc (car x
) classification-table
))))
496 (incf i
)) ;See other (incf i) above.
497 (unless (or (nth 2 x
)
498 (eq 'closer
(cdr (assoc (car x
) classification-table
))))
500 (incf i
))))) ;See other (incf i) above.
501 (let ((ca (gethash :smie-closer-alist prec2
)))
502 (when ca
(push (cons :smie-closer-alist ca
) table
)))
505 ;;; Parsing using a precedence level table.
507 (defvar smie-grammar
'unset
508 "List of token parsing info.
509 This list is normally built by `smie-prec2->grammar'.
510 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
511 Parsing is done using an operator precedence parser.
512 LEFT-LEVEL and RIGHT-LEVEL can be either numbers or nil, where nil
513 means that this operator does not bind on the corresponding side,
514 i.e. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
515 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
516 like a close-paren.")
518 (defvar smie-forward-token-function
'smie-default-forward-token
519 "Function to scan forward for the next token.
520 Called with no argument should return a token and move to its end.
521 If no token is found, return nil or the empty string.
522 It can return nil when bumping into a parenthesis, which lets SMIE
523 use syntax-tables to handle them in efficient C code.")
525 (defvar smie-backward-token-function
'smie-default-backward-token
526 "Function to scan backward the previous token.
527 Same calling convention as `smie-forward-token-function' except
528 it should move backward to the beginning of the previous token.")
530 (defalias 'smie-op-left
'car
)
531 (defalias 'smie-op-right
'cadr
)
533 (defun smie-default-backward-token ()
534 (forward-comment (- (point)))
535 (buffer-substring-no-properties
537 (progn (if (zerop (skip-syntax-backward "."))
538 (skip-syntax-backward "w_'"))
541 (defun smie-default-forward-token ()
542 (forward-comment (point-max))
543 (buffer-substring-no-properties
545 (progn (if (zerop (skip-syntax-forward "."))
546 (skip-syntax-forward "w_'"))
549 (defun smie--associative-p (toklevels)
550 ;; in "a + b + c" we want to stop at each +, but in
551 ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
552 ;; To distinguish the two cases, we made smie-prec2->grammar choose
553 ;; different levels for each part of "if a then b else c", so that
554 ;; by checking if the left-level is equal to the right level, we can
555 ;; figure out that it's an associative operator.
556 ;; This is not 100% foolproof, tho, since the "elsif" will have to have
557 ;; equal left and right levels (since it's optional), so smie-next-sexp
558 ;; has to be careful to distinguish those different cases.
559 (eq (smie-op-left toklevels
) (smie-op-right toklevels
)))
561 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp
)
563 NEXT-TOKEN is a function of no argument that moves forward by one
564 token (after skipping comments if needed) and returns it.
565 NEXT-SEXP is a lower-level function to skip one sexp.
566 OP-FORW is the accessor to the forward level of the level data.
567 OP-BACK is the accessor to the backward level of the level data.
568 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
569 first token we see is an operator, skip over its left-hand-side argument.
570 Possible return values:
571 (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
572 is too high. FORW-LEVEL is the forw-level of TOKEN,
573 POS is its start position in the buffer.
574 (t POS TOKEN): same thing when we bump on the wrong side of a paren.
575 (nil POS TOKEN): we skipped over a paren-like pair.
576 nil: we skipped over an identifier, matched parentheses, ..."
581 (token (funcall next-token
))
582 (toklevels (cdr (assoc token smie-grammar
))))
585 (when (zerop (length token
))
587 (progn (goto-char pos
) (funcall next-sexp
1) nil
)
588 (scan-error (throw 'return
590 (buffer-substring-no-properties
593 (if (< (point) (caddr err
))
596 ;; We did not move, so let's abort the loop.
597 (throw 'return
(list t
(point))))))
598 ((null (funcall op-back toklevels
))
599 ;; A token like a paren-close.
600 (assert (funcall op-forw toklevels
)) ;Otherwise, why mention it?
601 (push toklevels levels
))
603 (while (and levels
(< (funcall op-back toklevels
)
604 (funcall op-forw
(car levels
))))
605 (setq levels
(cdr levels
)))
608 (if (and halfsexp
(funcall op-forw toklevels
))
609 (push toklevels levels
)
611 (prog1 (list (or (car toklevels
) t
) (point) token
)
614 (let ((lastlevels levels
))
615 (if (and levels
(= (funcall op-back toklevels
)
616 (funcall op-forw
(car levels
))))
617 (setq levels
(cdr levels
)))
618 ;; We may have found a match for the previously pending
619 ;; operator. Is this the end?
621 ;; Keep looking as long as we haven't matched the
624 (if (funcall op-forw toklevels
)
625 (push toklevels levels
)))
626 ;; We matched the topmost operator. If the new operator
627 ;; is the last in the corresponding BNF rule, we're done.
628 ((null (funcall op-forw toklevels
))
629 ;; It is the last element, let's stop here.
630 (throw 'return
(list nil
(point) token
)))
631 ;; If the new operator is not the last in the BNF rule,
632 ;; and is not associative, it's one of the inner operators
633 ;; (like the "in" in "let .. in .. end"), so keep looking.
634 ((not (smie--associative-p toklevels
))
635 (push toklevels levels
))
636 ;; The new operator is associative. Two cases:
637 ;; - it's really just an associative operator (like + or ;)
638 ;; in which case we should have stopped right before.
640 (smie--associative-p (car lastlevels
)))
642 (prog1 (list (or (car toklevels
) t
) (point) token
)
644 ;; - it's an associative operator within a larger construct
645 ;; (e.g. an "elsif"), so we should just ignore it and keep
646 ;; looking for the closing element.
647 (t (setq levels lastlevels
))))))))
649 (setq halfsexp nil
)))))
651 (defun smie-backward-sexp (&optional halfsexp
)
653 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
654 first token we see is an operator, skip over its left-hand-side argument.
655 Possible return values:
656 (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
657 is too high. LEFT-LEVEL is the left-level of TOKEN,
658 POS is its start position in the buffer.
659 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
660 (nil POS TOKEN): we skipped over a paren-like pair.
661 nil: we skipped over an identifier, matched parentheses, ..."
663 (indirect-function smie-backward-token-function
)
664 (indirect-function 'backward-sexp
)
665 (indirect-function 'smie-op-left
)
666 (indirect-function 'smie-op-right
)
669 (defun smie-forward-sexp (&optional halfsexp
)
671 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
672 first token we see is an operator, skip over its left-hand-side argument.
673 Possible return values:
674 (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
675 is too high. RIGHT-LEVEL is the right-level of TOKEN,
676 POS is its end position in the buffer.
677 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
678 (nil POS TOKEN): we skipped over a paren-like pair.
679 nil: we skipped over an identifier, matched parentheses, ..."
681 (indirect-function smie-forward-token-function
)
682 (indirect-function 'forward-sexp
)
683 (indirect-function 'smie-op-right
)
684 (indirect-function 'smie-op-left
)
687 ;;; Miscellanous commands using the precedence parser.
689 (defun smie-backward-sexp-command (&optional n
)
690 "Move backward through N logical elements."
692 (smie-forward-sexp-command (- n
)))
694 (defun smie-forward-sexp-command (&optional n
)
695 "Move forward through N logical elements."
698 (forward-sexp-function nil
))
700 (setq n
(- n
(if forw
1 -
1)))
703 (smie-forward-sexp 'halfsexp
)
704 (smie-backward-sexp 'halfsexp
))))
705 (if (and (car res
) (= pos
(point)) (not (if forw
(eobp) (bobp))))
707 (list "Containing expression ends prematurely"
708 (cadr res
) (cadr res
)))
711 (defvar smie-closer-alist nil
712 "Alist giving the closer corresponding to an opener.")
714 (defun smie-close-block ()
715 "Close the closest surrounding block."
720 (if (looking-at "\\s(")
721 (string (cdr (syntax-after (point))))
722 (let* ((open (funcall smie-forward-token-function
))
723 (closer (cdr (assoc open smie-closer-alist
)))
724 (levels (list (assoc open smie-grammar
)))
728 ;; Even if we improve the auto-computation of closers,
729 ;; there are still cases where we need manual
730 ;; intervention, e.g. for Octave's use of `until'
731 ;; as a pseudo-closer of `do'.
733 ((or (equal levels
'(nil)) (nth 1 (car levels
)))
734 (error "Doesn't look like a block"))
736 ;; Now that smie-setup automatically sets smie-closer-alist
737 ;; from the BNF, this is not really needed any more.
739 (let ((level (pop levels
)))
740 (dolist (other smie-grammar
)
741 (when (and (eq (nth 2 level
) (nth 1 other
))
742 (not (memq other seen
)))
746 (push (car other
) found
))))))
748 ((null found
) (error "No known closer for opener %s" open
))
749 ;; FIXME: what should we do if there are various closers?
750 (t (car found
))))))))))
751 (unless (save-excursion (skip-chars-backward " \t") (bolp))
754 (if (save-excursion (skip-chars-forward " \t") (eolp))
755 (indent-according-to-mode)
756 (reindent-then-newline-and-indent))))
758 (defun smie-down-list (&optional arg
)
759 "Move forward down one level paren-like blocks. Like `down-list'.
760 With argument ARG, do this that many times.
761 A negative argument means move backward but still go down a level.
762 This command assumes point is not in a string or comment."
764 (let ((start (point))
765 (inc (if (< arg
0) -
1 1))
766 (offset (if (< arg
0) 1 0))
767 (next-token (if (< arg
0)
768 smie-backward-token-function
769 smie-forward-token-function
)))
771 (setq arg
(- arg inc
))
774 (token (funcall next-token
))
775 (levels (assoc token smie-grammar
)))
777 ((zerop (length token
))
778 (if (if (< inc
0) (looking-back "\\s(\\|\\s)" (1- (point)))
779 (looking-at "\\s(\\|\\s)"))
780 ;; Go back to `start' in case of an error. This presumes
781 ;; none of the token we've found until now include a ( or ).
782 (progn (goto-char start
) (down-list inc
) nil
)
785 ((and levels
(null (nth (+ 1 offset
) levels
))) nil
)
786 ((and levels
(null (nth (- 2 offset
) levels
)))
790 (list "Containing expression ends prematurely"
794 (defvar smie-blink-matching-triggers
'(?\s ?
\n)
795 "Chars which might trigger `blink-matching-open'.
796 These can include the final chars of end-tokens, or chars that are
797 typically inserted right after an end token.
798 I.e. a good choice can be:
800 (mapcar (lambda (kw) (aref (cdr kw) (1- (length (cdr kw)))))
801 smie-closer-alist))")
803 (defcustom smie-blink-matching-inners t
804 "Whether SMIE should blink to matching opener for inner keywords.
805 If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
809 (defun smie-blink-matching-check (start end
)
812 (let ((ender (funcall smie-backward-token-function
)))
814 ((not (and ender
(rassoc ender smie-closer-alist
)))
815 ;; This not is one of the begin..end we know how to check.
816 (blink-matching-check-mismatch start end
))
818 ((eq t
(car (rassoc ender smie-closer-alist
))) nil
)
821 (let ((starter (funcall smie-forward-token-function
)))
822 (not (member (cons starter ender
) smie-closer-alist
))))))))
824 (defun smie-blink-matching-open ()
825 "Blink the matching opener when applicable.
826 This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
827 (let ((pos (point)) ;Position after the close token.
829 (when (and blink-matching-paren
830 smie-closer-alist
; Optimization.
831 (or (eq (char-before) last-command-event
) ;; Sanity check.
833 (or (progn (skip-chars-backward " \t")
835 (eq (char-before) last-command-event
))
836 (progn (skip-chars-backward " \n\t")
838 (eq (char-before) last-command-event
)))))
839 (memq last-command-event smie-blink-matching-triggers
)
840 (not (nth 8 (syntax-ppss))))
842 (setq token
(funcall smie-backward-token-function
))
843 (when (and (eq (point) (1- pos
))
845 (not (rassoc token smie-closer-alist
)))
846 ;; The trigger char is itself a token but is not one of the
847 ;; closers (e.g. ?\; in Octave mode), so go back to the
850 (setq token
(funcall smie-backward-token-function
)))
851 (when (rassoc token smie-closer-alist
)
852 ;; We're after a close token. Let's still make sure we
853 ;; didn't skip a comment to find that token.
854 (funcall smie-forward-token-function
)
855 (when (and (save-excursion
856 ;; Skip the trigger char, if applicable.
857 (if (eq (char-after) last-command-event
)
859 (if (eq ?
\n last-command-event
)
860 ;; Skip any auto-indentation, if applicable.
861 (skip-chars-forward " \t"))
863 ;; If token ends with a trigger char, don't blink for
864 ;; anything else than this trigger char, lest we'd blink
865 ;; both when inserting the trigger char and when
866 ;; inserting a subsequent trigger char like SPC.
868 (not (memq (char-before)
869 smie-blink-matching-triggers
)))
870 (or smie-blink-matching-inners
871 (null (nth 2 (assoc token smie-grammar
)))))
872 ;; The major mode might set blink-matching-check-function
873 ;; buffer-locally so that interactive calls to
874 ;; blink-matching-open work right, but let's not presume
876 (let ((blink-matching-check-function #'smie-blink-matching-check
))
877 (blink-matching-open))))))))
879 ;;; The indentation engine.
881 (defcustom smie-indent-basic
4
882 "Basic amount of indentation."
886 (defvar smie-rules-function
'ignore
887 "Function providing the indentation rules.
888 It takes two arguments METHOD and ARG where the meaning of ARG
889 and the expected return value depends on METHOD.
891 - :after, in which case ARG is a token and the function should return the
892 OFFSET to use for indentation after ARG.
893 - :before, in which case ARG is a token and the function should return the
894 OFFSET to use to indent ARG itself.
895 - :elem, in which case the function should return either:
896 - the offset to use to indent function arguments (ARG = `arg')
897 - the basic indentation step (ARG = `basic').
898 - :list-intro, in which case ARG is a token and the function should return
899 non-nil if TOKEN is followed by a list of expressions (not separated by any
900 token) rather than an expression.
902 When ARG is a token, the function is called with point just before that token.
903 A return value of nil always means to fallback on the default behavior, so the
904 function should return nil for arguments it does not expect.
907 nil use the default indentation rule.
908 `(column . COLUMN) indent to column COLUMN.
909 NUMBER offset by NUMBER, relative to a base token
910 which is the current token for :after and
911 its parent for :before.
913 The functions whose name starts with \"smie-rule-\" are helper functions
914 designed specifically for use in this function.")
916 (defalias 'smie-rule-hanging-p
'smie-indent--hanging-p
)
917 (defun smie-indent--hanging-p ()
918 "Return non-nil if the current token is \"hanging\".
919 A hanging keyword is one that's at the end of a line except it's not at
920 the beginning of a line."
921 (and (not (smie-indent--bolp))
923 (<= (line-end-position)
925 (when (zerop (length (funcall smie-forward-token-function
)))
926 ;; Could be an open-paren.
928 (skip-chars-forward " \t")
930 (and (looking-at comment-start-skip
)
931 (forward-comment (point-max))))
934 (defalias 'smie-rule-bolp
'smie-indent--bolp
)
935 (defun smie-indent--bolp ()
936 "Return non-nil if the current token is the first on the line."
937 (save-excursion (skip-chars-backward " \t") (bolp)))
939 ;; Dynamically scoped.
940 (defvar smie--parent
) (defvar smie--after
) (defvar smie--token
)
942 (defun smie-indent--parent ()
946 (tok (funcall smie-forward-token-function
)))
947 (unless (cadr (assoc tok smie-grammar
))
950 (smie-backward-sexp 'halfsexp
))))))
952 (defun smie-rule-parent-p (&rest parents
)
953 "Return non-nil if the current token's parent is among PARENTS.
954 Only meaningful when called from within `smie-rules-function'."
955 (member (nth 2 (smie-indent--parent)) parents
))
957 (defun smie-rule-next-p (&rest tokens
)
958 "Return non-nil if the next token is among TOKENS.
959 Only meaningful when called from within `smie-rules-function'."
963 (smie-indent-forward-token) (setq smie--after
(point)))
964 (goto-char smie--after
)
965 (smie-indent-forward-token))))
966 (member (car next
) tokens
)))
968 (defun smie-rule-prev-p (&rest tokens
)
969 "Return non-nil if the previous token is among TOKENS."
970 (let ((prev (save-excursion
971 (smie-indent-backward-token))))
972 (member (car prev
) tokens
)))
974 (defun smie-rule-sibling-p ()
975 "Return non-nil if the parent is actually a sibling.
976 Only meaningful when called from within `smie-rules-function'."
977 (eq (car (smie-indent--parent))
978 (cadr (assoc smie--token smie-grammar
))))
980 (defun smie-rule-parent (&optional offset
)
982 If non-nil, OFFSET should be an integer giving an additional offset to apply.
983 Only meaningful when called from within `smie-rules-function'."
985 (goto-char (cadr (smie-indent--parent)))
988 ;; Use smie-indent-virtual when indenting relative to an opener:
989 ;; this will also by default use current-column unless
990 ;; that opener is hanging, but will additionally consult
991 ;; rules-function, so it gives it a chance to tweak
992 ;; indentation (e.g. by forcing indentation relative to
993 ;; its own parent, as in fn a => fn b => fn c =>).
994 (if (or (null (car smie--parent
)) (smie-indent--hanging-p))
995 (smie-indent-virtual) (current-column))))))
997 (defvar smie-rule-separator-outdent
2)
999 (defun smie-indent--separator-outdent ()
1000 ;; FIXME: Here we actually have several reasonable behaviors.
1001 ;; E.g. for a parent token of "FOO" and a separator ";" we may want to:
1002 ;; 1- left-align ; with FOO.
1003 ;; 2- right-align ; with FOO.
1004 ;; 3- align content after ; with content after FOO.
1005 ;; 4- align content plus add/remove spaces so as to align ; with FOO.
1006 ;; Currently, we try to align the contents (option 3) which actually behaves
1007 ;; just like option 2 (if the number of spaces after FOO and ; is equal).
1008 (let ((afterpos (save-excursion
1009 (let ((tok (funcall smie-forward-token-function
)))
1011 (with-demoted-errors
1012 (error "smie-rule-separator: can't skip token %s"
1014 (skip-chars-forward " ")
1015 (unless (eolp) (point)))))
1017 ;; This should always be true, unless
1018 ;; smie-forward-token-function skipped a \n.
1019 (< afterpos
(line-end-position))
1020 (- afterpos
(point)))
1021 smie-rule-separator-outdent
)))
1023 (defun smie-rule-separator (method)
1024 "Indent current token as a \"separator\".
1025 By \"separator\", we mean here a token whose sole purpose is to separate
1026 various elements within some enclosing syntactic construct, and which does
1027 not have any semantic significance in itself (i.e. it would typically no exist
1028 as a node in an abstract syntax tree).
1029 Such a token is expected to have an associative syntax and be closely tied
1030 to its syntactic parent. Typical examples are \",\" in lists of arguments
1031 \(enclosed inside parentheses), or \";\" in sequences of instructions (enclosed
1032 in a {..} or begin..end block).
1033 METHOD should be the method name that was passed to `smie-rules-function'.
1034 Only meaningful when called from within `smie-rules-function'."
1035 ;; FIXME: The code below works OK for cases where the separators
1036 ;; are placed consistently always at beginning or always at the end,
1037 ;; but not if some are at the beginning and others are at the end.
1038 ;; I.e. it gets confused in cases such as:
1046 ;; Assuming token is associative, the default rule for associative
1047 ;; tokens (which assumes an infix operator) works fine for many cases.
1048 ;; We mostly need to take care of the case where token is at beginning of
1049 ;; line, in which case we want to align it with its enclosing parent.
1051 ((and (eq method
:before
) (smie-rule-bolp) (not (smie-rule-sibling-p)))
1052 ;; FIXME: Rather than consult the number of spaces, we could *set* the
1053 ;; number of spaces so as to align the separator with the close-paren
1054 ;; while aligning the content with the rest.
1055 (let ((parent-col (cdr (smie-rule-parent)))
1056 (parent-pos-col ;FIXME: we knew this when computing smie--parent.
1058 (goto-char (cadr smie--parent
))
1059 (smie-indent-forward-token)
1060 (forward-comment (point-max))
1065 (- parent-pos-col
(smie-indent--separator-outdent)))))))
1066 ((and (eq method
:after
) (smie-indent--bolp))
1067 (smie-indent--separator-outdent))))
1069 (defun smie-indent--offset (elem)
1070 (or (funcall smie-rules-function
:elem elem
)
1071 (if (not (eq elem
'basic
))
1072 (funcall smie-rules-function
:elem
'basic
))
1075 (defun smie-indent--rule (method token
1076 ;; FIXME: Too many parameters.
1077 &optional after parent base-pos
)
1078 "Compute indentation column according to `indent-rule-functions'.
1079 METHOD and TOKEN are passed to `indent-rule-functions'.
1080 AFTER is the position after TOKEN, if known.
1081 PARENT is the parent info returned by `smie-backward-sexp', if known.
1082 BASE-POS is the position relative to which offsets should be applied."
1083 ;; This is currently called in 3 cases:
1084 ;; - :before opener, where rest=nil but base-pos could as well be parent.
1085 ;; - :before other, where
1088 ;; ; base-pos=parent
1089 ;; - :after tok, where
1090 ;; ; after is set; parent=nil; base-pos=point;
1093 (let ((smie--parent parent
)
1095 (smie--after after
))
1096 (funcall smie-rules-function method token
))))
1099 ((eq (car-safe offset
) 'column
) (cdr offset
))
1102 (if (null base-pos
) 0
1103 (goto-char base-pos
)
1104 ;; Use smie-indent-virtual when indenting relative to an opener:
1105 ;; this will also by default use current-column unless
1106 ;; that opener is hanging, but will additionally consult
1107 ;; rules-function, so it gives it a chance to tweak indentation
1108 ;; (e.g. by forcing indentation relative to its own parent, as in
1109 ;; fn a => fn b => fn c =>).
1110 ;; When parent==nil it doesn't matter because the only case
1111 ;; where it's really used is when the base-pos is hanging anyway.
1112 (if (or (and parent
(null (car parent
)))
1113 (smie-indent--hanging-p))
1114 (smie-indent-virtual) (current-column)))))
1115 (t (error "Unknown indentation offset %s" offset
))))))
1117 (defun smie-indent-forward-token ()
1118 "Skip token forward and return it, along with its levels."
1119 (let ((tok (funcall smie-forward-token-function
)))
1121 ((< 0 (length tok
)) (assoc tok smie-grammar
))
1122 ((looking-at "\\s(\\|\\s)\\(\\)")
1124 (cons (buffer-substring (1- (point)) (point))
1125 (if (match-end 1) '(0 nil
) '(nil 0)))))))
1127 (defun smie-indent-backward-token ()
1128 "Skip token backward and return it, along with its levels."
1129 (let ((tok (funcall smie-backward-token-function
))
1132 ((< 0 (length tok
)) (assoc tok smie-grammar
))
1133 ;; 4 == open paren syntax, 5 == close.
1134 ((memq (setq class
(syntax-class (syntax-after (1- (point))))) '(4 5))
1136 (cons (buffer-substring (point) (1+ (point)))
1137 (if (eq class
4) '(nil 0) '(0 nil
)))))))
1139 (defun smie-indent-virtual ()
1140 ;; We used to take an optional arg (with value :not-hanging) to specify that
1141 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
1142 ;; keyword. This was a bad idea, because the virtual indent of a position
1143 ;; should not depend on the caller, since it leads to situations where two
1144 ;; dependent indentations get indented differently.
1145 "Compute the virtual indentation to use for point.
1146 This is used when we're not trying to indent point but just
1147 need to compute the column at which point should be indented
1148 in order to figure out the indentation of some other (further down) point."
1149 ;; Trust pre-existing indentation on other lines.
1150 (if (smie-indent--bolp) (current-column) (smie-indent-calculate)))
1152 (defun smie-indent-fixindent ()
1153 ;; Obey the `fixindent' special comment.
1154 (and (smie-indent--bolp)
1156 (comment-normalize-vars)
1157 (re-search-forward (concat comment-start-skip
1160 ;; 1+ to account for the \n comment termination.
1161 (1+ (line-end-position)) t
))
1164 (defun smie-indent-bob ()
1165 ;; Start the file at column 0.
1167 (forward-comment (- (point)))
1170 (defun smie-indent-close ()
1171 ;; Align close paren with opening paren.
1173 ;; (forward-comment (point-max))
1174 (when (looking-at "\\s)")
1175 (while (not (zerop (skip-syntax-forward ")")))
1176 (skip-chars-forward " \t"))
1180 (smie-indent-virtual)) ;:not-hanging
1181 (scan-error nil
)))))
1183 (defun smie-indent-keyword ()
1184 ;; Align closing token with the corresponding opening one.
1185 ;; (e.g. "of" with "case", or "in" with "let").
1187 (let* ((pos (point))
1188 (toklevels (smie-indent-forward-token))
1189 (token (pop toklevels
)))
1190 (if (null (car toklevels
))
1194 ;; - smie-indent--bolp: "indent according to others".
1195 ;; - common hanging: "indent according to others".
1196 ;; - SML-let hanging: "indent like parent".
1197 ;; - if-after-else: "indent-like parent".
1198 ;; - middle-of-line: "trust current position".
1200 ((null (cdr toklevels
)) nil
) ;Not a keyword.
1201 ((smie-indent--rule :before token
))
1202 ((smie-indent--bolp) ;I.e. non-virtual indent.
1203 ;; For an open-paren-like thingy at BOL, always indent only
1204 ;; based on other rules (typically smie-indent-after-keyword).
1207 ;; By default use point unless we're hanging.
1208 (unless (smie-indent--hanging-p) (current-column)))))
1210 ;; FIXME: This still looks too much like black magic!!
1211 (let* ((parent (smie-backward-sexp 'halfsexp
)))
1212 ;; Different behaviors:
1213 ;; - align with parent.
1214 ;; - parent + offset.
1215 ;; - after parent's column + offset (actually, after or before
1216 ;; depending on where backward-sexp stopped).
1217 ;; ? let it drop to some other indentation function (almost never).
1218 ;; ? parent + offset + parent's own offset.
1220 ;; - bump into a same-level operator.
1221 ;; - bump into a specific known parent.
1222 ;; - find a matching open-paren thingy.
1223 ;; - bump into some random parent.
1224 ;; ? borderline case (almost never).
1225 ;; ? bump immediately into a parent.
1227 ((not (or (< (point) pos
)
1228 (and (cadr parent
) (< (cadr parent
) pos
))))
1229 ;; If we didn't move at all, that means we didn't really skip
1230 ;; what we wanted. Should almost never happen, other than
1231 ;; maybe when an infix or close-paren is at the beginning
1236 (smie-indent--rule :before token nil parent
(cadr parent
))))
1237 ((eq (car parent
) (car toklevels
))
1238 ;; We bumped into a same-level operator; align with it.
1239 (if (and (smie-indent--bolp) (/= (point) pos
)
1241 (goto-char (goto-char (cadr parent
)))
1242 (not (smie-indent--bolp))))
1243 ;; If the parent is at EOL and its children are indented like
1244 ;; itself, then we can just obey the indentation chosen for the
1246 ;; This is important for operators like ";" which
1247 ;; are usually at EOL (and have an offset of 0): otherwise we'd
1248 ;; always go back over all the statements, which is
1249 ;; a performance problem and would also mean that fixindents
1250 ;; in the middle of such a sequence would be ignored.
1252 ;; This is a delicate point!
1253 ;; Even if the offset is not 0, we could follow the same logic
1254 ;; and subtract the offset from the child's indentation.
1255 ;; But that would more often be a bad idea: OT1H we generally
1256 ;; want to reuse the closest similar indentation point, so that
1257 ;; the user's choice (or the fixindents) are obeyed. But OTOH
1258 ;; we don't want this to affect "unrelated" parts of the code.
1259 ;; E.g. a fixindent in the body of a "begin..end" should not
1260 ;; affect the indentation of the "end".
1262 (goto-char (cadr parent
))
1263 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
1264 ;; want to jump back over a sequence of same-level ops such as
1267 ;; So as to align with the earliest appropriate place.
1268 (smie-indent-virtual)))
1270 (if (and (= (point) pos
) (smie-indent--bolp))
1271 ;; Since we started at BOL, we're not computing a virtual
1272 ;; indentation, and we're still at the starting point, so
1273 ;; we can't use `current-column' which would cause
1274 ;; indentation to depend on itself and we can't use
1275 ;; smie-indent-virtual since that would be an inf-loop.
1277 ;; In indent-keyword, if we're indenting `then' wrt `if', we
1278 ;; want to use indent-virtual rather than use just
1279 ;; current-column, so that we can apply the (:before . "if")
1280 ;; rule which does the "else if" dance in SML. But in other
1281 ;; cases, we do not want to use indent-virtual (e.g. indentation
1282 ;; of "*" w.r.t "+", or ";" wrt "("). We could just always use
1283 ;; indent-virtual and then have indent-rules say explicitly to
1284 ;; use `point' after things like "(" or "+" when they're not at
1285 ;; EOL, but you'd end up with lots of those rules.
1286 ;; So we use a heuristic here, which is that we only use virtual
1287 ;; if the parent is tightly linked to the child token (they're
1288 ;; part of the same BNF rule).
1289 (if (car parent
) (current-column) (smie-indent-virtual))))))))))
1291 (defun smie-indent-comment ()
1292 "Compute indentation of a comment."
1293 ;; Don't do it for virtual indentations. We should normally never be "in
1294 ;; front of a comment" when doing virtual-indentation anyway. And if we are
1295 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
1296 (and (smie-indent--bolp)
1297 (let ((pos (point)))
1300 (and (re-search-forward comment-start-skip
(line-end-position) t
)
1301 (eq pos
(or (match-end 1) (match-beginning 0))))))
1303 (forward-comment (point-max))
1304 (skip-chars-forward " \t\r\n")
1305 (smie-indent-calculate))))
1307 (defun smie-indent-comment-continue ()
1308 ;; indentation of comment-continue lines.
1309 (let ((continue (and comment-continue
1310 (comment-string-strip comment-continue t t
))))
1311 (and (< 0 (length continue
))
1312 (looking-at (regexp-quote continue
)) (nth 4 (syntax-ppss))
1313 (let ((ppss (syntax-ppss)))
1316 (if (<= (point) (nth 8 ppss
))
1317 (progn (goto-char (1+ (nth 8 ppss
))) (current-column))
1318 (skip-chars-forward " \t")
1319 (if (looking-at (regexp-quote continue
))
1320 (current-column))))))))
1322 (defun smie-indent-comment-close ()
1323 (and (boundp 'comment-end-skip
)
1325 (not (looking-at " \t*$")) ;Not just a \n comment-closer.
1326 (looking-at comment-end-skip
)
1327 (let ((end (match-string 0)))
1328 (and (nth 4 (syntax-ppss))
1330 (goto-char (nth 8 (syntax-ppss)))
1331 (and (looking-at comment-start-skip
)
1332 (let ((start (match-string 0)))
1333 ;; Align the common substring between starter
1334 ;; and ender, if possible.
1335 (if (string-match "\\(.+\\).*\n\\(.*?\\)\\1"
1336 (concat start
"\n" end
))
1337 (+ (current-column) (match-beginning 0)
1338 (- (match-beginning 2) (match-end 2)))
1339 (current-column)))))))))
1341 (defun smie-indent-comment-inside ()
1342 (and (nth 4 (syntax-ppss))
1345 (defun smie-indent-after-keyword ()
1346 ;; Indentation right after a special keyword.
1348 (let* ((pos (point))
1349 (toklevel (smie-indent-backward-token))
1350 (tok (car toklevel
)))
1352 ((null toklevel
) nil
)
1353 ((smie-indent--rule :after tok pos nil
(point)))
1354 ;; The default indentation after a keyword/operator is
1355 ;; 0 for infix, t for prefix, and use another rule
1357 ((null (nth 2 toklevel
)) nil
) ;A closer.
1358 ((or (null (nth 1 toklevel
)) ;An opener.
1359 (rassoc tok smie-closer-alist
)) ;An inner.
1360 (+ (smie-indent-virtual) (smie-indent--offset 'basic
))) ;
1361 (t (smie-indent-virtual)))))) ;An infix.
1363 (defun smie-indent-exps ()
1364 ;; Indentation of sequences of simple expressions without
1365 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
1366 ;; Can be a list of expressions or a function call.
1367 ;; If it's a function call, the first element is special (it's the
1368 ;; function). We distinguish function calls from mere lists of
1369 ;; expressions based on whether the preceding token is listed in
1370 ;; the `list-intro' entry of smie-indent-rules.
1372 ;; TODO: to indent Lisp code, we should add a way to specify
1373 ;; particular indentation for particular args depending on the
1374 ;; function (which would require always skipping back until the
1376 ;; TODO: to indent C code, such as "if (...) {...}" we might need
1377 ;; to add similar indentation hooks for particular positions, but
1378 ;; based on the preceding token rather than based on the first exp.
1380 (let ((positions nil
)
1382 (while (and (null (car (smie-backward-sexp)))
1383 (push (point) positions
)
1384 (not (smie-indent--bolp))))
1386 ;; Figure out if the atom we just skipped is an argument rather
1389 (or (null (car (smie-backward-sexp)))
1390 (funcall smie-rules-function
:list-intro
1391 (funcall smie-backward-token-function
)))))
1394 ;; We're the first expression of the list. In that case, the
1395 ;; indentation should be (have been) determined by its context.
1398 ;; There's a previous element, and it's not special (it's not
1399 ;; the function), so let's just align with that one.
1400 (goto-char (car positions
))
1403 ;; We skipped some args plus the function and bumped into something.
1404 ;; Align with the first arg.
1405 (goto-char (cadr positions
))
1408 ;; We're the first arg.
1409 (goto-char (car positions
))
1410 (+ (smie-indent--offset 'args
)
1411 ;; We used to use (smie-indent-virtual), but that
1412 ;; doesn't seem right since it might then indent args less than
1413 ;; the function itself.
1414 (current-column)))))))
1416 (defvar smie-indent-functions
1417 '(smie-indent-fixindent smie-indent-bob smie-indent-close
1418 smie-indent-comment smie-indent-comment-continue smie-indent-comment-close
1419 smie-indent-comment-inside smie-indent-keyword smie-indent-after-keyword
1421 "Functions to compute the indentation.
1422 Each function is called with no argument, shouldn't move point, and should
1423 return either nil if it has no opinion, or an integer representing the column
1424 to which that point should be aligned, if we were to reindent it.")
1426 (defun smie-indent-calculate ()
1427 "Compute the indentation to use for point."
1428 (run-hook-with-args-until-success 'smie-indent-functions
))
1430 (defun smie-indent-line ()
1431 "Indent current line using the SMIE indentation engine."
1433 (let* ((savep (point))
1434 (indent (or (with-demoted-errors
1437 (skip-chars-forward " \t")
1438 (if (>= (point) savep
) (setq savep nil
))
1439 (or (smie-indent-calculate) 0)))
1441 (if (not (numberp indent
))
1442 ;; If something funny is used (e.g. `noindent'), return it.
1444 (if (< indent
0) (setq indent
0)) ;Just in case.
1446 (save-excursion (indent-line-to indent
))
1447 (indent-line-to indent
)))))
1449 (defun smie-setup (grammar rules-function
&rest keywords
)
1450 "Setup SMIE navigation and indentation.
1451 GRAMMAR is a grammar table generated by `smie-prec2->grammar'.
1452 RULES-FUNCTION is a set of indentation rules for use on `smie-rules-function'.
1453 KEYWORDS are additional arguments, which can use the following keywords:
1454 - :forward-token FUN
1455 - :backward-token FUN"
1456 (set (make-local-variable 'smie-rules-function
) rules-function
)
1457 (set (make-local-variable 'smie-grammar
) grammar
)
1458 (set (make-local-variable 'indent-line-function
) 'smie-indent-line
)
1459 (set (make-local-variable 'forward-sexp-function
)
1460 'smie-forward-sexp-command
)
1462 (let ((k (pop keywords
))
1466 (set (make-local-variable 'smie-forward-token-function
) v
))
1468 (set (make-local-variable 'smie-backward-token-function
) v
))
1469 (t (message "smie-setup: ignoring unknown keyword %s" k
)))))
1470 (let ((ca (cdr (assq :smie-closer-alist grammar
))))
1472 (set (make-local-variable 'smie-closer-alist
) ca
)
1473 ;; Only needed for interactive calls to blink-matching-open.
1474 (set (make-local-variable 'blink-matching-check-function
)
1475 #'smie-blink-matching-check
)
1476 (add-hook 'post-self-insert-hook
1477 #'smie-blink-matching-open
'append
'local
)
1478 (set (make-local-variable 'smie-blink-matching-triggers
)
1479 (append smie-blink-matching-triggers
1480 ;; Rather than wait for SPC to blink, try to blink as
1481 ;; soon as we type the last char of a block ender.
1482 (let ((closers (sort (mapcar #'cdr smie-closer-alist
)
1486 (while (setq closer
(pop closers
))
1487 (unless (and closers
1488 ;; FIXME: this eliminates prefixes of other
1489 ;; closers, but we should probably elimnate
1490 ;; prefixes of other keywords as well.
1491 (string-prefix-p closer
(car closers
)))
1492 (push (aref closer
(1- (length closer
))) triggers
)))
1493 (delete-dups triggers
)))))))
1497 ;;; smie.el ends here