]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/smie.el
merge changes in 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 (defun smie-down-list (&optional arg)
564 "Move forward down one level paren-like blocks. Like `down-list'.
565 With argument ARG, do this that many times.
566 A negative argument means move backward but still go down a level.
567 This command assumes point is not in a string or comment."
568 (interactive "p")
569 (let ((start (point))
570 (inc (if (< arg 0) -1 1))
571 (offset (if (< arg 0) 1 0))
572 (next-token (if (< arg 0)
573 smie-backward-token-function
574 smie-forward-token-function)))
575 (while (/= arg 0)
576 (setq arg (- arg inc))
577 (while
578 (let* ((pos (point))
579 (token (funcall next-token))
580 (levels (assoc token smie-op-levels)))
581 (cond
582 ((zerop (length token))
583 (if (if (< inc 0) (looking-back "\\s(\\|\\s)" (1- (point)))
584 (looking-at "\\s(\\|\\s)"))
585 ;; Go back to `start' in case of an error. This presumes
586 ;; none of the token we've found until now include a ( or ).
587 (progn (goto-char start) (down-list inc) nil)
588 (forward-sexp inc)
589 (/= (point) pos)))
590 ((and levels (null (nth (+ 1 offset) levels))) nil)
591 ((and levels (null (nth (- 2 offset) levels)))
592 (let ((end (point)))
593 (goto-char start)
594 (signal 'scan-error
595 (list "Containing expression ends prematurely"
596 pos end))))
597 (t)))))))
598
599 ;;; The indentation engine.
600
601 (defcustom smie-indent-basic 4
602 "Basic amount of indentation."
603 :type 'integer)
604
605 (defvar smie-indent-rules 'unset
606 ;; TODO: For SML, we need more rule formats, so as to handle
607 ;; structure Foo =
608 ;; Bar (toto)
609 ;; and
610 ;; structure Foo =
611 ;; struct ... end
612 ;; I.e. the indentation after "=" depends on the parent ("structure")
613 ;; as well as on the following token ("struct").
614 "Rules of the following form.
615 \((:before . TOK) . OFFSET-RULES) how to indent TOK itself.
616 \(TOK . OFFSET-RULES) how to indent right after TOK.
617 \(list-intro . TOKENS) declare TOKENS as being followed by what may look like
618 a funcall but is just a sequence of expressions.
619 \(t . OFFSET) basic indentation step.
620 \(args . OFFSET) indentation of arguments.
621 \((T1 . T2) OFFSET) like ((:before . T2) (:parent T1 OFFSET)).
622
623 OFFSET-RULES is a list of elements which can each either be:
624
625 \(:hanging . OFFSET-RULES) if TOK is hanging, use OFFSET-RULES.
626 \(:parent PARENT . OFFSET-RULES) if TOK's parent is PARENT, use OFFSET-RULES.
627 \(:next TOKEN . OFFSET-RULES) if TOK is followed by TOKEN, use OFFSET-RULES.
628 \(:prev TOKEN . OFFSET-RULES) if TOK is preceded by TOKEN, use
629 \(:bolp . OFFSET-RULES) If TOK is first on a line, use OFFSET-RULES.
630 OFFSET the offset to use.
631
632 PARENT can be either the name of the parent or a list of such names.
633
634 OFFSET can be of the form:
635 `point' align with the token.
636 `parent' align with the parent.
637 NUMBER offset by NUMBER.
638 \(+ OFFSETS...) use the sum of OFFSETS.
639 VARIABLE use the value of VARIABLE as offset.
640
641 The precise meaning of `point' depends on various details: it can
642 either mean the position of the token we're indenting, or the
643 position of its parent, or the position right after its parent.
644
645 A nil offset for indentation after an opening token defaults
646 to `smie-indent-basic'.")
647
648 (defun smie-indent-hanging-p ()
649 ;; A hanging keyword is one that's at the end of a line except it's not at
650 ;; the beginning of a line.
651 (and (save-excursion
652 (when (zerop (length (funcall smie-forward-token-function)))
653 ;; Could be an open-paren.
654 (forward-char 1))
655 (skip-chars-forward " \t")
656 (eolp))
657 (not (smie-bolp))))
658
659 (defun smie-bolp ()
660 (save-excursion (skip-chars-backward " \t") (bolp)))
661
662 (defun smie-indent-offset (elem)
663 (or (cdr (assq elem smie-indent-rules))
664 (cdr (assq t smie-indent-rules))
665 smie-indent-basic))
666
667 (defvar smie-indent-debug-log)
668
669 (defun smie-indent-offset-rule (tokinfo &optional after parent)
670 "Apply the OFFSET-RULES in TOKINFO.
671 Point is expected to be right in front of the token corresponding to TOKINFO.
672 If computing the indentation after the token, then AFTER is the position
673 after the token, otherwise it should be nil.
674 PARENT if non-nil should be the parent info returned by `smie-backward-sexp'."
675 (let ((rules (cdr tokinfo))
676 next prev
677 offset)
678 (while (consp rules)
679 (let ((rule (pop rules)))
680 (cond
681 ((not (consp rule)) (setq offset rule))
682 ((eq (car rule) '+) (setq offset rule))
683 ((eq (car rule) :hanging)
684 (when (smie-indent-hanging-p)
685 (setq rules (cdr rule))))
686 ((eq (car rule) :bolp)
687 (when (smie-bolp)
688 (setq rules (cdr rule))))
689 ((eq (car rule) :eolp)
690 (unless after
691 (error "Can't use :eolp in :before indentation rules"))
692 (when (> after (line-end-position))
693 (setq rules (cdr rule))))
694 ((eq (car rule) :prev)
695 (unless prev
696 (save-excursion
697 (setq prev (smie-indent-backward-token))))
698 (when (equal (car prev) (cadr rule))
699 (setq rules (cddr rule))))
700 ((eq (car rule) :next)
701 (unless next
702 (unless after
703 (error "Can't use :next in :before indentation rules"))
704 (save-excursion
705 (goto-char after)
706 (setq next (smie-indent-forward-token))))
707 (when (equal (car next) (cadr rule))
708 (setq rules (cddr rule))))
709 ((eq (car rule) :parent)
710 (unless parent
711 (save-excursion
712 (if after (goto-char after))
713 (setq parent (smie-backward-sexp 'halfsexp))))
714 (when (if (listp (cadr rule))
715 (member (nth 2 parent) (cadr rule))
716 (equal (nth 2 parent) (cadr rule)))
717 (setq rules (cddr rule))))
718 (t (error "Unknown rule %s for indentation of %s"
719 rule (car tokinfo))))))
720 ;; If `offset' is not set yet, use `rules' to handle the case where
721 ;; the tokinfo uses the old-style ((PARENT . TOK). OFFSET).
722 (unless offset (setq offset rules))
723 (when (boundp 'smie-indent-debug-log)
724 (push (list (point) offset tokinfo) smie-indent-debug-log))
725 offset))
726
727 (defun smie-indent-column (offset &optional base parent virtual-point)
728 "Compute the actual column to use for a given OFFSET.
729 BASE is the base position to use, and PARENT is the parent info, if any.
730 If VIRTUAL-POINT is non-nil, then `point' is virtual."
731 (cond
732 ((eq (car-safe offset) '+)
733 (apply '+ (mapcar (lambda (offset) (smie-indent-column offset nil parent))
734 (cdr offset))))
735 ((integerp offset)
736 (+ offset
737 (case base
738 ((nil) 0)
739 (parent (goto-char (cadr parent))
740 (smie-indent-virtual))
741 (t
742 (goto-char base)
743 ;; For indentation after "(let" in SML-mode, we end up accumulating
744 ;; the offset of "(" and the offset of "let", so we use `min' to try
745 ;; and get it right either way.
746 (min (smie-indent-virtual) (current-column))))))
747 ((eq offset 'point)
748 ;; In indent-keyword, if we're indenting `then' wrt `if', we want to use
749 ;; indent-virtual rather than use just current-column, so that we can
750 ;; apply the (:before . "if") rule which does the "else if" dance in SML.
751 ;; But in other cases, we do not want to use indent-virtual
752 ;; (e.g. indentation of "*" w.r.t "+", or ";" wrt "("). We could just
753 ;; always use indent-virtual and then have indent-rules say explicitly
754 ;; to use `point' after things like "(" or "+" when they're not at EOL,
755 ;; but you'd end up with lots of those rules.
756 ;; So we use a heuristic here, which is that we only use virtual if
757 ;; the parent is tightly linked to the child token (they're part of
758 ;; the same BNF rule).
759 (if (and virtual-point (null (car parent))) ;Black magic :-(
760 (smie-indent-virtual) (current-column)))
761 ((eq offset 'parent)
762 (unless parent
763 (setq parent (or (smie-backward-sexp 'halfsexp) :notfound)))
764 (if (consp parent) (goto-char (cadr parent)))
765 (smie-indent-virtual))
766 ((eq offset nil) nil)
767 ((and (symbolp offset) (boundp 'offset))
768 (smie-indent-column (symbol-value offset) base parent virtual-point))
769 (t (error "Unknown indentation offset %s" offset))))
770
771 (defun smie-indent-forward-token ()
772 "Skip token forward and return it, along with its levels."
773 (let ((tok (funcall smie-forward-token-function)))
774 (cond
775 ((< 0 (length tok)) (assoc tok smie-op-levels))
776 ((looking-at "\\s(")
777 (forward-char 1)
778 (list (buffer-substring (1- (point)) (point)) nil 0)))))
779
780 (defun smie-indent-backward-token ()
781 "Skip token backward and return it, along with its levels."
782 (let ((tok (funcall smie-backward-token-function)))
783 (cond
784 ((< 0 (length tok)) (assoc tok smie-op-levels))
785 ;; 4 == Open paren syntax.
786 ((eq 4 (syntax-class (syntax-after (1- (point)))))
787 (forward-char -1)
788 (list (buffer-substring (point) (1+ (point))) nil 0)))))
789
790 (defun smie-indent-virtual ()
791 ;; We used to take an optional arg (with value :not-hanging) to specify that
792 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
793 ;; keyword. This was a bad idea, because the virtual indent of a position
794 ;; should not depend on the caller, since it leads to situations where two
795 ;; dependent indentations get indented differently.
796 "Compute the virtual indentation to use for point.
797 This is used when we're not trying to indent point but just
798 need to compute the column at which point should be indented
799 in order to figure out the indentation of some other (further down) point."
800 ;; Trust pre-existing indentation on other lines.
801 (if (smie-bolp) (current-column) (smie-indent-calculate)))
802
803 (defun smie-indent-fixindent ()
804 ;; Obey the `fixindent' special comment.
805 (and (smie-bolp)
806 (save-excursion
807 (comment-normalize-vars)
808 (re-search-forward (concat comment-start-skip
809 "fixindent"
810 comment-end-skip)
811 ;; 1+ to account for the \n comment termination.
812 (1+ (line-end-position)) t))
813 (current-column)))
814
815 (defun smie-indent-bob ()
816 ;; Start the file at column 0.
817 (save-excursion
818 (forward-comment (- (point)))
819 (if (bobp) 0)))
820
821 (defun smie-indent-close ()
822 ;; Align close paren with opening paren.
823 (save-excursion
824 ;; (forward-comment (point-max))
825 (when (looking-at "\\s)")
826 (while (not (zerop (skip-syntax-forward ")")))
827 (skip-chars-forward " \t"))
828 (condition-case nil
829 (progn
830 (backward-sexp 1)
831 (smie-indent-virtual)) ;:not-hanging
832 (scan-error nil)))))
833
834 (defun smie-indent-keyword ()
835 ;; Align closing token with the corresponding opening one.
836 ;; (e.g. "of" with "case", or "in" with "let").
837 (save-excursion
838 (let* ((pos (point))
839 (toklevels (smie-indent-forward-token))
840 (token (pop toklevels)))
841 (if (null (car toklevels))
842 (save-excursion
843 (goto-char pos)
844 ;; Different cases:
845 ;; - smie-bolp: "indent according to others".
846 ;; - common hanging: "indent according to others".
847 ;; - SML-let hanging: "indent like parent".
848 ;; - if-after-else: "indent-like parent".
849 ;; - middle-of-line: "trust current position".
850 (cond
851 ((null (cdr toklevels)) nil) ;Not a keyword.
852 ((smie-bolp)
853 ;; For an open-paren-like thingy at BOL, always indent only
854 ;; based on other rules (typically smie-indent-after-keyword).
855 nil)
856 (t
857 ;; We're only ever here for virtual-indent, which is why
858 ;; we can use (current-column) as answer for `point'.
859 (let* ((tokinfo (or (assoc (cons :before token)
860 smie-indent-rules)
861 ;; By default use point unless we're hanging.
862 `((:before . ,token) (:hanging nil) point)))
863 ;; (after (prog1 (point) (goto-char pos)))
864 (offset (smie-indent-offset-rule tokinfo)))
865 (smie-indent-column offset)))))
866
867 ;; FIXME: This still looks too much like black magic!!
868 ;; FIXME: Rather than a bunch of rules like (PARENT . TOKEN), we
869 ;; want a single rule for TOKEN with different cases for each PARENT.
870 (let* ((parent (smie-backward-sexp 'halfsexp))
871 (tokinfo
872 (or (assoc (cons (caddr parent) token)
873 smie-indent-rules)
874 (assoc (cons :before token) smie-indent-rules)
875 ;; Default rule.
876 `((:before . ,token)
877 ;; (:parent open 0)
878 point)))
879 (offset (save-excursion
880 (goto-char pos)
881 (smie-indent-offset-rule tokinfo nil parent))))
882 ;; Different behaviors:
883 ;; - align with parent.
884 ;; - parent + offset.
885 ;; - after parent's column + offset (actually, after or before
886 ;; depending on where backward-sexp stopped).
887 ;; ? let it drop to some other indentation function (almost never).
888 ;; ? parent + offset + parent's own offset.
889 ;; Different cases:
890 ;; - bump into a same-level operator.
891 ;; - bump into a specific known parent.
892 ;; - find a matching open-paren thingy.
893 ;; - bump into some random parent.
894 ;; ? borderline case (almost never).
895 ;; ? bump immediately into a parent.
896 (cond
897 ((not (or (< (point) pos)
898 (and (cadr parent) (< (cadr parent) pos))))
899 ;; If we didn't move at all, that means we didn't really skip
900 ;; what we wanted. Should almost never happen, other than
901 ;; maybe when an infix or close-paren is at the beginning
902 ;; of a buffer.
903 nil)
904 ((eq (car parent) (car toklevels))
905 ;; We bumped into a same-level operator. align with it.
906 (if (and (smie-bolp) (/= (point) pos)
907 (save-excursion
908 (goto-char (goto-char (cadr parent)))
909 (not (smie-bolp)))
910 ;; Check the offset of `token' rather then its parent
911 ;; because its parent may have used a special rule. E.g.
912 ;; function foo;
913 ;; line2;
914 ;; line3;
915 ;; The ; on the first line had a special rule, but when
916 ;; indenting line3, we don't care about it and want to
917 ;; align with line2.
918 (memq offset '(point nil)))
919 ;; If the parent is at EOL and its children are indented like
920 ;; itself, then we can just obey the indentation chosen for the
921 ;; child.
922 ;; This is important for operators like ";" which
923 ;; are usually at EOL (and have an offset of 0): otherwise we'd
924 ;; always go back over all the statements, which is
925 ;; a performance problem and would also mean that fixindents
926 ;; in the middle of such a sequence would be ignored.
927 ;;
928 ;; This is a delicate point!
929 ;; Even if the offset is not 0, we could follow the same logic
930 ;; and subtract the offset from the child's indentation.
931 ;; But that would more often be a bad idea: OT1H we generally
932 ;; want to reuse the closest similar indentation point, so that
933 ;; the user's choice (or the fixindents) are obeyed. But OTOH
934 ;; we don't want this to affect "unrelated" parts of the code.
935 ;; E.g. a fixindent in the body of a "begin..end" should not
936 ;; affect the indentation of the "end".
937 (current-column)
938 (goto-char (cadr parent))
939 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
940 ;; want to jump back over a sequence of same-level ops such as
941 ;; a -> b -> c
942 ;; -> d
943 ;; So as to align with the earliest appropriate place.
944 (smie-indent-virtual)))
945 (tokinfo
946 (if (and (= (point) pos) (smie-bolp)
947 (or (eq offset 'point)
948 (and (consp offset) (memq 'point offset))))
949 ;; Since we started at BOL, we're not computing a virtual
950 ;; indentation, and we're still at the starting point, so
951 ;; we can't use `current-column' which would cause
952 ;; indentation to depend on itself.
953 nil
954 (smie-indent-column offset 'parent parent
955 ;; If we're still at pos, indent-virtual
956 ;; will inf-loop.
957 (unless (= (point) pos) 'virtual))))))))))
958
959 (defun smie-indent-comment ()
960 "Compute indentation of a comment."
961 ;; Don't do it for virtual indentations. We should normally never be "in
962 ;; front of a comment" when doing virtual-indentation anyway. And if we are
963 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
964 (and (smie-bolp)
965 (looking-at comment-start-skip)
966 (save-excursion
967 (forward-comment (point-max))
968 (skip-chars-forward " \t\r\n")
969 (smie-indent-calculate))))
970
971 (defun smie-indent-comment-continue ()
972 ;; indentation of comment-continue lines.
973 (let ((continue (and comment-continue
974 (comment-string-strip comment-continue t t))))
975 (and (< 0 (length continue))
976 (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
977 (let ((ppss (syntax-ppss)))
978 (save-excursion
979 (forward-line -1)
980 (if (<= (point) (nth 8 ppss))
981 (progn (goto-char (1+ (nth 8 ppss))) (current-column))
982 (skip-chars-forward " \t")
983 (if (looking-at (regexp-quote continue))
984 (current-column))))))))
985
986 (defun smie-indent-after-keyword ()
987 ;; Indentation right after a special keyword.
988 (save-excursion
989 (let* ((pos (point))
990 (toklevel (smie-indent-backward-token))
991 (tok (car toklevel))
992 (tokinfo (assoc tok smie-indent-rules)))
993 ;; Set some default indent rules.
994 (if (and toklevel (null (cadr toklevel)) (null tokinfo))
995 (setq tokinfo (list (car toklevel))))
996 ;; (if (and tokinfo (null toklevel))
997 ;; (error "Token %S has indent rule but has no parsing info" tok))
998 (when toklevel
999 (unless tokinfo
1000 ;; The default indentation after a keyword/operator is 0 for
1001 ;; infix and t for prefix.
1002 ;; Using the BNF syntax, we could come up with better
1003 ;; defaults, but we only have the precedence levels here.
1004 (setq tokinfo (list tok 'default-rule
1005 (if (cadr toklevel) 0 (smie-indent-offset t)))))
1006 (let ((offset
1007 (or (smie-indent-offset-rule tokinfo pos)
1008 (smie-indent-offset t))))
1009 (let ((before (point)))
1010 (goto-char pos)
1011 (smie-indent-column offset before)))))))
1012
1013 (defun smie-indent-exps ()
1014 ;; Indentation of sequences of simple expressions without
1015 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
1016 ;; Can be a list of expressions or a function call.
1017 ;; If it's a function call, the first element is special (it's the
1018 ;; function). We distinguish function calls from mere lists of
1019 ;; expressions based on whether the preceding token is listed in
1020 ;; the `list-intro' entry of smie-indent-rules.
1021 ;;
1022 ;; TODO: to indent Lisp code, we should add a way to specify
1023 ;; particular indentation for particular args depending on the
1024 ;; function (which would require always skipping back until the
1025 ;; function).
1026 ;; TODO: to indent C code, such as "if (...) {...}" we might need
1027 ;; to add similar indentation hooks for particular positions, but
1028 ;; based on the preceding token rather than based on the first exp.
1029 (save-excursion
1030 (let ((positions nil)
1031 arg)
1032 (while (and (null (car (smie-backward-sexp)))
1033 (push (point) positions)
1034 (not (smie-bolp))))
1035 (save-excursion
1036 ;; Figure out if the atom we just skipped is an argument rather
1037 ;; than a function.
1038 (setq arg (or (null (car (smie-backward-sexp)))
1039 (member (funcall smie-backward-token-function)
1040 (cdr (assoc 'list-intro smie-indent-rules))))))
1041 (cond
1042 ((null positions)
1043 ;; We're the first expression of the list. In that case, the
1044 ;; indentation should be (have been) determined by its context.
1045 nil)
1046 (arg
1047 ;; There's a previous element, and it's not special (it's not
1048 ;; the function), so let's just align with that one.
1049 (goto-char (car positions))
1050 (current-column))
1051 ((cdr positions)
1052 ;; We skipped some args plus the function and bumped into something.
1053 ;; Align with the first arg.
1054 (goto-char (cadr positions))
1055 (current-column))
1056 (positions
1057 ;; We're the first arg.
1058 (goto-char (car positions))
1059 ;; FIXME: Use smie-indent-column.
1060 (+ (smie-indent-offset 'args)
1061 ;; We used to use (smie-indent-virtual), but that
1062 ;; doesn't seem right since it might then indent args less than
1063 ;; the function itself.
1064 (current-column)))))))
1065
1066 (defvar smie-indent-functions
1067 '(smie-indent-fixindent smie-indent-bob smie-indent-close smie-indent-comment
1068 smie-indent-comment-continue smie-indent-keyword smie-indent-after-keyword
1069 smie-indent-exps)
1070 "Functions to compute the indentation.
1071 Each function is called with no argument, shouldn't move point, and should
1072 return either nil if it has no opinion, or an integer representing the column
1073 to which that point should be aligned, if we were to reindent it.")
1074
1075 (defun smie-indent-calculate ()
1076 "Compute the indentation to use for point."
1077 (run-hook-with-args-until-success 'smie-indent-functions))
1078
1079 (defun smie-indent-line ()
1080 "Indent current line using the SMIE indentation engine."
1081 (interactive)
1082 (let* ((savep (point))
1083 (indent (condition-case-no-debug nil
1084 (save-excursion
1085 (forward-line 0)
1086 (skip-chars-forward " \t")
1087 (if (>= (point) savep) (setq savep nil))
1088 (or (smie-indent-calculate) 0))
1089 (error 0))))
1090 (if (not (numberp indent))
1091 ;; If something funny is used (e.g. `noindent'), return it.
1092 indent
1093 (if (< indent 0) (setq indent 0)) ;Just in case.
1094 (if savep
1095 (save-excursion (indent-line-to indent))
1096 (indent-line-to indent)))))
1097
1098 (defun smie-indent-debug ()
1099 "Show the rules used to compute indentation of current line."
1100 (interactive)
1101 (let ((smie-indent-debug-log '()))
1102 (smie-indent-calculate)
1103 ;; FIXME: please improve!
1104 (message "%S" smie-indent-debug-log)))
1105
1106 (defun smie-setup (op-levels indent-rules)
1107 (set (make-local-variable 'smie-indent-rules) indent-rules)
1108 (set (make-local-variable 'smie-op-levels) op-levels)
1109 (set (make-local-variable 'indent-line-function) 'smie-indent-line))
1110
1111
1112 (provide 'smie)
1113 ;;; smie.el ends here