master lean-101 / emacs / lean.el
agent  ·  2026-10-27
  1;;; lean.el --- Emacs set-up for this project (nael + eglot)  -*- lexical-binding: t -*-
  2
  3;; Load it from your init.el with (load "/path/to/lean-101/emacs/lean.el").
  4;; See README.md, "Playing in Emacs".
  5;;
  6;; Needs: Emacs 29.1+ (eglot, use-package and ElDoc are built in), and Lean
  7;; from elan.  It works on a vanilla Emacs: it adds MELPA if it is missing and
  8;; installs `nael' from there.  Completion comes from eglot through
  9;; `completion-at-point' (C-M-i), so any completion UI you use shows it (corfu,
 10;; company, `completion-preview-mode', ...); this file doesn't choose one.
 11
 12;; -----------------------------------------------------------------------------
 13;; Packages
 14;; -----------------------------------------------------------------------------
 15;; nael is only on MELPA, which a fresh Emacs doesn't know.
 16(require 'package)
 17(unless (or (assoc "melpa" package-archives)
 18            (seq-some (lambda (a) (string-match-p "melpa\\.org" (cdr a)))
 19                      package-archives))
 20  (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t))
 21;; Emacs initializes packages before init.el; this is for an earlier load.
 22(unless (bound-and-true-p package--initialized)
 23  (package-initialize))
 24
 25;; -----------------------------------------------------------------------------
 26;; Lean 4
 27;; -----------------------------------------------------------------------------
 28;; elan puts lean and lake in ~/.elan/bin.  A daemon started before that was on
 29;; $PATH would not find `lake serve', so add it here too.
 30(let ((elan (expand-file-name "~/.elan/bin")))
 31  (when (and (file-directory-p elan) (not (member elan exec-path)))
 32    (add-to-list 'exec-path elan)
 33    (setenv "PATH" (concat elan path-separator (getenv "PATH")))))
 34
 35;; nael has no indentation of its own: TAB fell back to `indent-relative' and
 36;; inserted tab characters, which Lean rejects.  Lean's indentation carries
 37;; meaning (as in Python), so this works like python-mode: TAB goes to the most
 38;; likely column and, pressed again, cycles through the other plausible ones;
 39;; indenting a region keeps every line whose indentation is already plausible.
 40(defconst my/lean--command-re
 41  (concat "[ \t]*\\(?:@\\[\\|/--\\|/-!\\|#[a-z]+\\_>\\|"
 42          (regexp-opt '("import" "open" "namespace" "section" "end" "universe"
 43                        "variable" "set_option" "theorem" "lemma" "def" "example"
 44                        "abbrev" "instance" "axiom" "opaque" "inductive" "structure"
 45                        "class" "macro" "macro_rules" "syntax" "notation" "infix"
 46                        "infixl" "infixr" "prefix" "postfix" "attribute" "elab"
 47                        "noncomputable" "private" "protected" "partial" "unsafe" "public"
 48                        "mutual" "where" "termination_by" "decreasing_by" "deriving" "prelude" "module")
 49                      'symbols)
 50          "\\)")
 51  "A top-level command: its line starts in column 0.")
 52
 53(defconst my/lean--decl-re
 54  (concat "[ \t]*\\(?:@\\[[^]\n]*\\][ \t]*\\)?"
 55          "\\(?:\\(?:private\\|protected\\|noncomputable\\|partial\\|unsafe\\)[ \t]+\\)*"
 56          "\\(?:theorem\\|lemma\\|example\\|def\\|instance\\|abbrev\\)\\_>")
 57  "A declaration whose statement may continue on the following lines.")
 58
 59(defconst my/lean--opener-re
 60  "\\(?:\\_<by\\|:=\\|=>\\|\\_<do\\|\\_<where\\|\\_<then\\|\\_<else\\|\\_<calc\\)\\'"
 61  "Code ending like this is followed by a block indented 2 more.")
 62
 63(defun my/lean--code ()
 64  "The code on the line at point, without indentation or a trailing `--' comment."
 65  (let ((s (buffer-substring-no-properties
 66            (progn (back-to-indentation) (point)) (line-end-position))))
 67    (replace-regexp-in-string "[ \t]*\\(?:--.*\\)?\\'" "" s)))
 68
 69(defun my/lean--code-line-p ()
 70  "Non-nil if the line at point has code (not blank, not only a comment)."
 71  (save-excursion
 72    (beginning-of-line)
 73    (and (not (looking-at-p "[ \t]*\\(?:--\\|/-\\|$\\)"))
 74         (not (nth 4 (syntax-ppss))))))
 75
 76(defun my/lean--previous-code-line ()
 77  "Move to the previous line with code; nil if there is none."
 78  (let (found)
 79    (while (and (not found) (zerop (forward-line -1)))
 80      (setq found (my/lean--code-line-p)))
 81    found))
 82
 83(defun my/lean--statement-column ()
 84  "If the line at point is part of a declaration header, the declaration's column.
 85The line at point may end the header (with `:=' or `by'); the lines above may not."
 86  (save-excursion
 87    (let (col done (first t))
 88      (while (not done)
 89        (let ((code (my/lean--code)))
 90          (cond ((and (not first)
 91                      (or (string-match-p ":=" code)
 92                          (string-match-p my/lean--opener-re code)
 93                          (string-prefix-p "|" code)))
 94                 (setq done t))
 95                ((save-excursion (beginning-of-line) (looking-at-p my/lean--decl-re))
 96                 (setq col (current-indentation) done t))
 97                ((or (zerop (current-indentation))
 98                     (not (my/lean--previous-code-line)))
 99                 (setq done t))))
100        (setq first nil))
101      col)))
102
103(defun my/lean--bar-column ()
104  "Column for a line starting with `|', from the line at point upwards."
105  (save-excursion
106    (let (col)
107      (while (not col)
108        (let ((code (my/lean--code)) (ind (current-indentation)))
109          (cond ((string-prefix-p "|" code) (setq col ind))
110                ((string-match-p "\\_<with\\'" code) (setq col ind))
111                ((or (string-match-p "\\_<where\\'" code)
112                     (save-excursion (beginning-of-line) (looking-at-p my/lean--decl-re)))
113                 (setq col (+ ind 2)))
114                ((or (zerop ind) (not (my/lean--previous-code-line)))
115                 (setq col (+ ind 2))))))
116      col)))
117
118(defun my/lean--columns ()
119  "Return (BEST CYCLE MIN MAX) for the line at point.
120BEST is the most likely column, CYCLE the columns TAB cycles through, and
121any column from MIN to MAX is plausible."
122  (save-excursion
123    (beginning-of-line)
124    (let* ((cur (if (my/lean--code-line-p) (my/lean--code) ""))
125           (command (and (not (string-empty-p cur))
126                         (save-excursion (beginning-of-line)
127                                         (looking-at-p my/lean--command-re)))))
128      (if (not (my/lean--previous-code-line))
129          (list 0 '(0) 0 0)
130        (let* ((p (current-indentation))
131               (code (my/lean--code))
132               (stmt (my/lean--statement-column))
133               (opener (string-match-p my/lean--opener-re code))
134               (best (cond (command 0)
135                           ((string-prefix-p "|" cur) (my/lean--bar-column))
136                           ((string-match-p my/lean--opener-re code)
137                            (+ (or stmt p) 2))
138                           (stmt (+ stmt 4))
139                           ((string-match-p "\\`[·.][ \t]" code) (+ p 2))
140                           (t p)))
141               (cols (list best 0 p (+ p 2))))
142          (when stmt (push (+ stmt 2) cols) (push (+ stmt 4) cols))
143          ;; Every enclosing level above is plausible, and one level inside it.
144          (let ((ind p))
145            (while (and (> ind 0) (my/lean--previous-code-line))
146              (when (< (current-indentation) ind)
147                (setq ind (current-indentation))
148                (push ind cols)
149                (push (+ ind 2) cols))))
150          (list best (sort (delete-dups cols) #'<)
151                ;; Plausible range: up to 4 past the line above, and not
152                ;; column 0 after an opener (a tactic there ends the proof).
153                (if (and opener (not command)) 1 0)
154                ;; A line starting with a bracket or an operator (`(', `⟨',
155                ;; `|>', `_ =', …) continues the one above at any depth.
156                (if (string-match-p "\\`[^[:word:][:space:]|·]" cur)
157                    most-positive-fixnum
158                  (+ p 4))))))))
159
160(defun my/lean-indent-line ()
161  "Indent the current Lean line.
162The first TAB goes to the most likely column; TAB again cycles through the
163other plausible columns, deepest first.  Never inserts tab characters."
164  (let* ((cols (my/lean--columns))
165         (cur (current-indentation))
166         (target
167          (if (and (eq this-command 'indent-for-tab-command)
168                   (eq last-command 'indent-for-tab-command))
169              ;; Repeated TAB: the next shallower plausible column, wrapping.
170              (or (car (last (seq-filter (lambda (c) (< c cur)) (nth 1 cols))))
171                  (car (last (nth 1 cols))))
172            (car cols))))
173    (if (<= (current-column) cur)
174        (indent-line-to target)
175      (save-excursion (indent-line-to target)))))
176
177(defun my/lean--plausible-p (col)
178  "Non-nil if COL is a plausible indentation for the line at point."
179  (or (> (car (syntax-ppss (line-beginning-position))) 0) ; inside ( [ { ⟨
180      (pcase-let ((`(,_ ,_ ,lo ,hi) (my/lean--columns)))
181        (<= lo col hi))))
182
183(defun my/lean-indent-region (start end)
184  "Indent the Lean lines between START and END, conservatively.
185A line whose indentation is already plausible is kept; only the others move.
186Tab characters in indentation become spaces.  Comments are left alone."
187  (save-excursion
188    (goto-char start)
189    (beginning-of-line)
190    (let ((end (copy-marker end)))
191      (while (< (point) end)
192        (untabify (point) (save-excursion (skip-chars-forward " \t") (point)))
193        (when (and (my/lean--code-line-p)
194                   (not (my/lean--plausible-p (current-indentation))))
195          (indent-line-to (car (my/lean--columns))))
196        (forward-line 1))
197      (set-marker end nil))))
198
199(defun my/lean-dedent ()
200  "Move the line to the next shallower plausible column."
201  (interactive)
202  (let* ((cur (current-indentation))
203         (c (car (last (seq-filter (lambda (c) (< c cur)) (nth 1 (my/lean--columns)))))))
204    (when c
205      (if (<= (current-column) cur)
206          (indent-line-to c)
207        (save-excursion (indent-line-to c))))))
208
209(defun my/lean-setup ()
210  ;; Lean rejects tab characters ("tabs are not allowed").
211  (setq-local indent-tabs-mode nil)
212  (setq-local indent-line-function #'my/lean-indent-line)
213  (setq-local indent-region-function #'my/lean-indent-region)
214  ;; TAB indents (and cycles); it doesn't complete.  Complete with C-M-i, or
215  ;; with your completion UI.
216  (setq-local tab-always-indent t)
217  ;; RET indents the new line but leaves the one above as typed.
218  (setq-local electric-indent-inhibit t))
219
220;; `nael' is a small Lean 4 mode built on eglot (lean4-mode needs lsp-mode).
221;; Eglot runs `lake serve'; nael asks it for the proof goal at point and shows
222;; it through ElDoc.  `abbrev-mode' gives the Lean input: \l → ←, \to → →, …
223;; (C-c C-k lists them).
224(use-package nael
225  :ensure t
226  :hook
227  (nael-mode . eglot-ensure)
228  (nael-mode . abbrev-mode)
229  (nael-mode . my/lean-setup)
230  :bind (:map nael-mode-map
231              ("C-c C-g" . my/lean-goals)
232              ("<backtab>" . my/lean-dedent))
233  :config
234  ;; The ElDoc buffer, shown on the right, is the goal view: it follows point.
235  (add-to-list 'display-buffer-alist
236               '("\\`\\*eldoc"
237                 (display-buffer-in-side-window)
238                 (side . right)
239                 (window-width . 0.4)))
240  (defun my/lean-goals ()
241    "Show the Lean goal at point in a side window that follows point."
242    (interactive)
243    (condition-case nil
244        (eldoc-doc-buffer t)
245      (user-error
246       (message "No goal yet: wait for Lean to start, move point into a proof, retry")))))
247
248;;; lean.el ends here