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