Marking message as "seen" should not mark buffer as changed.
[bpt/emacs.git] / lisp / emacs-lisp / smie.el
index 55516d2..17cc566 100644 (file)
@@ -1,6 +1,6 @@
-;;; smie.el --- Simple Minded Indentation Engine
+;;; smie.el --- Simple Minded Indentation Engine -*- lexical-binding: t -*-
 
-;; Copyright (C) 2010  Free Software Foundation, Inc.
+;; Copyright (C) 2010-2011  Free Software Foundation, Inc.
 
 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
 ;; Keywords: languages, lisp, internal, parsing, indentation
@@ -52,9 +52,9 @@
 ;;   error because the parser just automatically does something.  Better yet,
 ;;   we can afford to use a sloppy grammar.
 
-;; The development (especially the parts building the 2D precedence
-;; tables and then computing the precedence levels from it) is largely
-;; inspired from page 187-194 of "Parsing techniques" by Dick Grune
+;; A good background to understand the development (especially the parts
+;; building the 2D precedence tables and then computing the precedence levels
+;; from it) can be found in pages 187-194 of "Parsing techniques" by Dick Grune
 ;; and Ceriel Jacobs (BookBody.pdf available at
 ;; http://www.cs.vu.nl/~dick/PTAPG.html).
 ;;
 ;; Since then, some of that code has been beaten into submission, but the
 ;; smie-indent-keyword is still pretty obscure.
 
-;;; Code:
+;; Conflict resolution:
+;;
+;; - One source of conflicts is when you have:
+;;     (exp ("IF" exp "ELSE" exp "END") ("CASE" cases "END"))
+;;     (cases (cases "ELSE" insts) ...)
+;;   The IF-rule implies ELSE=END and the CASE-rule implies ELSE>END.
+;;   FIXME: we could try to resolve such conflicts automatically by changing
+;;   the way BNF rules such as the IF-rule is handled.  I.e. rather than
+;;   IF=ELSE and ELSE=END, we could turn them into IF<ELSE and ELSE>END
+;;   and IF=END,
+
+;; TODO & BUGS:
+;;
+;; - Using the structural information SMIE gives us, it should be possible to
+;;   implement a `smie-align' command that would automatically figure out what
+;;   there is to align and how to do it (something like: align the token of
+;;   lowest precedence that appears the same number of times on all lines,
+;;   and then do the same on each side of that token).
+;; - Maybe accept two juxtaposed non-terminals in the BNF under the condition
+;;   that the first always ends with a terminal, or that the second always
+;;   starts with a terminal.
+;; - Permit EBNF-style notation.
+;; - If the grammar has conflicts, the only way is to make the lexer return
+;;   different tokens for the different cases.  This extra work performed by
+;;   the lexer can be costly and unnecessary: we perform this extra work every
+;;   time we find the conflicting token, regardless of whether or not the
+;;   difference between the various situations is relevant to the current
+;;   situation.  E.g. we may try to determine whether a ";" is a ";-operator"
+;;   or a ";-separator" in a case where we're skipping over a "begin..end" pair
+;;   where the difference doesn't matter.  For frequently occurring tokens and
+;;   rarely occurring conflicts, this can be a significant performance problem.
+;;   We could try and let the lexer return a "set of possible tokens
+;;   plus a refinement function" and then let parser call the refinement
+;;   function if needed.
+;; - Make it possible to better specify the behavior in the face of
+;;   syntax errors.  IOW provide some control over the choice of precedence
+;;   levels within the limits of the constraints.  E.g. make it possible for
+;;   the grammar to specify that "begin..end" has lower precedence than
+;;   "Module..EndModule", so that if a "begin" is missing, scanning from the
+;;   "end" will stop at "Module" rather than going past it (and similarly,
+;;   scanning from "Module" should not stop at a spurious "end").
 
-;; FIXME: I think the behavior on empty lines is wrong.  It shouldn't
-;; look at the next token on subsequent lines.
+;;; Code:
 
 (eval-when-compile (require 'cl))
 
+(defgroup smie nil
+  "Simple Minded Indentation Engine."
+  :group 'languages)
+
 (defvar comment-continue)
 (declare-function comment-string-strip "newcomment" (str beforep afterp))
 
 ;; - a 2 dimensional precedence table (key word "prec2"), is a 2D
 ;;   table recording the precedence relation (can be `<', `=', `>', or
 ;;   nil) between each pair of tokens.
-;; - a precedence-level table (key word "levels"), while is a alist
+;; - a precedence-level table (key word "grammar"), which is a alist
 ;;   giving for each token its left and right precedence level (a
-;;   number or nil).  This is used in `smie-op-levels'.
+;;   number or nil).  This is used in `smie-grammar'.
 ;; The prec2 tables are only intermediate data structures: the source
 ;; code normally provides a mix of BNF and precs tables, and then
 ;; turns them into a levels table, which is what's used by the rest of
           (display-warning 'smie (format "Conflict: %s %s/%s %s" x old val y)))
       (puthash key val table))))
 
-(defun smie-precs-precedence-table (precs)
+(put 'smie-precs->prec2 'pure t)
+(defun smie-precs->prec2 (precs)
   "Compute a 2D precedence table from a list of precedences.
 PRECS should be a list, sorted by precedence (e.g. \"+\" will
 come before \"*\"), of elements of the form \(left OP ...)
@@ -132,17 +176,29 @@ one of those elements share the same precedence level and associativity."
                 (smie-set-prec2tab prec2-table other-op op op1)))))))
     prec2-table))
 
+(put 'smie-merge-prec2s 'pure t)
 (defun smie-merge-prec2s (&rest tables)
   (if (null (cdr tables))
       (car tables)
     (let ((prec2 (make-hash-table :test 'equal)))
       (dolist (table tables)
         (maphash (lambda (k v)
-                   (smie-set-prec2tab prec2 (car k) (cdr k) v))
+                   (if (consp k)
+                       (smie-set-prec2tab prec2 (car k) (cdr k) v)
+                     (if (and (gethash k prec2)
+                              (not (equal (gethash k prec2) v)))
+                         (error "Conflicting values for %s property" k)
+                       (puthash k v prec2))))
                  table))
       prec2)))
 
-(defun smie-bnf-precedence-table (bnf &rest precs)
+(put 'smie-bnf->prec2 'pure t)
+(defun smie-bnf->prec2 (bnf &rest precs)
+  ;; FIXME: Add repetition operator like (repeat <separator> <elems>).
+  ;; Maybe also add (or <elem1> <elem2>...) for things like
+  ;; (exp (exp (or "+" "*" "=" ..) exp)).
+  ;; Basically, make it EBNF (except for the specification of a separator in
+  ;; the repetition, maybe).
   (let ((nts (mapcar 'car bnf))         ;Non-terminals
         (first-ops-table ())
         (last-ops-table ())
@@ -150,7 +206,7 @@ one of those elements share the same precedence level and associativity."
         (last-nts-table ())
         (prec2 (make-hash-table :test 'equal))
         (override (apply 'smie-merge-prec2s
-                         (mapcar 'smie-precs-precedence-table precs)))
+                         (mapcar 'smie-precs->prec2 precs)))
         again)
     (dolist (rules bnf)
       (let ((nt (car rules))
@@ -225,6 +281,10 @@ one of those elements share the same precedence level and associativity."
                                    '= override)))
            (t (smie-set-prec2tab prec2 (car rhs) (cadr rhs) '= override)))
           (setq rhs (cdr rhs)))))
+    ;; Keep track of which tokens are openers/closer, so they can get a nil
+    ;; precedence in smie-prec2->grammar.
+    (puthash :smie-open/close-alist (smie-bnf-classify bnf) prec2)
+    (puthash :smie-closer-alist (smie-bnf-closer-alist bnf) prec2)
     prec2))
 
 ;; (defun smie-prec2-closer-alist (prec2 include-inners)
@@ -306,7 +366,43 @@ from the table, e.g. the table will not include things like (\"if\" . \"else\").
               (unless (member term nts)
                 (pushnew (cons (car rhs) term) alist :test #'equal)))))))
     (nreverse alist)))
-    
+
+(defun smie-bnf-classify (bnf)
+  "Return a table classifying terminals.
+Each terminal can either be an `opener', a `closer', or neither."
+  (let ((table (make-hash-table :test #'equal))
+        (nts (mapcar #'car bnf))
+        (alist '()))
+    (dolist (category bnf)
+      (puthash (car category) 'neither table) ;Remove non-terminals.
+      (dolist (rhs (cdr category))
+        (if (null (cdr rhs))
+            (puthash (pop rhs) 'neither table)
+          (let ((first (pop rhs)))
+            (puthash first
+                     (if (memq (gethash first table) '(nil opener))
+                         'opener
+                       (unless (member first nts)
+                         (error "SMIE: token %s is both opener and non-opener"
+                                first))
+                       'neither)
+                     table))
+          (while (cdr rhs)
+            (puthash (pop rhs) 'neither table)) ;Remove internals.
+          (let ((last (pop rhs)))
+            (puthash last
+                     (if (memq (gethash last table) '(nil closer))
+                         'closer
+                       (unless (member last nts)
+                         (error "SMIE: token %s is both closer and non-closer"
+                                last))
+                       'neither)
+                     table)))))
+    (maphash (lambda (tok v)
+               (when (memq v '(closer opener))
+                 (push (cons tok v) alist)))
+             table)
+    alist))
 
 (defun smie-debug--prec2-cycle (csts)
   "Return a cycle in CSTS, assuming there's one.
@@ -324,7 +420,7 @@ CSTS is a list of pairs representing arcs in a graph."
               (push (cons (car path) (cons (cdr cst) (cdr path)))
                     paths))))))
     (cons (car cycle) (nreverse (cdr cycle)))))
-            
+
 (defun smie-debug--describe-cycle (table cycle)
   (let ((names
          (mapcar (lambda (val)
@@ -342,21 +438,23 @@ CSTS is a list of pairs representing arcs in a graph."
      (append names (list (car names)))
      " < ")))
 
-(defun smie-prec2-levels (prec2)
-  ;; FIXME: Rather than only return an alist of precedence levels, we should
-  ;; also extract other useful data from it:
-  ;; - matching sets of block openers&closers (which can otherwise become
-  ;;   collapsed into a single equivalence class in smie-op-levels) for
-  ;;   smie-close-block as well as to detect mismatches in smie-next-sexp
-  ;;   or in blink-paren (as well as to do the blink-paren for inner
-  ;;   keywords like the "in" of "let..in..end").
-  ;; - better default indentation rules (i.e. non-zero indentation after inner
-  ;;   keywords like the "in" of "let..in..end") for smie-indent-after-keyword.
-  ;; Of course, maybe those things would be even better handled in the
-  ;; bnf->prec function.
+;; (defun smie-check-grammar (grammar prec2 &optional dummy)
+;;   (maphash (lambda (k v)
+;;              (when (consp k)
+;;                (let ((left (nth 2 (assoc (car k) grammar)))
+;;                      (right (nth 1 (assoc (cdr k) grammar))))
+;;                  (when (and left right)
+;;                    (cond
+;;                     ((< left right) (assert (eq v '<)))
+;;                     ((> left right) (assert (eq v '>)))
+;;                     (t (assert (eq v '=))))))))
+;;            prec2))
+
+(put 'smie-prec2->grammar 'pure t)
+(defun smie-prec2->grammar (prec2)
   "Take a 2D precedence table and turn it into an alist of precedence levels.
-PREC2 is a table as returned by `smie-precs-precedence-table' or
-`smie-bnf-precedence-table'."
+PREC2 is a table as returned by `smie-precs->prec2' or
+`smie-bnf->prec2'."
   ;; For each operator, we create two "variables" (corresponding to
   ;; the left and right precedence level), which are represented by
   ;; cons cells.  Those are the very cons cells that appear in the
@@ -369,18 +467,19 @@ PREC2 is a table as returned by `smie-precs-precedence-table' or
     ;; variables (aka "precedence levels").  These can be either
     ;; equality constraints (in `eqs') or `<' constraints (in `csts').
     (maphash (lambda (k v)
-               (if (setq tmp (assoc (car k) table))
-                   (setq x (cddr tmp))
-                 (setq x (cons nil nil))
-                 (push (cons (car k) (cons nil x)) table))
-               (if (setq tmp (assoc (cdr k) table))
-                   (setq y (cdr tmp))
-                 (setq y (cons nil (cons nil nil)))
-                 (push (cons (cdr k) y) table))
-               (ecase v
-                 (= (push (cons x y) eqs))
-                 (< (push (cons x y) csts))
-                 (> (push (cons y x) csts))))
+               (when (consp k)
+                 (if (setq tmp (assoc (car k) table))
+                     (setq x (cddr tmp))
+                   (setq x (cons nil nil))
+                   (push (cons (car k) (cons nil x)) table))
+                 (if (setq tmp (assoc (cdr k) table))
+                     (setq y (cdr tmp))
+                   (setq y (cons nil (cons nil nil)))
+                   (push (cons (cdr k) y) table))
+                 (ecase v
+                   (= (push (cons x y) eqs))
+                   (< (push (cons x y) csts))
+                   (> (push (cons y x) csts)))))
              prec2)
     ;; First process the equality constraints.
     (let ((eqs eqs))
@@ -389,7 +488,7 @@ PREC2 is a table as returned by `smie-precs-precedence-table' or
               (to (cdar eqs)))
           (setq eqs (cdr eqs))
           (if (eq to from)
-              nil                   ;Nothing to do.
+              nil                       ;Nothing to do.
             (dolist (other-eq eqs)
               (if (eq from (cdr other-eq)) (setcdr other-eq to))
               (when (eq from (car other-eq))
@@ -419,6 +518,7 @@ PREC2 is a table as returned by `smie-precs-precedence-table' or
               ;; left = right).
               (unless (caar cst)
                 (setcar (car cst) i)
+                ;; (smie-check-grammar table prec2 'step1)
                 (incf i))
               (setq csts (delq cst csts))))
           (unless progress
@@ -428,31 +528,51 @@ PREC2 is a table as returned by `smie-precs-precedence-table' or
         (incf i 10))
       ;; Propagate equalities back to their source.
       (dolist (eq (nreverse eqs))
-        (assert (or (null (caar eq)) (eq (car eq) (cdr eq))))
-        (setcar (car eq) (cadr eq)))
-      ;; Finally, fill in the remaining vars (which only appeared on the
-      ;; right side of the < constraints).
+        (when (null (cadr eq))
+          ;; There's an equality constraint, but we still haven't given
+          ;; it a value: that means it binds tighter than anything else,
+          ;; and it can't be an opener/closer (those don't have equality
+          ;; constraints).
+          ;; So set it here rather than below since doing it below
+          ;; makes it more difficult to obey the equality constraints.
+          (setcar (cdr eq) i)
+          (incf i))
+        (assert (or (null (caar eq)) (eq (caar eq) (cadr eq))))
+        (setcar (car eq) (cadr eq))
+        ;; (smie-check-grammar table prec2 'step2)
+        )
+      ;; Finally, fill in the remaining vars (which did not appear on the
+      ;; left side of any < constraint).
       (dolist (x table)
-        ;; When both sides are nil, it means this operator binds very
-        ;; very tight, but it's still just an operator, so we give it
-        ;; the highest precedence.
-        ;; OTOH if only one side is nil, it usually means it's like an
-        ;; open-paren, which is very important for indentation purposes,
-        ;; so we keep it nil, to make it easier to recognize.
-        (unless (or (nth 1 x) (nth 2 x))
+        (unless (nth 1 x)
           (setf (nth 1 x) i)
-          (setf (nth 2 x) i))))
+          (incf i))                     ;See other (incf i) above.
+        (unless (nth 2 x)
+          (setf (nth 2 x) i)
+          (incf i))))                   ;See other (incf i) above.
+    ;; Mark closers and openers.
+    (dolist (x (gethash :smie-open/close-alist prec2))
+      (let* ((token (car x))
+             (cons (case (cdr x)
+                     (closer (cddr (assoc token table)))
+                     (opener (cdr (assoc token table))))))
+        (assert (numberp (car cons)))
+        (setf (car cons) (list (car cons)))))
+    (let ((ca (gethash :smie-closer-alist prec2)))
+      (when ca (push (cons :smie-closer-alist ca) table)))
+    ;; (smie-check-grammar table prec2 'step3)
     table))
 
 ;;; Parsing using a precedence level table.
 
-(defvar smie-op-levels 'unset
+(defvar smie-grammar 'unset
   "List of token parsing info.
+This list is normally built by `smie-prec2->grammar'.
 Each element is of the form (TOKEN LEFT-LEVEL RIGHT-LEVEL).
 Parsing is done using an operator precedence parser.
-LEFT-LEVEL and RIGHT-LEVEL can be either numbers or nil, where nil
+LEFT-LEVEL and RIGHT-LEVEL can be either numbers or a list, where a list
 means that this operator does not bind on the corresponding side,
-i.e. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
+e.g. a LEFT-LEVEL of nil means this is a token that behaves somewhat like
 an open-paren, whereas a RIGHT-LEVEL of nil would correspond to something
 like a close-paren.")
 
@@ -490,7 +610,7 @@ it should move backward to the beginning of the previous token.")
 (defun smie--associative-p (toklevels)
   ;; in "a + b + c" we want to stop at each +, but in
   ;; "if a then b elsif c then d else c" we don't want to stop at each keyword.
-  ;; To distinguish the two cases, we made smie-prec2-levels choose
+  ;; To distinguish the two cases, we made smie-prec2->grammar choose
   ;; different levels for each part of "if a then b else c", so that
   ;; by checking if the left-level is equal to the right level, we can
   ;; figure out that it's an associative operator.
@@ -508,6 +628,8 @@ OP-FORW is the accessor to the forward level of the level data.
 OP-BACK is the accessor to the backward level of the level data.
 HALFSEXP if non-nil, means skip over a partial sexp if needed.  I.e. if the
 first token we see is an operator, skip over its left-hand-side argument.
+HALFSEXP can also be a token, in which case it means to parse as if
+we had just successfully passed this token.
 Possible return values:
   (FORW-LEVEL POS TOKEN): we couldn't skip TOKEN because its back-level
     is too high.  FORW-LEVEL is the forw-level of TOKEN,
@@ -516,11 +638,14 @@ Possible return values:
   (nil POS TOKEN): we skipped over a paren-like pair.
   nil: we skipped over an identifier, matched parentheses, ..."
   (catch 'return
-    (let ((levels ()))
+    (let ((levels
+           (if (stringp halfsexp)
+               (prog1 (list (cdr (assoc halfsexp smie-grammar)))
+                 (setq halfsexp nil)))))
       (while
           (let* ((pos (point))
                  (token (funcall next-token))
-                 (toklevels (cdr (assoc token smie-op-levels))))
+                 (toklevels (cdr (assoc token smie-grammar))))
             (cond
              ((null toklevels)
               (when (zerop (length token))
@@ -536,9 +661,10 @@ Possible return values:
                 (if (eq pos (point))
                     ;; We did not move, so let's abort the loop.
                     (throw 'return (list t (point))))))
-             ((null (funcall op-back toklevels))
+             ((not (numberp (funcall op-back toklevels)))
               ;; A token like a paren-close.
-              (assert (funcall op-forw toklevels)) ;Otherwise, why mention it?
+              (assert (numberp     ; Otherwise, why mention it in smie-grammar.
+                       (funcall op-forw toklevels)))
               (push toklevels levels))
              (t
               (while (and levels (< (funcall op-back toklevels)
@@ -546,7 +672,7 @@ Possible return values:
                 (setq levels (cdr levels)))
               (cond
                ((null levels)
-                (if (and halfsexp (funcall op-forw toklevels))
+                (if (and halfsexp (numberp (funcall op-forw toklevels)))
                     (push toklevels levels)
                   (throw 'return
                          (prog1 (list (or (car toklevels) t) (point) token)
@@ -562,15 +688,15 @@ Possible return values:
                    ;; Keep looking as long as we haven't matched the
                    ;; topmost operator.
                    (levels
-                    (if (funcall op-forw toklevels)
+                    (if (numberp (funcall op-forw toklevels))
                         (push toklevels levels)))
                    ;; We matched the topmost operator.  If the new operator
                    ;; is the last in the corresponding BNF rule, we're done.
-                   ((null (funcall op-forw toklevels))
+                   ((not (numberp (funcall op-forw toklevels)))
                     ;; It is the last element, let's stop here.
                     (throw 'return (list nil (point) token)))
                    ;; If the new operator is not the last in the BNF rule,
-                   ;; ans is not associative, it's one of the inner operators
+                   ;; and is not associative, it's one of the inner operators
                    ;; (like the "in" in "let .. in .. end"), so keep looking.
                    ((not (smie--associative-p toklevels))
                     (push toklevels levels))
@@ -593,6 +719,8 @@ Possible return values:
   "Skip over one sexp.
 HALFSEXP if non-nil, means skip over a partial sexp if needed.  I.e. if the
 first token we see is an operator, skip over its left-hand-side argument.
+HALFSEXP can also be a token, in which case we should skip the text
+assuming it is the left-hand-side argument of that token.
 Possible return values:
   (LEFT-LEVEL POS TOKEN): we couldn't skip TOKEN because its right-level
     is too high.  LEFT-LEVEL is the left-level of TOKEN,
@@ -610,7 +738,9 @@ Possible return values:
 (defun smie-forward-sexp (&optional halfsexp)
   "Skip over one sexp.
 HALFSEXP if non-nil, means skip over a partial sexp if needed.  I.e. if the
-first token we see is an operator, skip over its left-hand-side argument.
+first token we see is an operator, skip over its right-hand-side argument.
+HALFSEXP can also be a token, in which case we should skip the text
+assuming it is the right-hand-side argument of that token.
 Possible return values:
   (RIGHT-LEVEL POS TOKEN): we couldn't skip TOKEN because its left-level
     is too high.  RIGHT-LEVEL is the right-level of TOKEN,
@@ -662,7 +792,7 @@ Possible return values:
                (string (cdr (syntax-after (point))))
              (let* ((open (funcall smie-forward-token-function))
                     (closer (cdr (assoc open smie-closer-alist)))
-                    (levels (list (assoc open smie-op-levels)))
+                    (levels (list (assoc open smie-grammar)))
                     (seen '())
                     (found '()))
                (cond
@@ -671,25 +801,23 @@ Possible return values:
                 ;; intervention, e.g. for Octave's use of `until'
                 ;; as a pseudo-closer of `do'.
                 (closer)
-                ((or (equal levels '(nil)) (nth 1 (car levels)))
+                ((or (equal levels '(nil)) (numberp (nth 1 (car levels))))
                  (error "Doesn't look like a block"))
                 (t
-                 ;; FIXME: With grammars like Octave's, every closer ("end",
-                 ;; "endif", "endwhile", ...) has the same level, so we'd need
-                 ;; to look at the BNF or at least at the 2D prec-table, in
-                 ;; order to find the right closer for a given opener.
+                 ;; Now that smie-setup automatically sets smie-closer-alist
+                 ;; from the BNF, this is not really needed any more.
                  (while levels
                    (let ((level (pop levels)))
-                     (dolist (other smie-op-levels)
+                     (dolist (other smie-grammar)
                        (when (and (eq (nth 2 level) (nth 1 other))
                                   (not (memq other seen)))
                          (push other seen)
-                         (if (nth 2 other)
+                         (if (numberp (nth 2 other))
                              (push other levels)
                            (push (car other) found))))))
                  (cond
                   ((null found) (error "No known closer for opener %s" open))
-                  ;; FIXME: what should we do if there are various closers?
+                  ;; What should we do if there are various closers?
                   (t (car found))))))))))
     (unless (save-excursion (skip-chars-backward " \t") (bolp))
       (newline))
@@ -715,7 +843,7 @@ This command assumes point is not in a string or comment."
       (while
           (let* ((pos (point))
                  (token (funcall next-token))
-                 (levels (assoc token smie-op-levels)))
+                 (levels (assoc token smie-grammar)))
             (cond
              ((zerop (length token))
               (if (if (< inc 0) (looking-back "\\s(\\|\\s)" (1- (point)))
@@ -725,8 +853,8 @@ This command assumes point is not in a string or comment."
                   (progn (goto-char start) (down-list inc) nil)
                 (forward-sexp inc)
                 (/= (point) pos)))
-             ((and levels (null (nth (+ 1 offset) levels))) nil)
-             ((and levels (null (nth (- 2 offset) levels)))
+             ((and levels (not (numberp (nth (+ 1 offset) levels)))) nil)
+             ((and levels (not (numberp (nth (- 2 offset) levels))))
               (let ((end (point)))
                 (goto-char start)
                 (signal 'scan-error
@@ -746,7 +874,8 @@ I.e. a good choice can be:
 (defcustom smie-blink-matching-inners t
   "Whether SMIE should blink to matching opener for inner keywords.
 If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"."
-  :type 'boolean)
+  :type 'boolean
+  :group 'smie)
 
 (defun smie-blink-matching-check (start end)
   (save-excursion
@@ -766,14 +895,22 @@ If non-nil, it will blink not only for \"begin..end\" but also for \"if...else\"
 (defun smie-blink-matching-open ()
   "Blink the matching opener when applicable.
 This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'."
-  (when (and blink-matching-paren
-             smie-closer-alist                     ; Optimization.
-             (eq (char-before) last-command-event) ; Sanity check.
-             (memq last-command-event smie-blink-matching-triggers)
-             (not (nth 8 (syntax-ppss))))
-    (save-excursion
-      (let ((pos (point))
-            (token (funcall smie-backward-token-function)))
+  (let ((pos (point))                   ;Position after the close token.
+        token)
+    (when (and blink-matching-paren
+               smie-closer-alist                     ; Optimization.
+               (or (eq (char-before) last-command-event) ;; Sanity check.
+                   (save-excursion
+                     (or (progn (skip-chars-backward " \t")
+                                (setq pos (point))
+                                (eq (char-before) last-command-event))
+                         (progn (skip-chars-backward " \n\t")
+                                (setq pos (point))
+                                (eq (char-before) last-command-event)))))
+               (memq last-command-event smie-blink-matching-triggers)
+               (not (nth 8 (syntax-ppss))))
+      (save-excursion
+        (setq token (funcall smie-backward-token-function))
         (when (and (eq (point) (1- pos))
                    (= 1 (length token))
                    (not (rassoc token smie-closer-alist)))
@@ -781,25 +918,28 @@ This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'.
           ;; closers (e.g. ?\; in Octave mode), so go back to the
           ;; previous token.
           (setq pos (point))
-          (setq token (save-excursion
-                        (funcall smie-backward-token-function))))
+          (setq token (funcall smie-backward-token-function)))
         (when (rassoc token smie-closer-alist)
           ;; We're after a close token.  Let's still make sure we
           ;; didn't skip a comment to find that token.
           (funcall smie-forward-token-function)
           (when (and (save-excursion
-                       ;; Trigger can be SPC, or reindent.
-                       (skip-chars-forward " \n\t")
+                       ;; Skip the trigger char, if applicable.
+                       (if (eq (char-after) last-command-event)
+                           (forward-char 1))
+                       (if (eq ?\n last-command-event)
+                           ;; Skip any auto-indentation, if applicable.
+                           (skip-chars-forward " \t"))
                        (>= (point) pos))
-                     ;; If token ends with a trigger char, so don't blink for
+                     ;; If token ends with a trigger char, don't blink for
                      ;; anything else than this trigger char, lest we'd blink
                      ;; both when inserting the trigger char and when
                      ;; inserting a subsequent trigger char like SPC.
-                     (or (eq (point) pos)
+                     (or (eq (char-before) last-command-event)
                          (not (memq (char-before)
                                     smie-blink-matching-triggers)))
                      (or smie-blink-matching-inners
-                         (null (nth 2 (assoc token smie-op-levels)))))
+                         (not (numberp (nth 2 (assoc token smie-grammar))))))
             ;; The major mode might set blink-matching-check-function
             ;; buffer-locally so that interactive calls to
             ;; blink-matching-open work right, but let's not presume
@@ -811,192 +951,261 @@ This uses SMIE's tables and is expected to be placed on `post-self-insert-hook'.
 
 (defcustom smie-indent-basic 4
   "Basic amount of indentation."
-  :type 'integer)
-
-(defvar smie-indent-rules 'unset
-  ;; TODO: For SML, we need more rule formats, so as to handle
-  ;;   structure Foo =
-  ;;      Bar (toto)
-  ;; and
-  ;;   structure Foo =
-  ;;   struct ... end
-  ;; I.e. the indentation after "=" depends on the parent ("structure")
-  ;; as well as on the following token ("struct").
-  "Rules of the following form.
-\((:before . TOK) . OFFSET-RULES)      how to indent TOK itself.
-\(TOK . OFFSET-RULES)  how to indent right after TOK.
-\(list-intro . TOKENS) declare TOKENS as being followed by what may look like
-                         a funcall but is just a sequence of expressions.
-\(t . OFFSET)          basic indentation step.
-\(args . OFFSET)               indentation of arguments.
-\((T1 . T2) OFFSET)    like ((:before . T2) (:parent T1 OFFSET)).
-
-OFFSET-RULES is a list of elements which can each either be:
-
-\(:hanging . OFFSET-RULES)     if TOK is hanging, use OFFSET-RULES.
-\(:parent PARENT . OFFSET-RULES) if TOK's parent is PARENT, use OFFSET-RULES.
-\(:next TOKEN . OFFSET-RULES)  if TOK is followed by TOKEN, use OFFSET-RULES.
-\(:prev TOKEN . OFFSET-RULES)  if TOK is preceded by TOKEN, use
-\(:bolp . OFFSET-RULES)                If TOK is first on a line, use OFFSET-RULES.
-OFFSET                         the offset to use.
-
-PARENT can be either the name of the parent or a list of such names.
-
-OFFSET can be of the form:
-`point'                                align with the token.
-`parent'                               align with the parent.
-NUMBER                         offset by NUMBER.
-\(+ OFFSETS...)                        use the sum of OFFSETS.
-VARIABLE                       use the value of VARIABLE as offset.
-
-The precise meaning of `point' depends on various details: it can
-either mean the position of the token we're indenting, or the
-position of its parent, or the position right after its parent.
-
-A nil offset for indentation after an opening token defaults
-to `smie-indent-basic'.")
-
+  :type 'integer
+  :group 'smie)
+
+(defvar smie-rules-function 'ignore
+  "Function providing the indentation rules.
+It takes two arguments METHOD and ARG where the meaning of ARG
+and the expected return value depends on METHOD.
+METHOD can be:
+- :after, in which case ARG is a token and the function should return the
+  OFFSET to use for indentation after ARG.
+- :before, in which case ARG is a token and the function should return the
+  OFFSET to use to indent ARG itself.
+- :elem, in which case the function should return either:
+  - the offset to use to indent function arguments (ARG = `arg')
+  - the basic indentation step (ARG = `basic').
+- :list-intro, in which case ARG is a token and the function should return
+  non-nil if TOKEN is followed by a list of expressions (not separated by any
+  token) rather than an expression.
+
+When ARG is a token, the function is called with point just before that token.
+A return value of nil always means to fallback on the default behavior, so the
+function should return nil for arguments it does not expect.
+
+OFFSET can be:
+nil                            use the default indentation rule.
+`(column . COLUMN)             indent to column COLUMN.
+NUMBER                         offset by NUMBER, relative to a base token
+                               which is the current token for :after and
+                               its parent for :before.
+
+The functions whose name starts with \"smie-rule-\" are helper functions
+designed specifically for use in this function.")
+
+(defalias 'smie-rule-hanging-p 'smie-indent--hanging-p)
 (defun smie-indent--hanging-p ()
-  ;; A hanging keyword is one that's at the end of a line except it's not at
-  ;; the beginning of a line.
-  (and (save-excursion
-         (when (zerop (length (funcall smie-forward-token-function)))
-           ;; Could be an open-paren.
-           (forward-char 1))
-         (skip-chars-forward " \t")
-         (eolp))
-       (not (smie-indent--bolp))))
+  "Return non-nil if the current token is \"hanging\".
+A hanging keyword is one that's at the end of a line except it's not at
+the beginning of a line."
+  (and (not (smie-indent--bolp))
+       (save-excursion
+         (<= (line-end-position)
+             (progn
+               (when (zerop (length (funcall smie-forward-token-function)))
+                 ;; Could be an open-paren.
+                 (forward-char 1))
+               (skip-chars-forward " \t")
+               (or (eolp)
+                   (and (looking-at comment-start-skip)
+                        (forward-comment (point-max))))
+               (point))))))
 
+(defalias 'smie-rule-bolp 'smie-indent--bolp)
 (defun smie-indent--bolp ()
+  "Return non-nil if the current token is the first on the line."
   (save-excursion (skip-chars-backward " \t") (bolp)))
 
+;; Dynamically scoped.
+(defvar smie--parent) (defvar smie--after) (defvar smie--token)
+
+(defun smie-indent--parent ()
+  (or smie--parent
+      (save-excursion
+        (let* ((pos (point))
+               (tok (funcall smie-forward-token-function)))
+          (unless (numberp (cadr (assoc tok smie-grammar)))
+            (goto-char pos))
+          (setq smie--parent
+                (or (smie-backward-sexp 'halfsexp)
+                    (let (res)
+                      (while (null (setq res (smie-backward-sexp))))
+                      (list nil (point) (nth 2 res)))))))))
+
+(defun smie-rule-parent-p (&rest parents)
+  "Return non-nil if the current token's parent is among PARENTS.
+Only meaningful when called from within `smie-rules-function'."
+  (member (nth 2 (smie-indent--parent)) parents))
+
+(defun smie-rule-next-p (&rest tokens)
+  "Return non-nil if the next token is among TOKENS.
+Only meaningful when called from within `smie-rules-function'."
+  (let ((next
+         (save-excursion
+           (unless smie--after
+             (smie-indent-forward-token) (setq smie--after (point)))
+           (goto-char smie--after)
+           (smie-indent-forward-token))))
+    (member (car next) tokens)))
+
+(defun smie-rule-prev-p (&rest tokens)
+  "Return non-nil if the previous token is among TOKENS."
+  (let ((prev (save-excursion
+                (smie-indent-backward-token))))
+    (member (car prev) tokens)))
+
+(defun smie-rule-sibling-p ()
+  "Return non-nil if the parent is actually a sibling.
+Only meaningful when called from within `smie-rules-function'."
+  (eq (car (smie-indent--parent))
+      (cadr (assoc smie--token smie-grammar))))
+
+(defun smie-rule-parent (&optional offset)
+  "Align with parent.
+If non-nil, OFFSET should be an integer giving an additional offset to apply.
+Only meaningful when called from within `smie-rules-function'."
+  (save-excursion
+    (goto-char (cadr (smie-indent--parent)))
+    (cons 'column
+          (+ (or offset 0)
+             ;; Use smie-indent-virtual when indenting relative to an opener:
+             ;; this will also by default use current-column unless
+             ;; that opener is hanging, but will additionally consult
+             ;; rules-function, so it gives it a chance to tweak
+             ;; indentation (e.g. by forcing indentation relative to
+             ;; its own parent, as in fn a => fn b => fn c =>).
+             (if (or (listp (car smie--parent)) (smie-indent--hanging-p))
+                 (smie-indent-virtual) (current-column))))))
+
+(defvar smie-rule-separator-outdent 2)
+
+(defun smie-indent--separator-outdent ()
+  ;; FIXME: Here we actually have several reasonable behaviors.
+  ;; E.g. for a parent token of "FOO" and a separator ";" we may want to:
+  ;; 1- left-align ; with FOO.
+  ;; 2- right-align ; with FOO.
+  ;; 3- align content after ; with content after FOO.
+  ;; 4- align content plus add/remove spaces so as to align ; with FOO.
+  ;; Currently, we try to align the contents (option 3) which actually behaves
+  ;; just like option 2 (if the number of spaces after FOO and ; is equal).
+  (let ((afterpos (save-excursion
+                    (let ((tok (funcall smie-forward-token-function)))
+                      (unless tok
+                        (with-demoted-errors
+                          (error "smie-rule-separator: can't skip token %s"
+                                 smie--token))))
+                    (skip-chars-forward " ")
+                    (unless (eolp) (point)))))
+    (or (and afterpos
+             ;; This should always be true, unless
+             ;; smie-forward-token-function skipped a \n.
+             (< afterpos (line-end-position))
+             (- afterpos (point)))
+        smie-rule-separator-outdent)))
+
+(defun smie-rule-separator (method)
+  "Indent current token as a \"separator\".
+By \"separator\", we mean here a token whose sole purpose is to separate
+various elements within some enclosing syntactic construct, and which does
+not have any semantic significance in itself (i.e. it would typically no exist
+as a node in an abstract syntax tree).
+Such a token is expected to have an associative syntax and be closely tied
+to its syntactic parent.  Typical examples are \",\" in lists of arguments
+\(enclosed inside parentheses), or \";\" in sequences of instructions (enclosed
+in a {..} or begin..end block).
+METHOD should be the method name that was passed to `smie-rules-function'.
+Only meaningful when called from within `smie-rules-function'."
+  ;; FIXME: The code below works OK for cases where the separators
+  ;; are placed consistently always at beginning or always at the end,
+  ;; but not if some are at the beginning and others are at the end.
+  ;; I.e. it gets confused in cases such as:
+  ;;     (  a
+  ;;     ,  a,
+  ;;        b
+  ;;     ,  c,
+  ;;        d
+  ;;     )
+  ;;
+  ;; Assuming token is associative, the default rule for associative
+  ;; tokens (which assumes an infix operator) works fine for many cases.
+  ;; We mostly need to take care of the case where token is at beginning of
+  ;; line, in which case we want to align it with its enclosing parent.
+  (cond
+   ((and (eq method :before) (smie-rule-bolp) (not (smie-rule-sibling-p)))
+    (let ((parent-col (cdr (smie-rule-parent)))
+          (parent-pos-col     ;FIXME: we knew this when computing smie--parent.
+           (save-excursion
+             (goto-char (cadr smie--parent))
+             (smie-indent-forward-token)
+             (forward-comment (point-max))
+             (current-column))))
+      (cons 'column
+            (max parent-col
+                 (min parent-pos-col
+                      (- parent-pos-col (smie-indent--separator-outdent)))))))
+   ((and (eq method :after) (smie-indent--bolp))
+    (smie-indent--separator-outdent))))
+
 (defun smie-indent--offset (elem)
-  (or (cdr (assq elem smie-indent-rules))
-      (cdr (assq t smie-indent-rules))
+  (or (funcall smie-rules-function :elem elem)
+      (if (not (eq elem 'basic))
+          (funcall smie-rules-function :elem 'basic))
       smie-indent-basic))
 
-(defvar smie-indent-debug-log)
-
-(defun smie-indent--offset-rule (tokinfo &optional after parent)
-  "Apply the OFFSET-RULES in TOKINFO.
-Point is expected to be right in front of the token corresponding to TOKINFO.
-If computing the indentation after the token, then AFTER is the position
-after the token, otherwise it should be nil.
-PARENT if non-nil should be the parent info returned by `smie-backward-sexp'."
-  (let ((rules (cdr tokinfo))
-        next prev
-        offset)
-    (while (consp rules)
-      (let ((rule (pop rules)))
-        (cond
-         ((not (consp rule)) (setq offset rule))
-         ((eq (car rule) '+) (setq offset rule))
-         ((eq (car rule) :hanging)
-          (when (smie-indent--hanging-p)
-            (setq rules (cdr rule))))
-         ((eq (car rule) :bolp)
-          (when (smie-indent--bolp)
-            (setq rules (cdr rule))))
-         ((eq (car rule) :eolp)
-          (unless after
-            (error "Can't use :eolp in :before indentation rules"))
-          (when (> after (line-end-position))
-            (setq rules (cdr rule))))
-         ((eq (car rule) :prev)
-          (unless prev
-            (save-excursion
-              (setq prev (smie-indent-backward-token))))
-          (when (equal (car prev) (cadr rule))
-            (setq rules (cddr rule))))
-         ((eq (car rule) :next)
-          (unless next
-            (unless after
-              (error "Can't use :next in :before indentation rules"))
-            (save-excursion
-              (goto-char after)
-              (setq next (smie-indent-forward-token))))
-          (when (equal (car next) (cadr rule))
-            (setq rules (cddr rule))))
-         ((eq (car rule) :parent)
-          (unless parent
-            (save-excursion
-              (if after (goto-char after))
-              (setq parent (smie-backward-sexp 'halfsexp))))
-          (when (if (listp (cadr rule))
-                    (member (nth 2 parent) (cadr rule))
-                  (equal (nth 2 parent) (cadr rule)))
-            (setq rules (cddr rule))))
-         (t (error "Unknown rule %s for indentation of %s"
-                   rule (car tokinfo))))))
-    ;; If `offset' is not set yet, use `rules' to handle the case where
-    ;; the tokinfo uses the old-style ((PARENT . TOK). OFFSET).
-    (unless offset (setq offset rules))
-    (when (boundp 'smie-indent-debug-log)
-      (push (list (point) offset tokinfo) smie-indent-debug-log))
-    offset))
-
-(defun smie-indent--column (offset &optional base parent virtual-point)
-  "Compute the actual column to use for a given OFFSET.
-BASE is the base position to use, and PARENT is the parent info, if any.
-If VIRTUAL-POINT is non-nil, then `point' is virtual."
-  (cond
-   ((eq (car-safe offset) '+)
-    (apply '+ (mapcar (lambda (offset) (smie-indent--column offset nil parent))
-                      (cdr offset))))
-   ((integerp offset)
-    (+ offset
-       (case base
-         ((nil) 0)
-         (parent (goto-char (cadr parent))
-                 (smie-indent-virtual))
-         (t
-          (goto-char base)
-          ;; For indentation after "(let" in SML-mode, we end up accumulating
-          ;; the offset of "(" and the offset of "let", so we use `min' to try
-          ;; and get it right either way.
-          (min (smie-indent-virtual) (current-column))))))
-   ((eq offset 'point)
-    ;; In indent-keyword, if we're indenting `then' wrt `if', we want to use
-    ;; indent-virtual rather than use just current-column, so that we can
-    ;; apply the (:before . "if") rule which does the "else if" dance in SML.
-    ;; But in other cases, we do not want to use indent-virtual
-    ;; (e.g. indentation of "*" w.r.t "+", or ";" wrt "(").  We could just
-    ;; always use indent-virtual and then have indent-rules say explicitly
-    ;; to use `point' after things like "(" or "+" when they're not at EOL,
-    ;; but you'd end up with lots of those rules.
-    ;; So we use a heuristic here, which is that we only use virtual if
-    ;; the parent is tightly linked to the child token (they're part of
-    ;; the same BNF rule).
-    (if (and virtual-point (null (car parent))) ;Black magic :-(
-        (smie-indent-virtual) (current-column)))
-   ((eq offset 'parent)
-    (unless parent
-      (setq parent (or (smie-backward-sexp 'halfsexp) :notfound)))
-    (if (consp parent) (goto-char (cadr parent)))
-    (smie-indent-virtual))
-   ((eq offset nil) nil)
-   ((and (symbolp offset) (boundp 'offset))
-    (smie-indent--column (symbol-value offset) base parent virtual-point))
-   (t (error "Unknown indentation offset %s" offset))))
+(defun smie-indent--rule (method token
+                          ;; FIXME: Too many parameters.
+                          &optional after parent base-pos)
+  "Compute indentation column according to `indent-rule-functions'.
+METHOD and TOKEN are passed to `indent-rule-functions'.
+AFTER is the position after TOKEN, if known.
+PARENT is the parent info returned by `smie-backward-sexp', if known.
+BASE-POS is the position relative to which offsets should be applied."
+  ;; This is currently called in 3 cases:
+  ;; - :before opener, where rest=nil but base-pos could as well be parent.
+  ;; - :before other, where
+  ;;                  ; after=nil
+  ;;                  ; parent is set
+  ;;                  ; base-pos=parent
+  ;; - :after tok, where
+  ;;                  ; after is set; parent=nil; base-pos=point;
+  (save-excursion
+    (let ((offset
+           (let ((smie--parent parent)
+                 (smie--token token)
+                 (smie--after after))
+             (funcall smie-rules-function method token))))
+      (cond
+       ((not offset) nil)
+       ((eq (car-safe offset) 'column) (cdr offset))
+       ((integerp offset)
+        (+ offset
+           (if (null base-pos) 0
+             (goto-char base-pos)
+             ;; Use smie-indent-virtual when indenting relative to an opener:
+             ;; this will also by default use current-column unless
+             ;; that opener is hanging, but will additionally consult
+             ;; rules-function, so it gives it a chance to tweak indentation
+             ;; (e.g. by forcing indentation relative to its own parent, as in
+             ;; fn a => fn b => fn c =>).
+             ;; When parent==nil it doesn't matter because the only case
+             ;; where it's really used is when the base-pos is hanging anyway.
+             (if (or (and parent (null (car parent)))
+                     (smie-indent--hanging-p))
+                 (smie-indent-virtual) (current-column)))))
+       (t (error "Unknown indentation offset %s" offset))))))
 
 (defun smie-indent-forward-token ()
   "Skip token forward and return it, along with its levels."
   (let ((tok (funcall smie-forward-token-function)))
     (cond
-     ((< 0 (length tok)) (assoc tok smie-op-levels))
-     ((looking-at "\\s(")
+     ((< 0 (length tok)) (assoc tok smie-grammar))
+     ((looking-at "\\s(\\|\\s)\\(\\)")
       (forward-char 1)
-      (list (buffer-substring (1- (point)) (point)) nil 0)))))
+      (cons (buffer-substring (1- (point)) (point))
+            (if (match-end 1) '(0 nil) '(nil 0)))))))
 
 (defun smie-indent-backward-token ()
   "Skip token backward and return it, along with its levels."
-  (let ((tok (funcall smie-backward-token-function)))
+  (let ((tok (funcall smie-backward-token-function))
+        class)
     (cond
-     ((< 0 (length tok)) (assoc tok smie-op-levels))
-     ;; 4 == Open paren syntax.
-     ((eq 4 (syntax-class (syntax-after (1- (point)))))
+     ((< 0 (length tok)) (assoc tok smie-grammar))
+     ;; 4 == open paren syntax, 5 == close.
+     ((memq (setq class (syntax-class (syntax-after (1- (point))))) '(4 5))
       (forward-char -1)
-      (list (buffer-substring (point) (1+ (point))) nil 0)))))
+      (cons (buffer-substring (point) (1+ (point)))
+            (if (eq class 4) '(nil 0) '(0 nil)))))))
 
 (defun smie-indent-virtual ()
   ;; We used to take an optional arg (with value :not-hanging) to specify that
@@ -1042,54 +1251,48 @@ in order to figure out the indentation of some other (further down) point."
             (smie-indent-virtual))      ;:not-hanging
         (scan-error nil)))))
 
-(defun smie-indent-keyword ()
-  ;; Align closing token with the corresponding opening one.
-  ;; (e.g. "of" with "case", or "in" with "let").
+(defun smie-indent-keyword (&optional token)
+  "Indent point based on the token that follows it immediately.
+If TOKEN is non-nil, assume that that is the token that follows point.
+Returns either a column number or nil if it considers that indentation
+should not be computed on the basis of the following token."
   (save-excursion
     (let* ((pos (point))
-           (toklevels (smie-indent-forward-token))
-           (token (pop toklevels)))
-      (if (null (car toklevels))
-          (save-excursion
-            (goto-char pos)
-            ;; Different cases:
-            ;; - smie-indent--bolp: "indent according to others".
-            ;; - common hanging: "indent according to others".
-            ;; - SML-let hanging: "indent like parent".
-            ;; - if-after-else: "indent-like parent".
-            ;; - middle-of-line: "trust current position".
-            (cond
-             ((null (cdr toklevels)) nil) ;Not a keyword.
-             ((smie-indent--bolp)
-              ;; For an open-paren-like thingy at BOL, always indent only
-              ;; based on other rules (typically smie-indent-after-keyword).
-              nil)
-             (t
-              ;; We're only ever here for virtual-indent, which is why
-              ;; we can use (current-column) as answer for `point'.
-              (let* ((tokinfo (or (assoc (cons :before token)
-                                         smie-indent-rules)
-                                  ;; By default use point unless we're hanging.
-                                  `((:before . ,token) (:hanging nil) point)))
-                     ;; (after (prog1 (point) (goto-char pos)))
-                     (offset (smie-indent--offset-rule tokinfo)))
-                (smie-indent--column offset)))))
-
+           (toklevels
+            (if token
+                (assoc token smie-grammar)
+              (let* ((res (smie-indent-forward-token)))
+                ;; Ignore tokens on subsequent lines.
+                (if (and (< pos (line-beginning-position))
+                         ;; Make sure `token' also *starts* on another line.
+                         (save-excursion
+                           (smie-indent-backward-token)
+                           (< pos (line-beginning-position))))
+                    nil
+                  (goto-char pos)
+                  res)))))
+      (setq token (pop toklevels))
+      (cond
+       ((null (cdr toklevels)) nil)     ;Not a keyword.
+       ((not (numberp (car toklevels)))
+        ;; Different cases:
+        ;; - smie-indent--bolp: "indent according to others".
+        ;; - common hanging: "indent according to others".
+        ;; - SML-let hanging: "indent like parent".
+        ;; - if-after-else: "indent-like parent".
+        ;; - middle-of-line: "trust current position".
+        (cond
+         ((smie-indent--rule :before token))
+         ((smie-indent--bolp)           ;I.e. non-virtual indent.
+          ;; For an open-paren-like thingy at BOL, always indent only
+          ;; based on other rules (typically smie-indent-after-keyword).
+          nil)
+         (t
+          ;; By default use point unless we're hanging.
+          (unless (smie-indent--hanging-p) (current-column)))))
+       (t
         ;; FIXME: This still looks too much like black magic!!
-        ;; FIXME: Rather than a bunch of rules like (PARENT . TOKEN), we
-        ;; want a single rule for TOKEN with different cases for each PARENT.
-        (let* ((parent (smie-backward-sexp 'halfsexp))
-               (tokinfo
-                (or (assoc (cons (caddr parent) token)
-                           smie-indent-rules)
-                    (assoc (cons :before token) smie-indent-rules)
-                    ;; Default rule.
-                    `((:before . ,token)
-                      ;; (:parent open 0)
-                      point)))
-               (offset (save-excursion
-                         (goto-char pos)
-                         (smie-indent--offset-rule tokinfo nil parent))))
+        (let* ((parent (smie-backward-sexp token)))
           ;; Different behaviors:
           ;; - align with parent.
           ;; - parent + offset.
@@ -1112,21 +1315,15 @@ in order to figure out the indentation of some other (further down) point."
             ;; maybe when an infix or close-paren is at the beginning
             ;; of a buffer.
             nil)
+           ((save-excursion
+              (goto-char pos)
+              (smie-indent--rule :before token nil parent (cadr parent))))
            ((eq (car parent) (car toklevels))
-            ;; We bumped into a same-level operator. align with it.
+            ;; We bumped into a same-level operator; align with it.
             (if (and (smie-indent--bolp) (/= (point) pos)
                      (save-excursion
                        (goto-char (goto-char (cadr parent)))
-                       (not (smie-indent--bolp)))
-                     ;; Check the offset of `token' rather then its parent
-                     ;; because its parent may have used a special rule.  E.g.
-                     ;;    function foo;
-                     ;;      line2;
-                     ;;      line3;
-                     ;; The ; on the first line had a special rule, but when
-                     ;; indenting line3, we don't care about it and want to
-                     ;; align with line2.
-                     (memq offset '(point nil)))
+                       (not (smie-indent--bolp))))
                 ;; If the parent is at EOL and its children are indented like
                 ;; itself, then we can just obey the indentation chosen for the
                 ;; child.
@@ -1153,19 +1350,27 @@ in order to figure out the indentation of some other (further down) point."
               ;;    -> d
               ;; So as to align with the earliest appropriate place.
               (smie-indent-virtual)))
-           (tokinfo
-            (if (and (= (point) pos) (smie-indent--bolp)
-                     (or (eq offset 'point)
-                         (and (consp offset) (memq 'point offset))))
+           (t
+            (if (and (= (point) pos) (smie-indent--bolp))
                 ;; Since we started at BOL, we're not computing a virtual
                 ;; indentation, and we're still at the starting point, so
                 ;; we can't use `current-column' which would cause
-                ;; indentation to depend on itself.
+                ;; indentation to depend on itself and we can't use
+                ;; smie-indent-virtual since that would be an inf-loop.
                 nil
-              (smie-indent--column offset 'parent parent
-                                  ;; If we're still at pos, indent-virtual
-                                  ;; will inf-loop.
-                                  (unless (= (point) pos) 'virtual))))))))))
+              ;; In indent-keyword, if we're indenting `then' wrt `if', we
+              ;; want to use indent-virtual rather than use just
+              ;; current-column, so that we can apply the (:before . "if")
+              ;; rule which does the "else if" dance in SML.  But in other
+              ;; cases, we do not want to use indent-virtual (e.g. indentation
+              ;; of "*" w.r.t "+", or ";" wrt "(").  We could just always use
+              ;; indent-virtual and then have indent-rules say explicitly to
+              ;; use `point' after things like "(" or "+" when they're not at
+              ;; EOL, but you'd end up with lots of those rules.
+              ;; So we use a heuristic here, which is that we only use virtual
+              ;; if the parent is tightly linked to the child token (they're
+              ;; part of the same BNF rule).
+              (if (car parent) (current-column) (smie-indent-virtual)))))))))))
 
 (defun smie-indent-comment ()
   "Compute indentation of a comment."
@@ -1203,41 +1408,45 @@ in order to figure out the indentation of some other (further down) point."
        comment-end-skip
        (not (looking-at " \t*$"))       ;Not just a \n comment-closer.
        (looking-at comment-end-skip)
-       (nth 4 (syntax-ppss))
-       (save-excursion
-         (goto-char (nth 8 (syntax-ppss)))
-         (current-column))))
+       (let ((end (match-string 0)))
+         (and (nth 4 (syntax-ppss))
+              (save-excursion
+                (goto-char (nth 8 (syntax-ppss)))
+                (and (looking-at comment-start-skip)
+                     (let ((start (match-string 0)))
+                       ;; Align the common substring between starter
+                       ;; and ender, if possible.
+                       (if (string-match "\\(.+\\).*\n\\(.*?\\)\\1"
+                                         (concat start "\n" end))
+                           (+ (current-column) (match-beginning 0)
+                              (- (match-beginning 2) (match-end 2)))
+                         (current-column)))))))))
 
 (defun smie-indent-comment-inside ()
   (and (nth 4 (syntax-ppss))
        'noindent))
 
+(defun smie-indent-inside-string ()
+  (and (nth 3 (syntax-ppss))
+       'noindent))
+
 (defun smie-indent-after-keyword ()
   ;; Indentation right after a special keyword.
   (save-excursion
     (let* ((pos (point))
            (toklevel (smie-indent-backward-token))
-           (tok (car toklevel))
-           (tokinfo (assoc tok smie-indent-rules)))
-      ;; Set some default indent rules.
-      (if (and toklevel (null (cadr toklevel)) (null tokinfo))
-          (setq tokinfo (list (car toklevel))))
-      ;; (if (and tokinfo (null toklevel))
-      ;;     (error "Token %S has indent rule but has no parsing info" tok))
-      (when toklevel
-        (unless tokinfo
-          ;; The default indentation after a keyword/operator is 0 for
-          ;; infix and t for prefix.
-          ;; Using the BNF syntax, we could come up with better
-          ;; defaults, but we only have the precedence levels here.
-          (setq tokinfo (list tok 'default-rule
-                              (if (cadr toklevel) 0 (smie-indent--offset t)))))
-        (let ((offset
-               (or (smie-indent--offset-rule tokinfo pos)
-                   (smie-indent--offset t))))
-          (let ((before (point)))
-            (goto-char pos)
-            (smie-indent--column offset before)))))))
+           (tok (car toklevel)))
+      (cond
+       ((null toklevel) nil)
+       ((smie-indent--rule :after tok pos nil (point)))
+       ;; The default indentation after a keyword/operator is
+       ;; 0 for infix, t for prefix, and use another rule
+       ;; for postfix.
+       ((not (numberp (nth 2 toklevel))) nil)                   ;A closer.
+       ((or (not (numberp (nth 1 toklevel)))                    ;An opener.
+            (rassoc tok smie-closer-alist))                     ;An inner.
+        (+ (smie-indent-virtual) (smie-indent--offset 'basic))) ;
+       (t (smie-indent-virtual))))))                            ;An infix.
 
 (defun smie-indent-exps ()
   ;; Indentation of sequences of simple expressions without
@@ -1264,9 +1473,10 @@ in order to figure out the indentation of some other (further down) point."
       (save-excursion
         ;; Figure out if the atom we just skipped is an argument rather
         ;; than a function.
-        (setq arg (or (null (car (smie-backward-sexp)))
-                      (member (funcall smie-backward-token-function)
-                              (cdr (assoc 'list-intro smie-indent-rules))))))
+        (setq arg
+              (or (null (car (smie-backward-sexp)))
+                  (funcall smie-rules-function :list-intro
+                           (funcall smie-backward-token-function)))))
       (cond
        ((null positions)
         ;; We're the first expression of the list.  In that case, the
@@ -1285,7 +1495,6 @@ in order to figure out the indentation of some other (further down) point."
        (positions
         ;; We're the first arg.
         (goto-char (car positions))
-        ;; FIXME: Use smie-indent--column.
         (+ (smie-indent--offset 'args)
            ;; We used to use (smie-indent-virtual), but that
            ;; doesn't seem right since it might then indent args less than
@@ -1295,8 +1504,9 @@ in order to figure out the indentation of some other (further down) point."
 (defvar smie-indent-functions
   '(smie-indent-fixindent smie-indent-bob smie-indent-close
     smie-indent-comment smie-indent-comment-continue smie-indent-comment-close
-    smie-indent-comment-inside smie-indent-keyword smie-indent-after-keyword
-    smie-indent-exps)
+    smie-indent-comment-inside smie-indent-inside-string
+    smie-indent-keyword smie-indent-after-keyword
+                          smie-indent-exps)
   "Functions to compute the indentation.
 Each function is called with no argument, shouldn't move point, and should
 return either nil if it has no opinion, or an integer representing the column
@@ -1310,13 +1520,13 @@ to which that point should be aligned, if we were to reindent it.")
   "Indent current line using the SMIE indentation engine."
   (interactive)
   (let* ((savep (point))
-        (indent (condition-case-no-debug nil
-                    (save-excursion
-                       (forward-line 0)
-                       (skip-chars-forward " \t")
-                       (if (>= (point) savep) (setq savep nil))
-                       (or (smie-indent-calculate) 0))
-                   (error 0))))
+        (indent (or (with-demoted-errors
+                       (save-excursion
+                         (forward-line 0)
+                         (skip-chars-forward " \t")
+                         (if (>= (point) savep) (setq savep nil))
+                         (or (smie-indent-calculate) 0)))
+                     0)))
     (if (not (numberp indent))
         ;; If something funny is used (e.g. `noindent'), return it.
         indent
@@ -1325,18 +1535,51 @@ to which that point should be aligned, if we were to reindent it.")
           (save-excursion (indent-line-to indent))
         (indent-line-to indent)))))
 
-(defun smie-indent-debug ()
-  "Show the rules used to compute indentation of current line."
-  (interactive)
-  (let ((smie-indent-debug-log '()))
-    (smie-indent-calculate)
-    ;; FIXME: please improve!
-    (message "%S" smie-indent-debug-log)))
-
-(defun smie-setup (op-levels indent-rules)
-  (set (make-local-variable 'smie-indent-rules) indent-rules)
-  (set (make-local-variable 'smie-op-levels) op-levels)
-  (set (make-local-variable 'indent-line-function) 'smie-indent-line))
+(defun smie-setup (grammar rules-function &rest keywords)
+  "Setup SMIE navigation and indentation.
+GRAMMAR is a grammar table generated by `smie-prec2->grammar'.
+RULES-FUNCTION is a set of indentation rules for use on `smie-rules-function'.
+KEYWORDS are additional arguments, which can use the following keywords:
+- :forward-token FUN
+- :backward-token FUN"
+  (set (make-local-variable 'smie-rules-function) rules-function)
+  (set (make-local-variable 'smie-grammar) grammar)
+  (set (make-local-variable 'indent-line-function) 'smie-indent-line)
+  (set (make-local-variable 'forward-sexp-function)
+       'smie-forward-sexp-command)
+  (while keywords
+    (let ((k (pop keywords))
+          (v (pop keywords)))
+      (case k
+        (:forward-token
+         (set (make-local-variable 'smie-forward-token-function) v))
+        (:backward-token
+         (set (make-local-variable 'smie-backward-token-function) v))
+        (t (message "smie-setup: ignoring unknown keyword %s" k)))))
+  (let ((ca (cdr (assq :smie-closer-alist grammar))))
+    (when ca
+      (set (make-local-variable 'smie-closer-alist) ca)
+      ;; Only needed for interactive calls to blink-matching-open.
+      (set (make-local-variable 'blink-matching-check-function)
+           #'smie-blink-matching-check)
+      (add-hook 'post-self-insert-hook
+                #'smie-blink-matching-open 'append 'local)
+      (set (make-local-variable 'smie-blink-matching-triggers)
+           (append smie-blink-matching-triggers
+                   ;; Rather than wait for SPC to blink, try to blink as
+                   ;; soon as we type the last char of a block ender.
+                   (let ((closers (sort (mapcar #'cdr smie-closer-alist)
+                                        #'string-lessp))
+                         (triggers ())
+                         closer)
+                     (while (setq closer (pop closers))
+                       (unless (and closers
+                                    ;; FIXME: this eliminates prefixes of other
+                                    ;; closers, but we should probably elimnate
+                                    ;; prefixes of other keywords as well.
+                                    (string-prefix-p closer (car closers)))
+                         (push (aref closer (1- (length closer))) triggers)))
+                     (delete-dups triggers)))))))
 
 
 (provide 'smie)