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