]> 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 (eval-when-compile (require 'cl))
69
70 (defvar comment-continue)
71 (declare-function comment-string-strip "newcomment" (str beforep afterp))
72
73 ;;; Building precedence level tables from BNF specs.
74
75 (defun smie-set-prec2tab (table x y val &optional override)
76 (assert (and x y))
77 (let* ((key (cons x y))
78 (old (gethash key table)))
79 (if (and old (not (eq old val)))
80 (if (and override (gethash key override))
81 ;; FIXME: The override is meant to resolve ambiguities,
82 ;; but it also hides real conflicts. It would be great to
83 ;; be able to distinguish the two cases so that overrides
84 ;; don't hide real conflicts.
85 (puthash key (gethash key override) table)
86 (display-warning 'smie (format "Conflict: %s %s/%s %s" x old val y)))
87 (puthash key val table))))
88
89 (defun smie-precs-precedence-table (precs)
90 "Compute a 2D precedence table from a list of precedences.
91 PRECS should be a list, sorted by precedence (e.g. \"+\" will
92 come before \"*\"), of elements of the form \(left OP ...)
93 or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
94 one of those elements share the same precedence level and associativity."
95 (let ((prec2-table (make-hash-table :test 'equal)))
96 (dolist (prec precs)
97 (dolist (op (cdr prec))
98 (let ((selfrule (cdr (assq (car prec)
99 '((left . >) (right . <) (assoc . =))))))
100 (when selfrule
101 (dolist (other-op (cdr prec))
102 (smie-set-prec2tab prec2-table op other-op selfrule))))
103 (let ((op1 '<) (op2 '>))
104 (dolist (other-prec precs)
105 (if (eq prec other-prec)
106 (setq op1 '> op2 '<)
107 (dolist (other-op (cdr other-prec))
108 (smie-set-prec2tab prec2-table op other-op op2)
109 (smie-set-prec2tab prec2-table other-op op op1)))))))
110 prec2-table))
111
112 (defun smie-merge-prec2s (&rest tables)
113 (if (null (cdr tables))
114 (car tables)
115 (let ((prec2 (make-hash-table :test 'equal)))
116 (dolist (table tables)
117 (maphash (lambda (k v)
118 (smie-set-prec2tab prec2 (car k) (cdr k) v))
119 table))
120 prec2)))
121
122 (defun smie-bnf-precedence-table (bnf &rest precs)
123 (let ((nts (mapcar 'car bnf)) ;Non-terminals
124 (first-ops-table ())
125 (last-ops-table ())
126 (first-nts-table ())
127 (last-nts-table ())
128 (prec2 (make-hash-table :test 'equal))
129 (override (apply 'smie-merge-prec2s
130 (mapcar 'smie-precs-precedence-table precs)))
131 again)
132 (dolist (rules bnf)
133 (let ((nt (car rules))
134 (last-ops ())
135 (first-ops ())
136 (last-nts ())
137 (first-nts ()))
138 (dolist (rhs (cdr rules))
139 (assert (consp rhs))
140 (if (not (member (car rhs) nts))
141 (pushnew (car rhs) first-ops)
142 (pushnew (car rhs) first-nts)
143 (when (consp (cdr rhs))
144 ;; If the first is not an OP we add the second (which
145 ;; should be an OP if BNF is an "operator grammar").
146 ;; Strictly speaking, this should only be done if the
147 ;; first is a non-terminal which can expand to a phrase
148 ;; without any OP in it, but checking doesn't seem worth
149 ;; the trouble, and it lets the writer of the BNF
150 ;; be a bit more sloppy by skipping uninteresting base
151 ;; cases which are terminals but not OPs.
152 (assert (not (member (cadr rhs) nts)))
153 (pushnew (cadr rhs) first-ops)))
154 (let ((shr (reverse rhs)))
155 (if (not (member (car shr) nts))
156 (pushnew (car shr) last-ops)
157 (pushnew (car shr) last-nts)
158 (when (consp (cdr shr))
159 (assert (not (member (cadr shr) nts)))
160 (pushnew (cadr shr) last-ops)))))
161 (push (cons nt first-ops) first-ops-table)
162 (push (cons nt last-ops) last-ops-table)
163 (push (cons nt first-nts) first-nts-table)
164 (push (cons nt last-nts) last-nts-table)))
165 ;; Compute all first-ops by propagating the initial ones we have
166 ;; now, according to first-nts.
167 (setq again t)
168 (while (prog1 again (setq again nil))
169 (dolist (first-nts first-nts-table)
170 (let* ((nt (pop first-nts))
171 (first-ops (assoc nt first-ops-table)))
172 (dolist (first-nt first-nts)
173 (dolist (op (cdr (assoc first-nt first-ops-table)))
174 (unless (member op first-ops)
175 (setq again t)
176 (push op (cdr first-ops))))))))
177 ;; Same thing for last-ops.
178 (setq again t)
179 (while (prog1 again (setq again nil))
180 (dolist (last-nts last-nts-table)
181 (let* ((nt (pop last-nts))
182 (last-ops (assoc nt last-ops-table)))
183 (dolist (last-nt last-nts)
184 (dolist (op (cdr (assoc last-nt last-ops-table)))
185 (unless (member op last-ops)
186 (setq again t)
187 (push op (cdr last-ops))))))))
188 ;; Now generate the 2D precedence table.
189 (dolist (rules bnf)
190 (dolist (rhs (cdr rules))
191 (while (cdr rhs)
192 (cond
193 ((member (car rhs) nts)
194 (dolist (last (cdr (assoc (car rhs) last-ops-table)))
195 (smie-set-prec2tab prec2 last (cadr rhs) '> override)))
196 ((member (cadr rhs) nts)
197 (dolist (first (cdr (assoc (cadr rhs) first-ops-table)))
198 (smie-set-prec2tab prec2 (car rhs) first '< override))
199 (if (and (cddr rhs) (not (member (car (cddr rhs)) nts)))
200 (smie-set-prec2tab prec2 (car rhs) (car (cddr rhs))
201 '= override)))
202 (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
203 (setq rhs (cdr rhs)))))
204 prec2))
205
206 (defun smie-prec2-levels (prec2)
207 "Take a 2D precedence table and turn it into an alist of precedence levels.
208 PREC2 is a table as returned by `smie-precs-precedence-table' or
209 `smie-bnf-precedence-table'."
210 ;; For each operator, we create two "variables" (corresponding to
211 ;; the left and right precedence level), which are represented by
212 ;; cons cells. Those are the vary cons cells that appear in the
213 ;; final `table'. The value of each "variable" is kept in the `car'.
214 (let ((table ())
215 (csts ())
216 (eqs ())
217 tmp x y)
218 ;; From `prec2' we construct a list of constraints between
219 ;; variables (aka "precedence levels"). These can be either
220 ;; equality constraints (in `eqs') or `<' constraints (in `csts').
221 (maphash (lambda (k v)
222 (if (setq tmp (assoc (car k) table))
223 (setq x (cddr tmp))
224 (setq x (cons nil nil))
225 (push (cons (car k) (cons nil x)) table))
226 (if (setq tmp (assoc (cdr k) table))
227 (setq y (cdr tmp))
228 (setq y (cons nil (cons nil nil)))
229 (push (cons (cdr k) y) table))
230 (ecase v
231 (= (push (cons x y) eqs))
232 (< (push (cons x y) csts))
233 (> (push (cons y x) csts))))
234 prec2)
235 ;; First process the equality constraints.
236 (let ((eqs eqs))
237 (while eqs
238 (let ((from (caar eqs))
239 (to (cdar eqs)))
240 (setq eqs (cdr eqs))
241 (if (eq to from)
242 nil ;Nothing to do.
243 (dolist (other-eq eqs)
244 (if (eq from (cdr other-eq)) (setcdr other-eq to))
245 (when (eq from (car other-eq))
246 ;; This can happen because of `assoc' settings in precs
247 ;; or because of a rhs like ("op" foo "op").
248 (setcar other-eq to)))
249 (dolist (cst csts)
250 (if (eq from (cdr cst)) (setcdr cst to))
251 (if (eq from (car cst)) (setcar cst to)))))))
252 ;; Then eliminate trivial constraints iteratively.
253 (let ((i 0))
254 (while csts
255 (let ((rhvs (mapcar 'cdr csts))
256 (progress nil))
257 (dolist (cst csts)
258 (unless (memq (car cst) rhvs)
259 (setq progress t)
260 ;; We could give each var in a given iteration the same value,
261 ;; but we can also give them arbitrarily different values.
262 ;; Basically, these are vars between which there is no
263 ;; constraint (neither equality nor inequality), so
264 ;; anything will do.
265 ;; We give them arbitrary values, which means that we
266 ;; replace the "no constraint" case with either > or <
267 ;; but not =. The reason we do that is so as to try and
268 ;; distinguish associative operators (which will have
269 ;; left = right).
270 (unless (caar cst)
271 (setcar (car cst) i)
272 (incf i))
273 (setq csts (delq cst csts))))
274 (unless progress
275 (error "Can't resolve the precedence table to precedence levels")))
276 (incf i 10))
277 ;; Propagate equalities back to their source.
278 (dolist (eq (nreverse eqs))
279 (assert (or (null (caar eq)) (eq (car eq) (cdr eq))))
280 (setcar (car eq) (cadr eq)))
281 ;; Finally, fill in the remaining vars (which only appeared on the
282 ;; right side of the < constraints).
283 (dolist (x table)
284 ;; When both sides are nil, it means this operator binds very
285 ;; very tight, but it's still just an operator, so we give it
286 ;; the highest precedence.
287 ;; OTOH if only one side is nil, it usually means it's like an
288 ;; open-paren, which is very important for indentation purposes,
289 ;; so we keep it nil, to make it easier to recognize.
290 (unless (or (nth 1 x) (nth 2 x))
291 (setf (nth 1 x) i)
292 (setf (nth 2 x) i))))
293 table))
294
295 ;;; Parsing using a precedence level table.
296
297 (defvar smie-op-levels 'unset
298 "List of token parsing info.
299 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
300 Parsing is done using an operator precedence parser.
301 LEFT-LEVEL and RIGHT-LEVEL can be either numbers or nil, where nil
302 means that this operator does not bind on the corresponding side,
303 i.e. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
304 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
305 like a close-paren.")
306
307 (defvar smie-forward-token-function 'smie-default-forward-token
308 "Function to scan forward for the next token.
309 Called with no argument should return a token and move to its end.
310 If no token is found, return nil or the empty string.
311 It can return nil when bumping into a parenthesis, which lets SMIE
312 use syntax-tables to handle them in efficient C code.")
313
314 (defvar smie-backward-token-function 'smie-default-backward-token
315 "Function to scan backward the previous token.
316 Same calling convention as `smie-forward-token-function' except
317 it should move backward to the beginning of the previous token.")
318
319 (defalias 'smie-op-left 'car)
320 (defalias 'smie-op-right 'cadr)
321
322 (defun smie-default-backward-token ()
323 (forward-comment (- (point)))
324 (buffer-substring (point)
325 (progn (if (zerop (skip-syntax-backward "."))
326 (skip-syntax-backward "w_'"))
327 (point))))
328
329 (defun smie-default-forward-token ()
330 (forward-comment (point-max))
331 (buffer-substring (point)
332 (progn (if (zerop (skip-syntax-forward "."))
333 (skip-syntax-forward "w_'"))
334 (point))))
335
336 (defun smie-associative-p (toklevels)
337 ;; in "a + b + c" we want to stop at each +, but in
338 ;; "if a then b else c" we don't want to stop at each keyword.
339 ;; To distinguish the two cases, we made smie-prec2-levels choose
340 ;; different levels for each part of "if a then b else c", so that
341 ;; by checking if the left-level is equal to the right level, we can
342 ;; figure out that it's an associative operator.
343 ;; This is not 100% foolproof, tho, since a grammar like
344 ;; (exp ("A" exp "C") ("A" exp "B" exp "C"))
345 ;; will cause "B" to have equal left and right levels, even though
346 ;; it is not an associative operator.
347 ;; A better check would be the check the actual previous operator
348 ;; against this one to see if it's the same, but we'd have to change
349 ;; `levels' to keep a stack of operators rather than only levels.
350 (eq (smie-op-left toklevels) (smie-op-right toklevels)))
351
352 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
353 "Skip over one sexp.
354 NEXT-TOKEN is a function of no argument that moves forward by one
355 token (after skipping comments if needed) and returns it.
356 NEXT-SEXP is a lower-level function to skip one sexp.
357 OP-FORW is the accessor to the forward level of the level data.
358 OP-BACK is the accessor to the backward level of the level data.
359 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
360 first token we see is an operator, skip over its left-hand-side argument.
361 Possible return values:
362 (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
363 is too high. FORW-LEVEL is the forw-level of TOKEN,
364 POS is its start position in the buffer.
365 (t POS TOKEN): same thing when we bump on the wrong side of a paren.
366 (nil POS TOKEN): we skipped over a paren-like pair.
367 nil: we skipped over an identifier, matched parentheses, ..."
368 (catch 'return
369 (let ((levels ()))
370 (while
371 (let* ((pos (point))
372 (token (funcall next-token))
373 (toklevels (cdr (assoc token smie-op-levels))))
374
375 (cond
376 ((null toklevels)
377 (when (zerop (length token))
378 (condition-case err
379 (progn (goto-char pos) (funcall next-sexp 1) nil)
380 (scan-error (throw 'return (list t (caddr err)))))
381 (if (eq pos (point))
382 ;; We did not move, so let's abort the loop.
383 (throw 'return (list t (point))))))
384 ((null (funcall op-back toklevels))
385 ;; A token like a paren-close.
386 (assert (funcall op-forw toklevels)) ;Otherwise, why mention it?
387 (push (funcall op-forw toklevels) levels))
388 (t
389 (while (and levels (< (funcall op-back toklevels) (car levels)))
390 (setq levels (cdr levels)))
391 (cond
392 ((null levels)
393 (if (and halfsexp (funcall op-forw toklevels))
394 (push (funcall op-forw toklevels) levels)
395 (throw 'return
396 (prog1 (list (or (car toklevels) t) (point) token)
397 (goto-char pos)))))
398 (t
399 (if (and levels (= (funcall op-back toklevels) (car levels)))
400 (setq levels (cdr levels)))
401 (cond
402 ((null levels)
403 (cond
404 ((null (funcall op-forw toklevels))
405 (throw 'return (list nil (point) token)))
406 ((smie-associative-p toklevels)
407 (throw 'return
408 (prog1 (list (or (car toklevels) t) (point) token)
409 (goto-char pos))))
410 ;; We just found a match to the previously pending operator
411 ;; but this new operator is still part of a larger RHS.
412 ;; E.g. we're now looking at the "then" in
413 ;; "if a then b else c". So we have to keep parsing the
414 ;; rest of the construct.
415 (t (push (funcall op-forw toklevels) levels))))
416 (t
417 (if (funcall op-forw toklevels)
418 (push (funcall op-forw toklevels) levels))))))))
419 levels)
420 (setq halfsexp nil)))))
421
422 (defun smie-backward-sexp (&optional halfsexp)
423 "Skip over one sexp.
424 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
425 first token we see is an operator, skip over its left-hand-side argument.
426 Possible return values:
427 (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
428 is too high. LEFT-LEVEL is the left-level of TOKEN,
429 POS is its start position in the buffer.
430 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
431 (nil POS TOKEN): we skipped over a paren-like pair.
432 nil: we skipped over an identifier, matched parentheses, ..."
433 (smie-next-sexp
434 (indirect-function smie-backward-token-function)
435 (indirect-function 'backward-sexp)
436 (indirect-function 'smie-op-left)
437 (indirect-function 'smie-op-right)
438 halfsexp))
439
440 (defun smie-forward-sexp (&optional halfsexp)
441 "Skip over one sexp.
442 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
443 first token we see is an operator, skip over its left-hand-side argument.
444 Possible return values:
445 (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
446 is too high. RIGHT-LEVEL is the right-level of TOKEN,
447 POS is its end position in the buffer.
448 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
449 (nil POS TOKEN): we skipped over a paren-like pair.
450 nil: we skipped over an identifier, matched parentheses, ..."
451 (smie-next-sexp
452 (indirect-function smie-forward-token-function)
453 (indirect-function 'forward-sexp)
454 (indirect-function 'smie-op-right)
455 (indirect-function 'smie-op-left)
456 halfsexp))
457
458 (defun smie-backward-sexp-command (&optional n)
459 "Move backward through N logical elements."
460 (interactive "p")
461 (if (< n 0)
462 (smie-forward-sexp-command (- n))
463 (let ((forward-sexp-function nil))
464 (while (> n 0)
465 (decf n)
466 (let ((pos (point))
467 (res (smie-backward-sexp 'halfsexp)))
468 (if (and (car res) (= pos (point)) (not (bolp)))
469 (signal 'scan-error
470 (list "Containing expression ends prematurely"
471 (cadr res) (cadr res)))
472 nil))))))
473
474 (defun smie-forward-sexp-command (&optional n)
475 "Move forward through N logical elements."
476 (interactive "p")
477 (if (< n 0)
478 (smie-backward-sexp-command (- n))
479 (let ((forward-sexp-function nil))
480 (while (> n 0)
481 (decf n)
482 (let ((pos (point))
483 (res (smie-forward-sexp 'halfsexp)))
484 (if (and (car res) (= pos (point)) (not (bolp)))
485 (signal 'scan-error
486 (list "Containing expression ends prematurely"
487 (cadr res) (cadr res)))
488 nil))))))
489
490 ;;; The indentation engine.
491
492 (defcustom smie-indent-basic 4
493 "Basic amount of indentation."
494 :type 'integer)
495
496 (defvar smie-indent-rules 'unset
497 ;; TODO: For SML, we need more rule formats, so as to handle
498 ;; structure Foo =
499 ;; Bar (toto)
500 ;; and
501 ;; structure Foo =
502 ;; struct ... end
503 ;; I.e. the indentation after "=" depends on the parent ("structure")
504 ;; as well as on the following token ("struct").
505 "Rules of the following form.
506 \((:before . TOK) . OFFSET-RULES) how to indent TOK itself.
507 \(TOK . OFFSET-RULES) how to indent right after TOK.
508 \((T1 . T2) . OFFSET) how to indent token T2 w.r.t T1.
509 \((t . TOK) . OFFSET) how to indent TOK with respect to its parent.
510 \(list-intro . TOKENS) declare TOKENS as being followed by what may look like
511 a funcall but is just a sequence of expressions.
512 \(t . OFFSET) basic indentation step.
513 \(args . OFFSET) indentation of arguments.
514
515 OFFSET-RULES is a list of elements which can each either be:
516
517 \(:hanging . OFFSET-RULES) if TOK is hanging, use OFFSET-RULES.
518 \(:parent PARENT . OFFSET-RULES) if TOK's parent is PARENT, use OFFSET-RULES.
519 \(:next TOKEN . OFFSET-RULES) if TOK is followed by TOKEN, use OFFSET-RULES.
520 \(:prev TOKEN . OFFSET-RULES) if TOK is preceded by TOKEN, use OFFSET-RULES.
521 a number the offset to use.
522 `point' align with the token.
523 `parent' align with the parent.
524
525 A nil offset for indentation after a token defaults to `smie-indent-basic'.")
526
527 (defun smie-indent-hanging-p ()
528 ;; A hanging keyword is one that's at the end of a line except it's not at
529 ;; the beginning of a line.
530 (and (save-excursion
531 (when (zerop (length (funcall smie-forward-token-function)))
532 ;; Could be an open-paren.
533 (forward-char 1))
534 (skip-chars-forward " \t")
535 (eolp))
536 (not (smie-bolp))))
537
538 (defun smie-bolp ()
539 (save-excursion (skip-chars-backward " \t") (bolp)))
540
541 (defun smie-indent-offset (elem)
542 (or (cdr (assq elem smie-indent-rules))
543 (cdr (assq t smie-indent-rules))
544 smie-indent-basic))
545
546 (defun smie-indent-offset-rule (tokinfo &optional after)
547 "Apply the OFFSET-RULES in TOKINFO.
548 Point is expected to be right in front of the token corresponding to TOKINFO.
549 If computing the indentation after the token, then AFTER is the position
550 after the token."
551 (let ((rules (cdr tokinfo))
552 parent next prev
553 offset)
554 (while (consp rules)
555 (let ((rule (pop rules)))
556 (cond
557 ((not (consp rule)) (setq offset rule))
558 ((eq (car rule) :hanging)
559 (when (smie-indent-hanging-p)
560 (setq rules (cdr rule))))
561 ((eq (car rule) :prev)
562 (unless prev
563 (save-excursion
564 (setq prev (smie-indent-backward-token))))
565 (when (equal (car prev) (cadr rule))
566 (setq rules (cddr rule))))
567 ((eq (car rule) :next)
568 (unless next
569 (unless after
570 (error "Can't use :next in :before indentation rules"))
571 (save-excursion
572 (goto-char after)
573 (setq next (smie-indent-forward-token))))
574 (when (equal (car next) (cadr rule))
575 (setq rules (cddr rule))))
576 ((eq (car rule) :parent)
577 (unless parent
578 (save-excursion
579 (if after (goto-char after))
580 (setq parent (smie-backward-sexp 'halfsexp))))
581 (when (equal (nth 2 parent) (cadr rule))
582 (setq rules (cddr rule))))
583 (t (error "Unknown rule %s for indentation of %s"
584 rule (car tokinfo))))))
585 offset))
586
587 (defun smie-indent-forward-token ()
588 "Skip token forward and return it, along with its levels."
589 (let ((tok (funcall smie-forward-token-function)))
590 (cond
591 ((< 0 (length tok)) (assoc tok smie-op-levels))
592 ((looking-at "\\s(")
593 (forward-char 1)
594 (list (buffer-substring (1- (point)) (point)) nil 0)))))
595
596 (defun smie-indent-backward-token ()
597 "Skip token backward and return it, along with its levels."
598 (let ((tok (funcall smie-backward-token-function)))
599 (cond
600 ((< 0 (length tok)) (assoc tok smie-op-levels))
601 ;; 4 == Open paren syntax.
602 ((eq 4 (syntax-class (syntax-after (1- (point)))))
603 (forward-char -1)
604 (list (buffer-substring (point) (1+ (point))) nil 0)))))
605
606 (defun smie-indent-virtual ()
607 ;; We used to take an optional arg (with value :not-hanging) to specify that
608 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
609 ;; keyword. This was a bad idea, because the virtual indent of a position
610 ;; should not depend on the caller, since it leads to situations where two
611 ;; dependent indentations get indented differently.
612 "Compute the virtual indentation to use for point.
613 This is used when we're not trying to indent point but just
614 need to compute the column at which point should be indented
615 in order to figure out the indentation of some other (further down) point."
616 ;; Trust pre-existing indentation on other lines.
617 (if (smie-bolp) (current-column) (smie-indent-calculate)))
618
619 (defun smie-indent-fixindent ()
620 ;; Obey the `fixindent' special comment.
621 (and (smie-bolp)
622 (save-excursion
623 (comment-normalize-vars)
624 (re-search-forward (concat comment-start-skip
625 "fixindent"
626 comment-end-skip)
627 ;; 1+ to account for the \n comment termination.
628 (1+ (line-end-position)) t))
629 (current-column)))
630
631 (defun smie-indent-bob ()
632 ;; Start the file at column 0.
633 (save-excursion
634 (forward-comment (- (point)))
635 (if (bobp) 0)))
636
637 (defun smie-indent-close ()
638 ;; Align close paren with opening paren.
639 (save-excursion
640 ;; (forward-comment (point-max))
641 (when (looking-at "\\s)")
642 (while (not (zerop (skip-syntax-forward ")")))
643 (skip-chars-forward " \t"))
644 (condition-case nil
645 (progn
646 (backward-sexp 1)
647 (smie-indent-virtual)) ;:not-hanging
648 (scan-error nil)))))
649
650 (defun smie-indent-keyword ()
651 ;; Align closing token with the corresponding opening one.
652 ;; (e.g. "of" with "case", or "in" with "let").
653 (save-excursion
654 (let* ((pos (point))
655 (toklevels (smie-indent-forward-token))
656 (token (pop toklevels)))
657 (if (null (car toklevels))
658 ;; Different case:
659 ;; - smie-bolp: "indent according to others".
660 ;; - common hanging: "indent according to others".
661 ;; - SML-let hanging: "indent like parent".
662 ;; - if-after-else: "indent-like parent".
663 ;; - middle-of-line: "trust current position".
664 (cond
665 ((null (cdr toklevels)) nil) ;Not a keyword.
666 ((smie-bolp)
667 ;; For an open-paren-like thingy at BOL, always indent only
668 ;; based on other rules (typically smie-indent-after-keyword).
669 nil)
670 (t
671 (let* ((tokinfo (or (assoc (cons :before token) smie-indent-rules)
672 ;; By default use point unless we're hanging.
673 (cons (cons :before token)
674 '((:hanging nil) point))))
675 (after (prog1 (point) (goto-char pos)))
676 (offset (smie-indent-offset-rule tokinfo)))
677 (cond
678 ((eq offset 'point) (current-column))
679 ((eq offset 'parent)
680 (let ((parent (smie-backward-sexp 'halfsexp)))
681 (if parent (goto-char (cadr parent))))
682 (smie-indent-virtual))
683 ((eq offset nil) nil)
684 (t (error "Unhandled offset %s in %s"
685 offset (cons :before token)))))))
686
687 ;; FIXME: This still looks too much like black magic!!
688 ;; FIXME: Rather than a bunch of rules like (PARENT . TOKEN), we
689 ;; want a single rule for TOKEN with different cases for each PARENT.
690 (let ((res (smie-backward-sexp 'halfsexp)) tmp)
691 (cond
692 ((not (or (< (point) pos)
693 (and (cadr res) (< (cadr res) pos))))
694 ;; If we didn't move at all, that means we didn't really skip
695 ;; what we wanted.
696 nil)
697 ((eq (car res) (car toklevels))
698 ;; We bumped into a same-level operator. align with it.
699 (goto-char (cadr res))
700 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
701 ;; want to jump back over a sequence of same-level ops such as
702 ;; a -> b -> c
703 ;; -> d
704 ;; So as to align with the earliest appropriate place.
705 (smie-indent-virtual))
706 ((setq tmp (assoc (cons (caddr res) token)
707 smie-indent-rules))
708 (goto-char (cadr res))
709 (+ (cdr tmp) (smie-indent-virtual))) ;:not-hanging
710 ;; FIXME: The rules ((t . TOK) . OFFSET) either indent
711 ;; relative to "before the parent" or "after the parent",
712 ;; depending on details of the grammar.
713 ((null (car res))
714 (assert (eq (point) (cadr res)))
715 (goto-char (cadr res))
716 (+ (or (cdr (assoc (cons t token) smie-indent-rules)) 0)
717 (smie-indent-virtual))) ;:not-hanging
718 ((and (= (point) pos) (smie-bolp))
719 ;; Since we started at BOL, we're not computing a virtual
720 ;; indentation, and we're still at the starting point, so the
721 ;; next (default) rule can't be used since it uses `current-column'
722 ;; which would cause. indentation to depend on itself.
723 ;; We could just return nil, but OTOH that's not good enough in
724 ;; some cases. Instead, we want to combine the offset-rules for
725 ;; the current token with the offset-rules of the previous one.
726 (+ (or (cdr (assoc (cons t token) smie-indent-rules)) 0)
727 ;; FIXME: This is odd. Can't we make it use
728 ;; smie-indent-(calculate|virtual) somehow?
729 (smie-indent-after-keyword)))
730 (t
731 (+ (or (cdr (assoc (cons t token) smie-indent-rules)) 0)
732 (current-column)))))))))
733
734 (defun smie-indent-comment ()
735 ;; Indentation of a comment.
736 (and (looking-at comment-start-skip)
737 (save-excursion
738 (forward-comment (point-max))
739 (skip-chars-forward " \t\r\n")
740 (smie-indent-calculate))))
741
742 (defun smie-indent-comment-continue ()
743 ;; indentation of comment-continue lines.
744 (let ((continue (and comment-continue
745 (comment-string-strip comment-continue t t))))
746 (and (< 0 (length continue))
747 (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
748 (let ((ppss (syntax-ppss)))
749 (save-excursion
750 (forward-line -1)
751 (if (<= (point) (nth 8 ppss))
752 (progn (goto-char (1+ (nth 8 ppss))) (current-column))
753 (skip-chars-forward " \t")
754 (if (looking-at (regexp-quote continue))
755 (current-column))))))))
756
757 (defun smie-indent-after-keyword ()
758 ;; Indentation right after a special keyword.
759 (save-excursion
760 (let* ((pos (point))
761 (toklevel (smie-indent-backward-token))
762 (tok (car toklevel))
763 (tokinfo (assoc tok smie-indent-rules)))
764 (if (and toklevel (null (cadr toklevel)) (null tokinfo))
765 (setq tokinfo (list (car toklevel))))
766 ;; (if (and tokinfo (null toklevel))
767 ;; (error "Token %S has indent rule but has no parsing info" tok))
768 (when toklevel
769 (let ((offset
770 (cond
771 (tokinfo (or (smie-indent-offset-rule tokinfo pos)
772 (smie-indent-offset t)))
773 ;; The default indentation after a keyword/operator
774 ;; is 0 for infix and t for prefix.
775 ;; Using the BNF syntax, we could come up with
776 ;; better defaults, but we only have the
777 ;; precedence levels here.
778 ((null (cadr toklevel)) (smie-indent-offset t))
779 (t 0))))
780 ;; For indentation after "(let" in SML-mode, we end up accumulating
781 ;; the offset of "(" and the offset of "let", so we use `min' to try
782 ;; and get it right either way.
783 (+ (min (smie-indent-virtual) (current-column)) offset))))))
784
785 (defun smie-indent-exps ()
786 ;; Indentation of sequences of simple expressions without
787 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
788 ;; Can be a list of expressions or a function call.
789 ;; If it's a function call, the first element is special (it's the
790 ;; function). We distinguish function calls from mere lists of
791 ;; expressions based on whether the preceding token is listed in
792 ;; the `list-intro' entry of smie-indent-rules.
793 ;;
794 ;; TODO: to indent Lisp code, we should add a way to specify
795 ;; particular indentation for particular args depending on the
796 ;; function (which would require always skipping back until the
797 ;; function).
798 ;; TODO: to indent C code, such as "if (...) {...}" we might need
799 ;; to add similar indentation hooks for particular positions, but
800 ;; based on the preceding token rather than based on the first exp.
801 (save-excursion
802 (let ((positions nil)
803 arg)
804 (while (and (null (car (smie-backward-sexp)))
805 (push (point) positions)
806 (not (smie-bolp))))
807 (save-excursion
808 ;; Figure out if the atom we just skipped is an argument rather
809 ;; than a function.
810 (setq arg (or (null (car (smie-backward-sexp)))
811 (member (funcall smie-backward-token-function)
812 (cdr (assoc 'list-intro smie-indent-rules))))))
813 (cond
814 ((null positions)
815 ;; We're the first expression of the list. In that case, the
816 ;; indentation should be (have been) determined by its context.
817 nil)
818 (arg
819 ;; There's a previous element, and it's not special (it's not
820 ;; the function), so let's just align with that one.
821 (goto-char (car positions))
822 (current-column))
823 ((cdr positions)
824 ;; We skipped some args plus the function and bumped into something.
825 ;; Align with the first arg.
826 (goto-char (cadr positions))
827 (current-column))
828 (positions
829 ;; We're the first arg.
830 (goto-char (car positions))
831 (+ (smie-indent-offset 'args)
832 ;; We used to use (smie-indent-virtual), but that
833 ;; doesn't seem right since it might then indent args less than
834 ;; the function itself.
835 (current-column)))))))
836
837 (defvar smie-indent-functions
838 '(smie-indent-fixindent smie-indent-bob smie-indent-close smie-indent-comment
839 smie-indent-comment-continue smie-indent-keyword smie-indent-after-keyword
840 smie-indent-exps)
841 "Functions to compute the indentation.
842 Each function is called with no argument, shouldn't move point, and should
843 return either nil if it has no opinion, or an integer representing the column
844 to which that point should be aligned, if we were to reindent it.")
845
846 (defun smie-indent-calculate ()
847 "Compute the indentation to use for point."
848 (run-hook-with-args-until-success 'smie-indent-functions))
849
850 (defun smie-indent-line ()
851 "Indent current line using the SMIE indentation engine."
852 (interactive)
853 (let* ((savep (point))
854 (indent (condition-case nil
855 (save-excursion
856 (forward-line 0)
857 (skip-chars-forward " \t")
858 (if (>= (point) savep) (setq savep nil))
859 (or (smie-indent-calculate) 0))
860 (error 0))))
861 (if (not (numberp indent))
862 ;; If something funny is used (e.g. `noindent'), return it.
863 indent
864 (if (< indent 0) (setq indent 0)) ;Just in case.
865 (if savep
866 (save-excursion (indent-line-to indent))
867 (indent-line-to indent)))))
868
869 ;;;###autoload
870 (defun smie-setup (op-levels indent-rules)
871 (set (make-local-variable 'smie-indent-rules) indent-rules)
872 (set (make-local-variable 'smie-op-levels) op-levels)
873 (set (make-local-variable 'indent-line-function) 'smie-indent-line))
874
875
876 (provide 'smie)
877 ;;; smie.el ends here