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