]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/smie.el
Merge changes from emacs-23 branch.
[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 `open' to mean any parent
597 which acts as an open-paren (i.e. has a nil left-precedence).
598
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.
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 a token defaults to `smie-indent-basic'.")
610
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.
614 (and (save-excursion
615 (when (zerop (length (funcall smie-forward-token-function)))
616 ;; Could be an open-paren.
617 (forward-char 1))
618 (skip-chars-forward " \t")
619 (eolp))
620 (not (smie-bolp))))
621
622 (defun smie-bolp ()
623 (save-excursion (skip-chars-backward " \t") (bolp)))
624
625 (defun smie-indent-offset (elem)
626 (or (cdr (assq elem smie-indent-rules))
627 (cdr (assq t smie-indent-rules))
628 smie-indent-basic))
629
630 (defvar smie-indent-debug-log)
631
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))
639 next prev
640 offset)
641 (while (consp rules)
642 (let ((rule (pop rules)))
643 (cond
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)
650 (when (smie-bolp)
651 (setq rules (cdr rule))))
652 ((eq (car rule) :eolp)
653 (unless after
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)
658 (unless prev
659 (save-excursion
660 (setq prev (smie-indent-backward-token))))
661 (when (equal (car prev) (cadr rule))
662 (setq rules (cddr rule))))
663 ((eq (car rule) :next)
664 (unless next
665 (unless after
666 (error "Can't use :next in :before indentation rules"))
667 (save-excursion
668 (goto-char after)
669 (setq next (smie-indent-forward-token))))
670 (when (equal (car next) (cadr rule))
671 (setq rules (cddr rule))))
672 ((eq (car rule) :parent)
673 (unless parent
674 (save-excursion
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))
687 offset))
688
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."
693 (cond
694 ((eq (car-safe offset) '+)
695 (apply '+ (mapcar (lambda (offset) (smie-indent-column offset nil parent))
696 (cdr offset))))
697 ((integerp offset)
698 (+ offset
699 (case base
700 ((nil) 0)
701 (parent (goto-char (cadr parent))
702 (smie-indent-virtual))
703 (t
704 (goto-char base)
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))))))
709 ((eq offset 'point)
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)))
723 ((eq offset 'parent)
724 (unless parent
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))))
730
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)))
734 (cond
735 ((< 0 (length tok)) (assoc tok smie-op-levels))
736 ((looking-at "\\s(")
737 (forward-char 1)
738 (list (buffer-substring (1- (point)) (point)) nil 0)))))
739
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)))
743 (cond
744 ((< 0 (length tok)) (assoc tok smie-op-levels))
745 ;; 4 == Open paren syntax.
746 ((eq 4 (syntax-class (syntax-after (1- (point)))))
747 (forward-char -1)
748 (list (buffer-substring (point) (1+ (point))) nil 0)))))
749
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)))
762
763 (defun smie-indent-fixindent ()
764 ;; Obey the `fixindent' special comment.
765 (and (smie-bolp)
766 (save-excursion
767 (comment-normalize-vars)
768 (re-search-forward (concat comment-start-skip
769 "fixindent"
770 comment-end-skip)
771 ;; 1+ to account for the \n comment termination.
772 (1+ (line-end-position)) t))
773 (current-column)))
774
775 (defun smie-indent-bob ()
776 ;; Start the file at column 0.
777 (save-excursion
778 (forward-comment (- (point)))
779 (if (bobp) 0)))
780
781 (defun smie-indent-close ()
782 ;; Align close paren with opening paren.
783 (save-excursion
784 ;; (forward-comment (point-max))
785 (when (looking-at "\\s)")
786 (while (not (zerop (skip-syntax-forward ")")))
787 (skip-chars-forward " \t"))
788 (condition-case nil
789 (progn
790 (backward-sexp 1)
791 (smie-indent-virtual)) ;:not-hanging
792 (scan-error nil)))))
793
794 (defun smie-indent-keyword ()
795 ;; Align closing token with the corresponding opening one.
796 ;; (e.g. "of" with "case", or "in" with "let").
797 (save-excursion
798 (let* ((pos (point))
799 (toklevels (smie-indent-forward-token))
800 (token (pop toklevels)))
801 (if (null (car toklevels))
802 (save-excursion
803 (goto-char pos)
804 ;; Different cases:
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".
810 (cond
811 ((null (cdr toklevels)) nil) ;Not a keyword.
812 ((smie-bolp)
813 ;; For an open-paren-like thingy at BOL, always indent only
814 ;; based on other rules (typically smie-indent-after-keyword).
815 nil)
816 (t
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)
820 smie-indent-rules)
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)))))
826
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))
831 (tokinfo
832 (or (assoc (cons (caddr parent) token)
833 smie-indent-rules)
834 (assoc (cons :before token) smie-indent-rules)
835 ;; Default rule.
836 `((:before . ,token)
837 ;; (:parent open 0)
838 point)))
839 (offset (save-excursion
840 (goto-char pos)
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.
849 ;; Different cases:
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.
856 (cond
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
862 ;; of a buffer.
863 nil)
864 ((eq (car parent) (car toklevels))
865 ;; We bumped into a same-level operator. align with it.
866 (if (and (smie-bolp) (/= (point) pos)
867 (save-excursion
868 (goto-char (goto-char (cadr parent)))
869 (not (smie-bolp)))
870 ;; Check the offset of `token' rather then its parent
871 ;; because its parent may have used a special rule. E.g.
872 ;; function foo;
873 ;; line2;
874 ;; line3;
875 ;; The ; on the first line had a special rule, but when
876 ;; indenting line3, we don't care about it and want to
877 ;; align with line2.
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
881 ;; child.
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.
887 ;;
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".
897 (current-column)
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
901 ;; a -> b -> c
902 ;; -> d
903 ;; So as to align with the earliest appropriate place.
904 (smie-indent-virtual)))
905 (tokinfo
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.
913 nil
914 (smie-indent-column offset 'parent parent
915 ;; If we're still at pos, indent-virtual
916 ;; will inf-loop.
917 (unless (= (point) pos) 'virtual))))))))))
918
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.
924 (and (smie-bolp)
925 (looking-at comment-start-skip)
926 (save-excursion
927 (forward-comment (point-max))
928 (skip-chars-forward " \t\r\n")
929 (smie-indent-calculate))))
930
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)))
938 (save-excursion
939 (forward-line -1)
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))))))))
945
946 (defun smie-indent-after-keyword ()
947 ;; Indentation right after a special keyword.
948 (save-excursion
949 (let* ((pos (point))
950 (toklevel (smie-indent-backward-token))
951 (tok (car toklevel))
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))
958 (when toklevel
959 (unless tokinfo
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)))))
966 (let ((offset
967 (or (smie-indent-offset-rule tokinfo pos)
968 (smie-indent-offset t))))
969 (let ((before (point)))
970 (goto-char pos)
971 (smie-indent-column offset before)))))))
972
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.
981 ;;
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
985 ;; function).
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.
989 (save-excursion
990 (let ((positions nil)
991 arg)
992 (while (and (null (car (smie-backward-sexp)))
993 (push (point) positions)
994 (not (smie-bolp))))
995 (save-excursion
996 ;; Figure out if the atom we just skipped is an argument rather
997 ;; than a function.
998 (setq arg (or (null (car (smie-backward-sexp)))
999 (member (funcall smie-backward-token-function)
1000 (cdr (assoc 'list-intro smie-indent-rules))))))
1001 (cond
1002 ((null positions)
1003 ;; We're the first expression of the list. In that case, the
1004 ;; indentation should be (have been) determined by its context.
1005 nil)
1006 (arg
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))
1010 (current-column))
1011 ((cdr positions)
1012 ;; We skipped some args plus the function and bumped into something.
1013 ;; Align with the first arg.
1014 (goto-char (cadr positions))
1015 (current-column))
1016 (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)))))))
1024
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
1028 smie-indent-exps)
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.")
1033
1034 (defun smie-indent-calculate ()
1035 "Compute the indentation to use for point."
1036 (run-hook-with-args-until-success 'smie-indent-functions))
1037
1038 (defun smie-indent-line ()
1039 "Indent current line using the SMIE indentation engine."
1040 (interactive)
1041 (let* ((savep (point))
1042 (indent (condition-case-no-debug nil
1043 (save-excursion
1044 (forward-line 0)
1045 (skip-chars-forward " \t")
1046 (if (>= (point) savep) (setq savep nil))
1047 (or (smie-indent-calculate) 0))
1048 (error 0))))
1049 (if (not (numberp indent))
1050 ;; If something funny is used (e.g. `noindent'), return it.
1051 indent
1052 (if (< indent 0) (setq indent 0)) ;Just in case.
1053 (if savep
1054 (save-excursion (indent-line-to indent))
1055 (indent-line-to indent)))))
1056
1057 (defun smie-indent-debug ()
1058 "Show the rules used to compute indentation of current line."
1059 (interactive)
1060 (let ((smie-indent-debug-log '()))
1061 (smie-indent-calculate)
1062 ;; FIXME: please improve!
1063 (message "%S" smie-indent-debug-log)))
1064
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))
1069
1070
1071 (provide 'smie)
1072 ;;; smie.el ends here