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