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 (defun smie-set-prec2tab (table x y val &optional override)
80 (let* ((key (cons x y))
81 (old (gethash key table)))
82 (if (and old (not (eq old val)))
83 (if (and override (gethash key override))
84 ;; FIXME: The override is meant to resolve ambiguities,
85 ;; but it also hides real conflicts. It would be great to
86 ;; be able to distinguish the two cases so that overrides
87 ;; don't hide real conflicts.
88 (puthash key (gethash key override) table)
89 (display-warning 'smie (format "Conflict: %s %s/%s %s" x old val y)))
90 (puthash key val table))))
92 (defun smie-precs-precedence-table (precs)
93 "Compute a 2D precedence table from a list of precedences.
94 PRECS should be a list, sorted by precedence (e.g. \"+\" will
95 come before \"*\"), of elements of the form \(left OP ...)
96 or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
97 one of those elements share the same precedence level and associativity."
98 (let ((prec2-table (make-hash-table :test 'equal)))
100 (dolist (op (cdr prec))
101 (let ((selfrule (cdr (assq (car prec)
102 '((left . >) (right . <) (assoc . =))))))
104 (dolist (other-op (cdr prec))
105 (smie-set-prec2tab prec2-table op other-op selfrule))))
106 (let ((op1 '<) (op2 '>))
107 (dolist (other-prec precs)
108 (if (eq prec other-prec)
110 (dolist (other-op (cdr other-prec))
111 (smie-set-prec2tab prec2-table op other-op op2)
112 (smie-set-prec2tab prec2-table other-op op op1)))))))
115 (defun smie-merge-prec2s (&rest tables)
116 (if (null (cdr tables))
118 (let ((prec2 (make-hash-table :test 'equal)))
119 (dolist (table tables)
120 (maphash (lambda (k v)
121 (smie-set-prec2tab prec2 (car k) (cdr k) v))
125 (defun smie-bnf-precedence-table (bnf &rest precs)
126 (let ((nts (mapcar 'car bnf)) ;Non-terminals
131 (prec2 (make-hash-table :test 'equal))
132 (override (apply 'smie-merge-prec2s
133 (mapcar 'smie-precs-precedence-table precs)))
136 (let ((nt (car rules))
141 (dolist (rhs (cdr rules))
143 (if (not (member (car rhs) nts))
144 (pushnew (car rhs) first-ops)
145 (pushnew (car rhs) first-nts)
146 (when (consp (cdr rhs))
147 ;; If the first is not an OP we add the second (which
148 ;; should be an OP if BNF is an "operator grammar").
149 ;; Strictly speaking, this should only be done if the
150 ;; first is a non-terminal which can expand to a phrase
151 ;; without any OP in it, but checking doesn't seem worth
152 ;; the trouble, and it lets the writer of the BNF
153 ;; be a bit more sloppy by skipping uninteresting base
154 ;; cases which are terminals but not OPs.
155 (assert (not (member (cadr rhs) nts)))
156 (pushnew (cadr rhs) first-ops)))
157 (let ((shr (reverse rhs)))
158 (if (not (member (car shr) nts))
159 (pushnew (car shr) last-ops)
160 (pushnew (car shr) last-nts)
161 (when (consp (cdr shr))
162 (assert (not (member (cadr shr) nts)))
163 (pushnew (cadr shr) last-ops)))))
164 (push (cons nt first-ops) first-ops-table)
165 (push (cons nt last-ops) last-ops-table)
166 (push (cons nt first-nts) first-nts-table)
167 (push (cons nt last-nts) last-nts-table)))
168 ;; Compute all first-ops by propagating the initial ones we have
169 ;; now, according to first-nts.
171 (while (prog1 again (setq again nil))
172 (dolist (first-nts first-nts-table)
173 (let* ((nt (pop first-nts))
174 (first-ops (assoc nt first-ops-table)))
175 (dolist (first-nt first-nts)
176 (dolist (op (cdr (assoc first-nt first-ops-table)))
177 (unless (member op first-ops)
179 (push op (cdr first-ops))))))))
180 ;; Same thing for last-ops.
182 (while (prog1 again (setq again nil))
183 (dolist (last-nts last-nts-table)
184 (let* ((nt (pop last-nts))
185 (last-ops (assoc nt last-ops-table)))
186 (dolist (last-nt last-nts)
187 (dolist (op (cdr (assoc last-nt last-ops-table)))
188 (unless (member op last-ops)
190 (push op (cdr last-ops))))))))
191 ;; Now generate the 2D precedence table.
193 (dolist (rhs (cdr rules))
196 ((member (car rhs) nts)
197 (dolist (last (cdr (assoc (car rhs) last-ops-table)))
198 (smie-set-prec2tab prec2 last (cadr rhs) '> override)))
199 ((member (cadr rhs) nts)
200 (dolist (first (cdr (assoc (cadr rhs) first-ops-table)))
201 (smie-set-prec2tab prec2 (car rhs) first '< override))
202 (if (and (cddr rhs) (not (member (car (cddr rhs)) nts)))
203 (smie-set-prec2tab prec2 (car rhs) (car (cddr rhs))
205 (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
206 (setq rhs (cdr rhs)))))
209 (defun smie-prec2-levels (prec2)
210 ;; FIXME: Rather than only return an alist of precedence levels, we should
211 ;; also extract other useful data from it:
212 ;; - matching sets of block openers&closers (which can otherwise become
213 ;; collapsed into a single equivalence class in smie-op-levels) for
214 ;; smie-close-block as well as to detect mismatches in smie-next-sexp
215 ;; or in blink-paren (as well as to do the blink-paren for inner
216 ;; keywords like the "in" of "let..in..end").
217 ;; - better default indentation rules (i.e. non-zero indentation after inner
218 ;; keywords like the "in" of "let..in..end") for smie-indent-after-keyword.
219 ;; Of course, maybe those things would be even better handled in the
220 ;; bnf->prec function.
221 "Take a 2D precedence table and turn it into an alist of precedence levels.
222 PREC2 is a table as returned by `smie-precs-precedence-table' or
223 `smie-bnf-precedence-table'."
224 ;; For each operator, we create two "variables" (corresponding to
225 ;; the left and right precedence level), which are represented by
226 ;; cons cells. Those are the vary cons cells that appear in the
227 ;; final `table'. The value of each "variable" is kept in the `car'.
232 ;; From `prec2' we construct a list of constraints between
233 ;; variables (aka "precedence levels"). These can be either
234 ;; equality constraints (in `eqs') or `<' constraints (in `csts').
235 (maphash (lambda (k v)
236 (if (setq tmp (assoc (car k) table))
238 (setq x (cons nil nil))
239 (push (cons (car k) (cons nil x)) table))
240 (if (setq tmp (assoc (cdr k) table))
242 (setq y (cons nil (cons nil nil)))
243 (push (cons (cdr k) y) table))
245 (= (push (cons x y) eqs))
246 (< (push (cons x y) csts))
247 (> (push (cons y x) csts))))
249 ;; First process the equality constraints.
252 (let ((from (caar eqs))
257 (dolist (other-eq eqs)
258 (if (eq from (cdr other-eq)) (setcdr other-eq to))
259 (when (eq from (car other-eq))
260 ;; This can happen because of `assoc' settings in precs
261 ;; or because of a rhs like ("op" foo "op").
262 (setcar other-eq to)))
264 (if (eq from (cdr cst)) (setcdr cst to))
265 (if (eq from (car cst)) (setcar cst to)))))))
266 ;; Then eliminate trivial constraints iteratively.
269 (let ((rhvs (mapcar 'cdr csts))
272 (unless (memq (car cst) rhvs)
274 ;; We could give each var in a given iteration the same value,
275 ;; but we can also give them arbitrarily different values.
276 ;; Basically, these are vars between which there is no
277 ;; constraint (neither equality nor inequality), so
279 ;; We give them arbitrary values, which means that we
280 ;; replace the "no constraint" case with either > or <
281 ;; but not =. The reason we do that is so as to try and
282 ;; distinguish associative operators (which will have
287 (setq csts (delq cst csts))))
289 (error "Can't resolve the precedence table to precedence levels")))
291 ;; Propagate equalities back to their source.
292 (dolist (eq (nreverse eqs))
293 (assert (or (null (caar eq)) (eq (car eq) (cdr eq))))
294 (setcar (car eq) (cadr eq)))
295 ;; Finally, fill in the remaining vars (which only appeared on the
296 ;; right side of the < constraints).
298 ;; When both sides are nil, it means this operator binds very
299 ;; very tight, but it's still just an operator, so we give it
300 ;; the highest precedence.
301 ;; OTOH if only one side is nil, it usually means it's like an
302 ;; open-paren, which is very important for indentation purposes,
303 ;; so we keep it nil, to make it easier to recognize.
304 (unless (or (nth 1 x) (nth 2 x))
306 (setf (nth 2 x) i))))
309 ;;; Parsing using a precedence level table.
311 (defvar smie-op-levels 'unset
312 "List of token parsing info.
313 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
314 Parsing is done using an operator precedence parser.
315 LEFT-LEVEL and RIGHT-LEVEL can be either numbers or nil, where nil
316 means that this operator does not bind on the corresponding side,
317 i.e. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
318 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
319 like a close-paren.")
321 (defvar smie-forward-token-function 'smie-default-forward-token
322 "Function to scan forward for the next token.
323 Called with no argument should return a token and move to its end.
324 If no token is found, return nil or the empty string.
325 It can return nil when bumping into a parenthesis, which lets SMIE
326 use syntax-tables to handle them in efficient C code.")
328 (defvar smie-backward-token-function 'smie-default-backward-token
329 "Function to scan backward the previous token.
330 Same calling convention as `smie-forward-token-function' except
331 it should move backward to the beginning of the previous token.")
333 (defalias 'smie-op-left 'car)
334 (defalias 'smie-op-right 'cadr)
336 (defun smie-default-backward-token ()
337 (forward-comment (- (point)))
338 (buffer-substring-no-properties
340 (progn (if (zerop (skip-syntax-backward "."))
341 (skip-syntax-backward "w_'"))
344 (defun smie-default-forward-token ()
345 (forward-comment (point-max))
346 (buffer-substring-no-properties
348 (progn (if (zerop (skip-syntax-forward "."))
349 (skip-syntax-forward "w_'"))
352 (defun smie-associative-p (toklevels)
353 ;; in "a + b + c" we want to stop at each +, but in
354 ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
355 ;; To distinguish the two cases, we made smie-prec2-levels choose
356 ;; different levels for each part of "if a then b else c", so that
357 ;; by checking if the left-level is equal to the right level, we can
358 ;; figure out that it's an associative operator.
359 ;; This is not 100% foolproof, tho, since the "elsif" will have to have
360 ;; equal left and right levels (since it's optional), so smie-next-sexp
361 ;; has to be careful to distinguish those different cases.
362 (eq (smie-op-left toklevels) (smie-op-right toklevels)))
364 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
366 NEXT-TOKEN is a function of no argument that moves forward by one
367 token (after skipping comments if needed) and returns it.
368 NEXT-SEXP is a lower-level function to skip one sexp.
369 OP-FORW is the accessor to the forward level of the level data.
370 OP-BACK is the accessor to the backward level of the level data.
371 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
372 first token we see is an operator, skip over its left-hand-side argument.
373 Possible return values:
374 (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
375 is too high. FORW-LEVEL is the forw-level of TOKEN,
376 POS is its start position in the buffer.
377 (t POS TOKEN): same thing when we bump on the wrong side of a paren.
378 (nil POS TOKEN): we skipped over a paren-like pair.
379 nil: we skipped over an identifier, matched parentheses, ..."
384 (token (funcall next-token))
385 (toklevels (cdr (assoc token smie-op-levels))))
388 (when (zerop (length token))
390 (progn (goto-char pos) (funcall next-sexp 1) nil)
391 (scan-error (throw 'return
393 (buffer-substring-no-properties
396 (if (< (point) (caddr err))
399 ;; We did not move, so let's abort the loop.
400 (throw 'return (list t (point))))))
401 ((null (funcall op-back toklevels))
402 ;; A token like a paren-close.
403 (assert (funcall op-forw toklevels)) ;Otherwise, why mention it?
404 (push toklevels levels))
406 (while (and levels (< (funcall op-back toklevels)
407 (funcall op-forw (car levels))))
408 (setq levels (cdr levels)))
411 (if (and halfsexp (funcall op-forw toklevels))
412 (push toklevels levels)
414 (prog1 (list (or (car toklevels) t) (point) token)
417 (let ((lastlevels levels))
418 (if (and levels (= (funcall op-back toklevels)
419 (funcall op-forw (car levels))))
420 (setq levels (cdr levels)))
421 ;; We may have found a match for the previously pending
422 ;; operator. Is this the end?
424 ;; Keep looking as long as we haven't matched the
427 (if (funcall op-forw toklevels)
428 (push toklevels levels)))
429 ;; We matched the topmost operator. If the new operator
430 ;; is the last in the corresponding BNF rule, we're done.
431 ((null (funcall op-forw toklevels))
432 ;; It is the last element, let's stop here.
433 (throw 'return (list nil (point) token)))
434 ;; If the new operator is not the last in the BNF rule,
435 ;; ans is not associative, it's one of the inner operators
436 ;; (like the "in" in "let .. in .. end"), so keep looking.
437 ((not (smie-associative-p toklevels))
438 (push toklevels levels))
439 ;; The new operator is associative. Two cases:
440 ;; - it's really just an associative operator (like + or ;)
441 ;; in which case we should have stopped right before.
443 (smie-associative-p (car lastlevels)))
445 (prog1 (list (or (car toklevels) t) (point) token)
447 ;; - it's an associative operator within a larger construct
448 ;; (e.g. an "elsif"), so we should just ignore it and keep
449 ;; looking for the closing element.
450 (t (setq levels lastlevels))))))))
452 (setq halfsexp nil)))))
454 (defun smie-backward-sexp (&optional halfsexp)
456 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
457 first token we see is an operator, skip over its left-hand-side argument.
458 Possible return values:
459 (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
460 is too high. LEFT-LEVEL is the left-level of TOKEN,
461 POS is its start position in the buffer.
462 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
463 (nil POS TOKEN): we skipped over a paren-like pair.
464 nil: we skipped over an identifier, matched parentheses, ..."
466 (indirect-function smie-backward-token-function)
467 (indirect-function 'backward-sexp)
468 (indirect-function 'smie-op-left)
469 (indirect-function 'smie-op-right)
472 (defun smie-forward-sexp (&optional halfsexp)
474 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
475 first token we see is an operator, skip over its left-hand-side argument.
476 Possible return values:
477 (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
478 is too high. RIGHT-LEVEL is the right-level of TOKEN,
479 POS is its end position in the buffer.
480 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
481 (nil POS TOKEN): we skipped over a paren-like pair.
482 nil: we skipped over an identifier, matched parentheses, ..."
484 (indirect-function smie-forward-token-function)
485 (indirect-function 'forward-sexp)
486 (indirect-function 'smie-op-right)
487 (indirect-function 'smie-op-left)
490 ;;; Miscellanous commands using the precedence parser.
492 (defun smie-backward-sexp-command (&optional n)
493 "Move backward through N logical elements."
495 (smie-forward-sexp-command (- n)))
497 (defun smie-forward-sexp-command (&optional n)
498 "Move forward through N logical elements."
501 (forward-sexp-function nil))
503 (setq n (- n (if forw 1 -1)))
506 (smie-forward-sexp 'halfsexp)
507 (smie-backward-sexp 'halfsexp))))
508 (if (and (car res) (= pos (point)) (not (if forw (eolp) (bobp))))
510 (list "Containing expression ends prematurely"
511 (cadr res) (cadr res)))
514 (defvar smie-closer-alist nil
515 "Alist giving the closer corresponding to an opener.")
517 (defun smie-close-block ()
518 "Close the closest surrounding block."
523 (if (looking-at "\\s(")
524 (string (cdr (syntax-after (point))))
525 (let* ((open (funcall smie-forward-token-function))
526 (closer (cdr (assoc open smie-closer-alist)))
527 (levels (list (assoc open smie-op-levels)))
531 ;; Even if we improve the auto-computation of closers,
532 ;; there are still cases where we need manual
533 ;; intervention, e.g. for Octave's use of `until'
534 ;; as a pseudo-closer of `do'.
536 ((or (equal levels '(nil)) (nth 1 (car levels)))
537 (error "Doesn't look like a block"))
539 ;; FIXME: With grammars like Octave's, every closer ("end",
540 ;; "endif", "endwhile", ...) has the same level, so we'd need
541 ;; to look at the BNF or at least at the 2D prec-table, in
542 ;; order to find the right closer for a given opener.
544 (let ((level (pop levels)))
545 (dolist (other smie-op-levels)
546 (when (and (eq (nth 2 level) (nth 1 other))
547 (not (memq other seen)))
551 (push (car other) found))))))
553 ((null found) (error "No known closer for opener %s" open))
554 ;; FIXME: what should we do if there are various closers?
555 (t (car found))))))))))
556 (unless (save-excursion (skip-chars-backward " \t") (bolp))
559 (if (save-excursion (skip-chars-forward " \t") (eolp))
560 (indent-according-to-mode)
561 (reindent-then-newline-and-indent))))
563 ;;; The indentation engine.
565 (defcustom smie-indent-basic 4
566 "Basic amount of indentation."
569 (defvar smie-indent-rules 'unset
570 ;; TODO: For SML, we need more rule formats, so as to handle
576 ;; I.e. the indentation after "=" depends on the parent ("structure")
577 ;; as well as on the following token ("struct").
578 "Rules of the following form.
579 \((:before . TOK) . OFFSET-RULES) how to indent TOK itself.
580 \(TOK . OFFSET-RULES) how to indent right after TOK.
581 \(list-intro . TOKENS) declare TOKENS as being followed by what may look like
582 a funcall but is just a sequence of expressions.
583 \(t . OFFSET) basic indentation step.
584 \(args . OFFSET) indentation of arguments.
585 \((T1 . T2) OFFSET) like ((:before . T2) (:parent T1 OFFSET)).
587 OFFSET-RULES is a list of elements which can each either be:
589 \(:hanging . OFFSET-RULES) if TOK is hanging, use OFFSET-RULES.
590 \(:parent PARENT . OFFSET-RULES) if TOK's parent is PARENT, use OFFSET-RULES.
591 \(:next TOKEN . OFFSET-RULES) if TOK is followed by TOKEN, use OFFSET-RULES.
592 \(:prev TOKEN . OFFSET-RULES) if TOK is preceded by TOKEN, use
593 \(:bolp . OFFSET-RULES) If TOK is first on a line, use OFFSET-RULES.
594 OFFSET the offset to use.
596 PARENT can be either the name of the parent or `open' to mean any parent
597 which acts as an open-paren (i.e. has a nil left-precedence).
599 OFFSET can be of the form:
600 `point' align with the token.
601 `parent' align with the parent.
602 NUMBER offset by NUMBER.
603 \(+ OFFSETS...) use the sum of OFFSETS.
605 The precise meaning of `point' depends on various details: it can
606 either mean the position of the token we're indenting, or the
607 position of its parent, or the position right after its parent.
609 A nil offset for indentation after a token defaults to `smie-indent-basic'.")
611 (defun smie-indent-hanging-p ()
612 ;; A hanging keyword is one that's at the end of a line except it's not at
613 ;; the beginning of a line.
615 (when (zerop (length (funcall smie-forward-token-function)))
616 ;; Could be an open-paren.
618 (skip-chars-forward " \t")
623 (save-excursion (skip-chars-backward " \t") (bolp)))
625 (defun smie-indent-offset (elem)
626 (or (cdr (assq elem smie-indent-rules))
627 (cdr (assq t smie-indent-rules))
630 (defvar smie-indent-debug-log)
632 (defun smie-indent-offset-rule (tokinfo &optional after parent)
633 "Apply the OFFSET-RULES in TOKINFO.
634 Point is expected to be right in front of the token corresponding to TOKINFO.
635 If computing the indentation after the token, then AFTER is the position
636 after the token, otherwise it should be nil.
637 PARENT if non-nil should be the parent info returned by `smie-backward-sexp'."
638 (let ((rules (cdr tokinfo))
642 (let ((rule (pop rules)))
644 ((not (consp rule)) (setq offset rule))
645 ((eq (car rule) '+) (setq offset rule))
646 ((eq (car rule) :hanging)
647 (when (smie-indent-hanging-p)
648 (setq rules (cdr rule))))
649 ((eq (car rule) :bolp)
651 (setq rules (cdr rule))))
652 ((eq (car rule) :eolp)
654 (error "Can't use :eolp in :before indentation rules"))
655 (when (> after (line-end-position))
656 (setq rules (cdr rule))))
657 ((eq (car rule) :prev)
660 (setq prev (smie-indent-backward-token))))
661 (when (equal (car prev) (cadr rule))
662 (setq rules (cddr rule))))
663 ((eq (car rule) :next)
666 (error "Can't use :next in :before indentation rules"))
669 (setq next (smie-indent-forward-token))))
670 (when (equal (car next) (cadr rule))
671 (setq rules (cddr rule))))
672 ((eq (car rule) :parent)
675 (if after (goto-char after))
676 (setq parent (smie-backward-sexp 'halfsexp))))
677 (when (or (equal (nth 2 parent) (cadr rule))
678 (and (eq (cadr rule) 'open) (null (car parent))))
679 (setq rules (cddr rule))))
680 (t (error "Unknown rule %s for indentation of %s"
681 rule (car tokinfo))))))
682 ;; If `offset' is not set yet, use `rules' to handle the case where
683 ;; the tokinfo uses the old-style ((PARENT . TOK). OFFSET).
684 (unless offset (setq offset rules))
685 (when (boundp 'smie-indent-debug-log)
686 (push (list (point) offset tokinfo) smie-indent-debug-log))
689 (defun smie-indent-column (offset &optional base parent virtual-point)
690 "Compute the actual column to use for a given OFFSET.
691 BASE is the base position to use, and PARENT is the parent info, if any.
692 If VIRTUAL-POINT is non-nil, then `point' is virtual."
694 ((eq (car-safe offset) '+)
695 (apply '+ (mapcar (lambda (offset) (smie-indent-column offset nil parent))
701 (parent (goto-char (cadr parent))
702 (smie-indent-virtual))
705 ;; For indentation after "(let" in SML-mode, we end up accumulating
706 ;; the offset of "(" and the offset of "let", so we use `min' to try
707 ;; and get it right either way.
708 (min (smie-indent-virtual) (current-column))))))
710 ;; In indent-keyword, if we're indenting `then' wrt `if', we want to use
711 ;; indent-virtual rather than use just current-column, so that we can
712 ;; apply the (:before . "if") rule which does the "else if" dance in SML.
713 ;; But in other cases, we do not want to use indent-virtual
714 ;; (e.g. indentation of "*" w.r.t "+", or ";" wrt "("). We could just
715 ;; always use indent-virtual and then have indent-rules say explicitly
716 ;; to use `point' after things like "(" or "+" when they're not at EOL,
717 ;; but you'd end up with lots of those rules.
718 ;; So we use a heuristic here, which is that we only use virtual if
719 ;; the parent is tightly linked to the child token (they're part of
720 ;; the same BNF rule).
721 (if (and virtual-point (null (car parent))) ;Black magic :-(
722 (smie-indent-virtual) (current-column)))
725 (setq parent (or (smie-backward-sexp 'halfsexp) :notfound)))
726 (if (consp parent) (goto-char (cadr parent)))
727 (smie-indent-virtual))
728 ((eq offset nil) nil)
729 (t (error "Unknown indentation offset %s" offset))))
731 (defun smie-indent-forward-token ()
732 "Skip token forward and return it, along with its levels."
733 (let ((tok (funcall smie-forward-token-function)))
735 ((< 0 (length tok)) (assoc tok smie-op-levels))
738 (list (buffer-substring (1- (point)) (point)) nil 0)))))
740 (defun smie-indent-backward-token ()
741 "Skip token backward and return it, along with its levels."
742 (let ((tok (funcall smie-backward-token-function)))
744 ((< 0 (length tok)) (assoc tok smie-op-levels))
745 ;; 4 == Open paren syntax.
746 ((eq 4 (syntax-class (syntax-after (1- (point)))))
748 (list (buffer-substring (point) (1+ (point))) nil 0)))))
750 (defun smie-indent-virtual ()
751 ;; We used to take an optional arg (with value :not-hanging) to specify that
752 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
753 ;; keyword. This was a bad idea, because the virtual indent of a position
754 ;; should not depend on the caller, since it leads to situations where two
755 ;; dependent indentations get indented differently.
756 "Compute the virtual indentation to use for point.
757 This is used when we're not trying to indent point but just
758 need to compute the column at which point should be indented
759 in order to figure out the indentation of some other (further down) point."
760 ;; Trust pre-existing indentation on other lines.
761 (if (smie-bolp) (current-column) (smie-indent-calculate)))
763 (defun smie-indent-fixindent ()
764 ;; Obey the `fixindent' special comment.
767 (comment-normalize-vars)
768 (re-search-forward (concat comment-start-skip
771 ;; 1+ to account for the \n comment termination.
772 (1+ (line-end-position)) t))
775 (defun smie-indent-bob ()
776 ;; Start the file at column 0.
778 (forward-comment (- (point)))
781 (defun smie-indent-close ()
782 ;; Align close paren with opening paren.
784 ;; (forward-comment (point-max))
785 (when (looking-at "\\s)")
786 (while (not (zerop (skip-syntax-forward ")")))
787 (skip-chars-forward " \t"))
791 (smie-indent-virtual)) ;:not-hanging
794 (defun smie-indent-keyword ()
795 ;; Align closing token with the corresponding opening one.
796 ;; (e.g. "of" with "case", or "in" with "let").
799 (toklevels (smie-indent-forward-token))
800 (token (pop toklevels)))
801 (if (null (car toklevels))
805 ;; - smie-bolp: "indent according to others".
806 ;; - common hanging: "indent according to others".
807 ;; - SML-let hanging: "indent like parent".
808 ;; - if-after-else: "indent-like parent".
809 ;; - middle-of-line: "trust current position".
811 ((null (cdr toklevels)) nil) ;Not a keyword.
813 ;; For an open-paren-like thingy at BOL, always indent only
814 ;; based on other rules (typically smie-indent-after-keyword).
817 ;; We're only ever here for virtual-indent, which is why
818 ;; we can use (current-column) as answer for `point'.
819 (let* ((tokinfo (or (assoc (cons :before token)
821 ;; By default use point unless we're hanging.
822 `((:before . ,token) (:hanging nil) point)))
823 ;; (after (prog1 (point) (goto-char pos)))
824 (offset (smie-indent-offset-rule tokinfo)))
825 (smie-indent-column offset)))))
827 ;; FIXME: This still looks too much like black magic!!
828 ;; FIXME: Rather than a bunch of rules like (PARENT . TOKEN), we
829 ;; want a single rule for TOKEN with different cases for each PARENT.
830 (let* ((parent (smie-backward-sexp 'halfsexp))
832 (or (assoc (cons (caddr parent) token)
834 (assoc (cons :before token) smie-indent-rules)
839 (offset (save-excursion
841 (smie-indent-offset-rule tokinfo nil parent))))
842 ;; Different behaviors:
843 ;; - align with parent.
844 ;; - parent + offset.
845 ;; - after parent's column + offset (actually, after or before
846 ;; depending on where backward-sexp stopped).
847 ;; ? let it drop to some other indentation function (almost never).
848 ;; ? parent + offset + parent's own offset.
850 ;; - bump into a same-level operator.
851 ;; - bump into a specific known parent.
852 ;; - find a matching open-paren thingy.
853 ;; - bump into some random parent.
854 ;; ? borderline case (almost never).
855 ;; ? bump immediately into a parent.
857 ((not (or (< (point) pos)
858 (and (cadr parent) (< (cadr parent) pos))))
859 ;; If we didn't move at all, that means we didn't really skip
860 ;; what we wanted. Should almost never happen, other than
861 ;; maybe when an infix or close-paren is at the beginning
864 ((eq (car parent) (car toklevels))
865 ;; We bumped into a same-level operator. align with it.
866 (if (and (smie-bolp) (/= (point) pos)
868 (goto-char (goto-char (cadr parent)))
870 ;; Check the offset of `token' rather then its parent
871 ;; because its parent may have used a special rule. E.g.
875 ;; The ; on the first line had a special rule, but when
876 ;; indenting line3, we don't care about it and want to
878 (memq offset '(point nil)))
879 ;; If the parent is at EOL and its children are indented like
880 ;; itself, then we can just obey the indentation chosen for the
882 ;; This is important for operators like ";" which
883 ;; are usually at EOL (and have an offset of 0): otherwise we'd
884 ;; always go back over all the statements, which is
885 ;; a performance problem and would also mean that fixindents
886 ;; in the middle of such a sequence would be ignored.
888 ;; This is a delicate point!
889 ;; Even if the offset is not 0, we could follow the same logic
890 ;; and subtract the offset from the child's indentation.
891 ;; But that would more often be a bad idea: OT1H we generally
892 ;; want to reuse the closest similar indentation point, so that
893 ;; the user's choice (or the fixindents) are obeyed. But OTOH
894 ;; we don't want this to affect "unrelated" parts of the code.
895 ;; E.g. a fixindent in the body of a "begin..end" should not
896 ;; affect the indentation of the "end".
898 (goto-char (cadr parent))
899 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
900 ;; want to jump back over a sequence of same-level ops such as
903 ;; So as to align with the earliest appropriate place.
904 (smie-indent-virtual)))
906 (if (and (= (point) pos) (smie-bolp)
907 (or (eq offset 'point)
908 (and (consp offset) (memq 'point offset))))
909 ;; Since we started at BOL, we're not computing a virtual
910 ;; indentation, and we're still at the starting point, so
911 ;; we can't use `current-column' which would cause
912 ;; indentation to depend on itself.
914 (smie-indent-column offset 'parent parent
915 ;; If we're still at pos, indent-virtual
917 (unless (= (point) pos) 'virtual))))))))))
919 (defun smie-indent-comment ()
920 "Compute indentation of a comment."
921 ;; Don't do it for virtual indentations. We should normally never be "in
922 ;; front of a comment" when doing virtual-indentation anyway. And if we are
923 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
925 (looking-at comment-start-skip)
927 (forward-comment (point-max))
928 (skip-chars-forward " \t\r\n")
929 (smie-indent-calculate))))
931 (defun smie-indent-comment-continue ()
932 ;; indentation of comment-continue lines.
933 (let ((continue (and comment-continue
934 (comment-string-strip comment-continue t t))))
935 (and (< 0 (length continue))
936 (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
937 (let ((ppss (syntax-ppss)))
940 (if (<= (point) (nth 8 ppss))
941 (progn (goto-char (1+ (nth 8 ppss))) (current-column))
942 (skip-chars-forward " \t")
943 (if (looking-at (regexp-quote continue))
944 (current-column))))))))
946 (defun smie-indent-after-keyword ()
947 ;; Indentation right after a special keyword.
950 (toklevel (smie-indent-backward-token))
952 (tokinfo (assoc tok smie-indent-rules)))
953 ;; Set some default indent rules.
954 (if (and toklevel (null (cadr toklevel)) (null tokinfo))
955 (setq tokinfo (list (car toklevel))))
956 ;; (if (and tokinfo (null toklevel))
957 ;; (error "Token %S has indent rule but has no parsing info" tok))
960 ;; The default indentation after a keyword/operator is 0 for
961 ;; infix and t for prefix.
962 ;; Using the BNF syntax, we could come up with better
963 ;; defaults, but we only have the precedence levels here.
964 (setq tokinfo (list tok 'default-rule
965 (if (cadr toklevel) 0 (smie-indent-offset t)))))
967 (or (smie-indent-offset-rule tokinfo pos)
968 (smie-indent-offset t))))
969 (let ((before (point)))
971 (smie-indent-column offset before)))))))
973 (defun smie-indent-exps ()
974 ;; Indentation of sequences of simple expressions without
975 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
976 ;; Can be a list of expressions or a function call.
977 ;; If it's a function call, the first element is special (it's the
978 ;; function). We distinguish function calls from mere lists of
979 ;; expressions based on whether the preceding token is listed in
980 ;; the `list-intro' entry of smie-indent-rules.
982 ;; TODO: to indent Lisp code, we should add a way to specify
983 ;; particular indentation for particular args depending on the
984 ;; function (which would require always skipping back until the
986 ;; TODO: to indent C code, such as "if (...) {...}" we might need
987 ;; to add similar indentation hooks for particular positions, but
988 ;; based on the preceding token rather than based on the first exp.
990 (let ((positions nil)
992 (while (and (null (car (smie-backward-sexp)))
993 (push (point) positions)
996 ;; Figure out if the atom we just skipped is an argument rather
998 (setq arg (or (null (car (smie-backward-sexp)))
999 (member (funcall smie-backward-token-function)
1000 (cdr (assoc 'list-intro smie-indent-rules))))))
1003 ;; We're the first expression of the list. In that case, the
1004 ;; indentation should be (have been) determined by its context.
1007 ;; There's a previous element, and it's not special (it's not
1008 ;; the function), so let's just align with that one.
1009 (goto-char (car positions))
1012 ;; We skipped some args plus the function and bumped into something.
1013 ;; Align with the first arg.
1014 (goto-char (cadr positions))
1017 ;; We're the first arg.
1018 (goto-char (car positions))
1019 (+ (smie-indent-offset 'args)
1020 ;; We used to use (smie-indent-virtual), but that
1021 ;; doesn't seem right since it might then indent args less than
1022 ;; the function itself.
1023 (current-column)))))))
1025 (defvar smie-indent-functions
1026 '(smie-indent-fixindent smie-indent-bob smie-indent-close smie-indent-comment
1027 smie-indent-comment-continue smie-indent-keyword smie-indent-after-keyword
1029 "Functions to compute the indentation.
1030 Each function is called with no argument, shouldn't move point, and should
1031 return either nil if it has no opinion, or an integer representing the column
1032 to which that point should be aligned, if we were to reindent it.")
1034 (defun smie-indent-calculate ()
1035 "Compute the indentation to use for point."
1036 (run-hook-with-args-until-success 'smie-indent-functions))
1038 (defun smie-indent-line ()
1039 "Indent current line using the SMIE indentation engine."
1041 (let* ((savep (point))
1042 (indent (condition-case-no-debug nil
1045 (skip-chars-forward " \t")
1046 (if (>= (point) savep) (setq savep nil))
1047 (or (smie-indent-calculate) 0))
1049 (if (not (numberp indent))
1050 ;; If something funny is used (e.g. `noindent'), return it.
1052 (if (< indent 0) (setq indent 0)) ;Just in case.
1054 (save-excursion (indent-line-to indent))
1055 (indent-line-to indent)))))
1057 (defun smie-indent-debug ()
1058 "Show the rules used to compute indentation of current line."
1060 (let ((smie-indent-debug-log '()))
1061 (smie-indent-calculate)
1062 ;; FIXME: please improve!
1063 (message "%S" smie-indent-debug-log)))
1065 (defun smie-setup (op-levels indent-rules)
1066 (set (make-local-variable 'smie-indent-rules) indent-rules)
1067 (set (make-local-variable 'smie-op-levels) op-levels)
1068 (set (make-local-variable 'indent-line-function) 'smie-indent-line))
1072 ;;; smie.el ends here