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