1 ;;; smie.el --- Simple Minded Indentation Engine -*- lexical-binding: t -*-
3 ;; Copyright (C) 2010-2012 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: languages, lisp, internal, parsing, indentation
8 ;; This file is part of GNU Emacs.
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.
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.
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/>.
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
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.
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
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
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.
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://dickgrune.com/Books/PTAPG_1st_Edition/).
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.
66 ;; Conflict resolution:
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 ;; This can be resolved simply with:
73 ;; (exp ("IF" expelseexp "END") ("CASE" cases "END"))
74 ;; (expelseexp (exp) (exp "ELSE" exp))
75 ;; (cases (cases "ELSE" insts) ...)
76 ;; - Another source of conflict is when a terminator/separator is used to
77 ;; terminate elements at different levels, as in:
78 ;; (decls ("VAR" vars) (decls "," decls))
79 ;; (vars (id) (vars "," vars))
80 ;; often these can be resolved by making the lexer distinguish the two
81 ;; kinds of commas, e.g. based on the following token.
85 ;; - We could try to resolve conflicts such as the IFexpELSEexpEND -vs-
86 ;; CASE(casesELSEexp)END automatically by changing the way BNF rules such as
87 ;; the IF-rule is handled. I.e. rather than IF=ELSE and ELSE=END, we could
88 ;; turn them into IF<ELSE and ELSE>END and IF=END.
89 ;; - Using the structural information SMIE gives us, it should be possible to
90 ;; implement a `smie-align' command that would automatically figure out what
91 ;; there is to align and how to do it (something like: align the token of
92 ;; lowest precedence that appears the same number of times on all lines,
93 ;; and then do the same on each side of that token).
94 ;; - Maybe accept two juxtaposed non-terminals in the BNF under the condition
95 ;; that the first always ends with a terminal, or that the second always
96 ;; starts with a terminal.
97 ;; - Permit EBNF-style notation.
98 ;; - If the grammar has conflicts, the only way is to make the lexer return
99 ;; different tokens for the different cases. This extra work performed by
100 ;; the lexer can be costly and unnecessary: we perform this extra work every
101 ;; time we find the conflicting token, regardless of whether or not the
102 ;; difference between the various situations is relevant to the current
103 ;; situation. E.g. we may try to determine whether a ";" is a ";-operator"
104 ;; or a ";-separator" in a case where we're skipping over a "begin..end" pair
105 ;; where the difference doesn't matter. For frequently occurring tokens and
106 ;; rarely occurring conflicts, this can be a significant performance problem.
107 ;; We could try and let the lexer return a "set of possible tokens
108 ;; plus a refinement function" and then let parser call the refinement
109 ;; function if needed.
110 ;; - Make it possible to better specify the behavior in the face of
111 ;; syntax errors. IOW provide some control over the choice of precedence
112 ;; levels within the limits of the constraints. E.g. make it possible for
113 ;; the grammar to specify that "begin..end" has lower precedence than
114 ;; "Module..EndModule", so that if a "begin" is missing, scanning from the
115 ;; "end" will stop at "Module" rather than going past it (and similarly,
116 ;; scanning from "Module" should not stop at a spurious "end").
121 ;; - smie-indent-comment doesn't interact well with mis-indented lines (where
122 ;; the indent rules don't do what the user wants). Not sure what to do.
124 (eval-when-compile (require 'cl
))
127 "Simple Minded Indentation Engine."
130 (defvar comment-continue
)
131 (declare-function comment-string-strip
"newcomment" (str beforep afterp
))
133 ;;; Building precedence level tables from BNF specs.
135 ;; We have 4 different representations of a "grammar":
136 ;; - a BNF table, which is a list of BNF rules of the form
137 ;; (NONTERM RHS1 ... RHSn) where each RHS is a list of terminals (tokens)
138 ;; or nonterminals. Any element in these lists which does not appear as
139 ;; the `car' of a BNF rule is taken to be a terminal.
140 ;; - A list of precedences (key word "precs"), is a list, sorted
141 ;; from lowest to highest precedence, of precedence classes that
142 ;; have the form (ASSOCIATIVITY TERMINAL1 .. TERMINALn), where
143 ;; ASSOCIATIVITY can be `assoc', `left', `right' or `nonassoc'.
144 ;; - a 2 dimensional precedence table (key word "prec2"), is a 2D
145 ;; table recording the precedence relation (can be `<', `=', `>', or
146 ;; nil) between each pair of tokens.
147 ;; - a precedence-level table (key word "grammar"), which is an alist
148 ;; giving for each token its left and right precedence level (a
149 ;; number or nil). This is used in `smie-grammar'.
150 ;; The prec2 tables are only intermediate data structures: the source
151 ;; code normally provides a mix of BNF and precs tables, and then
152 ;; turns them into a levels table, which is what's used by the rest of
155 (defvar smie-warning-count
0)
157 (defun smie-set-prec2tab (table x y val
&optional override
)
159 (let* ((key (cons x y
))
160 (old (gethash key table
)))
161 (if (and old
(not (eq old val
)))
162 (if (and override
(gethash key override
))
163 ;; FIXME: The override is meant to resolve ambiguities,
164 ;; but it also hides real conflicts. It would be great to
165 ;; be able to distinguish the two cases so that overrides
166 ;; don't hide real conflicts.
167 (puthash key
(gethash key override
) table
)
168 (display-warning 'smie
(format "Conflict: %s %s/%s %s" x old val y
))
169 (incf smie-warning-count
))
170 (puthash key val table
))))
172 (put 'smie-precs-
>prec2
'pure t
)
173 (defun smie-precs->prec2
(precs)
174 "Compute a 2D precedence table from a list of precedences.
175 PRECS should be a list, sorted by precedence (e.g. \"+\" will
176 come before \"*\"), of elements of the form \(left OP ...)
177 or (right OP ...) or (nonassoc OP ...) or (assoc OP ...). All operators in
178 one of those elements share the same precedence level and associativity."
179 (let ((prec2-table (make-hash-table :test
'equal
)))
181 (dolist (op (cdr prec
))
182 (let ((selfrule (cdr (assq (car prec
)
183 '((left .
>) (right .
<) (assoc .
=))))))
185 (dolist (other-op (cdr prec
))
186 (smie-set-prec2tab prec2-table op other-op selfrule
))))
187 (let ((op1 '<) (op2 '>))
188 (dolist (other-prec precs
)
189 (if (eq prec other-prec
)
191 (dolist (other-op (cdr other-prec
))
192 (smie-set-prec2tab prec2-table op other-op op2
)
193 (smie-set-prec2tab prec2-table other-op op op1
)))))))
196 (put 'smie-merge-prec2s
'pure t
)
197 (defun smie-merge-prec2s (&rest tables
)
198 (if (null (cdr tables
))
200 (let ((prec2 (make-hash-table :test
'equal
)))
201 (dolist (table tables
)
202 (maphash (lambda (k v
)
204 (smie-set-prec2tab prec2
(car k
) (cdr k
) v
)
205 (if (and (gethash k prec2
)
206 (not (equal (gethash k prec2
) v
)))
207 (error "Conflicting values for %s property" k
)
208 (puthash k v prec2
))))
212 (put 'smie-bnf-
>prec2
'pure t
)
213 (defun smie-bnf->prec2
(bnf &rest resolvers
)
214 "Convert the BNF grammar into a prec2 table.
215 BNF is a list of nonterminal definitions of the form:
216 \(NONTERM RHS1 RHS2 ...)
217 where each RHS is a (non-empty) list of terminals (aka tokens) or non-terminals.
218 Not all grammars are accepted:
219 - an RHS cannot be an empty list (this is not needed, since SMIE allows all
220 non-terminals to match the empty string anyway).
221 - an RHS cannot have 2 consecutive non-terminals: between each non-terminal
222 needs to be a terminal (aka token). This is a fundamental limitation of
223 the parsing technology used (operator precedence grammar).
224 Additionally, conflicts can occur:
225 - The returned prec2 table holds constraints between pairs of
226 token, and for any given pair only one constraint can be
227 present, either: T1 < T2, T1 = T2, or T1 > T2.
228 - A token can either be an `opener' (something similar to an open-paren),
229 a `closer' (like a close-paren), or `neither' of the two (e.g. an infix
230 operator, or an inner token like \"else\").
231 Conflicts can be resolved via RESOLVERS, which is a list of elements that can
233 - a precs table (see `smie-precs->prec2') to resolve conflicting constraints,
234 - a constraint (T1 REL T2) where REL is one of = < or >."
235 ;; FIXME: Add repetition operator like (repeat <separator> <elems>).
236 ;; Maybe also add (or <elem1> <elem2>...) for things like
237 ;; (exp (exp (or "+" "*" "=" ..) exp)).
238 ;; Basically, make it EBNF (except for the specification of a separator in
239 ;; the repetition, maybe).
240 (let* ((nts (mapcar 'car bnf
)) ;Non-terminals.
245 (smie-warning-count 0)
246 (prec2 (make-hash-table :test
'equal
))
249 (over (make-hash-table :test
'equal
)))
250 (dolist (resolver resolvers
)
252 ((and (= 3 (length resolver
)) (memq (nth 1 resolver
) '(= < >)))
254 over
(nth 0 resolver
) (nth 2 resolver
) (nth 1 resolver
)))
255 ((memq (caar resolver
) '(left right assoc nonassoc
))
256 (push resolver precs
))
257 (t (error "Unknown resolver %S" resolver
))))
258 (apply #'smie-merge-prec2s over
259 (mapcar 'smie-precs-
>prec2 precs
))))
262 (let ((nt (car rules
))
267 (dolist (rhs (cdr rules
))
269 (signal 'wrong-type-argument
`(consp ,rhs
)))
270 (if (not (member (car rhs
) nts
))
271 (pushnew (car rhs
) first-ops
)
272 (pushnew (car rhs
) first-nts
)
273 (when (consp (cdr rhs
))
274 ;; If the first is not an OP we add the second (which
275 ;; should be an OP if BNF is an "operator grammar").
276 ;; Strictly speaking, this should only be done if the
277 ;; first is a non-terminal which can expand to a phrase
278 ;; without any OP in it, but checking doesn't seem worth
279 ;; the trouble, and it lets the writer of the BNF
280 ;; be a bit more sloppy by skipping uninteresting base
281 ;; cases which are terminals but not OPs.
282 (when (member (cadr rhs
) nts
)
283 (error "Adjacent non-terminals: %s %s"
284 (car rhs
) (cadr rhs
)))
285 (pushnew (cadr rhs
) first-ops
)))
286 (let ((shr (reverse rhs
)))
287 (if (not (member (car shr
) nts
))
288 (pushnew (car shr
) last-ops
)
289 (pushnew (car shr
) last-nts
)
290 (when (consp (cdr shr
))
291 (when (member (cadr shr
) nts
)
292 (error "Adjacent non-terminals: %s %s"
293 (cadr shr
) (car shr
)))
294 (pushnew (cadr shr
) last-ops
)))))
295 (push (cons nt first-ops
) first-ops-table
)
296 (push (cons nt last-ops
) last-ops-table
)
297 (push (cons nt first-nts
) first-nts-table
)
298 (push (cons nt last-nts
) last-nts-table
)))
299 ;; Compute all first-ops by propagating the initial ones we have
300 ;; now, according to first-nts.
302 (while (prog1 again
(setq again nil
))
303 (dolist (first-nts first-nts-table
)
304 (let* ((nt (pop first-nts
))
305 (first-ops (assoc nt first-ops-table
)))
306 (dolist (first-nt first-nts
)
307 (dolist (op (cdr (assoc first-nt first-ops-table
)))
308 (unless (member op first-ops
)
310 (push op
(cdr first-ops
))))))))
311 ;; Same thing for last-ops.
313 (while (prog1 again
(setq again nil
))
314 (dolist (last-nts last-nts-table
)
315 (let* ((nt (pop last-nts
))
316 (last-ops (assoc nt last-ops-table
)))
317 (dolist (last-nt last-nts
)
318 (dolist (op (cdr (assoc last-nt last-ops-table
)))
319 (unless (member op last-ops
)
321 (push op
(cdr last-ops
))))))))
322 ;; Now generate the 2D precedence table.
324 (dolist (rhs (cdr rules
))
327 ((member (car rhs
) nts
)
328 (dolist (last (cdr (assoc (car rhs
) last-ops-table
)))
329 (smie-set-prec2tab prec2 last
(cadr rhs
) '> override
)))
330 ((member (cadr rhs
) nts
)
331 (dolist (first (cdr (assoc (cadr rhs
) first-ops-table
)))
332 (smie-set-prec2tab prec2
(car rhs
) first
'< override
))
333 (if (and (cddr rhs
) (not (member (car (cddr rhs
)) nts
)))
334 (smie-set-prec2tab prec2
(car rhs
) (car (cddr rhs
))
336 (t (smie-set-prec2tab prec2
(car rhs
) (cadr rhs
) '= override
)))
337 (setq rhs
(cdr rhs
)))))
338 ;; Keep track of which tokens are openers/closer, so they can get a nil
339 ;; precedence in smie-prec2->grammar.
340 (puthash :smie-open
/close-alist
(smie-bnf--classify bnf
) prec2
)
341 (puthash :smie-closer-alist
(smie-bnf--closer-alist bnf
) prec2
)
342 (if (> smie-warning-count
0)
344 'smie
(format "Total: %d warnings" smie-warning-count
)))
347 ;; (defun smie-prec2-closer-alist (prec2 include-inners)
348 ;; "Build a closer-alist from a PREC2 table.
349 ;; The return value is in the same form as `smie-closer-alist'.
350 ;; INCLUDE-INNERS if non-nil means that inner keywords will be included
351 ;; in the table, e.g. the table will include things like (\"if\" . \"else\")."
352 ;; (let* ((non-openers '())
354 ;; ;; For each keyword, this gives the matching openers, if any.
355 ;; (openers (make-hash-table :test 'equal))
358 ;; ;; First, find the non-openers and non-closers.
359 ;; (maphash (lambda (k v)
360 ;; (unless (or (eq v '<) (member (cdr k) non-openers))
361 ;; (push (cdr k) non-openers))
362 ;; (unless (or (eq v '>) (member (car k) non-closers))
363 ;; (push (car k) non-closers)))
365 ;; ;; Then find the openers and closers.
366 ;; (maphash (lambda (k _)
367 ;; (unless (member (car k) non-openers)
368 ;; (puthash (car k) (list (car k)) openers))
369 ;; (unless (or (member (cdr k) non-closers)
370 ;; (member (cdr k) closers))
371 ;; (push (cdr k) closers)))
373 ;; ;; Then collect the matching elements.
376 ;; (maphash (lambda (k v)
378 ;; (let ((aopeners (gethash (car k) openers))
379 ;; (dopeners (gethash (cdr k) openers))
381 ;; (dolist (o aopeners)
382 ;; (unless (member o dopeners)
384 ;; (push o dopeners)))
387 ;; (puthash (cdr k) dopeners openers)))))
389 ;; ;; Finally, dump the resulting table.
390 ;; (let ((alist '()))
391 ;; (maphash (lambda (k v)
392 ;; (when (or include-inners (member k closers))
393 ;; (dolist (opener v)
394 ;; (unless (equal opener k)
395 ;; (push (cons opener k) alist)))))
399 (defun smie-bnf--closer-alist (bnf &optional no-inners
)
400 ;; We can also build this closer-alist table from a prec2 table,
401 ;; but it takes more work, and the order is unpredictable, which
402 ;; is a problem for smie-close-block.
403 ;; More convenient would be to build it from a levels table since we
404 ;; always have this table (contrary to the BNF), but it has all the
405 ;; disadvantages of the prec2 case plus the disadvantage that the levels
406 ;; table has lost some info which would result in extra invalid pairs.
407 "Build a closer-alist from a BNF table.
408 The return value is in the same form as `smie-closer-alist'.
409 NO-INNERS if non-nil means that inner keywords will be excluded
410 from the table, e.g. the table will not include things like (\"if\" . \"else\")."
411 (let ((nts (mapcar #'car bnf
)) ;non terminals.
414 (dolist (rhs (cdr nt
))
415 (unless (or (< (length rhs
) 2) (member (car rhs
) nts
))
417 (let ((last (car (last rhs
))))
418 (unless (member last nts
)
419 (pushnew (cons (car rhs
) last
) alist
:test
#'equal
)))
420 ;; Reverse so that the "real" closer gets there first,
421 ;; which is important for smie-close-block.
422 (dolist (term (reverse (cdr rhs
)))
423 (unless (member term nts
)
424 (pushnew (cons (car rhs
) term
) alist
:test
#'equal
)))))))
427 (defun smie-bnf--set-class (table token class
)
428 (let ((prev (gethash token table class
)))
431 ((eq prev class
) class
)
432 ((eq prev t
) t
) ;Non-terminal.
435 (format "token %s is both %s and %s" token class prev
))
439 (defun smie-bnf--classify (bnf)
440 "Return a table classifying terminals.
441 Each terminal can either be an `opener', a `closer', or `neither'."
442 (let ((table (make-hash-table :test
#'equal
))
444 (dolist (category bnf
)
445 (puthash (car category
) t table
)) ;Mark non-terminals.
446 (dolist (category bnf
)
447 (dolist (rhs (cdr category
))
449 (smie-bnf--set-class table
(pop rhs
) 'neither
)
450 (smie-bnf--set-class table
(pop rhs
) 'opener
)
451 (while (cdr rhs
) ;Remove internals.
452 (smie-bnf--set-class table
(pop rhs
) 'neither
))
453 (smie-bnf--set-class table
(pop rhs
) 'closer
))))
454 (maphash (lambda (tok v
)
455 (when (memq v
'(closer opener
))
456 (push (cons tok v
) alist
)))
460 (defun smie-debug--prec2-cycle (csts)
461 "Return a cycle in CSTS, assuming there's one.
462 CSTS is a list of pairs representing arcs in a graph."
463 ;; A PATH is of the form (START . REST) where REST is a reverse
464 ;; list of nodes through which the path goes.
465 (let ((paths (mapcar (lambda (pair) (list (car pair
) (cdr pair
))) csts
))
468 (dolist (path (prog1 paths
(setq paths nil
)))
470 (when (eq (car cst
) (nth 1 path
))
471 (if (eq (cdr cst
) (car path
))
473 (push (cons (car path
) (cons (cdr cst
) (cdr path
)))
475 (cons (car cycle
) (nreverse (cdr cycle
)))))
477 (defun smie-debug--describe-cycle (table cycle
)
479 (mapcar (lambda (val)
482 (if (eq (cdr elem
) val
)
483 (push (concat "." (car elem
)) res
))
484 (if (eq (cddr elem
) val
)
485 (push (concat (car elem
) ".") res
)))
490 (lambda (elems) (mapconcat 'identity elems
"="))
491 (append names
(list (car names
)))
494 ;; (defun smie-check-grammar (grammar prec2 &optional dummy)
495 ;; (maphash (lambda (k v)
497 ;; (let ((left (nth 2 (assoc (car k) grammar)))
498 ;; (right (nth 1 (assoc (cdr k) grammar))))
499 ;; (when (and left right)
501 ;; ((< left right) (assert (eq v '<)))
502 ;; ((> left right) (assert (eq v '>)))
503 ;; (t (assert (eq v '=))))))))
506 (put 'smie-prec2-
>grammar
'pure t
)
507 (defun smie-prec2->grammar
(prec2)
508 "Take a 2D precedence table and turn it into an alist of precedence levels.
509 PREC2 is a table as returned by `smie-precs->prec2' or
511 ;; For each operator, we create two "variables" (corresponding to
512 ;; the left and right precedence level), which are represented by
513 ;; cons cells. Those are the very cons cells that appear in the
514 ;; final `table'. The value of each "variable" is kept in the `car'.
519 ;; From `prec2' we construct a list of constraints between
520 ;; variables (aka "precedence levels"). These can be either
521 ;; equality constraints (in `eqs') or `<' constraints (in `csts').
522 (maphash (lambda (k v
)
524 (if (setq tmp
(assoc (car k
) table
))
526 (setq x
(cons nil nil
))
527 (push (cons (car k
) (cons nil x
)) table
))
528 (if (setq tmp
(assoc (cdr k
) table
))
530 (setq y
(cons nil
(cons nil nil
)))
531 (push (cons (cdr k
) y
) table
))
533 (= (push (cons x y
) eqs
))
534 (< (push (cons x y
) csts
))
535 (> (push (cons y x
) csts
)))))
537 ;; First process the equality constraints.
540 (let ((from (caar eqs
))
545 (dolist (other-eq eqs
)
546 (if (eq from
(cdr other-eq
)) (setcdr other-eq to
))
547 (when (eq from
(car other-eq
))
548 ;; This can happen because of `assoc' settings in precs
549 ;; or because of a rhs like ("op" foo "op").
550 (setcar other-eq to
)))
552 (if (eq from
(cdr cst
)) (setcdr cst to
))
553 (if (eq from
(car cst
)) (setcar cst to
)))))))
554 ;; Then eliminate trivial constraints iteratively.
557 (let ((rhvs (mapcar 'cdr csts
))
560 (unless (memq (car cst
) rhvs
)
562 ;; We could give each var in a given iteration the same value,
563 ;; but we can also give them arbitrarily different values.
564 ;; Basically, these are vars between which there is no
565 ;; constraint (neither equality nor inequality), so
567 ;; We give them arbitrary values, which means that we
568 ;; replace the "no constraint" case with either > or <
569 ;; but not =. The reason we do that is so as to try and
570 ;; distinguish associative operators (which will have
574 ;; (smie-check-grammar table prec2 'step1)
576 (setq csts
(delq cst csts
))))
578 (error "Can't resolve the precedence cycle: %s"
579 (smie-debug--describe-cycle
580 table
(smie-debug--prec2-cycle csts
)))))
582 ;; Propagate equality constraints back to their sources.
583 (dolist (eq (nreverse eqs
))
584 (when (null (cadr eq
))
585 ;; There's an equality constraint, but we still haven't given
586 ;; it a value: that means it binds tighter than anything else,
587 ;; and it can't be an opener/closer (those don't have equality
589 ;; So set it here rather than below since doing it below
590 ;; makes it more difficult to obey the equality constraints.
593 (assert (or (null (caar eq
)) (eq (caar eq
) (cadr eq
))))
594 (setcar (car eq
) (cadr eq
))
595 ;; (smie-check-grammar table prec2 'step2)
597 ;; Finally, fill in the remaining vars (which did not appear on the
598 ;; left side of any < constraint).
602 (incf i
)) ;See other (incf i) above.
605 (incf i
)))) ;See other (incf i) above.
606 ;; Mark closers and openers.
607 (dolist (x (gethash :smie-open
/close-alist prec2
))
608 (let* ((token (car x
))
610 (closer (cddr (assoc token table
)))
611 (opener (cdr (assoc token table
))))))
612 (assert (numberp (car cons
)))
613 (setf (car cons
) (list (car cons
)))))
614 (let ((ca (gethash :smie-closer-alist prec2
)))
615 (when ca
(push (cons :smie-closer-alist ca
) table
)))
616 ;; (smie-check-grammar table prec2 'step3)
619 ;;; Parsing using a precedence level table.
621 (defvar smie-grammar
'unset
622 "List of token parsing info.
623 This list is normally built by `smie-prec2->grammar'.
624 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
625 Parsing is done using an operator precedence parser.
626 LEFT-LEVEL and RIGHT-LEVEL can be either numbers or a list, where a list
627 means that this operator does not bind on the corresponding side,
628 e.g. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
629 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
630 like a close-paren.")
632 (defvar smie-forward-token-function
'smie-default-forward-token
633 "Function to scan forward for the next token.
634 Called with no argument should return a token and move to its end.
635 If no token is found, return nil or the empty string.
636 It can return nil when bumping into a parenthesis, which lets SMIE
637 use syntax-tables to handle them in efficient C code.")
639 (defvar smie-backward-token-function
'smie-default-backward-token
640 "Function to scan backward the previous token.
641 Same calling convention as `smie-forward-token-function' except
642 it should move backward to the beginning of the previous token.")
644 (defalias 'smie-op-left
'car
)
645 (defalias 'smie-op-right
'cadr
)
647 (defun smie-default-backward-token ()
648 (forward-comment (- (point)))
649 (buffer-substring-no-properties
651 (progn (if (zerop (skip-syntax-backward "."))
652 (skip-syntax-backward "w_'"))
655 (defun smie-default-forward-token ()
656 (forward-comment (point-max))
657 (buffer-substring-no-properties
659 (progn (if (zerop (skip-syntax-forward "."))
660 (skip-syntax-forward "w_'"))
663 (defun smie--associative-p (toklevels)
664 ;; in "a + b + c" we want to stop at each +, but in
665 ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
666 ;; To distinguish the two cases, we made smie-prec2->grammar choose
667 ;; different levels for each part of "if a then b else c", so that
668 ;; by checking if the left-level is equal to the right level, we can
669 ;; figure out that it's an associative operator.
670 ;; This is not 100% foolproof, tho, since the "elsif" will have to have
671 ;; equal left and right levels (since it's optional), so smie-next-sexp
672 ;; has to be careful to distinguish those different cases.
673 (eq (smie-op-left toklevels
) (smie-op-right toklevels
)))
675 (defun smie-next-sexp (next-token next-sexp op-forw op-back halfsexp
)
677 NEXT-TOKEN is a function of no argument that moves forward by one
678 token (after skipping comments if needed) and returns it.
679 NEXT-SEXP is a lower-level function to skip one sexp.
680 OP-FORW is the accessor to the forward level of the level data.
681 OP-BACK is the accessor to the backward level of the level data.
682 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
683 first token we see is an operator, skip over its left-hand-side argument.
684 HALFSEXP can also be a token, in which case it means to parse as if
685 we had just successfully passed this token.
686 Possible return values:
687 (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
688 is too high. FORW-LEVEL is the forw-level of TOKEN,
689 POS is its start position in the buffer.
690 (t POS TOKEN): same thing when we bump on the wrong side of a paren.
691 Instead of t, the `car' can also be some other non-nil non-number value.
692 (nil POS TOKEN): we skipped over a paren-like pair.
693 nil: we skipped over an identifier, matched parentheses, ..."
696 (if (stringp halfsexp
)
697 (prog1 (list (cdr (assoc halfsexp smie-grammar
)))
698 (setq halfsexp nil
)))))
701 (token (funcall next-token
))
702 (toklevels (cdr (assoc token smie-grammar
))))
705 (when (zerop (length token
))
707 (progn (goto-char pos
) (funcall next-sexp
1) nil
)
708 (scan-error (throw 'return
710 (buffer-substring-no-properties
713 (if (< (point) (caddr err
))
716 ;; We did not move, so let's abort the loop.
717 (throw 'return
(list t
(point))))))
718 ((not (numberp (funcall op-back toklevels
)))
719 ;; A token like a paren-close.
720 (assert (numberp ; Otherwise, why mention it in smie-grammar.
721 (funcall op-forw toklevels
)))
722 (push toklevels levels
))
724 (while (and levels
(< (funcall op-back toklevels
)
725 (funcall op-forw
(car levels
))))
726 (setq levels
(cdr levels
)))
729 (if (and halfsexp
(numberp (funcall op-forw toklevels
)))
730 (push toklevels levels
)
732 (prog1 (list (or (funcall op-forw toklevels
) t
)
736 (let ((lastlevels levels
))
737 (if (and levels
(= (funcall op-back toklevels
)
738 (funcall op-forw
(car levels
))))
739 (setq levels
(cdr levels
)))
740 ;; We may have found a match for the previously pending
741 ;; operator. Is this the end?
743 ;; Keep looking as long as we haven't matched the
747 ((numberp (funcall op-forw toklevels
))
748 (push toklevels levels
))
749 ;; FIXME: For some languages, we can express the grammar
750 ;; OK, but next-sexp doesn't stop where we'd want it to.
751 ;; E.g. in SML, we'd want to stop right in front of
752 ;; "local" if we're scanning (both forward and backward)
753 ;; from a "val/fun/..." at the same level.
754 ;; Same for Pascal/Modula2's "procedure" w.r.t
757 ;; ((and (functionp (cadr (funcall op-forw toklevels)))
758 ;; (funcall (cadr (funcall op-forw toklevels))
760 ;; (setq levels nil))
762 ;; We matched the topmost operator. If the new operator
763 ;; is the last in the corresponding BNF rule, we're done.
764 ((not (numberp (funcall op-forw toklevels
)))
765 ;; It is the last element, let's stop here.
766 (throw 'return
(list nil
(point) token
)))
767 ;; If the new operator is not the last in the BNF rule,
768 ;; and is not associative, it's one of the inner operators
769 ;; (like the "in" in "let .. in .. end"), so keep looking.
770 ((not (smie--associative-p toklevels
))
771 (push toklevels levels
))
772 ;; The new operator is associative. Two cases:
773 ;; - it's really just an associative operator (like + or ;)
774 ;; in which case we should have stopped right before.
776 (smie--associative-p (car lastlevels
)))
778 (prog1 (list (or (funcall op-forw toklevels
) t
)
781 ;; - it's an associative operator within a larger construct
782 ;; (e.g. an "elsif"), so we should just ignore it and keep
783 ;; looking for the closing element.
784 (t (setq levels lastlevels
))))))))
786 (setq halfsexp nil
)))))
788 (defun smie-backward-sexp (&optional halfsexp
)
790 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
791 first token we see is an operator, skip over its left-hand-side argument.
792 HALFSEXP can also be a token, in which case we should skip the text
793 assuming it is the left-hand-side argument of that token.
794 Possible return values:
795 (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
796 is too high. LEFT-LEVEL is the left-level of TOKEN,
797 POS is its start position in the buffer.
798 (t POS TOKEN): same thing but for an open-paren or the beginning of buffer.
799 Instead of t, the `car' can also be some other non-nil non-number value.
800 (nil POS TOKEN): we skipped over a paren-like pair.
801 nil: we skipped over an identifier, matched parentheses, ..."
803 (indirect-function smie-backward-token-function
)
804 (indirect-function 'backward-sexp
)
805 (indirect-function 'smie-op-left
)
806 (indirect-function 'smie-op-right
)
809 (defun smie-forward-sexp (&optional halfsexp
)
811 HALFSEXP if non-nil, means skip over a partial sexp if needed. I.e. if the
812 first token we see is an operator, skip over its right-hand-side argument.
813 HALFSEXP can also be a token, in which case we should skip the text
814 assuming it is the right-hand-side argument of that token.
815 Possible return values:
816 (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
817 is too high. RIGHT-LEVEL is the right-level of TOKEN,
818 POS is its end position in the buffer.
819 (t POS TOKEN): same thing but for a close-paren or the end of buffer.
820 Instead of t, the `car' can also be some other non-nil non-number value.
821 (nil POS TOKEN): we skipped over a paren-like pair.
822 nil: we skipped over an identifier, matched parentheses, ..."
824 (indirect-function smie-forward-token-function
)
825 (indirect-function 'forward-sexp
)
826 (indirect-function 'smie-op-right
)
827 (indirect-function 'smie-op-left
)
830 ;;; Miscellaneous commands using the precedence parser.
832 (defun smie-backward-sexp-command (&optional n
)
833 "Move backward through N logical elements."
835 (smie-forward-sexp-command (- n
)))
837 (defun smie-forward-sexp-command (&optional n
)
838 "Move forward through N logical elements."
841 (forward-sexp-function nil
))
843 (setq n
(- n
(if forw
1 -
1)))
846 (smie-forward-sexp 'halfsexp
)
847 (smie-backward-sexp 'halfsexp
))))
848 (if (and (car res
) (= pos
(point)) (not (if forw
(eobp) (bobp))))
850 (list "Containing expression ends prematurely"
851 (cadr res
) (cadr res
)))
854 (defvar smie-closer-alist nil
855 "Alist giving the closer corresponding to an opener.")
857 (defun smie-close-block ()
858 "Close the closest surrounding block."
863 (if (looking-at "\\s(")
864 (string (cdr (syntax-after (point))))
865 (let* ((open (funcall smie-forward-token-function
))
866 (closer (cdr (assoc open smie-closer-alist
)))
867 (levels (list (assoc open smie-grammar
)))
871 ;; Even if we improve the auto-computation of closers,
872 ;; there are still cases where we need manual
873 ;; intervention, e.g. for Octave's use of `until'
874 ;; as a pseudo-closer of `do'.
876 ((or (equal levels
'(nil)) (numberp (nth 1 (car levels
))))
877 (error "Doesn't look like a block"))
879 ;; Now that smie-setup automatically sets smie-closer-alist
880 ;; from the BNF, this is not really needed any more.
882 (let ((level (pop levels
)))
883 (dolist (other smie-grammar
)
884 (when (and (eq (nth 2 level
) (nth 1 other
))
885 (not (memq other seen
)))
887 (if (numberp (nth 2 other
))
889 (push (car other
) found
))))))
891 ((null found
) (error "No known closer for opener %s" open
))
892 ;; What should we do if there are various closers?
893 (t (car found
))))))))))
894 (unless (save-excursion (skip-chars-backward " \t") (bolp))
897 (if (save-excursion (skip-chars-forward " \t") (eolp))
898 (indent-according-to-mode)
899 (reindent-then-newline-and-indent))))
901 (defun smie-down-list (&optional arg
)
902 "Move forward down one level paren-like blocks. Like `down-list'.
903 With argument ARG, do this that many times.
904 A negative argument means move backward but still go down a level.
905 This command assumes point is not in a string or comment."
907 (let ((start (point))
908 (inc (if (< arg
0) -
1 1))
909 (offset (if (< arg
0) 1 0))
910 (next-token (if (< arg
0)
911 smie-backward-token-function
912 smie-forward-token-function
)))
914 (setq arg
(- arg inc
))
917 (token (funcall next-token
))
918 (levels (assoc token smie-grammar
)))
920 ((zerop (length token
))
921 (if (if (< inc
0) (looking-back "\\s(\\|\\s)" (1- (point)))
922 (looking-at "\\s(\\|\\s)"))
923 ;; Go back to `start' in case of an error. This presumes
924 ;; none of the token we've found until now include a ( or ).
925 (progn (goto-char start
) (down-list inc
) nil
)
928 ((and levels
(not (numberp (nth (+ 1 offset
) levels
)))) nil
)
929 ((and levels
(not (numberp (nth (- 2 offset
) levels
))))
933 (list "Containing expression ends prematurely"
937 (defvar smie-blink-matching-triggers
'(?\s ?
\n)
938 "Chars which might trigger `blink-matching-open'.
939 These can include the final chars of end-tokens, or chars that are
940 typically inserted right after an end token.
941 I.e. a good choice can be:
943 (mapcar (lambda (kw) (aref (cdr kw) (1- (length (cdr kw)))))
944 smie-closer-alist))")
946 (defcustom smie-blink-matching-inners t
947 "Whether SMIE should blink to matching opener for inner keywords.
948 If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
952 (defun smie-blink-matching-check (start end
)
955 (let ((ender (funcall smie-backward-token-function
)))
957 ((not (and ender
(rassoc ender smie-closer-alist
)))
958 ;; This not is one of the begin..end we know how to check.
959 (blink-matching-check-mismatch start end
))
961 ((eq t
(car (rassoc ender smie-closer-alist
))) nil
)
964 (let ((starter (funcall smie-forward-token-function
)))
965 (not (member (cons starter ender
) smie-closer-alist
))))))))
967 (defun smie-blink-matching-open ()
968 "Blink the matching opener when applicable.
969 This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
970 (let ((pos (point)) ;Position after the close token.
972 (when (and blink-matching-paren
973 smie-closer-alist
; Optimization.
974 (or (eq (char-before) last-command-event
) ;; Sanity check.
976 (or (progn (skip-chars-backward " \t")
978 (eq (char-before) last-command-event
))
979 (progn (skip-chars-backward " \n\t")
981 (eq (char-before) last-command-event
)))))
982 (memq last-command-event smie-blink-matching-triggers
)
983 (not (nth 8 (syntax-ppss))))
985 (setq token
(funcall smie-backward-token-function
))
986 (when (and (eq (point) (1- pos
))
988 (not (rassoc token smie-closer-alist
)))
989 ;; The trigger char is itself a token but is not one of the
990 ;; closers (e.g. ?\; in Octave mode), so go back to the
993 (setq token
(funcall smie-backward-token-function
)))
994 (when (rassoc token smie-closer-alist
)
995 ;; We're after a close token. Let's still make sure we
996 ;; didn't skip a comment to find that token.
997 (funcall smie-forward-token-function
)
998 (when (and (save-excursion
999 ;; Skip the trigger char, if applicable.
1000 (if (eq (char-after) last-command-event
)
1002 (if (eq ?
\n last-command-event
)
1003 ;; Skip any auto-indentation, if applicable.
1004 (skip-chars-forward " \t"))
1006 ;; If token ends with a trigger char, don't blink for
1007 ;; anything else than this trigger char, lest we'd blink
1008 ;; both when inserting the trigger char and when
1009 ;; inserting a subsequent trigger char like SPC.
1010 (or (eq (char-before) last-command-event
)
1011 (not (memq (char-before)
1012 smie-blink-matching-triggers
)))
1013 (or smie-blink-matching-inners
1014 (not (numberp (nth 2 (assoc token smie-grammar
))))))
1015 ;; The major mode might set blink-matching-check-function
1016 ;; buffer-locally so that interactive calls to
1017 ;; blink-matching-open work right, but let's not presume
1019 (let ((blink-matching-check-function #'smie-blink-matching-check
))
1020 (blink-matching-open))))))))
1022 ;;; The indentation engine.
1024 (defcustom smie-indent-basic
4
1025 "Basic amount of indentation."
1029 (defvar smie-rules-function
'ignore
1030 "Function providing the indentation rules.
1031 It takes two arguments METHOD and ARG where the meaning of ARG
1032 and the expected return value depends on METHOD.
1034 - :after, in which case ARG is a token and the function should return the
1035 OFFSET to use for indentation after ARG.
1036 - :before, in which case ARG is a token and the function should return the
1037 OFFSET to use to indent ARG itself.
1038 - :elem, in which case the function should return either:
1039 - the offset to use to indent function arguments (ARG = `arg')
1040 - the basic indentation step (ARG = `basic').
1041 - :list-intro, in which case ARG is a token and the function should return
1042 non-nil if TOKEN is followed by a list of expressions (not separated by any
1043 token) rather than an expression.
1045 When ARG is a token, the function is called with point just before that token.
1046 A return value of nil always means to fallback on the default behavior, so the
1047 function should return nil for arguments it does not expect.
1050 nil use the default indentation rule.
1051 \(column . COLUMN) indent to column COLUMN.
1052 NUMBER offset by NUMBER, relative to a base token
1053 which is the current token for :after and
1054 its parent for :before.
1056 The functions whose name starts with \"smie-rule-\" are helper functions
1057 designed specifically for use in this function.")
1059 (defalias 'smie-rule-hanging-p
'smie-indent--hanging-p
)
1060 (defun smie-indent--hanging-p ()
1061 "Return non-nil if the current token is \"hanging\".
1062 A hanging keyword is one that's at the end of a line except it's not at
1063 the beginning of a line."
1064 (and (not (smie-indent--bolp))
1066 (<= (line-end-position)
1068 (when (zerop (length (funcall smie-forward-token-function
)))
1069 ;; Could be an open-paren.
1071 (skip-chars-forward " \t")
1073 (and (looking-at comment-start-skip
)
1074 (forward-comment (point-max))))
1077 (defalias 'smie-rule-bolp
'smie-indent--bolp
)
1078 (defun smie-indent--bolp ()
1079 "Return non-nil if the current token is the first on the line."
1080 (save-excursion (skip-chars-backward " \t") (bolp)))
1082 (defun smie-indent--bolp-1 ()
1083 ;; Like smie-indent--bolp but also returns non-nil if it's the first
1084 ;; non-comment token. Maybe we should simply always use this?
1085 "Return non-nil if the current token is the first on the line.
1086 Comments are treated as spaces."
1087 (let ((bol (line-beginning-position)))
1089 (forward-comment (- (point)))
1092 ;; Dynamically scoped.
1093 (defvar smie--parent
) (defvar smie--after
) (defvar smie--token
)
1095 (defun smie-indent--parent ()
1098 (let* ((pos (point))
1099 (tok (funcall smie-forward-token-function
)))
1100 (unless (numberp (cadr (assoc tok smie-grammar
)))
1103 (or (smie-backward-sexp 'halfsexp
)
1105 (while (null (setq res
(smie-backward-sexp))))
1106 (list nil
(point) (nth 2 res
)))))))))
1108 (defun smie-rule-parent-p (&rest parents
)
1109 "Return non-nil if the current token's parent is among PARENTS.
1110 Only meaningful when called from within `smie-rules-function'."
1111 (member (nth 2 (smie-indent--parent)) parents
))
1113 (defun smie-rule-next-p (&rest tokens
)
1114 "Return non-nil if the next token is among TOKENS.
1115 Only meaningful when called from within `smie-rules-function'."
1119 (smie-indent-forward-token) (setq smie--after
(point)))
1120 (goto-char smie--after
)
1121 (smie-indent-forward-token))))
1122 (member (car next
) tokens
)))
1124 (defun smie-rule-prev-p (&rest tokens
)
1125 "Return non-nil if the previous token is among TOKENS."
1126 (let ((prev (save-excursion
1127 (smie-indent-backward-token))))
1128 (member (car prev
) tokens
)))
1130 (defun smie-rule-sibling-p ()
1131 "Return non-nil if the parent is actually a sibling.
1132 Only meaningful when called from within `smie-rules-function'."
1133 (eq (car (smie-indent--parent))
1134 (cadr (assoc smie--token smie-grammar
))))
1136 (defun smie-rule-parent (&optional offset
)
1138 If non-nil, OFFSET should be an integer giving an additional offset to apply.
1139 Only meaningful when called from within `smie-rules-function'."
1141 (goto-char (cadr (smie-indent--parent)))
1144 ;; Use smie-indent-virtual when indenting relative to an opener:
1145 ;; this will also by default use current-column unless
1146 ;; that opener is hanging, but will additionally consult
1147 ;; rules-function, so it gives it a chance to tweak
1148 ;; indentation (e.g. by forcing indentation relative to
1149 ;; its own parent, as in fn a => fn b => fn c =>).
1150 (if (or (listp (car smie--parent
)) (smie-indent--hanging-p))
1151 (smie-indent-virtual) (current-column))))))
1153 (defvar smie-rule-separator-outdent
2)
1155 (defun smie-indent--separator-outdent ()
1156 ;; FIXME: Here we actually have several reasonable behaviors.
1157 ;; E.g. for a parent token of "FOO" and a separator ";" we may want to:
1158 ;; 1- left-align ; with FOO.
1159 ;; 2- right-align ; with FOO.
1160 ;; 3- align content after ; with content after FOO.
1161 ;; 4- align content plus add/remove spaces so as to align ; with FOO.
1162 ;; Currently, we try to align the contents (option 3) which actually behaves
1163 ;; just like option 2 (if the number of spaces after FOO and ; is equal).
1164 (let ((afterpos (save-excursion
1165 (let ((tok (funcall smie-forward-token-function
)))
1167 (with-demoted-errors
1168 (error "smie-rule-separator: can't skip token %s"
1170 (skip-chars-forward " ")
1171 (unless (eolp) (point)))))
1173 ;; This should always be true, unless
1174 ;; smie-forward-token-function skipped a \n.
1175 (< afterpos
(line-end-position))
1176 (- afterpos
(point)))
1177 smie-rule-separator-outdent
)))
1179 (defun smie-rule-separator (method)
1180 "Indent current token as a \"separator\".
1181 By \"separator\", we mean here a token whose sole purpose is to separate
1182 various elements within some enclosing syntactic construct, and which does
1183 not have any semantic significance in itself (i.e. it would typically no exist
1184 as a node in an abstract syntax tree).
1185 Such a token is expected to have an associative syntax and be closely tied
1186 to its syntactic parent. Typical examples are \",\" in lists of arguments
1187 \(enclosed inside parentheses), or \";\" in sequences of instructions (enclosed
1188 in a {..} or begin..end block).
1189 METHOD should be the method name that was passed to `smie-rules-function'.
1190 Only meaningful when called from within `smie-rules-function'."
1191 ;; FIXME: The code below works OK for cases where the separators
1192 ;; are placed consistently always at beginning or always at the end,
1193 ;; but not if some are at the beginning and others are at the end.
1194 ;; I.e. it gets confused in cases such as:
1202 ;; Assuming token is associative, the default rule for associative
1203 ;; tokens (which assumes an infix operator) works fine for many cases.
1204 ;; We mostly need to take care of the case where token is at beginning of
1205 ;; line, in which case we want to align it with its enclosing parent.
1207 ((and (eq method
:before
) (smie-rule-bolp) (not (smie-rule-sibling-p)))
1208 (let ((parent-col (cdr (smie-rule-parent)))
1209 (parent-pos-col ;FIXME: we knew this when computing smie--parent.
1211 (goto-char (cadr smie--parent
))
1212 (smie-indent-forward-token)
1213 (forward-comment (point-max))
1218 (- parent-pos-col
(smie-indent--separator-outdent)))))))
1219 ((and (eq method
:after
) (smie-indent--bolp))
1220 (smie-indent--separator-outdent))))
1222 (defun smie-indent--offset (elem)
1223 (or (funcall smie-rules-function
:elem elem
)
1224 (if (not (eq elem
'basic
))
1225 (funcall smie-rules-function
:elem
'basic
))
1228 (defun smie-indent--rule (method token
1229 ;; FIXME: Too many parameters.
1230 &optional after parent base-pos
)
1231 "Compute indentation column according to `indent-rule-functions'.
1232 METHOD and TOKEN are passed to `indent-rule-functions'.
1233 AFTER is the position after TOKEN, if known.
1234 PARENT is the parent info returned by `smie-backward-sexp', if known.
1235 BASE-POS is the position relative to which offsets should be applied."
1236 ;; This is currently called in 3 cases:
1237 ;; - :before opener, where rest=nil but base-pos could as well be parent.
1238 ;; - :before other, where
1241 ;; ; base-pos=parent
1242 ;; - :after tok, where
1243 ;; ; after is set; parent=nil; base-pos=point;
1246 (let ((smie--parent parent
)
1248 (smie--after after
))
1249 (funcall smie-rules-function method token
))))
1252 ((eq (car-safe offset
) 'column
) (cdr offset
))
1255 (if (null base-pos
) 0
1256 (goto-char base-pos
)
1257 ;; Use smie-indent-virtual when indenting relative to an opener:
1258 ;; this will also by default use current-column unless
1259 ;; that opener is hanging, but will additionally consult
1260 ;; rules-function, so it gives it a chance to tweak indentation
1261 ;; (e.g. by forcing indentation relative to its own parent, as in
1262 ;; fn a => fn b => fn c =>).
1263 ;; When parent==nil it doesn't matter because the only case
1264 ;; where it's really used is when the base-pos is hanging anyway.
1265 (if (or (and parent
(null (car parent
)))
1266 (smie-indent--hanging-p))
1267 (smie-indent-virtual) (current-column)))))
1268 (t (error "Unknown indentation offset %s" offset
))))))
1270 (defun smie-indent-forward-token ()
1271 "Skip token forward and return it, along with its levels."
1272 (let ((tok (funcall smie-forward-token-function
)))
1274 ((< 0 (length tok
)) (assoc tok smie-grammar
))
1275 ((looking-at "\\s(\\|\\s)\\(\\)")
1277 (cons (buffer-substring (1- (point)) (point))
1278 (if (match-end 1) '(0 nil
) '(nil 0)))))))
1280 (defun smie-indent-backward-token ()
1281 "Skip token backward and return it, along with its levels."
1282 (let ((tok (funcall smie-backward-token-function
))
1285 ((< 0 (length tok
)) (assoc tok smie-grammar
))
1286 ;; 4 == open paren syntax, 5 == close.
1287 ((memq (setq class
(syntax-class (syntax-after (1- (point))))) '(4 5))
1289 (cons (buffer-substring (point) (1+ (point)))
1290 (if (eq class
4) '(nil 0) '(0 nil
)))))))
1292 (defun smie-indent-virtual ()
1293 ;; We used to take an optional arg (with value :not-hanging) to specify that
1294 ;; we should only use (smie-indent-calculate) if we're looking at a hanging
1295 ;; keyword. This was a bad idea, because the virtual indent of a position
1296 ;; should not depend on the caller, since it leads to situations where two
1297 ;; dependent indentations get indented differently.
1298 "Compute the virtual indentation to use for point.
1299 This is used when we're not trying to indent point but just
1300 need to compute the column at which point should be indented
1301 in order to figure out the indentation of some other (further down) point."
1302 ;; Trust pre-existing indentation on other lines.
1303 (if (smie-indent--bolp) (current-column) (smie-indent-calculate)))
1305 (defun smie-indent-fixindent ()
1306 ;; Obey the `fixindent' special comment.
1307 (and (smie-indent--bolp)
1309 (comment-normalize-vars)
1310 (re-search-forward (concat comment-start-skip
1313 ;; 1+ to account for the \n comment termination.
1314 (1+ (line-end-position)) t
))
1317 (defun smie-indent-bob ()
1318 ;; Start the file at column 0.
1320 (forward-comment (- (point)))
1323 (defun smie-indent-close ()
1324 ;; Align close paren with opening paren.
1326 ;; (forward-comment (point-max))
1327 (when (looking-at "\\s)")
1328 (while (not (zerop (skip-syntax-forward ")")))
1329 (skip-chars-forward " \t"))
1333 (smie-indent-virtual)) ;:not-hanging
1334 (scan-error nil
)))))
1336 (defun smie-indent-keyword (&optional token
)
1337 "Indent point based on the token that follows it immediately.
1338 If TOKEN is non-nil, assume that that is the token that follows point.
1339 Returns either a column number or nil if it considers that indentation
1340 should not be computed on the basis of the following token."
1342 (let* ((pos (point))
1345 (assoc token smie-grammar
)
1346 (let* ((res (smie-indent-forward-token)))
1347 ;; Ignore tokens on subsequent lines.
1348 (if (and (< pos
(line-beginning-position))
1349 ;; Make sure `token' also *starts* on another line.
1351 (smie-indent-backward-token)
1352 (< pos
(line-beginning-position))))
1356 (setq token
(pop toklevels
))
1358 ((null (cdr toklevels
)) nil
) ;Not a keyword.
1359 ((not (numberp (car toklevels
)))
1361 ;; - smie-indent--bolp: "indent according to others".
1362 ;; - common hanging: "indent according to others".
1363 ;; - SML-let hanging: "indent like parent".
1364 ;; - if-after-else: "indent-like parent".
1365 ;; - middle-of-line: "trust current position".
1367 ((smie-indent--rule :before token
))
1368 ((smie-indent--bolp-1) ;I.e. non-virtual indent.
1369 ;; For an open-paren-like thingy at BOL, always indent only
1370 ;; based on other rules (typically smie-indent-after-keyword).
1371 ;; FIXME: we do the same if after a comment, since we may be trying
1372 ;; to compute the indentation of this comment and we shouldn't indent
1373 ;; based on the indentation of subsequent code.
1376 ;; By default use point unless we're hanging.
1377 (unless (smie-indent--hanging-p) (current-column)))))
1379 ;; FIXME: This still looks too much like black magic!!
1380 (let* ((parent (smie-backward-sexp token
)))
1381 ;; Different behaviors:
1382 ;; - align with parent.
1383 ;; - parent + offset.
1384 ;; - after parent's column + offset (actually, after or before
1385 ;; depending on where backward-sexp stopped).
1386 ;; ? let it drop to some other indentation function (almost never).
1387 ;; ? parent + offset + parent's own offset.
1389 ;; - bump into a same-level operator.
1390 ;; - bump into a specific known parent.
1391 ;; - find a matching open-paren thingy.
1392 ;; - bump into some random parent.
1393 ;; ? borderline case (almost never).
1394 ;; ? bump immediately into a parent.
1396 ((not (or (< (point) pos
)
1397 (and (cadr parent
) (< (cadr parent
) pos
))))
1398 ;; If we didn't move at all, that means we didn't really skip
1399 ;; what we wanted. Should almost never happen, other than
1400 ;; maybe when an infix or close-paren is at the beginning
1405 (smie-indent--rule :before token nil parent
(cadr parent
))))
1406 ((eq (car parent
) (car toklevels
))
1407 ;; We bumped into a same-level operator; align with it.
1408 (if (and (smie-indent--bolp) (/= (point) pos
)
1410 (goto-char (goto-char (cadr parent
)))
1411 (not (smie-indent--bolp))))
1412 ;; If the parent is at EOL and its children are indented like
1413 ;; itself, then we can just obey the indentation chosen for the
1415 ;; This is important for operators like ";" which
1416 ;; are usually at EOL (and have an offset of 0): otherwise we'd
1417 ;; always go back over all the statements, which is
1418 ;; a performance problem and would also mean that fixindents
1419 ;; in the middle of such a sequence would be ignored.
1421 ;; This is a delicate point!
1422 ;; Even if the offset is not 0, we could follow the same logic
1423 ;; and subtract the offset from the child's indentation.
1424 ;; But that would more often be a bad idea: OT1H we generally
1425 ;; want to reuse the closest similar indentation point, so that
1426 ;; the user's choice (or the fixindents) are obeyed. But OTOH
1427 ;; we don't want this to affect "unrelated" parts of the code.
1428 ;; E.g. a fixindent in the body of a "begin..end" should not
1429 ;; affect the indentation of the "end".
1431 (goto-char (cadr parent
))
1432 ;; Don't use (smie-indent-virtual :not-hanging) here, because we
1433 ;; want to jump back over a sequence of same-level ops such as
1436 ;; So as to align with the earliest appropriate place.
1437 (smie-indent-virtual)))
1439 (if (and (= (point) pos
) (smie-indent--bolp))
1440 ;; Since we started at BOL, we're not computing a virtual
1441 ;; indentation, and we're still at the starting point, so
1442 ;; we can't use `current-column' which would cause
1443 ;; indentation to depend on itself and we can't use
1444 ;; smie-indent-virtual since that would be an inf-loop.
1446 ;; In indent-keyword, if we're indenting `then' wrt `if', we
1447 ;; want to use indent-virtual rather than use just
1448 ;; current-column, so that we can apply the (:before . "if")
1449 ;; rule which does the "else if" dance in SML. But in other
1450 ;; cases, we do not want to use indent-virtual (e.g. indentation
1451 ;; of "*" w.r.t "+", or ";" wrt "("). We could just always use
1452 ;; indent-virtual and then have indent-rules say explicitly to
1453 ;; use `point' after things like "(" or "+" when they're not at
1454 ;; EOL, but you'd end up with lots of those rules.
1455 ;; So we use a heuristic here, which is that we only use virtual
1456 ;; if the parent is tightly linked to the child token (they're
1457 ;; part of the same BNF rule).
1458 (if (car parent
) (current-column) (smie-indent-virtual)))))))))))
1460 (defun smie-indent-comment ()
1461 "Compute indentation of a comment."
1462 ;; Don't do it for virtual indentations. We should normally never be "in
1463 ;; front of a comment" when doing virtual-indentation anyway. And if we are
1464 ;; (as can happen in octave-mode), moving forward can lead to inf-loops.
1465 (and (smie-indent--bolp)
1466 (let ((pos (point)))
1469 (and (re-search-forward comment-start-skip
(line-end-position) t
)
1470 (eq pos
(or (match-end 1) (match-beginning 0))))))
1472 (forward-comment (point-max))
1473 (skip-chars-forward " \t\r\n")
1474 ;; FIXME: We assume here that smie-indent-calculate will compute the
1475 ;; indentation of the next token based on text before the comment, but
1476 ;; this is not guaranteed, so maybe we should let
1477 ;; smie-indent-calculate return some info about which buffer position
1478 ;; was used as the "indentation base" and check that this base is
1480 (smie-indent-calculate))))
1482 (defun smie-indent-comment-continue ()
1483 ;; indentation of comment-continue lines.
1484 (let ((continue (and comment-continue
1485 (comment-string-strip comment-continue t t
))))
1486 (and (< 0 (length continue
))
1487 (looking-at (regexp-quote continue
)) (nth 4 (syntax-ppss))
1488 (let ((ppss (syntax-ppss)))
1491 (if (<= (point) (nth 8 ppss
))
1492 (progn (goto-char (1+ (nth 8 ppss
))) (current-column))
1493 (skip-chars-forward " \t")
1494 (if (looking-at (regexp-quote continue
))
1495 (current-column))))))))
1497 (defun smie-indent-comment-close ()
1498 (and (boundp 'comment-end-skip
)
1500 (not (looking-at " \t*$")) ;Not just a \n comment-closer.
1501 (looking-at comment-end-skip
)
1502 (let ((end (match-string 0)))
1503 (and (nth 4 (syntax-ppss))
1505 (goto-char (nth 8 (syntax-ppss)))
1506 (and (looking-at comment-start-skip
)
1507 (let ((start (match-string 0)))
1508 ;; Align the common substring between starter
1509 ;; and ender, if possible.
1510 (if (string-match "\\(.+\\).*\n\\(.*?\\)\\1"
1511 (concat start
"\n" end
))
1512 (+ (current-column) (match-beginning 0)
1513 (- (match-beginning 2) (match-end 2)))
1514 (current-column)))))))))
1516 (defun smie-indent-comment-inside ()
1517 (and (nth 4 (syntax-ppss))
1520 (defun smie-indent-inside-string ()
1521 (and (nth 3 (syntax-ppss))
1524 (defun smie-indent-after-keyword ()
1525 ;; Indentation right after a special keyword.
1527 (let* ((pos (point))
1528 (toklevel (smie-indent-backward-token))
1529 (tok (car toklevel
)))
1531 ((null toklevel
) nil
)
1532 ((smie-indent--rule :after tok pos nil
(point)))
1533 ;; The default indentation after a keyword/operator is
1534 ;; 0 for infix, t for prefix, and use another rule
1536 ((not (numberp (nth 2 toklevel
))) nil
) ;A closer.
1537 ((or (not (numberp (nth 1 toklevel
))) ;An opener.
1538 (rassoc tok smie-closer-alist
)) ;An inner.
1539 (+ (smie-indent-virtual) (smie-indent--offset 'basic
))) ;
1540 (t (smie-indent-virtual)))))) ;An infix.
1542 (defun smie-indent-exps ()
1543 ;; Indentation of sequences of simple expressions without
1544 ;; intervening keywords or operators. E.g. "a b c" or "g (balbla) f".
1545 ;; Can be a list of expressions or a function call.
1546 ;; If it's a function call, the first element is special (it's the
1547 ;; function). We distinguish function calls from mere lists of
1548 ;; expressions based on whether the preceding token is listed in
1549 ;; the `list-intro' entry of smie-indent-rules.
1551 ;; TODO: to indent Lisp code, we should add a way to specify
1552 ;; particular indentation for particular args depending on the
1553 ;; function (which would require always skipping back until the
1555 ;; TODO: to indent C code, such as "if (...) {...}" we might need
1556 ;; to add similar indentation hooks for particular positions, but
1557 ;; based on the preceding token rather than based on the first exp.
1559 (let ((positions nil
)
1561 (while (and (null (car (smie-backward-sexp)))
1562 (push (point) positions
)
1563 (not (smie-indent--bolp))))
1565 ;; Figure out if the atom we just skipped is an argument rather
1568 (or (null (car (smie-backward-sexp)))
1569 (funcall smie-rules-function
:list-intro
1570 (funcall smie-backward-token-function
)))))
1573 ;; We're the first expression of the list. In that case, the
1574 ;; indentation should be (have been) determined by its context.
1577 ;; There's a previous element, and it's not special (it's not
1578 ;; the function), so let's just align with that one.
1579 (goto-char (car positions
))
1582 ;; We skipped some args plus the function and bumped into something.
1583 ;; Align with the first arg.
1584 (goto-char (cadr positions
))
1587 ;; We're the first arg.
1588 (goto-char (car positions
))
1589 (+ (smie-indent--offset 'args
)
1590 ;; We used to use (smie-indent-virtual), but that
1591 ;; doesn't seem right since it might then indent args less than
1592 ;; the function itself.
1593 (current-column)))))))
1595 (defvar smie-indent-functions
1596 '(smie-indent-fixindent smie-indent-bob smie-indent-close
1597 smie-indent-comment smie-indent-comment-continue smie-indent-comment-close
1598 smie-indent-comment-inside smie-indent-inside-string
1599 smie-indent-keyword smie-indent-after-keyword
1601 "Functions to compute the indentation.
1602 Each function is called with no argument, shouldn't move point, and should
1603 return either nil if it has no opinion, or an integer representing the column
1604 to which that point should be aligned, if we were to reindent it.")
1606 (defun smie-indent-calculate ()
1607 "Compute the indentation to use for point."
1608 (run-hook-with-args-until-success 'smie-indent-functions
))
1610 (defun smie-indent-line ()
1611 "Indent current line using the SMIE indentation engine."
1613 (let* ((savep (point))
1614 (indent (or (with-demoted-errors
1617 (skip-chars-forward " \t")
1618 (if (>= (point) savep
) (setq savep nil
))
1619 (or (smie-indent-calculate) 0)))
1621 (if (not (numberp indent
))
1622 ;; If something funny is used (e.g. `noindent'), return it.
1624 (if (< indent
0) (setq indent
0)) ;Just in case.
1626 (save-excursion (indent-line-to indent
))
1627 (indent-line-to indent
)))))
1629 (defun smie-auto-fill ()
1630 (let ((fc (current-fill-column)))
1631 (while (and fc
(> (current-column) fc
))
1633 ((not (or (nth 8 (save-excursion
1634 (syntax-ppss (line-beginning-position))))
1635 (nth 8 (syntax-ppss))))
1638 (smie-indent-forward-token)
1642 (while (<= (setq curcol
(current-column)) fc
)
1643 ;; FIXME? `smie-indent-calculate' can (and often will)
1644 ;; return a result that actually depends on the presence/absence
1645 ;; of a newline, so the gain computed here may not be accurate,
1646 ;; but in practice it seems to works well enough.
1647 (let* ((newcol (smie-indent-calculate))
1648 (newgain (- curcol newcol
)))
1649 (when (> newgain gain
)
1651 (setq bsf
(point))))
1652 (smie-indent-forward-token))
1655 (newline-and-indent)))))
1656 (t (do-auto-fill))))))
1659 (defun smie-setup (grammar rules-function
&rest keywords
)
1660 "Setup SMIE navigation and indentation.
1661 GRAMMAR is a grammar table generated by `smie-prec2->grammar'.
1662 RULES-FUNCTION is a set of indentation rules for use on `smie-rules-function'.
1663 KEYWORDS are additional arguments, which can use the following keywords:
1664 - :forward-token FUN
1665 - :backward-token FUN"
1666 (set (make-local-variable 'smie-rules-function
) rules-function
)
1667 (set (make-local-variable 'smie-grammar
) grammar
)
1668 (set (make-local-variable 'indent-line-function
) 'smie-indent-line
)
1669 (set (make-local-variable 'normal-auto-fill-function
) 'smie-auto-fill
)
1670 (set (make-local-variable 'forward-sexp-function
)
1671 'smie-forward-sexp-command
)
1673 (let ((k (pop keywords
))
1677 (set (make-local-variable 'smie-forward-token-function
) v
))
1679 (set (make-local-variable 'smie-backward-token-function
) v
))
1680 (t (message "smie-setup: ignoring unknown keyword %s" k
)))))
1681 (let ((ca (cdr (assq :smie-closer-alist grammar
))))
1683 (set (make-local-variable 'smie-closer-alist
) ca
)
1684 ;; Only needed for interactive calls to blink-matching-open.
1685 (set (make-local-variable 'blink-matching-check-function
)
1686 #'smie-blink-matching-check
)
1687 (add-hook 'post-self-insert-hook
1688 #'smie-blink-matching-open
'append
'local
)
1689 (set (make-local-variable 'smie-blink-matching-triggers
)
1690 (append smie-blink-matching-triggers
1691 ;; Rather than wait for SPC to blink, try to blink as
1692 ;; soon as we type the last char of a block ender.
1693 (let ((closers (sort (mapcar #'cdr smie-closer-alist
)
1697 (while (setq closer
(pop closers
))
1698 (unless (and closers
1699 ;; FIXME: this eliminates prefixes of other
1700 ;; closers, but we should probably
1701 ;; eliminate prefixes of other keywords
1703 (string-prefix-p closer
(car closers
)))
1704 (push (aref closer
(1- (length closer
))) triggers
)))
1705 (delete-dups triggers
)))))))
1709 ;;; smie.el ends here