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