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