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