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