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