]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/smie.el
* lisp/emacs-lisp/smie.el (smie-indent-offset-rule): Let :parent take
[gnu-emacs] / lisp / emacs-lisp / smie.el
1 ;;; smie.el --- Simple Minded Indentation Engine
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: languages, lisp, internal, parsing, indentation
7
8 ;; This file is part of GNU Emacs.
9
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.
14
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.
19
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/>.
22
23 ;;; Commentary:
24
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
29 ;; LaTeX indentation.
30 ;;
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.
36
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
40 ;; for Emacs:
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
49 ;; decision.
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.
54
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).
60 ;;
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.
65
66 ;;; Code:
67
68 ;; FIXME: I think the behavior on empty lines is wrong. It shouldn't
69 ;; look at the next token on subsequent lines.
70
71 (eval-when-compile (require 'cl))
72
73 (defvar comment-continue)
74 (declare-function comment-string-strip "newcomment" (str beforep afterp))
75
76 ;;; Building precedence level tables from BNF specs.
77
78 (defun smie-set-prec2tab (table x y val &optional override)
79 (assert (and x y))
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))))
91
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)))
99 (dolist (prec precs)
100 (dolist (op (cdr prec))
101 (let ((selfrule (cdr (assq (car prec)
102 '((left . >) (right . <) (assoc . =))))))
103 (when selfrule
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)
109 (setq op1 '> op2 '<)
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)))))))
113 prec2-table))
114
115 (defun smie-merge-prec2s (&rest tables)
116 (if (null (cdr tables))
117 (car 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))
122 table))
123 prec2)))
124
125 (defun smie-bnf-precedence-table (bnf &rest precs)
126 (let ((nts (mapcar 'car bnf)) ;Non-terminals
127 (first-ops-table ())
128 (last-ops-table ())
129 (first-nts-table ())
130 (last-nts-table ())
131 (prec2 (make-hash-table :test 'equal))
132 (override (apply 'smie-merge-prec2s
133 (mapcar 'smie-precs-precedence-table precs)))
134 again)
135 (dolist (rules bnf)
136 (let ((nt (car rules))
137 (last-ops ())
138 (first-ops ())
139 (last-nts ())
140 (first-nts ()))
141 (dolist (rhs (cdr rules))
142 (assert (consp rhs))
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.
170 (setq again t)
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)
178 (setq again t)
179 (push op (cdr first-ops))))))))
180 ;; Same thing for last-ops.
181 (setq again t)
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)
189 (setq again t)
190 (push op (cdr last-ops))))))))
191 ;; Now generate the 2D precedence table.
192 (dolist (rules bnf)
193 (dolist (rhs (cdr rules))
194 (while (cdr rhs)
195 (cond
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))
204 '= override)))
205 (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
206 (setq rhs (cdr rhs)))))
207 prec2))
208
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'.
228 (let ((table ())
229 (csts ())
230 (eqs ())
231 tmp x y)
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))
237 (setq x (cddr tmp))
238 (setq x (cons nil nil))
239 (push (cons (car k) (cons nil x)) table))
240 (if (setq tmp (assoc (cdr k) table))
241 (setq y (cdr tmp))
242 (setq y (cons nil (cons nil nil)))
243 (push (cons (cdr k) y) table))
244 (ecase v
245 (= (push (cons x y) eqs))
246 (< (push (cons x y) csts))
247 (> (push (cons y x) csts))))
248 prec2)
249 ;; First process the equality constraints.
250 (let ((eqs eqs))
251 (while eqs
252 (let ((from (caar eqs))
253 (to (cdar eqs)))
254 (setq eqs (cdr eqs))
255 (if (eq to from)
256 nil ;Nothing to do.
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)))
263 (dolist (cst csts)
264 (if (eq from (cdr cst)) (setcdr cst to))
265 (if (eq from (car cst)) (setcar cst to)))))))
266 ;; Then eliminate trivial constraints iteratively.
267 (let ((i 0))
268 (while csts
269 (let ((rhvs (mapcar 'cdr csts))
270 (progress nil))
271 (dolist (cst csts)
272 (unless (memq (car cst) rhvs)
273 (setq progress t)
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
278 ;; anything will do.
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
283 ;; left = right).
284 (unless (caar cst)
285 (setcar (car cst) i)
286 (incf i))
287 (setq csts (delq cst csts))))
288 (unless progress
289 (error "Can't resolve the precedence table to precedence levels")))
290 (incf i 10))
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).
297 (dolist (x table)
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))
305 (setf (nth 1 x) i)
306 (setf (nth 2 x) i))))
307 table))
308
309 ;;; Parsing using a precedence level table.
310
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.")
320
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.")
327
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.")
332
333 (defalias 'smie-op-left 'car)
334 (defalias 'smie-op-right 'cadr)
335
336 (defun smie-default-backward-token ()
337 (forward-comment (- (point)))
338 (buffer-substring-no-properties
339 (point)
340 (progn (if (zerop (skip-syntax-backward "."))
341 (skip-syntax-backward "w_'"))
342 (point))))
343
344 (defun smie-default-forward-token ()
345 (forward-comment (point-max))
346 (buffer-substring-no-properties
347 (point)
348 (progn (if (zerop (skip-syntax-forward "."))
349 (skip-syntax-forward "w_'"))
350 (point))))
351
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)))
363
364 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
365 "Skip over one sexp.
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, ..."
380 (catch 'return
381 (let ((levels ()))
382 (while
383 (let* ((pos (point))
384 (token (funcall next-token))
385 (toklevels (cdr (assoc token smie-op-levels))))
386 (cond
387 ((null toklevels)
388 (when (zerop (length token))
389 (condition-case err
390 (progn (goto-char pos) (funcall next-sexp 1) nil)
391 (scan-error (throw 'return
392 (list t (caddr err)
393 (buffer-substring-no-properties
394 (caddr err)
395 (+ (caddr err)
396 (if (< (point) (caddr err))
397 -1 1)))))))
398 (if (eq pos (point))
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))
405 (t
406 (while (and levels (< (funcall op-back toklevels)
407 (funcall op-forw (car levels))))
408 (setq levels (cdr levels)))
409 (cond
410 ((null levels)
411 (if (and halfsexp (funcall op-forw toklevels))
412 (push toklevels levels)
413 (throw 'return
414 (prog1 (list (or (car toklevels) t) (point) token)
415 (goto-char pos)))))
416 (t
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?
423 (cond
424 ;; Keep looking as long as we haven't matched the
425 ;; topmost operator.
426 (levels
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.
442 ((and lastlevels
443 (smie-associative-p (car lastlevels)))
444 (throw 'return
445 (prog1 (list (or (car toklevels) t) (point) token)
446 (goto-char pos))))
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))))))))
451 levels)
452 (setq halfsexp nil)))))
453
454 (defun smie-backward-sexp (&optional halfsexp)
455 "Skip over one sexp.
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, ..."
465 (smie-next-sexp
466 (indirect-function smie-backward-token-function)
467 (indirect-function 'backward-sexp)
468 (indirect-function 'smie-op-left)
469 (indirect-function 'smie-op-right)
470 halfsexp))
471
472 (defun smie-forward-sexp (&optional halfsexp)
473 "Skip over one sexp.
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, ..."
483 (smie-next-sexp
484 (indirect-function smie-forward-token-function)
485 (indirect-function 'forward-sexp)
486 (indirect-function 'smie-op-right)
487 (indirect-function 'smie-op-left)
488 halfsexp))
489
490 ;;; Miscellanous commands using the precedence parser.
491
492 (defun smie-backward-sexp-command (&optional n)
493 "Move backward through N logical elements."
494 (interactive "^p")
495 (smie-forward-sexp-command (- n)))
496
497 (defun smie-forward-sexp-command (&optional n)
498 "Move forward through N logical elements."
499 (interactive "^p")
500 (let ((forw (> n 0))
501 (forward-sexp-function nil))
502 (while (/= n 0)
503 (setq n (- n (if forw 1 -1)))
504 (let ((pos (point))
505 (res (if forw
506 (smie-forward-sexp 'halfsexp)
507 (smie-backward-sexp 'halfsexp))))
508 (if (and (car res) (= pos (point)) (not (if forw (eobp) (bobp))))
509 (signal 'scan-error
510 (list "Containing expression ends prematurely"
511 (cadr res) (cadr res)))
512 nil)))))
513
514 (defvar smie-closer-alist nil
515 "Alist giving the closer corresponding to an opener.")
516
517 (defun smie-close-block ()
518 "Close the closest surrounding block."
519 (interactive)
520 (let ((closer
521 (save-excursion
522 (backward-up-list 1)
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)))
528 (seen '())
529 (found '()))
530 (cond
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'.
535 (closer)
536 ((or (equal levels '(nil)) (nth 1 (car levels)))
537 (error "Doesn't look like a block"))
538 (t
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.
543 (while levels
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)))
548 (push other seen)
549 (if (nth 2 other)
550 (push other levels)
551 (push (car other) found))))))
552 (cond
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))
557 (newline))
558 (insert closer)
559 (if (save-excursion (skip-chars-forward " \t") (eolp))
560 (indent-according-to-mode)
561 (reindent-then-newline-and-indent))))
562
563 ;;; The indentation engine.
564
565 (defcustom smie-indent-basic 4
566 "Basic amount of indentation."
567 :type 'integer)
568
569 (defvar smie-indent-rules 'unset
570 ;; TODO: For SML, we need more rule formats, so as to handle
571 ;; structure Foo =
572 ;; Bar (toto)
573 ;; and
574 ;; structure Foo =
575 ;; struct ... end
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)).
586
587 OFFSET-RULES is a list of elements which can each either be:
588
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.
595
596 PARENT can be either the name of the parent or a list of such names.
597
598 OFFSET can be of the form:
599 `point' align with the token.
600 `parent' align with the parent.
601 NUMBER offset by NUMBER.
602 \(+ OFFSETS...) use the sum of OFFSETS.
603 VARIABLE use the value of VARIABLE as offset.
604
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.
608
609 A nil offset for indentation after an opening token defaults
610 to `smie-indent-basic'.")
611
612 (defun smie-indent-hanging-p ()
613 ;; A hanging keyword is one that's at the end of a line except it's not at
614 ;; the beginning of a line.
615 (and (save-excursion
616 (when (zerop (length (funcall smie-forward-token-function)))
617 ;; Could be an open-paren.
618 (forward-char 1))
619 (skip-chars-forward " \t")
620 (eolp))
621 (not (smie-bolp))))
622
623 (defun smie-bolp ()
624 (save-excursion (skip-chars-backward " \t") (bolp)))
625
626 (defun smie-indent-offset (elem)
627 (or (cdr (assq elem smie-indent-rules))
628 (cdr (assq t smie-indent-rules))
629 smie-indent-basic))
630
631 (defvar smie-indent-debug-log)
632
633 (defun smie-indent-offset-rule (tokinfo &optional after parent)
634 "Apply the OFFSET-RULES in TOKINFO.
635 Point is expected to be right in front of the token corresponding to TOKINFO.
636 If computing the indentation after the token, then AFTER is the position
637 after the token, otherwise it should be nil.
638 PARENT if non-nil should be the parent info returned by `smie-backward-sexp'."
639 (let ((rules (cdr tokinfo))
640 next prev
641 offset)
642 (while (consp rules)
643 (let ((rule (pop rules)))
644 (cond
645 ((not (consp rule)) (setq offset rule))
646 ((eq (car rule) '+) (setq offset rule))
647 ((eq (car rule) :hanging)
648 (when (smie-indent-hanging-p)
649 (setq rules (cdr rule))))
650 ((eq (car rule) :bolp)
651 (when (smie-bolp)
652 (setq rules (cdr rule))))
653 ((eq (car rule) :eolp)
654 (unless after
655 (error "Can't use :eolp in :before indentation rules"))
656 (when (> after (line-end-position))
657 (setq rules (cdr rule))))
658 ((eq (car rule) :prev)
659 (unless prev
660 (save-excursion
661 (setq prev (smie-indent-backward-token))))
662 (when (equal (car prev) (cadr rule))
663 (setq rules (cddr rule))))
664 ((eq (car rule) :next)
665 (unless next
666 (unless after
667 (error "Can't use :next in :before indentation rules"))
668 (save-excursion
669 (goto-char after)
670 (setq next (smie-indent-forward-token))))
671 (when (equal (car next) (cadr rule))
672 (setq rules (cddr rule))))
673 ((eq (car rule) :parent)
674 (unless parent
675 (save-excursion
676 (if after (goto-char after))
677 (setq parent (smie-backward-sexp 'halfsexp))))
678 (when (if (listp (cadr rule))
679 (member (nth 2 parent) (cadr rule))
680 (equal (nth 2 parent) (cadr rule)))
681 (setq rules (cddr rule))))
682 (t (error "Unknown rule %s for indentation of %s"
683 rule (car tokinfo))))))
684 ;; If `offset' is not set yet, use `rules' to handle the case where
685 ;; the tokinfo uses the old-style ((PARENT . TOK). OFFSET).
686 (unless offset (setq offset rules))
687 (when (boundp 'smie-indent-debug-log)
688 (push (list (point) offset tokinfo) smie-indent-debug-log))
689 offset))
690
691 (defun smie-indent-column (offset &optional base parent virtual-point)
692 "Compute the actual column to use for a given OFFSET.
693 BASE is the base position to use, and PARENT is the parent info, if any.
694 If VIRTUAL-POINT is non-nil, then `point' is virtual."
695 (cond
696 ((eq (car-safe offset) '+)
697 (apply '+ (mapcar (lambda (offset) (smie-indent-column offset nil parent))
698 (cdr offset))))
699 ((integerp offset)
700 (+ offset
701 (case base
702 ((nil) 0)
703 (parent (goto-char (cadr parent))
704 (smie-indent-virtual))
705 (t
706 (goto-char base)
707 ;; For indentation after "(let" in SML-mode, we end up accumulating
708 ;; the offset of "(" and the offset of "let", so we use `min' to try
709 ;; and get it right either way.
710 (min (smie-indent-virtual) (current-column))))))
711 ((eq offset 'point)
712 ;; In indent-keyword, if we're indenting `then' wrt `if', we want to use
713 ;; indent-virtual rather than use just current-column, so that we can
714 ;; apply the (:before . "if") rule which does the "else if" dance in SML.
715 ;; But in other cases, we do not want to use indent-virtual
716 ;; (e.g. indentation of "*" w.r.t "+", or ";" wrt "("). We could just
717 ;; always use indent-virtual and then have indent-rules say explicitly
718 ;; to use `point' after things like "(" or "+" when they're not at EOL,
719 ;; but you'd end up with lots of those rules.
720 ;; So we use a heuristic here, which is that we only use virtual if
721 ;; the parent is tightly linked to the child token (they're part of
722 ;; the same BNF rule).
723 (if (and virtual-point (null (car parent))) ;Black magic :-(
724 (smie-indent-virtual) (current-column)))
725 ((eq offset 'parent)
726 (unless parent
727 (setq parent (or (smie-backward-sexp 'halfsexp) :notfound)))
728 (if (consp parent) (goto-char (cadr parent)))
729 (smie-indent-virtual))
730 ((eq offset nil) nil)
731 ((and (symbolp offset) (boundp 'offset))
732 (smie-indent-column (symbol-value offset) base parent virtual-point))
733 (t (error "Unknown indentation offset %s" offset))))
734
735 (defun smie-indent-forward-token ()
736 "Skip token forward and return it, along with its levels."
737 (let ((tok (funcall smie-forward-token-function)))
738 (cond
739 ((< 0 (length tok)) (assoc tok smie-op-levels))
740 ((looking-at "\\s(")
741 (forward-char 1)
742 (list (buffer-substring (1- (point)) (point)) nil 0)))))
743
744 (defun smie-indent-backward-token ()
745 "Skip token backward and return it, along with its levels."
746 (let ((tok (funcall smie-backward-token-function)))
747 (cond
748 ((< 0 (length tok)) (assoc tok smie-op-levels))
749 ;; 4 == Open paren syntax.
750 ((eq 4 (syntax-class (syntax-after (1- (point)))))
751 (forward-char -1)
752 (list (buffer-substring (point) (1+ (point))) nil 0)))))
753
754 (defun smie-indent-virtual ()
755 ;; We used to take an optional arg (with value :not-hanging) to specify that
756 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
757 ;; keyword. This was a bad idea, because the virtual indent of a position
758 ;; should not depend on the caller, since it leads to situations where two
759 ;; dependent indentations get indented differently.
760 "Compute the virtual indentation to use for point.
761 This is used when we're not trying to indent point but just
762 need to compute the column at which point should be indented
763 in order to figure out the indentation of some other (further down) point."
764 ;; Trust pre-existing indentation on other lines.
765 (if (smie-bolp) (current-column) (smie-indent-calculate)))
766
767 (defun smie-indent-fixindent ()
768 ;; Obey the `fixindent' special comment.
769 (and (smie-bolp)
770 (save-excursion
771 (comment-normalize-vars)
772 (re-search-forward (concat comment-start-skip
773 "fixindent"
774 comment-end-skip)
775 ;; 1+ to account for the \n comment termination.
776 (1+ (line-end-position)) t))
777 (current-column)))
778
779 (defun smie-indent-bob ()
780 ;; Start the file at column 0.
781 (save-excursion
782 (forward-comment (- (point)))
783 (if (bobp) 0)))
784
785 (defun smie-indent-close ()
786 ;; Align close paren with opening paren.
787 (save-excursion
788 ;; (forward-comment (point-max))
789 (when (looking-at "\\s)")
790 (while (not (zerop (skip-syntax-forward ")")))
791 (skip-chars-forward " \t"))
792 (condition-case nil
793 (progn
794 (backward-sexp 1)
795 (smie-indent-virtual)) ;:not-hanging
796 (scan-error nil)))))
797
798 (defun smie-indent-keyword ()
799 ;; Align closing token with the corresponding opening one.
800 ;; (e.g. "of" with "case", or "in" with "let").
801 (save-excursion
802 (let* ((pos (point))
803 (toklevels (smie-indent-forward-token))
804 (token (pop toklevels)))
805 (if (null (car toklevels))
806 (save-excursion
807 (goto-char pos)
808 ;; Different cases:
809 ;; - smie-bolp: "indent according to others".
810 ;; - common hanging: "indent according to others".
811 ;; - SML-let hanging: "indent like parent".
812 ;; - if-after-else: "indent-like parent".
813 ;; - middle-of-line: "trust current position".
814 (cond
815 ((null (cdr toklevels)) nil) ;Not a keyword.
816 ((smie-bolp)
817 ;; For an open-paren-like thingy at BOL, always indent only
818 ;; based on other rules (typically smie-indent-after-keyword).
819 nil)
820 (t
821 ;; We're only ever here for virtual-indent, which is why
822 ;; we can use (current-column) as answer for `point'.
823 (let* ((tokinfo (or (assoc (cons :before token)
824 smie-indent-rules)
825 ;; By default use point unless we're hanging.
826 `((:before . ,token) (:hanging nil) point)))
827 ;; (after (prog1 (point) (goto-char pos)))
828 (offset (smie-indent-offset-rule tokinfo)))
829 (smie-indent-column offset)))))
830
831 ;; FIXME: This still looks too much like black magic!!
832 ;; FIXME: Rather than a bunch of rules like (PARENT . TOKEN), we
833 ;; want a single rule for TOKEN with different cases for each PARENT.
834 (let* ((parent (smie-backward-sexp 'halfsexp))
835 (tokinfo
836 (or (assoc (cons (caddr parent) token)
837 smie-indent-rules)
838 (assoc (cons :before token) smie-indent-rules)
839 ;; Default rule.
840 `((:before . ,token)
841 ;; (:parent open 0)
842 point)))
843 (offset (save-excursion
844 (goto-char pos)
845 (smie-indent-offset-rule tokinfo nil parent))))
846 ;; Different behaviors:
847 ;; - align with parent.
848 ;; - parent + offset.
849 ;; - after parent's column + offset (actually, after or before
850 ;; depending on where backward-sexp stopped).
851 ;; ? let it drop to some other indentation function (almost never).
852 ;; ? parent + offset + parent's own offset.
853 ;; Different cases:
854 ;; - bump into a same-level operator.
855 ;; - bump into a specific known parent.
856 ;; - find a matching open-paren thingy.
857 ;; - bump into some random parent.
858 ;; ? borderline case (almost never).
859 ;; ? bump immediately into a parent.
860 (cond
861 ((not (or (< (point) pos)
862 (and (cadr parent) (< (cadr parent) pos))))
863 ;; If we didn't move at all, that means we didn't really skip
864 ;; what we wanted. Should almost never happen, other than
865 ;; maybe when an infix or close-paren is at the beginning
866 ;; of a buffer.
867 nil)
868 ((eq (car parent) (car toklevels))
869 ;; We bumped into a same-level operator. align with it.
870 (if (and (smie-bolp) (/= (point) pos)
871 (save-excursion
872 (goto-char (goto-char (cadr parent)))
873 (not (smie-bolp)))
874 ;; Check the offset of `token' rather then its parent
875 ;; because its parent may have used a special rule. E.g.
876 ;; function foo;
877 ;; line2;
878 ;; line3;
879 ;; The ; on the first line had a special rule, but when
880 ;; indenting line3, we don't care about it and want to
881 ;; align with line2.
882 (memq offset '(point nil)))
883 ;; If the parent is at EOL and its children are indented like
884 ;; itself, then we can just obey the indentation chosen for the
885 ;; child.
886 ;; This is important for operators like ";" which
887 ;; are usually at EOL (and have an offset of 0): otherwise we'd
888 ;; always go back over all the statements, which is
889 ;; a performance problem and would also mean that fixindents
890 ;; in the middle of such a sequence would be ignored.
891 ;;
892 ;; This is a delicate point!
893 ;; Even if the offset is not 0, we could follow the same logic
894 ;; and subtract the offset from the child's indentation.
895 ;; But that would more often be a bad idea: OT1H we generally
896 ;; want to reuse the closest similar indentation point, so that
897 ;; the user's choice (or the fixindents) are obeyed. But OTOH
898 ;; we don't want this to affect "unrelated" parts of the code.
899 ;; E.g. a fixindent in the body of a "begin..end" should not
900 ;; affect the indentation of the "end".
901 (current-column)
902 (goto-char (cadr parent))
903 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
904 ;; want to jump back over a sequence of same-level ops such as
905 ;; a -> b -> c
906 ;; -> d
907 ;; So as to align with the earliest appropriate place.
908 (smie-indent-virtual)))
909 (tokinfo
910 (if (and (= (point) pos) (smie-bolp)
911 (or (eq offset 'point)
912 (and (consp offset) (memq 'point offset))))
913 ;; Since we started at BOL, we're not computing a virtual
914 ;; indentation, and we're still at the starting point, so
915 ;; we can't use `current-column' which would cause
916 ;; indentation to depend on itself.
917 nil
918 (smie-indent-column offset 'parent parent
919 ;; If we're still at pos, indent-virtual
920 ;; will inf-loop.
921 (unless (= (point) pos) 'virtual))))))))))
922
923 (defun smie-indent-comment ()
924 "Compute indentation of a comment."
925 ;; Don't do it for virtual indentations. We should normally never be "in
926 ;; front of a comment" when doing virtual-indentation anyway. And if we are
927 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
928 (and (smie-bolp)
929 (looking-at comment-start-skip)
930 (save-excursion
931 (forward-comment (point-max))
932 (skip-chars-forward " \t\r\n")
933 (smie-indent-calculate))))
934
935 (defun smie-indent-comment-continue ()
936 ;; indentation of comment-continue lines.
937 (let ((continue (and comment-continue
938 (comment-string-strip comment-continue t t))))
939 (and (< 0 (length continue))
940 (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
941 (let ((ppss (syntax-ppss)))
942 (save-excursion
943 (forward-line -1)
944 (if (<= (point) (nth 8 ppss))
945 (progn (goto-char (1+ (nth 8 ppss))) (current-column))
946 (skip-chars-forward " \t")
947 (if (looking-at (regexp-quote continue))
948 (current-column))))))))
949
950 (defun smie-indent-after-keyword ()
951 ;; Indentation right after a special keyword.
952 (save-excursion
953 (let* ((pos (point))
954 (toklevel (smie-indent-backward-token))
955 (tok (car toklevel))
956 (tokinfo (assoc tok smie-indent-rules)))
957 ;; Set some default indent rules.
958 (if (and toklevel (null (cadr toklevel)) (null tokinfo))
959 (setq tokinfo (list (car toklevel))))
960 ;; (if (and tokinfo (null toklevel))
961 ;; (error "Token %S has indent rule but has no parsing info" tok))
962 (when toklevel
963 (unless tokinfo
964 ;; The default indentation after a keyword/operator is 0 for
965 ;; infix and t for prefix.
966 ;; Using the BNF syntax, we could come up with better
967 ;; defaults, but we only have the precedence levels here.
968 (setq tokinfo (list tok 'default-rule
969 (if (cadr toklevel) 0 (smie-indent-offset t)))))
970 (let ((offset
971 (or (smie-indent-offset-rule tokinfo pos)
972 (smie-indent-offset t))))
973 (let ((before (point)))
974 (goto-char pos)
975 (smie-indent-column offset before)))))))
976
977 (defun smie-indent-exps ()
978 ;; Indentation of sequences of simple expressions without
979 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
980 ;; Can be a list of expressions or a function call.
981 ;; If it's a function call, the first element is special (it's the
982 ;; function). We distinguish function calls from mere lists of
983 ;; expressions based on whether the preceding token is listed in
984 ;; the `list-intro' entry of smie-indent-rules.
985 ;;
986 ;; TODO: to indent Lisp code, we should add a way to specify
987 ;; particular indentation for particular args depending on the
988 ;; function (which would require always skipping back until the
989 ;; function).
990 ;; TODO: to indent C code, such as "if (...) {...}" we might need
991 ;; to add similar indentation hooks for particular positions, but
992 ;; based on the preceding token rather than based on the first exp.
993 (save-excursion
994 (let ((positions nil)
995 arg)
996 (while (and (null (car (smie-backward-sexp)))
997 (push (point) positions)
998 (not (smie-bolp))))
999 (save-excursion
1000 ;; Figure out if the atom we just skipped is an argument rather
1001 ;; than a function.
1002 (setq arg (or (null (car (smie-backward-sexp)))
1003 (member (funcall smie-backward-token-function)
1004 (cdr (assoc 'list-intro smie-indent-rules))))))
1005 (cond
1006 ((null positions)
1007 ;; We're the first expression of the list. In that case, the
1008 ;; indentation should be (have been) determined by its context.
1009 nil)
1010 (arg
1011 ;; There's a previous element, and it's not special (it's not
1012 ;; the function), so let's just align with that one.
1013 (goto-char (car positions))
1014 (current-column))
1015 ((cdr positions)
1016 ;; We skipped some args plus the function and bumped into something.
1017 ;; Align with the first arg.
1018 (goto-char (cadr positions))
1019 (current-column))
1020 (positions
1021 ;; We're the first arg.
1022 (goto-char (car positions))
1023 ;; FIXME: Use smie-indent-column.
1024 (+ (smie-indent-offset 'args)
1025 ;; We used to use (smie-indent-virtual), but that
1026 ;; doesn't seem right since it might then indent args less than
1027 ;; the function itself.
1028 (current-column)))))))
1029
1030 (defvar smie-indent-functions
1031 '(smie-indent-fixindent smie-indent-bob smie-indent-close smie-indent-comment
1032 smie-indent-comment-continue smie-indent-keyword smie-indent-after-keyword
1033 smie-indent-exps)
1034 "Functions to compute the indentation.
1035 Each function is called with no argument, shouldn't move point, and should
1036 return either nil if it has no opinion, or an integer representing the column
1037 to which that point should be aligned, if we were to reindent it.")
1038
1039 (defun smie-indent-calculate ()
1040 "Compute the indentation to use for point."
1041 (run-hook-with-args-until-success 'smie-indent-functions))
1042
1043 (defun smie-indent-line ()
1044 "Indent current line using the SMIE indentation engine."
1045 (interactive)
1046 (let* ((savep (point))
1047 (indent (condition-case-no-debug nil
1048 (save-excursion
1049 (forward-line 0)
1050 (skip-chars-forward " \t")
1051 (if (>= (point) savep) (setq savep nil))
1052 (or (smie-indent-calculate) 0))
1053 (error 0))))
1054 (if (not (numberp indent))
1055 ;; If something funny is used (e.g. `noindent'), return it.
1056 indent
1057 (if (< indent 0) (setq indent 0)) ;Just in case.
1058 (if savep
1059 (save-excursion (indent-line-to indent))
1060 (indent-line-to indent)))))
1061
1062 (defun smie-indent-debug ()
1063 "Show the rules used to compute indentation of current line."
1064 (interactive)
1065 (let ((smie-indent-debug-log '()))
1066 (smie-indent-calculate)
1067 ;; FIXME: please improve!
1068 (message "%S" smie-indent-debug-log)))
1069
1070 (defun smie-setup (op-levels indent-rules)
1071 (set (make-local-variable 'smie-indent-rules) indent-rules)
1072 (set (make-local-variable 'smie-op-levels) op-levels)
1073 (set (make-local-variable 'indent-line-function) 'smie-indent-line))
1074
1075
1076 (provide 'smie)
1077 ;;; smie.el ends here