]> 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 ;; We have 4 different representations of a "grammar":
79 ;; - a BNF table, which is a list of BNF rules of the form
80 ;; (NONTERM RHS1 ... RHSn) where each RHS is a list of terminals (tokens)
81 ;; or nonterminals. Any element in these lists which does not appear as
82 ;; the `car' of a BNF rule is taken to be a terminal.
83 ;; - A list of precedences (key word "precs"), is a list, sorted
84 ;; from lowest to highest precedence, of precedence classes that
85 ;; have the form (ASSOCIATIVITY TERMINAL1 .. TERMINALn), where
86 ;; ASSOCIATIVITY can be `assoc', `left', `right' or `nonassoc'.
87 ;; - a 2 dimensional precedence table (key word "prec2"), is a 2D
88 ;; table recording the precedence relation (can be `<', `=', `>', or
89 ;; nil) between each pair of tokens.
90 ;; - a precedence-level table (key word "levels"), while is a alist
91 ;; giving for each token its left and right precedence level (a
92 ;; number or nil). This is used in `smie-op-levels'.
93 ;; The prec2 tables are only intermediate data structures: the source
94 ;; code normally provides a mix of BNF and precs tables, and then
95 ;; turns them into a levels table, which is what's used by the rest of
96 ;; the SMIE code.
97
98 (defun smie-set-prec2tab (table x y val &optional override)
99 (assert (and x y))
100 (let* ((key (cons x y))
101 (old (gethash key table)))
102 (if (and old (not (eq old val)))
103 (if (and override (gethash key override))
104 ;; FIXME: The override is meant to resolve ambiguities,
105 ;; but it also hides real conflicts. It would be great to
106 ;; be able to distinguish the two cases so that overrides
107 ;; don't hide real conflicts.
108 (puthash key (gethash key override) table)
109 (display-warning 'smie (format "Conflict: %s %s/%s %s" x old val y)))
110 (puthash key val table))))
111
112 (defun smie-precs-precedence-table (precs)
113 "Compute a 2D precedence table from a list of precedences.
114 PRECS should be a list, sorted by precedence (e.g. \"+\" will
115 come before \"*\"), of elements of the form \(left OP ...)
116 or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
117 one of those elements share the same precedence level and associativity."
118 (let ((prec2-table (make-hash-table :test 'equal)))
119 (dolist (prec precs)
120 (dolist (op (cdr prec))
121 (let ((selfrule (cdr (assq (car prec)
122 '((left . >) (right . <) (assoc . =))))))
123 (when selfrule
124 (dolist (other-op (cdr prec))
125 (smie-set-prec2tab prec2-table op other-op selfrule))))
126 (let ((op1 '<) (op2 '>))
127 (dolist (other-prec precs)
128 (if (eq prec other-prec)
129 (setq op1 '> op2 '<)
130 (dolist (other-op (cdr other-prec))
131 (smie-set-prec2tab prec2-table op other-op op2)
132 (smie-set-prec2tab prec2-table other-op op op1)))))))
133 prec2-table))
134
135 (defun smie-merge-prec2s (&rest tables)
136 (if (null (cdr tables))
137 (car tables)
138 (let ((prec2 (make-hash-table :test 'equal)))
139 (dolist (table tables)
140 (maphash (lambda (k v)
141 (smie-set-prec2tab prec2 (car k) (cdr k) v))
142 table))
143 prec2)))
144
145 (defun smie-bnf-precedence-table (bnf &rest precs)
146 (let ((nts (mapcar 'car bnf)) ;Non-terminals
147 (first-ops-table ())
148 (last-ops-table ())
149 (first-nts-table ())
150 (last-nts-table ())
151 (prec2 (make-hash-table :test 'equal))
152 (override (apply 'smie-merge-prec2s
153 (mapcar 'smie-precs-precedence-table precs)))
154 again)
155 (dolist (rules bnf)
156 (let ((nt (car rules))
157 (last-ops ())
158 (first-ops ())
159 (last-nts ())
160 (first-nts ()))
161 (dolist (rhs (cdr rules))
162 (assert (consp rhs))
163 (if (not (member (car rhs) nts))
164 (pushnew (car rhs) first-ops)
165 (pushnew (car rhs) first-nts)
166 (when (consp (cdr rhs))
167 ;; If the first is not an OP we add the second (which
168 ;; should be an OP if BNF is an "operator grammar").
169 ;; Strictly speaking, this should only be done if the
170 ;; first is a non-terminal which can expand to a phrase
171 ;; without any OP in it, but checking doesn't seem worth
172 ;; the trouble, and it lets the writer of the BNF
173 ;; be a bit more sloppy by skipping uninteresting base
174 ;; cases which are terminals but not OPs.
175 (assert (not (member (cadr rhs) nts)))
176 (pushnew (cadr rhs) first-ops)))
177 (let ((shr (reverse rhs)))
178 (if (not (member (car shr) nts))
179 (pushnew (car shr) last-ops)
180 (pushnew (car shr) last-nts)
181 (when (consp (cdr shr))
182 (assert (not (member (cadr shr) nts)))
183 (pushnew (cadr shr) last-ops)))))
184 (push (cons nt first-ops) first-ops-table)
185 (push (cons nt last-ops) last-ops-table)
186 (push (cons nt first-nts) first-nts-table)
187 (push (cons nt last-nts) last-nts-table)))
188 ;; Compute all first-ops by propagating the initial ones we have
189 ;; now, according to first-nts.
190 (setq again t)
191 (while (prog1 again (setq again nil))
192 (dolist (first-nts first-nts-table)
193 (let* ((nt (pop first-nts))
194 (first-ops (assoc nt first-ops-table)))
195 (dolist (first-nt first-nts)
196 (dolist (op (cdr (assoc first-nt first-ops-table)))
197 (unless (member op first-ops)
198 (setq again t)
199 (push op (cdr first-ops))))))))
200 ;; Same thing for last-ops.
201 (setq again t)
202 (while (prog1 again (setq again nil))
203 (dolist (last-nts last-nts-table)
204 (let* ((nt (pop last-nts))
205 (last-ops (assoc nt last-ops-table)))
206 (dolist (last-nt last-nts)
207 (dolist (op (cdr (assoc last-nt last-ops-table)))
208 (unless (member op last-ops)
209 (setq again t)
210 (push op (cdr last-ops))))))))
211 ;; Now generate the 2D precedence table.
212 (dolist (rules bnf)
213 (dolist (rhs (cdr rules))
214 (while (cdr rhs)
215 (cond
216 ((member (car rhs) nts)
217 (dolist (last (cdr (assoc (car rhs) last-ops-table)))
218 (smie-set-prec2tab prec2 last (cadr rhs) '> override)))
219 ((member (cadr rhs) nts)
220 (dolist (first (cdr (assoc (cadr rhs) first-ops-table)))
221 (smie-set-prec2tab prec2 (car rhs) first '< override))
222 (if (and (cddr rhs) (not (member (car (cddr rhs)) nts)))
223 (smie-set-prec2tab prec2 (car rhs) (car (cddr rhs))
224 '= override)))
225 (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
226 (setq rhs (cdr rhs)))))
227 prec2))
228
229 ;; (defun smie-prec2-closer-alist (prec2 include-inners)
230 ;; "Build a closer-alist from a PREC2 table.
231 ;; The return value is in the same form as `smie-closer-alist'.
232 ;; INCLUDE-INNERS if non-nil means that inner keywords will be included
233 ;; in the table, e.g. the table will include things like (\"if\" . \"else\")."
234 ;; (let* ((non-openers '())
235 ;; (non-closers '())
236 ;; ;; For each keyword, this gives the matching openers, if any.
237 ;; (openers (make-hash-table :test 'equal))
238 ;; (closers '())
239 ;; (done nil))
240 ;; ;; First, find the non-openers and non-closers.
241 ;; (maphash (lambda (k v)
242 ;; (unless (or (eq v '<) (member (cdr k) non-openers))
243 ;; (push (cdr k) non-openers))
244 ;; (unless (or (eq v '>) (member (car k) non-closers))
245 ;; (push (car k) non-closers)))
246 ;; prec2)
247 ;; ;; Then find the openers and closers.
248 ;; (maphash (lambda (k _)
249 ;; (unless (member (car k) non-openers)
250 ;; (puthash (car k) (list (car k)) openers))
251 ;; (unless (or (member (cdr k) non-closers)
252 ;; (member (cdr k) closers))
253 ;; (push (cdr k) closers)))
254 ;; prec2)
255 ;; ;; Then collect the matching elements.
256 ;; (while (not done)
257 ;; (setq done t)
258 ;; (maphash (lambda (k v)
259 ;; (when (eq v '=)
260 ;; (let ((aopeners (gethash (car k) openers))
261 ;; (dopeners (gethash (cdr k) openers))
262 ;; (new nil))
263 ;; (dolist (o aopeners)
264 ;; (unless (member o dopeners)
265 ;; (setq new t)
266 ;; (push o dopeners)))
267 ;; (when new
268 ;; (setq done nil)
269 ;; (puthash (cdr k) dopeners openers)))))
270 ;; prec2))
271 ;; ;; Finally, dump the resulting table.
272 ;; (let ((alist '()))
273 ;; (maphash (lambda (k v)
274 ;; (when (or include-inners (member k closers))
275 ;; (dolist (opener v)
276 ;; (unless (equal opener k)
277 ;; (push (cons opener k) alist)))))
278 ;; openers)
279 ;; alist)))
280
281 (defun smie-bnf-closer-alist (bnf &optional no-inners)
282 ;; We can also build this closer-alist table from a prec2 table,
283 ;; but it takes more work, and the order is unpredictable, which
284 ;; is a problem for smie-close-block.
285 ;; More convenient would be to build it from a levels table since we
286 ;; always have this table (contrary to the BNF), but it has all the
287 ;; disadvantages of the prec2 case plus the disadvantage that the levels
288 ;; table has lost some info which would result in extra invalid pairs.
289 "Build a closer-alist from a BNF table.
290 The return value is in the same form as `smie-closer-alist'.
291 NO-INNERS if non-nil means that inner keywords will be excluded
292 from the table, e.g. the table will not include things like (\"if\" . \"else\")."
293 (let ((nts (mapcar #'car bnf)) ;non terminals.
294 (alist '()))
295 (dolist (nt bnf)
296 (dolist (rhs (cdr nt))
297 (unless (or (< (length rhs) 2) (member (car rhs) nts))
298 (if no-inners
299 (let ((last (car (last rhs))))
300 (unless (member last nts)
301 (pushnew (cons (car rhs) last) alist :test #'equal)))
302 ;; Reverse so that the "real" closer gets there first,
303 ;; which is important for smie-close-block.
304 (dolist (term (reverse (cdr rhs)))
305 (unless (member term nts)
306 (pushnew (cons (car rhs) term) alist :test #'equal)))))))
307 (nreverse alist)))
308
309
310 (defun smie-prec2-levels (prec2)
311 ;; FIXME: Rather than only return an alist of precedence levels, we should
312 ;; also extract other useful data from it:
313 ;; - matching sets of block openers&closers (which can otherwise become
314 ;; collapsed into a single equivalence class in smie-op-levels) for
315 ;; smie-close-block as well as to detect mismatches in smie-next-sexp
316 ;; or in blink-paren (as well as to do the blink-paren for inner
317 ;; keywords like the "in" of "let..in..end").
318 ;; - better default indentation rules (i.e. non-zero indentation after inner
319 ;; keywords like the "in" of "let..in..end") for smie-indent-after-keyword.
320 ;; Of course, maybe those things would be even better handled in the
321 ;; bnf->prec function.
322 "Take a 2D precedence table and turn it into an alist of precedence levels.
323 PREC2 is a table as returned by `smie-precs-precedence-table' or
324 `smie-bnf-precedence-table'."
325 ;; For each operator, we create two "variables" (corresponding to
326 ;; the left and right precedence level), which are represented by
327 ;; cons cells. Those are the very cons cells that appear in the
328 ;; final `table'. The value of each "variable" is kept in the `car'.
329 (let ((table ())
330 (csts ())
331 (eqs ())
332 tmp x y)
333 ;; From `prec2' we construct a list of constraints between
334 ;; variables (aka "precedence levels"). These can be either
335 ;; equality constraints (in `eqs') or `<' constraints (in `csts').
336 (maphash (lambda (k v)
337 (if (setq tmp (assoc (car k) table))
338 (setq x (cddr tmp))
339 (setq x (cons nil nil))
340 (push (cons (car k) (cons nil x)) table))
341 (if (setq tmp (assoc (cdr k) table))
342 (setq y (cdr tmp))
343 (setq y (cons nil (cons nil nil)))
344 (push (cons (cdr k) y) table))
345 (ecase v
346 (= (push (cons x y) eqs))
347 (< (push (cons x y) csts))
348 (> (push (cons y x) csts))))
349 prec2)
350 ;; First process the equality constraints.
351 (let ((eqs eqs))
352 (while eqs
353 (let ((from (caar eqs))
354 (to (cdar eqs)))
355 (setq eqs (cdr eqs))
356 (if (eq to from)
357 nil ;Nothing to do.
358 (dolist (other-eq eqs)
359 (if (eq from (cdr other-eq)) (setcdr other-eq to))
360 (when (eq from (car other-eq))
361 ;; This can happen because of `assoc' settings in precs
362 ;; or because of a rhs like ("op" foo "op").
363 (setcar other-eq to)))
364 (dolist (cst csts)
365 (if (eq from (cdr cst)) (setcdr cst to))
366 (if (eq from (car cst)) (setcar cst to)))))))
367 ;; Then eliminate trivial constraints iteratively.
368 (let ((i 0))
369 (while csts
370 (let ((rhvs (mapcar 'cdr csts))
371 (progress nil))
372 (dolist (cst csts)
373 (unless (memq (car cst) rhvs)
374 (setq progress t)
375 ;; We could give each var in a given iteration the same value,
376 ;; but we can also give them arbitrarily different values.
377 ;; Basically, these are vars between which there is no
378 ;; constraint (neither equality nor inequality), so
379 ;; anything will do.
380 ;; We give them arbitrary values, which means that we
381 ;; replace the "no constraint" case with either > or <
382 ;; but not =. The reason we do that is so as to try and
383 ;; distinguish associative operators (which will have
384 ;; left = right).
385 (unless (caar cst)
386 (setcar (car cst) i)
387 (incf i))
388 (setq csts (delq cst csts))))
389 (unless progress
390 (error "Can't resolve the precedence table to precedence levels")))
391 (incf i 10))
392 ;; Propagate equalities back to their source.
393 (dolist (eq (nreverse eqs))
394 (assert (or (null (caar eq)) (eq (car eq) (cdr eq))))
395 (setcar (car eq) (cadr eq)))
396 ;; Finally, fill in the remaining vars (which only appeared on the
397 ;; right side of the < constraints).
398 (dolist (x table)
399 ;; When both sides are nil, it means this operator binds very
400 ;; very tight, but it's still just an operator, so we give it
401 ;; the highest precedence.
402 ;; OTOH if only one side is nil, it usually means it's like an
403 ;; open-paren, which is very important for indentation purposes,
404 ;; so we keep it nil, to make it easier to recognize.
405 (unless (or (nth 1 x) (nth 2 x))
406 (setf (nth 1 x) i)
407 (setf (nth 2 x) i))))
408 table))
409
410 ;;; Parsing using a precedence level table.
411
412 (defvar smie-op-levels 'unset
413 "List of token parsing info.
414 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
415 Parsing is done using an operator precedence parser.
416 LEFT-LEVEL and RIGHT-LEVEL can be either numbers or nil, where nil
417 means that this operator does not bind on the corresponding side,
418 i.e. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
419 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
420 like a close-paren.")
421
422 (defvar smie-forward-token-function 'smie-default-forward-token
423 "Function to scan forward for the next token.
424 Called with no argument should return a token and move to its end.
425 If no token is found, return nil or the empty string.
426 It can return nil when bumping into a parenthesis, which lets SMIE
427 use syntax-tables to handle them in efficient C code.")
428
429 (defvar smie-backward-token-function 'smie-default-backward-token
430 "Function to scan backward the previous token.
431 Same calling convention as `smie-forward-token-function' except
432 it should move backward to the beginning of the previous token.")
433
434 (defalias 'smie-op-left 'car)
435 (defalias 'smie-op-right 'cadr)
436
437 (defun smie-default-backward-token ()
438 (forward-comment (- (point)))
439 (buffer-substring-no-properties
440 (point)
441 (progn (if (zerop (skip-syntax-backward "."))
442 (skip-syntax-backward "w_'"))
443 (point))))
444
445 (defun smie-default-forward-token ()
446 (forward-comment (point-max))
447 (buffer-substring-no-properties
448 (point)
449 (progn (if (zerop (skip-syntax-forward "."))
450 (skip-syntax-forward "w_'"))
451 (point))))
452
453 (defun smie-associative-p (toklevels)
454 ;; in "a + b + c" we want to stop at each +, but in
455 ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
456 ;; To distinguish the two cases, we made smie-prec2-levels choose
457 ;; different levels for each part of "if a then b else c", so that
458 ;; by checking if the left-level is equal to the right level, we can
459 ;; figure out that it's an associative operator.
460 ;; This is not 100% foolproof, tho, since the "elsif" will have to have
461 ;; equal left and right levels (since it's optional), so smie-next-sexp
462 ;; has to be careful to distinguish those different cases.
463 (eq (smie-op-left toklevels) (smie-op-right toklevels)))
464
465 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp)
466 "Skip over one sexp.
467 NEXT-TOKEN is a function of no argument that moves forward by one
468 token (after skipping comments if needed) and returns it.
469 NEXT-SEXP is a lower-level function to skip one sexp.
470 OP-FORW is the accessor to the forward level of the level data.
471 OP-BACK is the accessor to the backward level of the level data.
472 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
473 first token we see is an operator, skip over its left-hand-side argument.
474 Possible return values:
475 (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
476 is too high. FORW-LEVEL is the forw-level of TOKEN,
477 POS is its start position in the buffer.
478 (t POS TOKEN): same thing when we bump on the wrong side of a paren.
479 (nil POS TOKEN): we skipped over a paren-like pair.
480 nil: we skipped over an identifier, matched parentheses, ..."
481 (catch 'return
482 (let ((levels ()))
483 (while
484 (let* ((pos (point))
485 (token (funcall next-token))
486 (toklevels (cdr (assoc token smie-op-levels))))
487 (cond
488 ((null toklevels)
489 (when (zerop (length token))
490 (condition-case err
491 (progn (goto-char pos) (funcall next-sexp 1) nil)
492 (scan-error (throw 'return
493 (list t (caddr err)
494 (buffer-substring-no-properties
495 (caddr err)
496 (+ (caddr err)
497 (if (< (point) (caddr err))
498 -1 1)))))))
499 (if (eq pos (point))
500 ;; We did not move, so let's abort the loop.
501 (throw 'return (list t (point))))))
502 ((null (funcall op-back toklevels))
503 ;; A token like a paren-close.
504 (assert (funcall op-forw toklevels)) ;Otherwise, why mention it?
505 (push toklevels levels))
506 (t
507 (while (and levels (< (funcall op-back toklevels)
508 (funcall op-forw (car levels))))
509 (setq levels (cdr levels)))
510 (cond
511 ((null levels)
512 (if (and halfsexp (funcall op-forw toklevels))
513 (push toklevels levels)
514 (throw 'return
515 (prog1 (list (or (car toklevels) t) (point) token)
516 (goto-char pos)))))
517 (t
518 (let ((lastlevels levels))
519 (if (and levels (= (funcall op-back toklevels)
520 (funcall op-forw (car levels))))
521 (setq levels (cdr levels)))
522 ;; We may have found a match for the previously pending
523 ;; operator. Is this the end?
524 (cond
525 ;; Keep looking as long as we haven't matched the
526 ;; topmost operator.
527 (levels
528 (if (funcall op-forw toklevels)
529 (push toklevels levels)))
530 ;; We matched the topmost operator. If the new operator
531 ;; is the last in the corresponding BNF rule, we're done.
532 ((null (funcall op-forw toklevels))
533 ;; It is the last element, let's stop here.
534 (throw 'return (list nil (point) token)))
535 ;; If the new operator is not the last in the BNF rule,
536 ;; ans is not associative, it's one of the inner operators
537 ;; (like the "in" in "let .. in .. end"), so keep looking.
538 ((not (smie-associative-p toklevels))
539 (push toklevels levels))
540 ;; The new operator is associative. Two cases:
541 ;; - it's really just an associative operator (like + or ;)
542 ;; in which case we should have stopped right before.
543 ((and lastlevels
544 (smie-associative-p (car lastlevels)))
545 (throw 'return
546 (prog1 (list (or (car toklevels) t) (point) token)
547 (goto-char pos))))
548 ;; - it's an associative operator within a larger construct
549 ;; (e.g. an "elsif"), so we should just ignore it and keep
550 ;; looking for the closing element.
551 (t (setq levels lastlevels))))))))
552 levels)
553 (setq halfsexp nil)))))
554
555 (defun smie-backward-sexp (&optional halfsexp)
556 "Skip over one sexp.
557 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
558 first token we see is an operator, skip over its left-hand-side argument.
559 Possible return values:
560 (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
561 is too high. LEFT-LEVEL is the left-level of TOKEN,
562 POS is its start position in the buffer.
563 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
564 (nil POS TOKEN): we skipped over a paren-like pair.
565 nil: we skipped over an identifier, matched parentheses, ..."
566 (smie-next-sexp
567 (indirect-function smie-backward-token-function)
568 (indirect-function 'backward-sexp)
569 (indirect-function 'smie-op-left)
570 (indirect-function 'smie-op-right)
571 halfsexp))
572
573 (defun smie-forward-sexp (&optional halfsexp)
574 "Skip over one sexp.
575 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
576 first token we see is an operator, skip over its left-hand-side argument.
577 Possible return values:
578 (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
579 is too high. RIGHT-LEVEL is the right-level of TOKEN,
580 POS is its end position in the buffer.
581 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
582 (nil POS TOKEN): we skipped over a paren-like pair.
583 nil: we skipped over an identifier, matched parentheses, ..."
584 (smie-next-sexp
585 (indirect-function smie-forward-token-function)
586 (indirect-function 'forward-sexp)
587 (indirect-function 'smie-op-right)
588 (indirect-function 'smie-op-left)
589 halfsexp))
590
591 ;;; Miscellanous commands using the precedence parser.
592
593 (defun smie-backward-sexp-command (&optional n)
594 "Move backward through N logical elements."
595 (interactive "^p")
596 (smie-forward-sexp-command (- n)))
597
598 (defun smie-forward-sexp-command (&optional n)
599 "Move forward through N logical elements."
600 (interactive "^p")
601 (let ((forw (> n 0))
602 (forward-sexp-function nil))
603 (while (/= n 0)
604 (setq n (- n (if forw 1 -1)))
605 (let ((pos (point))
606 (res (if forw
607 (smie-forward-sexp 'halfsexp)
608 (smie-backward-sexp 'halfsexp))))
609 (if (and (car res) (= pos (point)) (not (if forw (eobp) (bobp))))
610 (signal 'scan-error
611 (list "Containing expression ends prematurely"
612 (cadr res) (cadr res)))
613 nil)))))
614
615 (defvar smie-closer-alist nil
616 "Alist giving the closer corresponding to an opener.")
617
618 (defun smie-close-block ()
619 "Close the closest surrounding block."
620 (interactive)
621 (let ((closer
622 (save-excursion
623 (backward-up-list 1)
624 (if (looking-at "\\s(")
625 (string (cdr (syntax-after (point))))
626 (let* ((open (funcall smie-forward-token-function))
627 (closer (cdr (assoc open smie-closer-alist)))
628 (levels (list (assoc open smie-op-levels)))
629 (seen '())
630 (found '()))
631 (cond
632 ;; Even if we improve the auto-computation of closers,
633 ;; there are still cases where we need manual
634 ;; intervention, e.g. for Octave's use of `until'
635 ;; as a pseudo-closer of `do'.
636 (closer)
637 ((or (equal levels '(nil)) (nth 1 (car levels)))
638 (error "Doesn't look like a block"))
639 (t
640 ;; FIXME: With grammars like Octave's, every closer ("end",
641 ;; "endif", "endwhile", ...) has the same level, so we'd need
642 ;; to look at the BNF or at least at the 2D prec-table, in
643 ;; order to find the right closer for a given opener.
644 (while levels
645 (let ((level (pop levels)))
646 (dolist (other smie-op-levels)
647 (when (and (eq (nth 2 level) (nth 1 other))
648 (not (memq other seen)))
649 (push other seen)
650 (if (nth 2 other)
651 (push other levels)
652 (push (car other) found))))))
653 (cond
654 ((null found) (error "No known closer for opener %s" open))
655 ;; FIXME: what should we do if there are various closers?
656 (t (car found))))))))))
657 (unless (save-excursion (skip-chars-backward " \t") (bolp))
658 (newline))
659 (insert closer)
660 (if (save-excursion (skip-chars-forward " \t") (eolp))
661 (indent-according-to-mode)
662 (reindent-then-newline-and-indent))))
663
664 (defun smie-down-list (&optional arg)
665 "Move forward down one level paren-like blocks. Like `down-list'.
666 With argument ARG, do this that many times.
667 A negative argument means move backward but still go down a level.
668 This command assumes point is not in a string or comment."
669 (interactive "p")
670 (let ((start (point))
671 (inc (if (< arg 0) -1 1))
672 (offset (if (< arg 0) 1 0))
673 (next-token (if (< arg 0)
674 smie-backward-token-function
675 smie-forward-token-function)))
676 (while (/= arg 0)
677 (setq arg (- arg inc))
678 (while
679 (let* ((pos (point))
680 (token (funcall next-token))
681 (levels (assoc token smie-op-levels)))
682 (cond
683 ((zerop (length token))
684 (if (if (< inc 0) (looking-back "\\s(\\|\\s)" (1- (point)))
685 (looking-at "\\s(\\|\\s)"))
686 ;; Go back to `start' in case of an error. This presumes
687 ;; none of the token we've found until now include a ( or ).
688 (progn (goto-char start) (down-list inc) nil)
689 (forward-sexp inc)
690 (/= (point) pos)))
691 ((and levels (null (nth (+ 1 offset) levels))) nil)
692 ((and levels (null (nth (- 2 offset) levels)))
693 (let ((end (point)))
694 (goto-char start)
695 (signal 'scan-error
696 (list "Containing expression ends prematurely"
697 pos end))))
698 (t)))))))
699
700 (defvar smie-blink-matching-triggers '(?\s ?\n)
701 "Chars which might trigger `blink-matching-open'.
702 These can include the final chars of end-tokens, or chars that are
703 typically inserted right after an end token.
704 I.e. a good choice can be:
705 (delete-dups
706 (mapcar (lambda (kw) (aref (cdr kw) (1- (length (cdr kw)))))
707 smie-closer-alist))")
708
709 (defcustom smie-blink-matching-inners t
710 "Whether SMIE should blink to matching opener for inner keywords.
711 If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
712 :type 'boolean)
713
714 (defun smie-blink-matching-check (start end)
715 (save-excursion
716 (goto-char end)
717 (let ((ender (funcall smie-backward-token-function)))
718 (cond
719 ((not (and ender (rassoc ender smie-closer-alist)))
720 ;; This not is one of the begin..end we know how to check.
721 (blink-matching-check-mismatch start end))
722 ((not start) t)
723 (t
724 (goto-char start)
725 (let ((starter (funcall smie-forward-token-function)))
726 (not (member (cons starter ender) smie-closer-alist))))))))
727
728 (defun smie-blink-matching-open ()
729 "Blink the matching opener when applicable.
730 This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
731 (when (and blink-matching-paren
732 smie-closer-alist ; Optimization.
733 (eq (char-before) last-command-event) ; Sanity check.
734 (memq last-command-event smie-blink-matching-triggers)
735 (save-excursion
736 ;; FIXME: Here we assume that closers all end
737 ;; with a word-syntax char.
738 (unless (eq ?\w (char-syntax last-command-event))
739 (forward-char -1))
740 (and (looking-at "\\>")
741 (not (nth 8 (syntax-ppss))))))
742 (save-excursion
743 (let ((pos (point))
744 (token (funcall smie-backward-token-function)))
745 (if (= 1 (length token))
746 ;; The trigger char is itself a token but is not
747 ;; one of the closers (e.g. ?\; in Octave mode),
748 ;; so go back to the previous token
749 (setq token (save-excursion
750 (funcall smie-backward-token-function)))
751 (goto-char pos))
752 ;; Here we assume that smie-backward-token-function
753 ;; returns a token that is a string and whose content
754 ;; match the buffer's representation of this token.
755 (when (and (> (length token) 1) (stringp token)
756 (memq (aref token (1- (length token)))
757 smie-blink-matching-triggers)
758 (not (eq (aref token (1- (length token)))
759 last-command-event)))
760 ;; Token ends with a trigger char, so don't blink for
761 ;; anything else than this trigger char, lest we'd blink
762 ;; both when inserting the trigger char and when inserting a
763 ;; subsequent SPC.
764 (setq token nil))
765 (when (and (rassoc token smie-closer-alist)
766 (or smie-blink-matching-inners
767 (null (nth 2 (assoc token smie-op-levels)))))
768 ;; The major mode might set blink-matching-check-function
769 ;; buffer-locally so that interactive calls to
770 ;; blink-matching-open work right, but let's not presume
771 ;; that's the case.
772 (let ((blink-matching-check-function #'smie-blink-matching-check))
773 (blink-matching-open)))))))
774
775 ;;; The indentation engine.
776
777 (defcustom smie-indent-basic 4
778 "Basic amount of indentation."
779 :type 'integer)
780
781 (defvar smie-indent-rules 'unset
782 ;; TODO: For SML, we need more rule formats, so as to handle
783 ;; structure Foo =
784 ;; Bar (toto)
785 ;; and
786 ;; structure Foo =
787 ;; struct ... end
788 ;; I.e. the indentation after "=" depends on the parent ("structure")
789 ;; as well as on the following token ("struct").
790 "Rules of the following form.
791 \((:before . TOK) . OFFSET-RULES) how to indent TOK itself.
792 \(TOK . OFFSET-RULES) how to indent right after TOK.
793 \(list-intro . TOKENS) declare TOKENS as being followed by what may look like
794 a funcall but is just a sequence of expressions.
795 \(t . OFFSET) basic indentation step.
796 \(args . OFFSET) indentation of arguments.
797 \((T1 . T2) OFFSET) like ((:before . T2) (:parent T1 OFFSET)).
798
799 OFFSET-RULES is a list of elements which can each either be:
800
801 \(:hanging . OFFSET-RULES) if TOK is hanging, use OFFSET-RULES.
802 \(:parent PARENT . OFFSET-RULES) if TOK's parent is PARENT, use OFFSET-RULES.
803 \(:next TOKEN . OFFSET-RULES) if TOK is followed by TOKEN, use OFFSET-RULES.
804 \(:prev TOKEN . OFFSET-RULES) if TOK is preceded by TOKEN, use
805 \(:bolp . OFFSET-RULES) If TOK is first on a line, use OFFSET-RULES.
806 OFFSET the offset to use.
807
808 PARENT can be either the name of the parent or a list of such names.
809
810 OFFSET can be of the form:
811 `point' align with the token.
812 `parent' align with the parent.
813 NUMBER offset by NUMBER.
814 \(+ OFFSETS...) use the sum of OFFSETS.
815 VARIABLE use the value of VARIABLE as offset.
816
817 The precise meaning of `point' depends on various details: it can
818 either mean the position of the token we're indenting, or the
819 position of its parent, or the position right after its parent.
820
821 A nil offset for indentation after an opening token defaults
822 to `smie-indent-basic'.")
823
824 (defun smie-indent-hanging-p ()
825 ;; A hanging keyword is one that's at the end of a line except it's not at
826 ;; the beginning of a line.
827 (and (save-excursion
828 (when (zerop (length (funcall smie-forward-token-function)))
829 ;; Could be an open-paren.
830 (forward-char 1))
831 (skip-chars-forward " \t")
832 (eolp))
833 (not (smie-bolp))))
834
835 (defun smie-bolp ()
836 (save-excursion (skip-chars-backward " \t") (bolp)))
837
838 (defun smie-indent-offset (elem)
839 (or (cdr (assq elem smie-indent-rules))
840 (cdr (assq t smie-indent-rules))
841 smie-indent-basic))
842
843 (defvar smie-indent-debug-log)
844
845 (defun smie-indent-offset-rule (tokinfo &optional after parent)
846 "Apply the OFFSET-RULES in TOKINFO.
847 Point is expected to be right in front of the token corresponding to TOKINFO.
848 If computing the indentation after the token, then AFTER is the position
849 after the token, otherwise it should be nil.
850 PARENT if non-nil should be the parent info returned by `smie-backward-sexp'."
851 (let ((rules (cdr tokinfo))
852 next prev
853 offset)
854 (while (consp rules)
855 (let ((rule (pop rules)))
856 (cond
857 ((not (consp rule)) (setq offset rule))
858 ((eq (car rule) '+) (setq offset rule))
859 ((eq (car rule) :hanging)
860 (when (smie-indent-hanging-p)
861 (setq rules (cdr rule))))
862 ((eq (car rule) :bolp)
863 (when (smie-bolp)
864 (setq rules (cdr rule))))
865 ((eq (car rule) :eolp)
866 (unless after
867 (error "Can't use :eolp in :before indentation rules"))
868 (when (> after (line-end-position))
869 (setq rules (cdr rule))))
870 ((eq (car rule) :prev)
871 (unless prev
872 (save-excursion
873 (setq prev (smie-indent-backward-token))))
874 (when (equal (car prev) (cadr rule))
875 (setq rules (cddr rule))))
876 ((eq (car rule) :next)
877 (unless next
878 (unless after
879 (error "Can't use :next in :before indentation rules"))
880 (save-excursion
881 (goto-char after)
882 (setq next (smie-indent-forward-token))))
883 (when (equal (car next) (cadr rule))
884 (setq rules (cddr rule))))
885 ((eq (car rule) :parent)
886 (unless parent
887 (save-excursion
888 (if after (goto-char after))
889 (setq parent (smie-backward-sexp 'halfsexp))))
890 (when (if (listp (cadr rule))
891 (member (nth 2 parent) (cadr rule))
892 (equal (nth 2 parent) (cadr rule)))
893 (setq rules (cddr rule))))
894 (t (error "Unknown rule %s for indentation of %s"
895 rule (car tokinfo))))))
896 ;; If `offset' is not set yet, use `rules' to handle the case where
897 ;; the tokinfo uses the old-style ((PARENT . TOK). OFFSET).
898 (unless offset (setq offset rules))
899 (when (boundp 'smie-indent-debug-log)
900 (push (list (point) offset tokinfo) smie-indent-debug-log))
901 offset))
902
903 (defun smie-indent-column (offset &optional base parent virtual-point)
904 "Compute the actual column to use for a given OFFSET.
905 BASE is the base position to use, and PARENT is the parent info, if any.
906 If VIRTUAL-POINT is non-nil, then `point' is virtual."
907 (cond
908 ((eq (car-safe offset) '+)
909 (apply '+ (mapcar (lambda (offset) (smie-indent-column offset nil parent))
910 (cdr offset))))
911 ((integerp offset)
912 (+ offset
913 (case base
914 ((nil) 0)
915 (parent (goto-char (cadr parent))
916 (smie-indent-virtual))
917 (t
918 (goto-char base)
919 ;; For indentation after "(let" in SML-mode, we end up accumulating
920 ;; the offset of "(" and the offset of "let", so we use `min' to try
921 ;; and get it right either way.
922 (min (smie-indent-virtual) (current-column))))))
923 ((eq offset 'point)
924 ;; In indent-keyword, if we're indenting `then' wrt `if', we want to use
925 ;; indent-virtual rather than use just current-column, so that we can
926 ;; apply the (:before . "if") rule which does the "else if" dance in SML.
927 ;; But in other cases, we do not want to use indent-virtual
928 ;; (e.g. indentation of "*" w.r.t "+", or ";" wrt "("). We could just
929 ;; always use indent-virtual and then have indent-rules say explicitly
930 ;; to use `point' after things like "(" or "+" when they're not at EOL,
931 ;; but you'd end up with lots of those rules.
932 ;; So we use a heuristic here, which is that we only use virtual if
933 ;; the parent is tightly linked to the child token (they're part of
934 ;; the same BNF rule).
935 (if (and virtual-point (null (car parent))) ;Black magic :-(
936 (smie-indent-virtual) (current-column)))
937 ((eq offset 'parent)
938 (unless parent
939 (setq parent (or (smie-backward-sexp 'halfsexp) :notfound)))
940 (if (consp parent) (goto-char (cadr parent)))
941 (smie-indent-virtual))
942 ((eq offset nil) nil)
943 ((and (symbolp offset) (boundp 'offset))
944 (smie-indent-column (symbol-value offset) base parent virtual-point))
945 (t (error "Unknown indentation offset %s" offset))))
946
947 (defun smie-indent-forward-token ()
948 "Skip token forward and return it, along with its levels."
949 (let ((tok (funcall smie-forward-token-function)))
950 (cond
951 ((< 0 (length tok)) (assoc tok smie-op-levels))
952 ((looking-at "\\s(")
953 (forward-char 1)
954 (list (buffer-substring (1- (point)) (point)) nil 0)))))
955
956 (defun smie-indent-backward-token ()
957 "Skip token backward and return it, along with its levels."
958 (let ((tok (funcall smie-backward-token-function)))
959 (cond
960 ((< 0 (length tok)) (assoc tok smie-op-levels))
961 ;; 4 == Open paren syntax.
962 ((eq 4 (syntax-class (syntax-after (1- (point)))))
963 (forward-char -1)
964 (list (buffer-substring (point) (1+ (point))) nil 0)))))
965
966 (defun smie-indent-virtual ()
967 ;; We used to take an optional arg (with value :not-hanging) to specify that
968 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
969 ;; keyword. This was a bad idea, because the virtual indent of a position
970 ;; should not depend on the caller, since it leads to situations where two
971 ;; dependent indentations get indented differently.
972 "Compute the virtual indentation to use for point.
973 This is used when we're not trying to indent point but just
974 need to compute the column at which point should be indented
975 in order to figure out the indentation of some other (further down) point."
976 ;; Trust pre-existing indentation on other lines.
977 (if (smie-bolp) (current-column) (smie-indent-calculate)))
978
979 (defun smie-indent-fixindent ()
980 ;; Obey the `fixindent' special comment.
981 (and (smie-bolp)
982 (save-excursion
983 (comment-normalize-vars)
984 (re-search-forward (concat comment-start-skip
985 "fixindent"
986 comment-end-skip)
987 ;; 1+ to account for the \n comment termination.
988 (1+ (line-end-position)) t))
989 (current-column)))
990
991 (defun smie-indent-bob ()
992 ;; Start the file at column 0.
993 (save-excursion
994 (forward-comment (- (point)))
995 (if (bobp) 0)))
996
997 (defun smie-indent-close ()
998 ;; Align close paren with opening paren.
999 (save-excursion
1000 ;; (forward-comment (point-max))
1001 (when (looking-at "\\s)")
1002 (while (not (zerop (skip-syntax-forward ")")))
1003 (skip-chars-forward " \t"))
1004 (condition-case nil
1005 (progn
1006 (backward-sexp 1)
1007 (smie-indent-virtual)) ;:not-hanging
1008 (scan-error nil)))))
1009
1010 (defun smie-indent-keyword ()
1011 ;; Align closing token with the corresponding opening one.
1012 ;; (e.g. "of" with "case", or "in" with "let").
1013 (save-excursion
1014 (let* ((pos (point))
1015 (toklevels (smie-indent-forward-token))
1016 (token (pop toklevels)))
1017 (if (null (car toklevels))
1018 (save-excursion
1019 (goto-char pos)
1020 ;; Different cases:
1021 ;; - smie-bolp: "indent according to others".
1022 ;; - common hanging: "indent according to others".
1023 ;; - SML-let hanging: "indent like parent".
1024 ;; - if-after-else: "indent-like parent".
1025 ;; - middle-of-line: "trust current position".
1026 (cond
1027 ((null (cdr toklevels)) nil) ;Not a keyword.
1028 ((smie-bolp)
1029 ;; For an open-paren-like thingy at BOL, always indent only
1030 ;; based on other rules (typically smie-indent-after-keyword).
1031 nil)
1032 (t
1033 ;; We're only ever here for virtual-indent, which is why
1034 ;; we can use (current-column) as answer for `point'.
1035 (let* ((tokinfo (or (assoc (cons :before token)
1036 smie-indent-rules)
1037 ;; By default use point unless we're hanging.
1038 `((:before . ,token) (:hanging nil) point)))
1039 ;; (after (prog1 (point) (goto-char pos)))
1040 (offset (smie-indent-offset-rule tokinfo)))
1041 (smie-indent-column offset)))))
1042
1043 ;; FIXME: This still looks too much like black magic!!
1044 ;; FIXME: Rather than a bunch of rules like (PARENT . TOKEN), we
1045 ;; want a single rule for TOKEN with different cases for each PARENT.
1046 (let* ((parent (smie-backward-sexp 'halfsexp))
1047 (tokinfo
1048 (or (assoc (cons (caddr parent) token)
1049 smie-indent-rules)
1050 (assoc (cons :before token) smie-indent-rules)
1051 ;; Default rule.
1052 `((:before . ,token)
1053 ;; (:parent open 0)
1054 point)))
1055 (offset (save-excursion
1056 (goto-char pos)
1057 (smie-indent-offset-rule tokinfo nil parent))))
1058 ;; Different behaviors:
1059 ;; - align with parent.
1060 ;; - parent + offset.
1061 ;; - after parent's column + offset (actually, after or before
1062 ;; depending on where backward-sexp stopped).
1063 ;; ? let it drop to some other indentation function (almost never).
1064 ;; ? parent + offset + parent's own offset.
1065 ;; Different cases:
1066 ;; - bump into a same-level operator.
1067 ;; - bump into a specific known parent.
1068 ;; - find a matching open-paren thingy.
1069 ;; - bump into some random parent.
1070 ;; ? borderline case (almost never).
1071 ;; ? bump immediately into a parent.
1072 (cond
1073 ((not (or (< (point) pos)
1074 (and (cadr parent) (< (cadr parent) pos))))
1075 ;; If we didn't move at all, that means we didn't really skip
1076 ;; what we wanted. Should almost never happen, other than
1077 ;; maybe when an infix or close-paren is at the beginning
1078 ;; of a buffer.
1079 nil)
1080 ((eq (car parent) (car toklevels))
1081 ;; We bumped into a same-level operator. align with it.
1082 (if (and (smie-bolp) (/= (point) pos)
1083 (save-excursion
1084 (goto-char (goto-char (cadr parent)))
1085 (not (smie-bolp)))
1086 ;; Check the offset of `token' rather then its parent
1087 ;; because its parent may have used a special rule. E.g.
1088 ;; function foo;
1089 ;; line2;
1090 ;; line3;
1091 ;; The ; on the first line had a special rule, but when
1092 ;; indenting line3, we don't care about it and want to
1093 ;; align with line2.
1094 (memq offset '(point nil)))
1095 ;; If the parent is at EOL and its children are indented like
1096 ;; itself, then we can just obey the indentation chosen for the
1097 ;; child.
1098 ;; This is important for operators like ";" which
1099 ;; are usually at EOL (and have an offset of 0): otherwise we'd
1100 ;; always go back over all the statements, which is
1101 ;; a performance problem and would also mean that fixindents
1102 ;; in the middle of such a sequence would be ignored.
1103 ;;
1104 ;; This is a delicate point!
1105 ;; Even if the offset is not 0, we could follow the same logic
1106 ;; and subtract the offset from the child's indentation.
1107 ;; But that would more often be a bad idea: OT1H we generally
1108 ;; want to reuse the closest similar indentation point, so that
1109 ;; the user's choice (or the fixindents) are obeyed. But OTOH
1110 ;; we don't want this to affect "unrelated" parts of the code.
1111 ;; E.g. a fixindent in the body of a "begin..end" should not
1112 ;; affect the indentation of the "end".
1113 (current-column)
1114 (goto-char (cadr parent))
1115 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
1116 ;; want to jump back over a sequence of same-level ops such as
1117 ;; a -> b -> c
1118 ;; -> d
1119 ;; So as to align with the earliest appropriate place.
1120 (smie-indent-virtual)))
1121 (tokinfo
1122 (if (and (= (point) pos) (smie-bolp)
1123 (or (eq offset 'point)
1124 (and (consp offset) (memq 'point offset))))
1125 ;; Since we started at BOL, we're not computing a virtual
1126 ;; indentation, and we're still at the starting point, so
1127 ;; we can't use `current-column' which would cause
1128 ;; indentation to depend on itself.
1129 nil
1130 (smie-indent-column offset 'parent parent
1131 ;; If we're still at pos, indent-virtual
1132 ;; will inf-loop.
1133 (unless (= (point) pos) 'virtual))))))))))
1134
1135 (defun smie-indent-comment ()
1136 "Compute indentation of a comment."
1137 ;; Don't do it for virtual indentations. We should normally never be "in
1138 ;; front of a comment" when doing virtual-indentation anyway. And if we are
1139 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
1140 (and (smie-bolp)
1141 (looking-at comment-start-skip)
1142 (save-excursion
1143 (forward-comment (point-max))
1144 (skip-chars-forward " \t\r\n")
1145 (smie-indent-calculate))))
1146
1147 (defun smie-indent-comment-continue ()
1148 ;; indentation of comment-continue lines.
1149 (let ((continue (and comment-continue
1150 (comment-string-strip comment-continue t t))))
1151 (and (< 0 (length continue))
1152 (looking-at (regexp-quote continue)) (nth 4 (syntax-ppss))
1153 (let ((ppss (syntax-ppss)))
1154 (save-excursion
1155 (forward-line -1)
1156 (if (<= (point) (nth 8 ppss))
1157 (progn (goto-char (1+ (nth 8 ppss))) (current-column))
1158 (skip-chars-forward " \t")
1159 (if (looking-at (regexp-quote continue))
1160 (current-column))))))))
1161
1162 (defun smie-indent-after-keyword ()
1163 ;; Indentation right after a special keyword.
1164 (save-excursion
1165 (let* ((pos (point))
1166 (toklevel (smie-indent-backward-token))
1167 (tok (car toklevel))
1168 (tokinfo (assoc tok smie-indent-rules)))
1169 ;; Set some default indent rules.
1170 (if (and toklevel (null (cadr toklevel)) (null tokinfo))
1171 (setq tokinfo (list (car toklevel))))
1172 ;; (if (and tokinfo (null toklevel))
1173 ;; (error "Token %S has indent rule but has no parsing info" tok))
1174 (when toklevel
1175 (unless tokinfo
1176 ;; The default indentation after a keyword/operator is 0 for
1177 ;; infix and t for prefix.
1178 ;; Using the BNF syntax, we could come up with better
1179 ;; defaults, but we only have the precedence levels here.
1180 (setq tokinfo (list tok 'default-rule
1181 (if (cadr toklevel) 0 (smie-indent-offset t)))))
1182 (let ((offset
1183 (or (smie-indent-offset-rule tokinfo pos)
1184 (smie-indent-offset t))))
1185 (let ((before (point)))
1186 (goto-char pos)
1187 (smie-indent-column offset before)))))))
1188
1189 (defun smie-indent-exps ()
1190 ;; Indentation of sequences of simple expressions without
1191 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
1192 ;; Can be a list of expressions or a function call.
1193 ;; If it's a function call, the first element is special (it's the
1194 ;; function). We distinguish function calls from mere lists of
1195 ;; expressions based on whether the preceding token is listed in
1196 ;; the `list-intro' entry of smie-indent-rules.
1197 ;;
1198 ;; TODO: to indent Lisp code, we should add a way to specify
1199 ;; particular indentation for particular args depending on the
1200 ;; function (which would require always skipping back until the
1201 ;; function).
1202 ;; TODO: to indent C code, such as "if (...) {...}" we might need
1203 ;; to add similar indentation hooks for particular positions, but
1204 ;; based on the preceding token rather than based on the first exp.
1205 (save-excursion
1206 (let ((positions nil)
1207 arg)
1208 (while (and (null (car (smie-backward-sexp)))
1209 (push (point) positions)
1210 (not (smie-bolp))))
1211 (save-excursion
1212 ;; Figure out if the atom we just skipped is an argument rather
1213 ;; than a function.
1214 (setq arg (or (null (car (smie-backward-sexp)))
1215 (member (funcall smie-backward-token-function)
1216 (cdr (assoc 'list-intro smie-indent-rules))))))
1217 (cond
1218 ((null positions)
1219 ;; We're the first expression of the list. In that case, the
1220 ;; indentation should be (have been) determined by its context.
1221 nil)
1222 (arg
1223 ;; There's a previous element, and it's not special (it's not
1224 ;; the function), so let's just align with that one.
1225 (goto-char (car positions))
1226 (current-column))
1227 ((cdr positions)
1228 ;; We skipped some args plus the function and bumped into something.
1229 ;; Align with the first arg.
1230 (goto-char (cadr positions))
1231 (current-column))
1232 (positions
1233 ;; We're the first arg.
1234 (goto-char (car positions))
1235 ;; FIXME: Use smie-indent-column.
1236 (+ (smie-indent-offset 'args)
1237 ;; We used to use (smie-indent-virtual), but that
1238 ;; doesn't seem right since it might then indent args less than
1239 ;; the function itself.
1240 (current-column)))))))
1241
1242 (defvar smie-indent-functions
1243 '(smie-indent-fixindent smie-indent-bob smie-indent-close smie-indent-comment
1244 smie-indent-comment-continue smie-indent-keyword smie-indent-after-keyword
1245 smie-indent-exps)
1246 "Functions to compute the indentation.
1247 Each function is called with no argument, shouldn't move point, and should
1248 return either nil if it has no opinion, or an integer representing the column
1249 to which that point should be aligned, if we were to reindent it.")
1250
1251 (defun smie-indent-calculate ()
1252 "Compute the indentation to use for point."
1253 (run-hook-with-args-until-success 'smie-indent-functions))
1254
1255 (defun smie-indent-line ()
1256 "Indent current line using the SMIE indentation engine."
1257 (interactive)
1258 (let* ((savep (point))
1259 (indent (condition-case-no-debug nil
1260 (save-excursion
1261 (forward-line 0)
1262 (skip-chars-forward " \t")
1263 (if (>= (point) savep) (setq savep nil))
1264 (or (smie-indent-calculate) 0))
1265 (error 0))))
1266 (if (not (numberp indent))
1267 ;; If something funny is used (e.g. `noindent'), return it.
1268 indent
1269 (if (< indent 0) (setq indent 0)) ;Just in case.
1270 (if savep
1271 (save-excursion (indent-line-to indent))
1272 (indent-line-to indent)))))
1273
1274 (defun smie-indent-debug ()
1275 "Show the rules used to compute indentation of current line."
1276 (interactive)
1277 (let ((smie-indent-debug-log '()))
1278 (smie-indent-calculate)
1279 ;; FIXME: please improve!
1280 (message "%S" smie-indent-debug-log)))
1281
1282 (defun smie-setup (op-levels indent-rules)
1283 (set (make-local-variable 'smie-indent-rules) indent-rules)
1284 (set (make-local-variable 'smie-op-levels) op-levels)
1285 (set (make-local-variable 'indent-line-function) 'smie-indent-line))
1286
1287
1288 (provide 'smie)
1289 ;;; smie.el ends here