Agda-2.9.0: src/data/emacs-mode/agda2-mode.el
;; -*- lexical-binding: t -*-
;;; agda2-mode.el --- Major mode for Agda
;; SPDX-License-Identifier: MIT License
;;; Commentary:
;; A major mode for editing Agda (the dependently typed programming
;; language / interactive theorem prover).
;;
;; Major features include:
;;
;; - syntax highlighting.
;;
;; - on the fly Agda interpretation.
;;
;; - goal-driven development
;;
;; - interactive case-splitting
;;
;; - proof search
;;
;; - input support (for utf8 characters)
;;
;; see https://agda.readthedocs.io/ for more information
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Dependency
;;; Code:
(defvar agda2-version "2.9.0"
"The version of the Agda mode.
Note that the same version of the Agda executable must be used.")
(require 'cl-lib)
(require 'compile)
(require 'time-date)
(require 'eri)
(require 'annotation)
(require 'fontset)
(require 'agda-input)
(require 'agda2)
(require 'agda2-highlight)
(require 'agda2-abbrevs)
(require 'agda2-queue)
(require 'xref)
(eval-and-compile
;; Load filladapt, if it is installed.
(condition-case nil
(require 'filladapt)
(error nil))
(unless (fboundp 'overlays-in) (load "overlay")) ; for Xemacs
(unless (fboundp 'propertize) ; for Xemacs 21.4
;; FIXME: XEmacs-21.4 (patch 22) does have `propertize' and so does Emacs-22
;; (and agda2-mode doesn't work in Emacs-21, AFAICT).
(defun propertize (string &rest properties)
"Return a copy of STRING with text properties added.
First argument is the string to copy.
Remaining arguments form a sequence of PROPERTY VALUE pairs for text
properties to add to the result."
(let ((str (copy-sequence string)))
(add-text-properties 0 (length str) properties str)
str)))
(unless (fboundp 'prog-mode) ;For Emacs<24.
(defalias 'prog-mode 'fundamental-mode)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Utilities
(defmacro agda2-let (varbind funcbind &rest body)
"Expands to (let* VARBIND (cl-labels FUNCBIND BODY...)).
Or possibly (let* VARBIND (labels FUNCBIND BODY...))."
(declare (debug ((&rest [&or symbolp (symbolp form)])
(&rest (cl-defun))
body))
(indent 2))
;; Use cl-labels if available to avoid obsolescence warnings.
`(let* ,varbind (,(if (fboundp 'cl-labels) 'cl-labels 'labels) ,funcbind ,@body)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; User options
(defgroup agda2 nil
"Major mode for interactively developing Agda programs."
:group 'languages)
(defcustom agda2-program-name "agda"
"The name of the Agda executable."
:type 'string
:group 'agda2)
(defcustom agda2-program-args nil
"Command-line arguments given to the Agda executable (one per string).
Note: Do not give several arguments in the same string.
The flag \"--interaction\" is always included as the first
argument, and does not need to be listed here."
:type '(repeat string)
:group 'agda2)
(defvar agda2-backends '("GHC" "GHCNoMain" "JS" "LaTeX" "QuickLaTeX" "HTML")
"Compilation backends.")
(defcustom agda2-backend
nil
"The backend used to compile Agda programs (nil to ask every time)."
:type 'string
:group 'agda2)
(defcustom agda2-backend-default-payload
nil
"The default payload for interactive backend commands (nil to ask every time)."
:type 'string
:group 'agda2)
(defcustom agda2-restart-timeout
5
"The number of seconds to wait before timing out restart attempts.
If nil, never time out."
:type '(choice (const :tag "No timeout")
(number :tag "Number of seconds"))
:group 'agda2)
(defcustom agda2-information-window-max-height
0.35
"The maximum height of the information window.
A multiple of the frame height."
:type 'number
:group 'agda2)
(defcustom agda2-fontset-name
;; Emacs-23 uses a revamped font engine which should make
;; agda2-fontset-name unnecessary in most cases. And if it turns
;; out to be necessary, we should probably use face-remapping-alist
;; rather than set-frame-font so the special font only applies to
;; Agda buffers, and so it applies in all frames where Agda buffers
;; are displayed.
(and (not (boundp 'face-remapping-alist)) "fontset-agda2")
"Default font to use in the selected frame when activating the Agda mode.
This is only used if it's non-nil and Emacs is not running in a
terminal.
Note that this setting (if non-nil) affects non-Agda buffers as
well, and that you have to restart Emacs if you want settings to
this variable to take effect."
:type '(choice (string :tag "Fontset name")
(const :tag "Do not change the font" nil))
:group 'agda2)
(defcustom agda2-fontset-spec-of-fontset-agda2
"-*-fixed-Medium-r-Normal-*-18-*-*-*-c-*-fontset-agda2,
ascii:-Misc-Fixed-Medium-R-Normal--18-120-100-100-C-90-ISO8859-1,
latin-iso8859-2:-*-Fixed-*-r-*-*-18-*-*-*-c-*-iso8859-2,
latin-iso8859-3:-*-Fixed-*-r-*-*-18-*-*-*-c-*-iso8859-3,
latin-iso8859-4:-*-Fixed-*-r-*-*-18-*-*-*-c-*-iso8859-4,
cyrillic-iso8859-5:-*-Fixed-*-r-*-*-18-*-*-*-c-*-iso8859-5,
greek-iso8859-7:-*-Fixed-*-r-*-*-18-*-*-*-c-*-iso8859-7,
latin-iso8859-9:-*-Fixed-*-r-*-*-18-*-*-*-c-*-iso8859-9,
mule-unicode-0100-24ff:-Misc-Fixed-Medium-R-Normal--18-120-100-100-C-90-ISO10646-1,
mule-unicode-2500-33ff:-Misc-Fixed-Medium-R-Normal--18-120-100-100-C-90-ISO10646-1,
mule-unicode-e000-ffff:-Misc-Fixed-Medium-R-Normal--18-120-100-100-C-90-ISO10646-1,
japanese-jisx0208:-Misc-Fixed-Medium-R-Normal-ja-18-*-*-*-C-*-JISX0208.1990-0,
japanese-jisx0212:-Misc-Fixed-Medium-R-Normal-ja-18-*-*-*-C-*-JISX0212.1990-0,
thai-tis620:-Misc-Fixed-Medium-R-Normal--24-240-72-72-C-120-TIS620.2529-1,
lao:-Misc-Fixed-Medium-R-Normal--24-240-72-72-C-120-MuleLao-1,
tibetan:-TibMdXA-fixed-medium-r-normal--16-160-72-72-m-160-MuleTibetan-0,
tibetan-1-column:-TibMdXA-fixed-medium-r-normal--16-160-72-72-m-80-MuleTibetan-1,
korean-ksc5601:-Daewoo-Mincho-Medium-R-Normal--16-120-100-100-C-160-KSC5601.1987-0,
chinese-gb2312:-ISAS-Fangsong ti-Medium-R-Normal--16-160-72-72-c-160-GB2312.1980-0,
chinese-cns11643-1:-HKU-Fixed-Medium-R-Normal--16-160-72-72-C-160-CNS11643.1992.1-0,
chinese-big5-1:-ETen-Fixed-Medium-R-Normal--16-150-75-75-C-160-Big5.ETen-0,
chinese-big5-2:-ETen-Fixed-Medium-R-Normal--16-150-75-75-C-160-Big5.ETen-0"
"Specification of the \"fontset-agda2\" fontset.
This fontset is only created if `agda2-fontset-name' is
\"fontset-agda2\" and Emacs is not run in a terminal.
Note that the text \"fontset-agda2\" has to be part of the
string (in a certain way; see the default setting) in order for the
agda2 fontset to be created properly.
Note also that the default setting may not work unless suitable
fonts are installed on your system. Refer to the README file
accompanying the Agda distribution for more details.
Note finally that you have to restart Emacs if you want settings
to this variable to take effect."
:group 'agda2
:type 'string)
(if (and (equal agda2-fontset-name "fontset-agda2") (display-graphic-p))
(create-fontset-from-fontset-spec agda2-fontset-spec-of-fontset-agda2 t t))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Global and buffer-local vars, initialization
(defconst agda2-mode-syntax-table
(with-syntax-table (make-syntax-table)
;; The `standard-syntax-table' marks characters like "[" and "⟨" as delimiters.
;; This breaks `symbol-at-point' for identifiers like "[[X]]" when the point
;; is on the outer brackets. To fix this, we go through and mark all non-whitespace
;; characters as word constitutents, and then patch things up afterwards.
(map-char-table
(lambda (range val)
(unless (memq (car val) (eval-when-compile (mapcar (lambda (c) (car (string-to-syntax c))) '(" " "w"))))
(modify-syntax-entry range "w")))
(char-table-parent (syntax-table)))
;; String literals
;;
;; We do not include ?\' as a quote char, as it can
;; be used in identifiers.
(modify-syntax-entry ?\" "\"")
;; Comments
;;
;; We use the "c" alternative comment style over "b", as "b"
;; only can be attached to the second char of a starting sequence
;; or the first char of an ending sequence. This leads to ambiguities,
;; as "{-" and "--" both have "-" as their second char.
(modify-syntax-entry ?\{ "(}1nc")
(modify-syntax-entry ?\} "){4nc")
(modify-syntax-entry ?\n ">")
;; [HACK: Reed M, 04/03/2026]
;; We mark "-" as a word character so that `word-at-point' selects
;; whole identifiers in kebab-case like "foo-bar-baz". However, we
;; also mark the sequences "--", "{-", and "-}" as comment sequences.
;; This makes `comment-kill' function, but has the somewhat unintended
;; side effect of making killing off "--bar" in an identifier like "foo--bar".
(modify-syntax-entry ?- "w 123")
;; Parens
(modify-syntax-entry ?\( "()")
(modify-syntax-entry ?\) ")(")
;; Adding ⦃⦄ and ⦇⦈ is a bit dubious here, as ⦃a⦄ and ⦇a⦈ are
;; valid identifers. However, it is more useful to be able
;; to get matching paren highlights then it is to support this
;; somewhat suspicious grammatical choice.
(modify-syntax-entry ?⦃ "(⦄")
(modify-syntax-entry ?⦄ ")⦃")
(modify-syntax-entry ?⦇ "(⦈")
(modify-syntax-entry ?⦈ ")⦇")
;; Punctuation
(modify-syntax-entry ?. ".")
(modify-syntax-entry ?\; ".")
;; [FIXME: Reed M, 04/03/2026]
;; Why is this marked as puncutation?
(modify-syntax-entry ?! ".")
(syntax-table))
"Syntax table used by `agda2-mode':
\" | String delimiter.
- | Comment character, word constituent.
{} | Comment character, parentheses.
\n | Comment ender.
⦃⦄⦇⦈() | Parenthesis.
.;! | Punctuation.
Remaining characters inherit their syntax classes from the
`standard-syntax-table' if that table treats them as matching
whitespace. Otherwise they are treated as word
constituents.")
(defconst agda2-command-table
`(
(agda2-load "\C-c\C-l" (global) "Load")
(agda2-load "\C-c\C-x\C-l")
(agda2-compile "\C-c\C-x\C-c" (global) "Compile")
(agda2-backend-cmd "\C-c\C-i" (global) "Run backend interaction")
(agda2-quit "\C-c\C-x\C-q" (global) "Quit")
(agda2-restart "\C-c\C-x\C-r" (global) "Kill and restart Agda")
(agda2-abort "\C-c\C-x\C-a" (global) "Abort a command")
(agda2-remove-annotations "\C-c\C-x\C-d" (global) "Remove goals and highlighting (\"deactivate\")")
(agda2-display-implicit-arguments "\C-c\C-x\C-h" (global) "Toggle display of hidden arguments")
(agda2-display-irrelevant-arguments "\C-c\C-x\C-i" (global) "Toggle display of irrelevant arguments")
(agda2-show-constraints ,(kbd "C-c C-=") (global) "Show constraints")
(agda2-solve-maybe-all ,(kbd "C-c C-s") (local global) "Solve constraints")
(agda2-show-goals ,(kbd "C-c C-?") (global) "Show goals")
(agda2-next-goal "\C-c\C-f" (global) "Next goal") ; Forward.
(agda2-previous-goal "\C-c\C-b" (global) "Previous goal") ; Back.
(agda2-give ,(kbd "C-c C-SPC") (local) "Give")
(agda2-elaborate-give ,(kbd "C-c C-m") (local) "Elaborate and Give")
(agda2-refine "\C-c\C-r" (local) "Refine")
(agda2-mimer-maybe-all "\C-c\C-a" (local global) "Auto")
(agda2-make-case "\C-c\C-c" (local) "Case")
(agda2-goal-type "\C-c\C-t" (local) "Goal type")
(agda2-show-context "\C-c\C-e" (local) "Context (environment)")
(agda2-helper-function-type "\C-c\C-h" (local) "Helper function type")
(agda2-infer-type-maybe-toplevel "\C-c\C-d" (local global) "Infer (deduce) type")
(agda2-why-in-scope-maybe-toplevel "\C-c\C-w" (local global) "Explain why a particular name is in scope")
(agda2-goal-and-context ,(kbd "C-c C-,") (local) "Goal type and context")
(agda2-goal-and-context-and-inferred ,(kbd "C-c C-.") (local) "Goal type, context and inferred type")
(agda2-goal-and-context-and-checked ,(kbd "C-c C-;") (local) "Goal type, context and checked type")
(agda2-search-about-toplevel ,(kbd "C-c C-z") (local global) "Search About")
(agda2-module-contents-maybe-toplevel ,(kbd "C-c C-o") (local global) "Module contents")
(agda2-compute-normalised-maybe-toplevel "\C-c\C-n" (local global) "Evaluate term to normal form")
(describe-char nil (global) "Information about the character at point")
(agda2-comment-dwim-rest-of-buffer ,(kbd "C-c C-x M-;") (global) "Comment/uncomment the rest of the buffer")
(agda2-display-program-version nil (global) "Version")
(agda2-set-program-version "\C-c\C-x\C-s" (global) "Switch to another version of Agda")
(eri-indent ,(kbd "TAB"))
(eri-indent-reverse [S-iso-lefttab])
(eri-indent-reverse [S-lefttab])
(eri-indent-reverse [S-tab])
(agda2-goto-definition-mouse [mouse-2]))
"Table of commands, used to build keymaps and menus.
Each element has the form (CMD &optional KEYS WHERE DESC) where
CMD is a command; KEYS is its key binding (if any); WHERE is a
list which should contain \\='local if the command should exist in
the goal menu and \\='global if the command should exist in the main
menu; and DESC is the description of the command used in the
menus.")
(defvar agda2-movement-repeat-map (make-sparse-keymap))
(defcustom agda2-repeatable-commands
'(agda2-next-goal
agda2-previous-goal
agda2-give
agda2-refine
agda2-make-case
agda2-goal-and-context
agda2-goal-and-context-and-inferred
agda2-goal-and-context-and-checked)
"List of commands that should be supported by `repeat-mode'.
This feature added in Emacs 28 enables a transient keymap after invoking
a command that binds shorter key chords. For Agda, the shorter keys
derived from the last key of the global key chord (so \"C-c C-f\" just
becomes \"C-f\" until you invoke a non-repeatable command). To make use
of this feature, the global minor mode `repeat-mode' must be enabled
separately."
:set (lambda (sym val)
(let ((m (make-sparse-keymap)))
(map-keymap
(lambda (_ev def)
(when (symbolp def)
(put def 'repeat-map nil)))
agda2-movement-repeat-map)
(dolist (fn val)
(let* ((chord (cadr (assq fn agda2-command-table)))
(key (aref chord (1- (length chord))))
(kbd (vector key))
(prev (lookup-key m kbd)))
(when prev
(error "Repeat-key duplicate: %S for `%S' already bound for `%S'"
kbd fn prev))
(define-key m kbd fn))
(put fn 'repeat-map agda2-movement-repeat-map))
(setq agda2-movement-repeat-map m))
(custom-set-default sym val))
:type '(repeat function))
(defvar agda2-mode-map
(let ((map (make-sparse-keymap "Agda mode")))
(define-key map [menu-bar Agda]
(cons "Agda" (make-sparse-keymap "Agda")))
(define-key map [down-mouse-3] 'agda2-popup-menu-3)
(dolist (d (reverse agda2-command-table))
(cl-destructuring-bind (f &optional keys kinds desc) d
(if keys (define-key map keys f))
(if (member 'global kinds)
(define-key map
(vector 'menu-bar 'Agda (intern desc)) (cons desc f)))))
map)
"Keymap for `agda2-mode'.")
(defvar agda2-goal-map
(let ((map (make-sparse-keymap "Agda goal")))
(dolist (d (reverse agda2-command-table))
(cl-destructuring-bind (f &optional _keys kinds desc) d
(if (member 'local kinds)
(define-key map
(vector (intern desc)) (cons desc f)))))
map)
"Keymap for agda2 goal menu.")
(defvar agda2-info-buffer nil
"Agda information buffer.")
(defvar agda2-process-buffer nil
"Agda subprocess buffer.
Set in `agda2-restart'.")
(defvar agda2-process nil
"Agda subprocess.
Set in `agda2-restart'.")
(defvar agda2-in-progress nil
"Is the Agda process currently busy?
Valid values: `nil' (not busy), `busy' (busy),
`not-so-busy' (busy with something that should typically
terminate fairly quickly).")
;; Some buffer locals
(defvar agda2-buffer-external-status ""
"External status of an `agda2-mode' buffer (dictated by the Haskell side).")
(make-variable-buffer-local 'agda2-buffer-external-status)
(defvar agda2-output-prompt "Agda2> "
"The Agda2 buffer's prompt.")
(defconst agda2-help-address
""
"Address accepting submissions of bug reports and questions.")
;; Annotation for a goal
;; {! .... !}
;; ---------- overlay: agda2-gn num, face highlight, after-string num,
;; modification-hooks (agda2-protect-goal-markers)
;; - text-props: category agda2-delim1
;; - text-props: category agda2-delim2
;; - text-props: category agda2-delim3
;; - text-props: category agda2-delim4
;;
;; Char categories for {! ... !}
(defvar agda2-open-brace "{")
(defvar agda2-close-brace " }")
(setplist 'agda2-delim1 `(display ,agda2-open-brace))
(setplist 'agda2-delim2 `(display ,agda2-open-brace rear-nonsticky t
agda2-delim2 t))
(setplist 'agda2-delim3 `(display ,agda2-close-brace agda2-delim3 t))
(setplist 'agda2-delim4 `(display ,agda2-close-brace rear-nonsticky t))
;; Note that strings used with the display property are compared by
;; reference. If the agda2-*-brace definitions were inlined, then
;; goals would be displayed as "{{ }}n" instead of "{ }n".
;; The following variables are used by the filter process,
;; `agda2-output-filter'. Their values are only modified by the filter
;; process, `agda2-go', `agda2-restart', `agda2-abort-highlighting',
;; and `agda2-abort-done'.
(defvar agda2-output-chunk-incomplete (agda2-queue-empty)
"Buffer for incomplete lines.
\(See `agda2-output-filter'.)")
(make-variable-buffer-local 'agda2-output-chunk-incomplete)
(defvar agda2-last-responses nil
"Response commands which should be run after other commands.
The command which arrived last is stored first in the list.")
(make-variable-buffer-local 'agda2-last-responses)
(defvar agda2-file-buffer nil
"The Agda buffer.
Note that this variable is not buffer-local.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; agda2-mode
;;;###autoload
(add-to-list 'completion-ignored-extensions ".agdai")
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.l?agda\\'" . agda2-mode))
;;;###autoload
(modify-coding-system-alist 'file "\\.l?agda\\'" 'utf-8)
;;;###autoload
(define-derived-mode agda2-mode prog-mode "Agda"
"Major mode for Agda files.
The following paragraph does not apply to Emacs 23 or newer.
Note that when this mode is activated the default font of the
current frame is changed to the fontset `agda2-fontset-name'.
The reason is that Agda programs often use mathematical symbols
and other Unicode characters, so we try to provide a suitable
default font setting, which can display many of the characters
encountered. If you prefer to use your own settings, set
`agda2-fontset-name' to nil.
Special commands:
\\{agda2-mode-map}"
:group 'agda2
:interactive t
:after-hook (agda2-initialize)
(if (boundp 'agda2-include-dirs)
(display-warning 'agda2 "Note that the variable agda2-include-dirs is
no longer used. You may want to update your configuration. You
have at least two choices:
* Use the library management system.
* Set the include path using agda2-program-args.
One way to avoid seeing this warning is to make sure that
agda2-include-dirs is not bound." :warning))
(setq local-abbrev-table agda2-mode-abbrev-table
indent-tabs-mode nil
mode-line-process
'((:eval (unless (eq 0 (length agda2-buffer-external-status))
(concat ":" agda2-buffer-external-status)))))
(let ((l '(max-specpdl-size 2600
max-lisp-eval-depth 2800)))
(while l (set (make-local-variable (pop l)) (pop l))))
(if (and (display-graphic-p) agda2-fontset-name)
(condition-case nil
(set-frame-font agda2-fontset-name)
(error (error "Unable to change the font; change agda2-fontset-name or tweak agda2-fontset-spec-of-fontset-agda2"))))
;; Deactivate highlighting if the buffer is edited before
;; typechecking is complete.
(add-hook 'first-change-hook 'agda2-abort-highlighting nil 'local)
;; Make sure that Font Lock mode is not used.
(font-lock-mode 0)
(agda2-highlight-setup)
(agda2-comments-and-paragraphs-setup)
(force-mode-line-update)
;; Don't take script into account when determining word boundaries
(set (make-local-variable 'word-combining-categories) (cons '(nil . nil) word-combining-categories))
(activate-input-method "Agda")
;; Highlighting etc. is removed when we switch from the Agda mode.
;; Use case: When a file M.lagda with a local variables list
;; including "mode: latex" is loaded chances are that the Agda mode
;; is activated before the LaTeX mode, and the LaTeX mode does not
;; seem to remove the text properties set by the Agda mode.
(add-hook 'change-major-mode-hook 'agda2-quit nil 'local)
;; Enable Xref
(add-hook 'xref-backend-functions #'agda2-xref-backend -90 t))
(defun agda2-initialize ()
"Initialize the `agda2-process'."
(unless (eq 'run (agda2-process-status))
(agda2-restart))
(condition-case err
(agda2-highlight-reload)
(error (message "Highlighting not loaded: %s"
(error-message-string err)))))
(defun agda2-restart ()
"Tries to start or restart the Agda process."
(interactive)
;; Kill any running instance of the Agda process.
(condition-case nil
(agda2-term)
(error nil))
;; Check that the right version of Agda is used.
(let* ((coding-system-for-read 'utf-8)
(output (with-output-to-string
(call-process agda2-program-name
nil standard-output nil "--version")))
(version (and (string-match "^Agda version \\([0-9.]+\\)" output)
(match-string 1 output))))
(unless (equal version agda2-version)
(error "The Agda mode's version (%s) does not match that of %s (%s)."
agda2-version
agda2-program-name (or version "unknown"))))
(let ((all-program-args (cons "--interaction" agda2-program-args)))
;; Check that the arguments are not malformed.
(let* ((coding-system-for-read 'utf-8)
(status)
(output
(with-output-to-string
(setq status
(apply 'call-process agda2-program-name
nil standard-output nil all-program-args)))))
(unless (equal status 0)
(error "Failed to start the Agda process:\n%s" output)))
;; Start the Agda process.
(let ((agda2-bufname "*agda2*"))
(let ((process-connection-type nil)) ; Pipes are faster than PTYs.
(setq agda2-process
(apply 'start-process "Agda2" agda2-bufname
agda2-program-name all-program-args)))
(set-process-coding-system agda2-process 'utf-8 'utf-8)
(set-process-query-on-exit-flag agda2-process nil)
(set-process-filter agda2-process 'agda2-output-filter)
(setq agda2-in-progress 'busy
agda2-file-buffer (current-buffer))
(with-current-buffer agda2-bufname
(setq agda2-process-buffer (current-buffer)
mode-name "Agda executable"
agda2-last-responses nil)
(set-buffer-file-coding-system 'utf-8))
;; Block until we see an initial prompt.
;;
;; This avoids a race condition triggered by sending a command before we've had
;; a chance to read any process output, which in turn makes `agda2-output-filter'
;; erroneously set `agda2-in-progress' to nil when it sees the initial prompt.
(while agda2-in-progress
(unless (accept-process-output agda2-process agda2-restart-timeout nil t)
(error "Failed to start the Agda process")))
(agda2-remove-annotations))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Communicating with Agda
(defun agda2-raise-error ()
"Raises an error.
The error message directs the user to the *agda2* buffer."
(error "Problem encountered. The *agda2* buffer can perhaps explain why."))
(defun agda2-running-p nil
"Does the *agda2* buffer exist, and is the Agda2 process running?"
(and (buffer-live-p agda2-process-buffer)
(eq (agda2-process-status) 'run)))
(defun agda2-send-command (restart &rest args)
"Send a command to the Agda process.
Sends the list of strings ARGS to the process. If RESTART is
non-nil and the process is not running, or the *agda2*
buffer does not exist, then an attempt is made to restart the
process."
(when (and restart (not (agda2-running-p)))
;; Try restarting automatically, but only once, in case there is
;; some major problem.
(agda2-restart)
(unless (agda2-running-p)
(agda2-raise-error)))
(let ((command (apply 'concat (agda2-intersperse " " args))))
(with-current-buffer agda2-process-buffer
(goto-char (point-max))
(insert command)
(insert "\n")
(process-send-string agda2-process (concat command "\n")))))
(defun agda2-go (save highlight how-busy do-abort &rest args)
"Executes commands in the Agda2 interpreter.
Sends the list of strings ARGS to the Agda2 interpreter, waits
for output and executes the responses, if any.
If SAVE is \\='save, then the buffer is saved first.
If HIGHLIGHT is non-nil, then the buffer's syntax highlighting
may be updated. This is also the case if the Agda process is
busy (or `not-so-busy') and `agda2-highlight-in-process' is
non-nil.
The value HOW-BUSY should be `busy' if it should not be possible
to invoke other commands while this command is running (with the
exception of commands for which DO-ABORT is nil). Otherwise it
should be `not-so-busy' (which should only be used for commands
that typically terminate fairly quickly).
If the Agda process is busy (or `not-so-busy'), and the current
buffer does not match `agda2-file-buffer', then the command is
not executed and an error is raised. The same applies if DO-ABORT
is non-nil and the Agda process is `busy'."
; Check that how-busy is well-formed.
(cl-assert (or (equal how-busy 'busy)
(equal how-busy 'not-so-busy)))
(when (and agda2-in-progress
(not (equal agda2-file-buffer
(current-buffer))))
(error "Agda is busy with something in the buffer %s"
agda2-file-buffer))
(when (and do-abort
(equal agda2-in-progress 'busy))
(error "Agda is busy with something
\(you have the option to abort or restart Agda)"))
(setq agda2-file-buffer (current-buffer))
(setq agda2-highlight-in-progress
(or highlight
(and agda2-in-progress
agda2-highlight-in-progress)))
(unless agda2-in-progress
(setq agda2-output-chunk-incomplete (agda2-queue-empty)))
(setq agda2-in-progress
(if (or (equal how-busy 'busy)
(equal agda2-in-progress 'busy))
'busy
'not-so-busy))
(when (equal save 'save) (save-buffer))
(apply 'agda2-send-command
'restart
"IOTCM"
(agda2-string-quote (buffer-file-name))
(if highlight (agda2-highlight-level) "None")
"Indirect"
"("
(append args '(")"))))
(defun agda2-abort ()
"Tries to abort the current computation, if any.
May be more efficient than restarting Agda."
(interactive)
(agda2-send-command nil
"IOTCM"
(agda2-string-quote (buffer-file-name))
"None"
"Indirect"
"Cmd_abort"))
(defun agda2-abort-done ()
"Resets certain variables.
Intended to be used by the backend if an abort command was
successful."
(declare (agda2-command ()))
(agda2-info-action "*Aborted*" "Aborted." t)
(setq agda2-highlight-in-progress nil
agda2-last-responses nil))
(defun agda2-output-filter (_proc chunk)
"Evaluate the Agda process's commands.
This filter function assumes that every line contains either some
kind of error message (which cannot be parsed as a list), or
exactly one command. Incomplete lines are stored in a
buffer (`agda2-output-chunk-incomplete').
Every command is run by this function, unless it has the form
\"(('last . priority) . cmd)\", in which case it is run by
`agda2-run-last-commands' at the end, after the Agda2 prompt
has reappeared, after all non-last commands, and after all
interactive highlighting is complete. The last commands can have
different integer priorities; those with the lowest priority are
executed first.
Non-last commands should not call the Agda process.
All commands are echoed to the *agda2* buffer, with the exception
of commands of the form \"(agda2-highlight-... ...)\".
The non-last commands are run in the order in which they appear.
When the prompt has been reached highlighting annotations are
reloaded from `agda2-highlighting-file', unless
`agda2-highlighting-in-progress' is nil."
;; Beware: the buffer may have been killed in the mean time. E.g. when
;; viewing an attachment containing Agda code in Gnus, Gnus will
;; create a temp buffer, set it in agda2-mode, call font-lock-ensure on it
;; (which won't know that it needs to wait for some process to reply), then
;; extract the fontified text and kill the temp buffer; so when Agda
;; finally answers, the temp buffer is long gone.
(when (buffer-live-p agda2-file-buffer)
(let (;; The input lines in the current chunk.
(lines (split-string chunk "\n"))
;; Non-last commands found in the current chunk (reversed).
(non-last-commands ())
;; Last incomplete line, if any.
(output-chunk-incomplete ""))
(with-current-buffer agda2-file-buffer
(when (consp lines)
(agda2-queue-enqueue agda2-output-chunk-incomplete (pop lines))
(when (consp lines)
;; The previous uncomplete chunk is now complete.
(push (agda2-queue-to-string agda2-output-chunk-incomplete)
lines)
;; Stash away the last incomplete line, if any. (Note that
;; (split-string "...\n" "\n") evaluates to (... "").)
(setq output-chunk-incomplete (car (last lines))
agda2-output-chunk-incomplete
(agda2-queue-from-string output-chunk-incomplete))
;; Handle every complete line.
(dolist (line (butlast lines))
(let* (;; The command. Lines which cannot be parsed as a single
;; list, without any junk, are ignored.
(cmd (condition-case nil
(let ((result (read-from-string line)))
(if (and (listp (car result))
(= (cdr result) (length line)))
(car result)))
(error nil)))
(is-highlighting-command
(and cmd
(symbolp (car cmd))
(let ((case-fold-search nil))
(string-match "^agda2-highlight-"
(symbol-name (car cmd)))))))
;; Do not echo highlighting commands.
(unless is-highlighting-command
(with-current-buffer agda2-process-buffer
(save-excursion
(goto-char (point-max))
(insert line)
(insert "\n"))))
(when cmd
(if (equal 'last (car-safe (car cmd)))
(push (cons (cdr (car cmd)) (cdr cmd))
agda2-last-responses)
(push cmd non-last-commands)))))
;; Run non-last commands.
(mapc 'agda2-exec-response (nreverse non-last-commands)))
;; Check if the prompt has been reached. This function assumes
;; that the prompt does not include any newline characters.
(when (agda2-queue-is-prefix-of agda2-output-prompt
agda2-output-chunk-incomplete)
(with-current-buffer agda2-process-buffer
(insert output-chunk-incomplete))
(setq agda2-output-chunk-incomplete (agda2-queue-empty)
agda2-in-progress nil
agda2-last-responses (nreverse agda2-last-responses))
(agda2-run-last-commands)))))))
(defun agda2-run-last-commands nil
"Execute the last commands in the right order.
\(After the prompt has reappeared.) See `agda2-output-filter'."
;; with-current-buffer is used repeatedly below, because some last
;; commands may switch the focus to another buffer.
(while (with-current-buffer agda2-file-buffer
(and (not agda2-in-progress) (consp agda2-last-responses)))
(with-current-buffer agda2-file-buffer
;; The list is sorted repeatedly because this function may be
;; called recursively (via `agda2-exec-response').
(setq agda2-last-responses (sort agda2-last-responses
(lambda (x y) (<= (car x) (car y)))))
(let ((r (pop agda2-last-responses)))
(agda2-exec-response (cdr r)))))
;; Unset agda2-highlight-in-progress when all the asynchronous
;; commands have terminated.
(unless agda2-in-progress
(setq agda2-highlight-in-progress nil)))
(defun agda2-abort-highlighting nil
"Abort any interactive highlighting.
This function should be used in `first-change-hook'."
(when agda2-highlight-in-progress
(setq agda2-highlight-in-progress nil)
(message "\"%s\" has been modified. Interrupting highlighting."
(buffer-name (current-buffer)))))
(defun agda2-goal-cmd (cmd save &optional want ask &rest args)
"Reads input from goal or minibuffer and sends command to Agda.
An error is raised if point is not in a goal.
The command sent to Agda is
CMD <goal number> <goal range> <user input> ARGS.
The user input is computed as follows:
* If WANT is nil, then the user input is the empty string.
* If WANT is a string, and either ASK is non-nil or the goal only
contains whitespace, then the input is taken from the
minibuffer. In this case WANT is used as the prompt string.
* Otherwise (including if WANT is \\='goal) the goal contents are
used.
If the user input is not taken from the goal, then an empty goal
range is given.
If SAVE is \\='save, then the buffer is saved just before the
command is sent to Agda (if it is sent)."
(cl-multiple-value-bind (o g) (agda2-goal-at (point))
(unless g (error "For this command, please place the cursor in a goal"))
(let ((txt (buffer-substring-no-properties (+ (overlay-start o) 2)
(- (overlay-end o) 2)))
(input-from-goal nil))
(cond ((null want) (setq txt ""))
((and (stringp want)
(or ask (string-match "\\`\\s *\\'" txt)))
(setq txt (read-string (concat want ": ") nil nil txt t)))
(t (setq input-from-goal t)))
(apply 'agda2-go save input-from-goal 'busy t cmd
(format "%d" g)
(if input-from-goal (agda2-goal-Range o) (agda2-mkRange nil))
(agda2-string-quote txt) args))))
(defun agda2-exec-response (response)
"Execute RESPONSE if recognised by `agda2-handler-alist'."
(cl-assert (symbolp (car-safe response)))
;; Agda sends us a an S-expression that we can just `eval'uate. To
;; avoid arbitrary code execution and ensure that the commands Agda
;; sends us are well-formed, we use `apply' without evaluating any
;; arguments. The symbol of the invoked function must have a
;; `agda2-safe-function' symbol property asserting the expected
;; types of all arguments, w.r.t `cl-typep'.
(let* ((inhibit-read-only t)
(func (car response))
(safe-p (plist-member (symbol-plist func) 'agda2-safe-function))
(safe-data (cadr safe-p))
(args '()))
(unless safe-p
(error "The function `%S' is not a valid Agda command" func))
;; Check each argument
(dolist (arg (cdr response))
(when (null safe-data)
(error "More arguments than expected for `%S' (%S, got %S)"
func safe-data response))
(when (eq (car-safe arg) 'quote) ;unquote arguments
(setq arg (cadr arg)))
(let ((type (pop safe-data)))
(unless (cl-typep arg type)
(error "The function `%S' was invoked with %S which is not a %S"
func arg type)))
(push arg args))
(condition-case err
(with-local-quit
(apply func (nreverse args)))
(error (warn "Error while evaluating %S: %S" response err)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; User commands and response processing
(defun agda2-load ()
"Load current buffer."
(interactive)
(agda2-go 'save t 'busy t "Cmd_load"
(agda2-string-quote (buffer-file-name))
(agda2-list-quote agda2-program-args)
))
(defun agda2-read-backend ()
"Get the currently set backend from the `agda2-backend' variable,
or ask the user for input in case the variable is not set."
(let ((name (cond
((equal agda2-backend "MAlonzo") "GHC")
((equal agda2-backend "MAlonzoNoMain") "GHCNoMain")
((equal agda2-backend nil)
(completing-read "Backend: " agda2-backends nil nil nil nil nil 'inherit-input-method))
(t agda2-backend))))
(when (equal name "") (error "No backend chosen"))
name))
(defun agda2-compile (backend)
"Compile the current module using BACKEND.
The variable `agda2-backend' determines which backend is used."
(interactive (list (agda2-read-backend)))
(agda2-go 'save t 'busy t "Cmd_compile"
backend
(agda2-string-quote (buffer-file-name))
(agda2-list-quote agda2-program-args)
))
(defun agda2-backend-cmd (backend payload)
"Run the current backend's (from variable `agda2-backend`) interaction command."
(interactive (list (agda2-read-backend) (or agda2-backend-default-payload (read-string "Payload: "))))
(if (agda2-goal-at (point))
(agda2-goal-cmd "Cmd_backend_hole" nil 'goal nil backend (agda2-string-quote payload))
(agda2-go 'save t 'busy t "Cmd_backend_top" backend (agda2-string-quote payload))
)
)
(defmacro agda2-maybe-forced (name comment cmd save want)
"This macro constructs a function NAME which runs CMD.
COMMENT is used to build the function's comment. The function
NAME takes a prefix argument which tells whether it should
apply force or not when running CMD (through
`agda2-goal-cmd';
SAVE is used as `agda2-goal-cmd's SAVE argument and
WANT is used as `agda2-goal-cmd's WANT argument)."
(let ((eval (make-symbol "eval")))
`(defun ,name (&optional prefix)
,(concat comment ".
The action depends on the prefix argument:
* If the prefix argument is `nil' (i.e., if no prefix argument is
given), then no force is applied.
* If any other prefix argument is used (for instance, if C-u is
typed once or twice right before the command is invoked), then
force is applied.")
(interactive "P")
(let ((,eval (cond ((equal prefix nil) "WithoutForce")
("WithForce"))))
(agda2-goal-cmd (concat ,cmd " " ,eval)
,save ,want)))))
(agda2-maybe-forced
agda2-give
"Give to the goal at point the expression in it"
"Cmd_give"
'save
"expression to give")
;; (defun agda2-give()
;; "Give to the goal at point the expression in it" (interactive)
;; (agda2-goal-cmd "Cmd_give" 'save "expression to give"))
(defun agda2-give-action (old-g paren)
"Update the goal OLD-G with the expression in it."
(declare (agda2-command (integer (or (eql paren)
(eql no-paren)
string
null))))
(let
;; Don't run modification hooks: we don't want this to
;; trigger agda2-abort-highlighting.
((inhibit-modification-hooks t))
(agda2-update old-g paren)))
(defun agda2-refine (pmlambda)
"Refine the goal at point.
If the goal contains an expression e, and some \"suffix\" of the
type of e unifies with the goal type, then the goal is replaced
by e applied to a suitable number of new goals.
PMLAMBDA is only used if the goal has a functional type.
When the prefix argument is given a pattern maching lambda will
be inserted, otherwise a standard lambda will be used.
If the goal is empty, the goal type is a data type, and there is
exactly one constructor which unifies with this type, then the
goal is replaced by the constructor applied to a suitable number
of new goals."
(interactive "P")
(if pmlambda
(agda2-goal-cmd "Cmd_refine_or_intro True" 'save 'goal)
(agda2-goal-cmd "Cmd_refine_or_intro False" 'save 'goal)))
(defun agda2-make-case ()
"Refine the pattern variables given in the goal.
Assumes that <clause> = {!<variables>!} is on one line."
(interactive)
(agda2-goal-cmd "Cmd_make_case" 'save "pattern variables to case (empty for split on result)"))
(defun agda2-make-case-action (newcls)
"Replace the line at point with new clauses NEWCLS and reload."
(declare (agda2-command (list)))
(agda2-forget-all-goals);; we reload later anyway.
(let* ((p0 (point))
(p1 (goto-char (+ (current-indentation) (line-beginning-position))))
(indent (current-column))
cl)
(delete-region p1 (line-end-position))
(while (setq cl (pop newcls))
(insert cl)
(if newcls (insert "\n" (make-string indent ? ))))
(goto-char p0))
(agda2-load))
(defun agda2-make-case-action-extendlam (newcls)
"Replace definition of extended lambda with new clauses NEWCLS and reload."
(declare (agda2-command (list)))
(agda2-forget-all-goals);; we reload later anyway.
(let* ((p0 (point))
(pmax (re-search-forward "!}"))
(bracketCount 0)
(p1 (goto-char (+ (current-indentation) (line-beginning-position))))
(indent (current-column))
cl)
(goto-char p0)
(re-search-backward "{!")
(while (and (not (equal (preceding-char) ?\;)) (>= bracketCount 0) (> (point) p1))
(backward-char)
(if (equal (preceding-char) ?}) (cl-incf bracketCount))
(if (equal (preceding-char) ?{) (cl-decf bracketCount)))
(let* ((is-lambda-where (= (point) p1))
(p (point)))
(delete-region (point) pmax)
(if (not is-lambda-where) (insert " "))
(while (setq cl (pop newcls))
(insert cl)
(if newcls (if is-lambda-where (insert "\n" (make-string indent ? )) (insert " ; "))))
(goto-char p)))
(agda2-load))
(defun agda2-status-action (status)
"Display the string STATUS in the current buffer's mode line.
\(precondition: the current buffer has to use the Agda mode as the
major mode)."
(declare (agda2-command (string)))
(setq agda2-buffer-external-status status)
(force-mode-line-update))
(defmacro agda2-information-buffer (buffer kind name-of-mode title)
"Used to define functions like `agda2-info-buffer'."
`(defun ,buffer nil
,(concat "Creates the Agda " kind
" buffer, if it does not already exist.
The buffer is returned.")
(unless (buffer-live-p ,buffer)
(setq ,buffer
(generate-new-buffer ,title))
(with-current-buffer ,buffer
(compilation-mode ,name-of-mode)
;; Support for jumping to positions mentioned in the text.
(set (make-local-variable 'compilation-error-regexp-alist)
'(("\\([\\\\/][^[:space:]]*\\):\\([0-9]+\\)\\.\\([0-9]+\\)\\(-\\(\\([0-9]+\\)\\.\\)?\\([0-9]+\\)\\)?"
1 (2 . 6) (3 . 7))))
;; compilation-mode adds font-lock keywords for highlighting
;; things like "make: ", assuming that they're command output.
;;
;; This is annoying because sometimes our messages get
;; line-wrapped to start with "declaration:" (e.g. Issue2899).
;;
;; Conveniently all of these stupid highlights are in a variable
;; that we can just undo!
(font-lock-remove-keywords nil compilation-mode-font-lock-keywords)
(font-lock-flush)
;; Do not skip errors that start in the same position as the
;; current one.
(set (make-local-variable 'compilation-skip-to-next-location) nil)
;; No support for recompilation. The key binding is removed, and
;; attempts to run `recompile' will (hopefully) result in an
;; error.
(let ((map (copy-keymap (current-local-map))))
(define-key map (kbd "g") 'undefined)
;; Hijack the bindings for going to definition in the info
;; buffer, away from compilation-mode's, into something that
;; can read definition sites from highlighting info.
(define-key map (kbd "RET") #'xref-find-definitions)
(define-key map '[mouse-2] #'agda2-goto-definition-mouse)
(use-local-map map))
(set (make-local-variable 'compile-command)
'agda2-does-not-support-compilation-via-the-compilation-mode)
(set-syntax-table agda2-mode-syntax-table)
(set (make-local-variable 'word-combining-categories) (cons '(nil . nil) word-combining-categories))
(set-input-method "Agda")
;; Andreas, 2025-08-05, PR #8047.
;; We setup highlighting so that annotation-bindings is defined
;; and can be accessed by annotation-annotate.
;; This allows us to create Agda-style highlighting from aspects
;; also in the Agda information buffer.
(agda2-highlight-setup)
;; Use Xref
(add-hook 'xref-backend-functions #'agda2-xref-backend -90 t)))
,buffer))
(agda2-information-buffer agda2-info-buffer "info" "AgdaInfo" "*Agda information*")
(defun agda2-display-information-buffer ()
"Make sure the Agda information buffer is displayed in the current window.
Helper factored out from agda2-info-action."
(interactive)
(let ((buf (agda2-info-buffer)))
;; If the current window displays the information buffer, then the
;; window configuration is left untouched.
(unless (equal (window-buffer) buf)
(let ((agda-window
(and agda2-file-buffer
(car-safe
;; All windows, including minibuffers, on any
;; frame on the current terminal, displaying the
;; present Agda file buffer.
(get-buffer-window-list agda2-file-buffer t 0)))))
(save-selected-window
;; Select a window displaying the Agda file buffer (if such
;; a window exists). With certain configurations of
;; display-buffer this should increase the likelihood that
;; the info buffer will be displayed on the same frame.
(when agda-window
(select-window agda-window 'no-record))
(let* (;; If there is only one window, then the info window
;; should be created above or below the code window,
;; not to the left or right.
(split-width-threshold nil)
(window
(display-buffer
buf
;; Under Emacs 23 the effect of the following
;; argument is only that the current window
;; should not be used.
'(nil
.
(;; Do not use the same window.
(inhibit-same-window . t)
;; Do not raise or select another frame.
(inhibit-switch-frame . t))))))
(if window
(fit-window-to-buffer window
(truncate
(* (frame-height)
agda2-information-window-max-height))))))))))
(defun agda2-info-action (name text append &rest annotations)
"Insert TEXT plus a final newline into the Agda info buffer and display it.
NAME is displayed in the buffer's mode line.
The TEXT is highlighted by the given ANNOTATIONS
which come in the same format as for agda2-highlight-apply.
If APPEND is non-nil, then TEXT is appended at the end of the
buffer, and point placed after this text.
If APPEND is nil, then any previous text is removed before TEXT
is inserted, and point is placed before this text."
(declare (agda2-command (string string boolean &repeat t))) ;
(interactive)
(let ((buf (agda2-info-buffer)))
(with-current-buffer buf
;; In some cases the jump-to-position-mentioned-in-text
;; functionality (see compilation-error-regexp-alist above)
;; didn't work: Emacs jumped to the wrong position. However, it
;; seems to work if compilation-forget-errors is used. This
;; problem may be related to Emacs bug #9679
;; (http://debbugs.gnu.org/cgi/bugreport.cgi?bug=9679). The idea
;; to use compilation-forget-errors comes from a comment due to
;; Oleksandr Manzyuk
;; (https://github.com/haskell/haskell-mode/issues/67).
(compilation-forget-errors)
(unless append (erase-buffer))
(unless (string-empty-p text)
;; (message "text = //%s//" text)
(save-excursion
(goto-char (point-max))
;; Andreas, 2025-08-04, PR #8047.
;; Experiment shows that 'face annotations do not survive in compilation-mode,
;; but 'font-lock-face is not removed.
;; https://emacs.stackexchange.com/questions/17141/how-do-i-insert-text-with-a-specific-face
;; (put-text-property 0 (max 0 (- (length text) 10)) 'font-lock-face '(:weight bold) text)
;; (message "text: %s" text)
;; (message "length: %i" (length text))
;; (message "annotations = %s" annotations)
(apply 'annotation-load "Click to jump to definition" nil text annotations)
;; (pp (text-properties-at 0 text))
(insert text)
(newline)))
;; Update the mode line of the Agda information buffer,
;; displaying NAME in bold
;; in the place where usually the file name is displayed.
(put-text-property 0 (length name) 'face '(:weight bold) name)
(setq mode-line-buffer-identification name)
(force-mode-line-update))
(agda2-display-information-buffer)
;; Move point in every window displaying the information buffer.
;; Exception: If we are appending, don't move point in selected
;; windows.
(dolist (window (get-buffer-window-list buf 'no-minibuffer t))
(unless (and append
(equal window (selected-window)))
(with-selected-window window
(if append
(goto-char (point-max))
(goto-char (point-min))))))))
(defun agda2-info-action-and-copy (name text &optional append)
"Same as agda2-info-action but also puts TEXT in the kill ring."
(declare (agda2-command (string string t)))
(kill-new text)
(agda2-info-action name text append))
(defun agda2-remove-annotations ()
"Removes buffer annotations (overlays and text properties)."
(interactive)
(dolist (o (overlays-in (point-min) (point-max)))
(delete-overlay o))
(let ((inhibit-read-only t))
(annotation-preserve-mod-p-and-undo
(set-text-properties (point-min) (point-max) '()))
(force-mode-line-update)))
(defun agda2-next-goal () "Go to the next goal, if any." (interactive)
(agda2-mv-goal 'next-single-property-change 'agda2-delim2 1 (point-min)))
(defun agda2-previous-goal () "Go to the previous goal, if any." (interactive)
(agda2-mv-goal 'previous-single-property-change 'agda2-delim3 0 (point-max)))
(defun agda2-mv-goal (change delim adjust wrapped)
(agda2-let ()
((go (p) (while (and (setq p (funcall change p 'category))
(not (eq (get-text-property p 'category) delim))))
(if p (goto-char (+ adjust p)))))
(or (go (point)) (go wrapped) (message "No goals in the buffer"))))
(defun agda2-quit ()
"Quit and clean up after agda2."
(interactive)
(remove-hook 'first-change-hook 'agda2-abort-highlighting 'local)
(remove-hook 'after-save-hook 'agda2-highlight-tokens 'local)
(agda2-remove-annotations)
(agda2-term))
(defun agda2-term (&optional nicely)
"Interrupt the Agda process and kill its buffer.
If this function is invoked with a prefix argument, then Agda is
asked nicely to terminate itself after any previously invoked
commands have completed."
(interactive "P")
(if nicely
(progn
;; Set up things so that if the Agda process terminates, then
;; its buffer is killed.
(when (and agda2-process
(process-status agda2-process))
(set-process-sentinel agda2-process 'agda2-kill-process-buffer))
;; Kill the process buffer if the Agda process has already
;; been killed.
(agda2-kill-process-buffer)
;; Try to kill the Agda process.
(agda2-send-command nil
"IOTCM"
(agda2-string-quote (buffer-file-name))
"None"
"Indirect"
"Cmd_exit"))
;; Try to kill the Agda process and the process buffer.
(when (and agda2-process
(process-status agda2-process))
(interrupt-process agda2-process))
(when (buffer-live-p agda2-process-buffer)
(kill-buffer agda2-process-buffer))))
(defun agda2-kill-process-buffer (&optional _process _event)
"Kills the Agda process buffer, if any.
But only if the Agda process does not exist or has terminated.
This function can be used as a process sentinel."
(when (and (or (null agda2-process)
(member (process-status agda2-process)
'(exit signal failed nil)))
(buffer-live-p agda2-process-buffer))
(kill-buffer agda2-process-buffer)))
(cl-defmacro agda2--with-gensyms ((&rest names) &body body)
"Bind NAMES to fresh symbols in BODY"
(declare (indent 1))
`(let ,(cl-loop for x in names collecting `(,x (make-symbol (symbol-name',x))))
,@body))
;; This macro is meant to be used to generate other macros which define
;; functions which can be used either directly from a goal or at a global
;; level and are modifiable using one of three levels of normalisation.
(defmacro agda2-proto-maybe-normalised (name comment cmd norm0 norm1 norm2 norm3 spec)
"This macro constructs a function NAME which runs CMD.
COMMENT is used to build the function's comment.
The function NAME takes a prefix argument which tells whether it
should normalise types according to either NORM0, NORM1, NORM2, or NORM3
when running CMD through `agda2-goal-cmd`.
SPEC can be either (fromgoal want) or (global prompt).
"
;; Names bound in a macro should be ``uninterned'' to avoid name capture
;; We use the macro `agda2--with-gensyms' to bind these.
(agda2--with-gensyms (eval prefix args)
`(defun ,name (,prefix &rest ,args)
,(format "%s.
The form of the result depends on the prefix argument:
* If the prefix argument is `nil' (i.e., if no prefix argument is
given), then the result is %s.
* If the prefix argument is `(4)' (for instance if C-u is typed
exactly once right before the command is invoked), then the
result is %s.
* If the prefix argument is `(16)' (for instance if C-u is typed
exactly twice right before the command is invoked), then the
result is %s.
* If any other prefix argument is used (for instance if C-u is
typed thrice right before the command is invoked), then the
result is %s." comment (nth 1 norm0) (nth 1 norm1) (nth 1 norm2) (nth 1 norm3))
;; All the commands generated by the macro are interactive.
;; Those called from a goal, grab the value present there (if any)
;; Whereas those called globally always use a prompt
(interactive ,(pcase spec
(`(fromgoal ,_want)
"P")
(`(global ,prompt)
(if prompt
(concat "P\nM" prompt ": ")
"P"))))
;; Depending on the prefix's value we pick one of the three
;; normalisation levels
(let ((,eval (cond ((null ,prefix)
,(car norm0))
((equal ,prefix '(4))
,(car norm1))
((equal ,prefix '(16))
,(car norm2))
(t ,(car norm3)))))
;; Finally, if the command is called from a goal, we use `agda2-goal-cmd'
;; Otherwise we resort to `agda2-go'
,(pcase spec
(`(fromgoal ,want)
`(agda2-goal-cmd (concat ,cmd " " ,eval) nil ,want))
(`(global ,prompt)
`(agda2-go nil t 'busy t
(concat ,cmd " "
,eval " "
(if ,prompt
(agda2-string-quote (car ,args))
"")))))))))
(defmacro agda2-maybe-normalised (name comment cmd want)
`(agda2-proto-maybe-normalised
,name ,comment ,cmd
("Simplified" "simplified")
("Instantiated" "neither explicitly normalised nor simplified")
("Normalised" "normalised")
("HeadNormal" "head normalised")
(fromgoal ,want)))
(defmacro agda2-maybe-normalised-asis (name comment cmd want)
`(agda2-proto-maybe-normalised
,name ,comment ,cmd
("AsIs" "returned as is")
("Simplified" "simplified")
("Normalised" "normalised")
("HeadNormal" "head normalised")
(fromgoal ,want)))
(defmacro agda2-maybe-normalised-toplevel (name comment cmd prompt)
`(agda2-proto-maybe-normalised
,name ,comment ,cmd
("Simplified" "simplified")
("Instantiated" "neither explicitly normalised nor simplified")
("Normalised" "normalised")
("HeadNormal" "head normalised")
(global ,prompt)))
(defmacro agda2-maybe-normalised-toplevel-noprompt (name comment cmd)
`(agda2-proto-maybe-normalised
,name ,comment ,cmd
("Simplified" "simplified")
("Instantiated" "neither explicitly normalised nor simplified")
("Normalised" "normalised")
("HeadNormal" "head normalised")
(global nil)))
(defmacro agda2-maybe-normalised-toplevel-asis-noprompt (name comment cmd)
`(agda2-proto-maybe-normalised
,name ,comment ,cmd
("AsIs" "returned as is")
("Simplified" "simplified")
("Normalised" "normalised")
("HeadNormal" "head normalised")
(global nil)))
(agda2-maybe-normalised
agda2-goal-type
"Show the type of the goal at point"
"Cmd_goal_type"
nil)
(agda2-maybe-normalised
agda2-infer-type
"Infer the type of the goal at point"
"Cmd_infer"
"expression to type")
(agda2-maybe-normalised-toplevel
agda2-infer-type-toplevel
"Infers the type of the given expression. The scope used for
the expression is that of the last point inside the current
top-level module"
"Cmd_infer_toplevel"
"Expression")
(defun agda2-infer-type-maybe-toplevel ()
"Infers the type of the given expression.
Either uses the scope of the current goal or, if point is not in a goal, the
top-level scope."
(interactive)
(call-interactively (if (agda2-goal-at (point))
'agda2-infer-type
'agda2-infer-type-toplevel)))
(defun agda2-why-in-scope ()
"Explain why something is in scope in a goal."
(interactive)
(agda2-goal-cmd "Cmd_why_in_scope" nil "Name"))
(defun agda2-why-in-scope-toplevel (name)
"Explain why something is in scope at the top level."
(interactive "MName: ")
(agda2-go nil t 'busy t
"Cmd_why_in_scope_toplevel"
(agda2-string-quote name)))
(defun agda2-why-in-scope-maybe-toplevel ()
"Explains why a given name is in scope."
(interactive)
(call-interactively (if (agda2-goal-at (point))
'agda2-why-in-scope
'agda2-why-in-scope-toplevel)))
(agda2-maybe-normalised
agda2-elaborate-give
"Elaborate check the given expression against the hole's type and fill in the
hole with the elaborated term"
"Cmd_elaborate_give"
"expression to elaborate and give")
(agda2-maybe-normalised
agda2-goal-and-context
"Shows the type of the goal at point and the currect context"
"Cmd_goal_type_context"
nil)
(agda2-maybe-normalised
agda2-goal-and-context-and-inferred
"Shows the context, the goal and the given expression's inferred type"
"Cmd_goal_type_context_infer"
"expression to type")
(agda2-maybe-normalised
agda2-goal-and-context-and-checked
"Shows the context, the goal and check the given expression's against
the hole's type"
"Cmd_goal_type_context_check"
"expression to type")
(agda2-maybe-normalised
agda2-show-context
"Show the context of the goal at point"
"Cmd_context"
nil)
(agda2-maybe-normalised-asis
agda2-helper-function-type
"Compute the type of a hypothetical helper function."
"Cmd_helper_function"
"Expression")
(agda2-maybe-normalised
agda2-module-contents
"Shows all the top-level names in the given module.
Along with their types."
"Cmd_show_module_contents"
"Module name (empty for current module)")
(agda2-maybe-normalised-toplevel
agda2-module-contents-toplevel
"Shows all the top-level names in the given module.
Along with their types."
"Cmd_show_module_contents_toplevel"
"Module name (empty for top-level module)"
)
(agda2-maybe-normalised-toplevel
agda2-search-about-toplevel
"Search About an identifier"
"Cmd_search_about_toplevel"
"Name"
)
(defun agda2-module-contents-maybe-toplevel ()
"Shows all the top-level names in the given module.
Along with their types.
Uses either the scope of the current goal or, if point is not in
a goal, the top-level scope."
(interactive)
(call-interactively (if (agda2-goal-at (point))
'agda2-module-contents
'agda2-module-contents-toplevel)))
(defun agda2-solve-maybe-all ()
"Solves goals that are already instantiated internally.
Either only one if point is a goal, or all of them."
(interactive)
(call-interactively (if (agda2-goal-at (point))
'agda2-solveOne
'agda2-solveAll))
)
(defun agda2-mimer-maybe-all ()
"Run proof search.
Either only one if point is a goal, or all of them."
(interactive)
(call-interactively (if (agda2-goal-at (point))
'agda2-mimer
'agda2-mimerAll))
)
(agda2-maybe-normalised-asis
agda2-mimer
"Run proof search on a goal."
"Cmd_autoOne"
'goal
)
(agda2-maybe-normalised-toplevel-asis-noprompt
agda2-mimerAll
"Solves all goals by simple proof search."
"Cmd_autoAll"
)
(agda2-maybe-normalised-toplevel-asis-noprompt
agda2-show-goals
"Show all goals."
"Cmd_metas"
)
(agda2-maybe-normalised-toplevel-asis-noprompt
agda2-solveAll
"Solves all goals that are already instantiated internally."
"Cmd_solveAll"
)
;; Andreas, 2025-09-12
;; Cmd_constraints has same normalization strategy as Cmd_solveOne
;; since after showing the meta solutions one might want to
;; apply them at the same normalization level.
(agda2-maybe-normalised-toplevel-noprompt
agda2-show-constraints
"Show meta solutions and constraints."
"Cmd_constraints"
)
(agda2-maybe-normalised
agda2-solveOne
"Solves the goal at point if it is already instantiated internally"
"Cmd_solveOne"
nil
)
(defun agda2-solveAll-action (iss)
(declare (agda2-command (list)))
(while iss
(let* ((g (pop iss)) (txt (pop iss))
(cmd (cons 'agda2-solve-action (cons g (cons txt nil)))))
(if (null agda2-last-responses)
(push (cons 1 cmd) agda2-last-responses)
(nconc agda2-last-responses (cons (cons 3 cmd) nil))))))
(defun agda2-solve-action (g txt)
(declare (agda2-command (integer string)))
(save-excursion
(agda2-replace-goal g txt)
(agda2-goto-goal g)
(agda2-give)))
(defun agda2-compute-normalised (&optional arg)
"Compute the normal form of the expression in the goal at point.
With the prefix argument `(4)' \"abstract\" is ignored during the
computation.
With a prefix argument `(16)' the normal form of
\"show <expression>\" is computed, and then the resulting string
is printed.
With any other prefix the head normal form is computed."
(interactive "P")
(let ((cmd (concat "Cmd_compute"
(cond ((equal arg nil) " DefaultCompute")
((equal arg '(4)) " IgnoreAbstract")
((equal arg '(16)) " UseShowInstance")
(" HeadCompute")))))
(agda2-goal-cmd cmd nil "expression to normalise")))
(defun agda2-compute-normalised-toplevel (expr &optional arg)
"Compute the normal form of the given expression.
The scope used for the expression is that of the last point
inside the current top-level module.
With a prefix argument distinct from `(4)' the normal form of
\"show <expression>\" is computed, and then the resulting string
is printed.
With the prefix argument `(4)' \"abstract\" is ignored during the
computation."
(interactive "MExpression: \nP")
(let ((cmd (concat "Cmd_compute_toplevel"
(cond ((equal arg nil) " DefaultCompute")
((equal arg '(4)) " IgnoreAbstract")
((equal arg '(16)) " UseShowInstance")
(" HeadCompute")) " ")))
(agda2-go nil t 'busy t
(concat cmd (agda2-string-quote expr)))))
(defun agda2-compute-normalised-maybe-toplevel ()
"Compute the normal form of the given expression.
The scope used for the expression is that of the last point
inside the current top-level module.
With a prefix argument distinct from `(4)' the normal form of
\"show <expression>\" is computed, and then the resulting string
is printed.
With the prefix argument `(4)' \"abstract\" is ignored during the
computation."
(interactive)
(if (agda2-goal-at (point))
(call-interactively 'agda2-compute-normalised)
(call-interactively 'agda2-compute-normalised-toplevel)))
(defun agda2-display-program-version ()
"Display version of Agda"
(interactive)
(agda2-go nil nil 'busy t "Cmd_show_version"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
(defun agda2-highlight-reload nil
"Loads precomputed syntax highlighting info for the current buffer.
Only if the buffer is unmodified, and only if there is anything to load."
(unless (buffer-modified-p)
(agda2-go nil t 'not-so-busy t
"Cmd_load_highlighting_info"
(agda2-string-quote (buffer-file-name)))))
(defun agda2-file-type (&optional path)
"Determine the type of literate agda file based off of the file extension.
If PATH is nil, use the filepath of the current buffer.
Will return one of the following options:
-- plain
-- latex
-- rst
-- markdown
-- org
-- typst
-- forester"
(pcase (file-name-extension (or path (buffer-file-name)))
("agda" 'plain)
((or "lagda" "tex") 'latex)
("rst" 'rst)
("org" 'org)
("md" 'markdown)
("typ" 'typst)
("tree" 'forester)
(ext (error "Unknown agda file extension %s" ext))))
(defun agda2-goals-action (goals)
"Annotates the goals in the current buffer with text properties.
GOALS is a list of the buffer's goal numbers, in the order in
which they appear in the buffer. Note that this function should
be run /after/ syntax highlighting information has been loaded,
because the two highlighting mechanisms interact in unfortunate
ways."
(declare (agda2-command (list)))
(agda2-forget-all-goals)
(agda2-let
((file-type (agda2-file-type))
;; All regexes in `code-start-rx' are headed by line-start (blank *) to avoid
;; creating interaction points in code blocks that are commented
;; out using the host languages comments (EG: % \begin{code})
;; See issue #1331.
;;
;; [TODO: Reed M, 14/04/2026] Literate RST support.
(code-start-rx
(pcase file-type
('latex
(rx line-start (* blank) "\\begin{code}"))
('org
(rx line-start (* blank) "#+begin_src" (+ blank) "agda2"))
((or 'typst 'markdown)
(rx line-start (* blank) "```"))
('forester
(rx line-start (* blank) "\\agda{"))))
;; We don't need to be as careful with comments in `code-end-rx', as
;; `code-rx' and the main lexer loop will handle comments for us.
(code-end-rx
(pcase file-type
('latex
(rx "\\end{code}"))
('org
(rx "#+end_src"))
((or 'typst 'markdown)
(rx "```"))
;; Forester uses } to close out code blocks,
;; which requires special handling due to implicit
;; arguments.
(_ (rx unmatchable))))
(comment-rx
(rx (or "{-" "-}")))
(string-end-rx
(rx (not "\\") "\""))
(char-end-rx
(rx (not "\\") "'"))
(goal-end-rx
(rx (or "{!" "!}")))
(code-rx
(rx (or
(submatch-n 1 "\"")
(and blank (submatch-n 1 "'"))
;; We want to make sure that we only match proper comments so that we don't
;; stop lexing on identifiers like foo--bar.
(and (or bol (any "." "{" "}" "(" ")" ";" space)) (submatch-n 1 "--"))
;; Similar idea: don't match ? inside of an identifier name.
(and (or bol (any "." "{" "}" "(" ")" ";" space))
(submatch-n 1 "?")
(or eol (any "." "{" "}" "(" ")" ";" space)))
(submatch-n 1 (and "{" (? (any "-" "!"))))
(submatch-n 1 "}")
(submatch-n 1 (regexp code-end-rx)))))
;; Don't run modification hooks: we don't want this function to
;; trigger `agda2-abort-highlighting'.
(inhibit-modification-hooks t)
;; Make sure that we don't use case-sensitive matching
;; so that we can pick up on all capitalizations of #+BEGIN_SRC.
(case-fold-search t)
(nbrackets 0))
((advance-to-code-block ()
(when code-start-rx (re-search-forward code-start-rx nil t)))
(advance-to-comment-end (n)
(re-search-forward comment-rx nil t)
(pcase (match-string 0)
("{-"
(advance-to-comment-end (1+ n)))
("-}"
(unless (zerop n)
(advance-to-comment-end (1- n))))))
(advance-to-string-end ()
(re-search-forward string-end-rx nil t))
(advance-to-char-end ()
(re-search-forward char-end-rx nil t))
(advance-to-goal-end (n)
(re-search-forward goal-end-rx nil t)
(pcase (match-string 0)
("{!"
(advance-to-goal-end (1+ n)))
("!}"
(if (zerop n)
(point)
(advance-to-goal-end (1- n))))))
(end-of-code-block (str)
(pcase file-type
('latex (equal str "\\end{code}"))
('org (equal (downcase str) "#+end_src"))
((or 'typst 'markdown) (equal str "```"))
('forester (and (equal str "}") (zerop nbrackets))))))
(save-excursion
(goto-char (point-min))
;; This code assumes that all delimiters in Agda code
;; are properly matched, which may not hold if the user
;; performs a slow load and then starts insert/deleting
;; braces or quotes. However, this sort of problem is unavoidable
;; with our current synchronization strategy (or lack thereof).
(advance-to-code-block)
(while (and goals (re-search-forward code-rx nil t))
(pcase (match-string 1)
((pred end-of-code-block)
(advance-to-code-block))
("\""
(advance-to-string-end))
("'"
(advance-to-char-end))
("{-"
(advance-to-comment-end 0))
("--"
(end-of-line))
("{!"
(let ((start (- (point) 2))
(end (advance-to-goal-end 0)))
(agda2-make-goal start end (pop goals))))
("?"
(goto-char (match-beginning 1))
(delete-char 1)
(insert "{!!}")
(agda2-make-goal (- (point) 4) (point) (pop goals)))
("{"
(cl-incf nbrackets))
("}"
(cl-decf nbrackets)))))))
(defun agda2-make-goal (p q n)
"Make a goal with number N at <P>{!...!}<Q>. Assume the region is clean."
(annotation-preserve-mod-p-and-undo
(let ((atp (lambda (x ps) (add-text-properties x (1+ x) ps))))
(funcall atp p '(category agda2-delim1))
(funcall atp (1+ p) '(category agda2-delim2))
(funcall atp (- q 2) '(category agda2-delim3))
(funcall atp (1- q) '(category agda2-delim4)))
(let ((o (make-overlay p q nil t nil)))
(overlay-put o 'modification-hooks '(agda2-protect-goal-markers))
(overlay-put o 'agda2-gn n)
(overlay-put o 'face 'highlight)
(overlay-put o 'after-string (propertize (format "%s" n) 'face 'highlight)))))
(defun agda2-protect-goal-markers (ol action beg end &optional _length)
"Ensures that the goal markers cannot be tampered with.
Except if `inhibit-read-only' is non-nil or /all/ of the goal is
modified."
(if action
;; This is the after-change hook.
nil
;; This is the before-change hook.
(cond
((and (<= beg (overlay-start ol)) (>= end (overlay-end ol)))
;; The user is trying to remove the whole goal:
;; manually evaporate the overlay and add an undo-log entry so
;; it gets re-added if needed.
(when (listp buffer-undo-list)
(push (list 'apply 0 (overlay-start ol) (overlay-end ol)
'move-overlay ol (overlay-start ol) (overlay-end ol))
buffer-undo-list))
(delete-overlay ol))
((or (< beg (+ (overlay-start ol) 2))
(> end (- (overlay-end ol) 2)))
(unless inhibit-read-only
(signal 'text-read-only nil))))))
(defun agda2-update (old-g new-txt)
"Update the goal OLD-G.
If NEW-TXT is a string, then the goal is replaced by the string,
and otherwise the text inside the goal is retained (parenthesised
if NEW-TXT is `'paren').
Removes the goal braces, but does not remove the goal overlay or
text properties."
(cl-multiple-value-bind (p q) (agda2-range-of-goal old-g)
(save-excursion
(cond ((stringp new-txt)
(agda2-replace-goal old-g new-txt))
((equal new-txt 'paren)
(goto-char (- q 2)) (insert ")")
(goto-char (+ p 2)) (insert "(")))
(cl-multiple-value-bind (p q) (agda2-range-of-goal old-g)
(delete-region (- q 2) q)
(delete-region p (+ p 2)))
;; Update highlighting
(if (and (not (equal new-txt 'paren)) (not (equal new-txt 'no-paren)))
(apply 'agda2-go 'save t 'busy nil "Cmd_highlight"
(format "%d" old-g)
(agda2-mkRange `(,p ,(- q 2)))
(agda2-string-quote new-txt) nil))
)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Misc
(defun agda2-process-status ()
"Status of `agda2-process-buffer', or \"no process\"."
(condition-case nil
(process-status agda2-process)
(error "no process")))
(defun agda2-intersperse (sep xs)
(let (ys)
(while xs
(push (pop xs) ys)
(push sep ys))
(pop ys)
(nreverse ys)))
(defun agda2-goal-Range (o)
"The Haskell Range of goal overlay O."
(agda2-mkRange `(,(+ (overlay-start o) 2)
,(- (overlay-end o) 2))))
(defun agda2-mkRange (points)
"A string representing a range corresponding to POINTS.
POINTS must be a list of integers, and its length must be 0 or 2."
(if points
(format "(intervalsToRange (Just (mkAbsolute %s)) %s)"
(agda2-string-quote (file-truename (buffer-file-name)))
(format "[Interval () %s %s]"
(agda2-mkPos (car points))
(agda2-mkPos (cadr points))))
"noRange"))
(defun agda2-mkPos (&optional p)
"The Haskell PositionWithoutFile corresponding to P or `point'."
(save-excursion
(save-restriction
(widen)
(if p (goto-char p))
(format "(Pn () %d %d %d)"
(point)
(count-lines (point-min) (point))
(1+ (current-column))))))
(defun agda2-char-quote (c)
"Convert character C to the notation used in Haskell strings.
The non-ASCII characters are actually rendered as
\"\\xNNNN\\&\", i.e. followed by a \"null character\", to avoid
problems if they are followed by digits. ASCII characters (code
points < 128) are converted to singleton strings."
(if (< c 128)
(list c)
;; FIXME: Why return a list rather than a string? --Stef
(append (format "\\x%x\\&" (encode-char c 'ucs)) nil)))
(defun agda2-string-quote (s)
"Format S as a Haskell string literal.
Removes any text properties, escapes newlines, double quotes,
etc., adds surrounding double quotes, and converts non-ASCII
characters to the \\xNNNN notation used in Haskell strings."
(let ((print-escape-newlines t)
(s2 (copy-sequence s)))
(set-text-properties 0 (length s2) nil s2)
(mapconcat 'agda2-char-quote (prin1-to-string s2) "")))
(defun agda2-list-quote (strings)
"Convert a list of STRINGS into a string representing it in Haskell syntax."
(concat "[" (mapconcat 'agda2-string-quote strings ", ") "]"))
(defun agda2-goal-at(pos)
"Return (goal overlay, goal number) at POS, or nil."
(let ((os (and pos (overlays-at pos))) o g)
(while (and os (not(setq g (overlay-get (setq o (pop os)) 'agda2-gn)))))
(if g (list o g))))
(defun agda2-goal-overlay (g)
"Returns the overlay of goal number G, if any."
(car
(remove nil
(mapcar (lambda (o) (if (equal (overlay-get o 'agda2-gn) g) o))
(overlays-in (point-min) (point-max))))))
(defun agda2-range-of-goal (g)
"The range of goal G."
(let ((o (agda2-goal-overlay g)))
(if o (list (overlay-start o) (overlay-end o)))))
(defun agda2-goto-goal (g)
(let ((p (+ 2 (car (agda2-range-of-goal g)))))
(if p (goto-char p))))
(defun agda2-replace-goal (g newtxt)
"Replace the content of goal G with NEWTXT." (interactive)
(save-excursion
(cl-multiple-value-bind (p q) (agda2-range-of-goal g)
(setq p (+ p 2) q (- q 2))
(let ((indent (and (goto-char p) (current-column))))
(delete-region p q) (insert newtxt)
(while (re-search-backward "^" p t)
(insert-char ? indent) (backward-char (1+ indent)))))))
(defun agda2-forget-all-goals ()
"Remove all goal annotations."
(annotation-preserve-mod-p-and-undo
(remove-text-properties (point-min) (point-max) '(category nil)))
(dolist (ovl (overlays-in (point-min) (point-max)))
(when (overlay-get ovl 'agda2-gn)
(delete-overlay ovl))))
(defun agda2-decl-beginning ()
"Find the beginning point of the declaration containing the point.
To do: dealing with semicolon separated decls."
(interactive)
(save-excursion
(let* ((pEnd (point))
(pDef (progn (goto-char (point-min))
(re-search-forward "\\s *" pEnd t)))
(cDef (current-column)))
(while (re-search-forward
"where\\(\\s +\\)\\S \\|^\\(\\s *\\)\\S " pEnd t)
(if (match-end 1)
(setq pDef (goto-char (match-end 1))
cDef (current-column))
(goto-char (match-end 2))
(if (>= cDef (current-column))
(setq pDef (point)
cDef (current-column))))
(forward-char))
(goto-char pDef)
(if (equal (current-word) "mutual")
(or (match-end 2) (match-end 1))
pDef))))
(defun agda2-beginning-of-decl ()
(interactive)
(goto-char (agda2-decl-beginning)))
(defvar agda2-debug-buffer-name "*Agda debug*"
"The name of the buffer used for Agda debug messages.")
(defvar agda2-debug-buffer nil
"Agda debug buffer.")
(agda2-information-buffer agda2-debug-buffer "debug" "AgdaDebug" agda2-debug-buffer-name)
(defun agda2-verbose (msg &rest annotations)
"Appends the string MSG plus a final newline
to the `agda2-debug-buffer-name' buffer.
Note that this buffer's contents is not erased automatically when
a file is loaded."
(declare (agda2-command (string &repeat t)))
(unless (string-empty-p msg)
(with-current-buffer (agda2-debug-buffer)
(save-excursion
(goto-char (point-max))
(apply 'annotation-load "Click to jump to definition" nil msg annotations)
(insert msg)
(newline)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Comments and paragraphs
(defun agda2-comments-and-paragraphs-setup nil
"Set up comment and paragraph handling for the Agda mode."
;; Empty lines (all white space according to Emacs) delimit
;; paragraphs.
(set (make-local-variable 'paragraph-start) "\\s-*$")
(set (make-local-variable 'paragraph-separate) paragraph-start)
;; Support for adding/removing comments.
(set (make-local-variable 'comment-start) "-- ")
;; Use the syntax table to locate comments (and possibly other
;; things). Syntax table setup for comments is done elsewhere.
(set (make-local-variable 'comment-use-syntax) t)
;; Update token-based highlighting after the buffer has been saved.
(add-hook 'after-save-hook 'agda2-highlight-tokens nil 'local)
;; Support for proper filling of text in comments (requires that
;; Filladapt is activated).
(when (featurep 'filladapt)
(add-to-list (make-local-variable
'filladapt-token-table)
'("--" agda2-comment))
(add-to-list (make-local-variable 'filladapt-token-match-table)
'(agda2-comment agda2-comment) t)
(add-to-list (make-local-variable 'filladapt-token-conversion-table)
'(agda2-comment . exact))))
(defun agda2-comment-dwim-rest-of-buffer ()
"Comment or uncomment the rest of the buffer.
From the beginning of the current line to the end of the buffer."
(interactive)
(save-excursion
(forward-line 0)
(push-mark (point) 'no-message 'activate-mark)
(unwind-protect
(progn
(goto-char (point-max))
(comment-dwim nil))
(pop-mark))))
(defun agda2-highlight-tokens nil
"Compute token-based highlighting information.
Unless `agda2-highlight-level' is `none' or the Agda process is
busy (or `not-so-busy') with something. This command might save
the buffer."
(unless (or agda2-in-progress
(equal agda2-highlight-level 'none))
(agda2-go 'save t 'not-so-busy t
"Cmd_tokenHighlighting"
(agda2-string-quote (buffer-file-name))
"Keep")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Xref integration
(defun agda2-xref-backend ()
"Return an Xref backend."
'agda2)
(cl-defmethod xref-backend-identifier-at-point ((_ (eql agda2)))
"Return the symbol at point with text properties."
(and (consp (get-text-property (point) 'annotation-goto))
(thing-at-point 'symbol)))
(defun agda2-make-xref (file point)
"Return a `xref-item' pointing to FILE at POINT."
(with-current-buffer (find-file-noselect file)
(save-excursion
(goto-char point)
(xref-make
(buffer-substring
(line-beginning-position)
(save-excursion
(goto-char (line-end-position))
(skip-syntax-backward " >")
(point)))
(xref-make-buffer-location
(current-buffer)
(point))))))
(defvar agda2-last-xref-ict (make-hash-table :test 'equal)
"Cached table of unambiguous identifiers and their locations.")
(defun agda2-slurp-identifiers ()
"Traverse the buffer for identifiers and update `agda2-last-xref-ict'."
(save-excursion
(let ((idents (make-hash-table)) start end)
(goto-char (point-min))
(catch 'done
(while t
(setq start (next-single-property-change
(point) 'annotation-goto))
(goto-char (or start (throw 'done t)))
(cl-assert (get-text-property (point) 'annotation-goto))
(setq end (next-single-property-change
(point) 'annotation-goto))
(goto-char (or end (throw 'done t)))
(cl-assert (null (get-text-property (point) 'annotation-goto)))
(when (< start end)
(push (get-text-property (1- (point)) 'annotation-goto)
(gethash (buffer-substring-no-properties start end)
idents)))))
(maphash
(lambda (ident refs)
(when (and (car refs) (null (cadr refs))) ;(length= refs 1)
(puthash ident
(agda2-make-xref (caar refs) (cdar refs))
agda2-last-xref-ict)))
idents)))
agda2-last-xref-ict)
(cl-defmethod xref-backend-identifier-completion-table ((_ (eql agda2)))
"Generate a list of possible candidates."
;; We clear and re-generate the hash-table mapping identifiers to
;; `xref-item' objects so that the completion is up-to-date and that
;; `xref-backend-definitions' can use the hash-table to lookup the
;; position of the identifier without a `annotation-goto'
(clrhash agda2-last-xref-ict)
(agda2-slurp-identifiers))
(cl-defmethod xref-backend-definitions ((_ (eql agda2)) ident)
"Generate a list of definitions for identifier IDENT."
(pcase (get-text-property 0 'annotation-goto ident)
(`(,file . ,pos) (list (agda2-make-xref file pos)))
((pred null) ;`nil' is not backwards compatible...
(let ((item (gethash ident agda2-last-xref-ict)))
(and item (list item))))
(prop (error "Unexpected `annotation-goto' on %S: %S" ident prop))))
(cl-defmethod xref-backend-references ((_ (eql agda2)) identifier)
"Generate a list of references for IDENTIFIER."
;; TODO: Do not defer to the default implementation. This is just
;; grep, but we could also look through all open buffers as well.
(xref-backend-references nil identifier))
;; Compatibility definition for releases of Emacs <28.1
(defalias 'agda2-mode-apropos-regexp
(if (fboundp 'xref-apropos-regexp)
'xref-apropos-regexp
(lambda (pattern)
"Return an Emacs regexp from PATTERN similar to `apropos'."
(require 'apropos)
(declare-function
apropos-parse-pattern "apropos"
(pattern &optional multiline-p))
(apropos-parse-pattern
(if (string-equal (regexp-quote pattern) pattern)
;; Split into words
(or (split-string pattern "[ \t]+" t)
(user-error "No word list given"))
pattern)))))
(cl-defmethod xref-backend-apropos ((_ (eql agda2)) pattern)
"Generate a list of definitions matching PATTERN."
(clrhash agda2-last-xref-ict)
(dolist (buf (buffer-list))
(with-current-buffer buf
(when (derived-mode-p 'agda2-mode)
(agda2-slurp-identifiers))))
;; TODO: add type annotations
(cl-loop with regexp = (agda2-mode-apropos-regexp pattern)
for ident being the hash-keys of agda2-last-xref-ict
using (hash-values item)
when (string-match-p regexp ident)
collect item))
(defun agda2-goto-definition-keyboard (&optional other-window)
"Go to the definition site of the name under point (if any).
If this function is invoked with a prefix argument then another window is used
to display the given position."
(interactive "P")
(annotation-goto-indirect (point) other-window))
(defun agda2-goto-definition-mouse (ev)
"Go to the definition site of the name clicked on, if any.
Otherwise, yank (see `mouse-yank-primary')."
(interactive "e")
(if (consp (save-excursion
(mouse-set-point ev)
(get-text-property (point) 'annotation-goto)))
(let ((xref-prompt-for-identifier nil))
(mouse-set-point ev)
(call-interactively #'xref-find-definitions))
;; FIXME: Shouldn't we use something like
;; (call-interactively (key-binding ev))? --Stef
(mouse-yank-primary ev)))
(defun agda2-info-goto-definition-mouse (ev)
"While in the information buffer, to the definition site of the name
clicked on, if any.
Otherwise, invoke `compile-goto'."
(interactive "e")
;; Always "use other window" because find-file-other-window will reuse
;; an existing window (i.e. the source file buffer) if it exists
(unless (and agda2-file-buffer (annotation-goto-indirect ev t))
(compile-goto-error ev)))
(defun agda2-info-goto-definition-keyboard ()
"As `agda2-info-goto-definition-mouse', but at point."
(declare (obsolete "Use `xref-find-definitions'" "2.9.0"))
(interactive)
(agda2-info-goto-definition-mouse (point)))
(defun agda2-go-back nil
"Go back to the previous position in which
`agda2-goto-definition-keyboard' or `agda2-goto-definition-mouse' was
invoked."
(declare (obsolete "Use `xref-go-back'" "2.9.0"))
(interactive)
(annotation-go-back))
(defun agda2-maybe-goto (filepos)
"Might move point to the given error.
FILEPOS should have the form (FILE . POSITION).
If `agda2-highlight-in-progress' is `nil', or if the selected
window does not visit (does not contain a buffer that visits)
`agda2-file-buffer', then nothing happens.
Otherwise:
* If the selected window visits FILE, or if no visible window
visits FILE, then the selected window is made to visit FILE,
and point is set to POSITION.
* Otherwise point is set to POSITION in every visible window that
visits FILE."
(declare (agda2-command (cons)))
(when (and agda2-highlight-in-progress
(consp filepos)
(stringp (car filepos))
(integerp (cdr filepos))
(eq (window-buffer) agda2-file-buffer))
;; We don't use `xref-show-xrefs', as we know that there is a
;; concrete position we want to jump to. nevertheless, we push
;; the current marker onto Xref' stack to make it seem like a Xref
;; jump.
(xref-push-marker-stack)
(if-let*
((buffer (find-buffer-visiting (car filepos)))
(windows
(get-buffer-window-list buffer 'no-minibuffer 'visible)))
;; Some visible window visits FILE.
(if (eq buffer (window-buffer))
;; The selected window visits FILE.
(goto-char (cdr filepos))
;; The selected window does not visit FILE. Update point in
;; all visible windows that visit FILE.
(dolist (window windows)
(with-selected-window window
(goto-char (cdr filepos)))))
;; No visible window visits FILE. Make the current window visit
;; FILE.
(switch-to-buffer
(find-file-noselect (car filepos)) nil 'force-same-window)
(goto-char (cdr filepos)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Implicit arguments
(defun agda2-display-implicit-arguments (&optional arg)
"Toggle display of implicit arguments.
With prefix argument, turn on display of implicit arguments if
the argument is a positive number, otherwise turn it off."
(interactive "P")
(cond
((eq arg nil)
(agda2-go nil t 'not-so-busy t "ToggleImplicitArgs"))
((and (numberp arg) (> arg 0))
(agda2-go nil t 'not-so-busy t "ShowImplicitArgs" "True"))
(t (agda2-go nil t 'not-so-busy t "ShowImplicitArgs" "False"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Irrelevant arguments
(defun agda2-display-irrelevant-arguments (&optional arg)
"Toggle display of irrelevant arguments.
With prefix argument, turn on display of irrelevant arguments if
the argument is a positive number, otherwise turn it off."
(interactive "P")
(cond
((eq arg nil)
(agda2-go nil t 'not-so-busy t "ToggleIrrelevantArgs"))
((and (numberp arg) (> arg 0))
(agda2-go nil t 'not-so-busy t "ShowIrrelevantArgs" "True"))
(t (agda2-go nil t 'not-so-busy t "ShowIrrelevantArgs" "False"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
(defun agda2-popup-menu-3 (ev)
"If in a goal, popup the goal menu and call chosen command."
(interactive "e")
(let (choice)
(save-excursion
(and (agda2-goal-at (goto-char (posn-point (event-end ev))))
(setq choice (x-popup-menu ev agda2-goal-map))
(call-interactively
(lookup-key agda2-goal-map (apply 'vector choice)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Switching to a different version of Agda
(defun agda2-get-agda-program-versions ()
"Get suffixes (\"version strings\") of executables starting with
\\='agda-\\=' in exec-path."
(interactive) ;; for debugging purposes
(delete-dups
(mapcar (lambda (path)
;; strip 'agda-' prefix
(replace-regexp-in-string "^agda-?" ""
(file-name-nondirectory path)))
(cl-remove-if-not 'file-executable-p
;; concatenate result
(cl-reduce 'append
;; for each directory in exec-path, get list of
;; files whose name starts with 'agda-'
(mapcar (lambda (path)
(when (file-accessible-directory-p path)
(directory-files path 't "^agda-")))
exec-path))))))
(defun agda2-old-version (version)
"Check if the given version is less that 2.8.
Agda 2.8 is the version where the agda-mode executable was deprecated.
If the version cannot be parsed, the answer is no.
So e.g. agda-fast would be interpreted as not older than
agda-2.9.0"
;; If the given string does not have a numeric prefix, we answer no.
(and (string-match "^[0-9][0-9.]*" version)
(version< (match-string 0 version) "2.8")))
;; Note that other versions of Agda may use different protocols, so
;; this function unloads the Emacs mode.
(defun agda2-set-program-version (version)
"Tries to switch to Agda version VERSION.
This command assumes that the agda and agda-mode executables for
Agda version VERSION are called agda-VERSION and agda-mode-VERSION.
It searches for these executables on the exec-path
which is often identical to PATH but can be different
depending how Emacs is configured and invoked.
Only if VERSION is numeric and less than \"2.8\"
the agda-mode executable is used to locate the respective agda2.el,
otherwise \"agda --emacs-mode locate\" is invoked.
If VERSION is empty or \"agda\", then agda is used.
A prefix \"agda-\" is stripped from VERSION,
so one can invoke this function e.g. with
\"agda-2.9.0\" instead of \"2.9.0\".
An attempt is made to preserve the default value of `agda2-mode-hook'."
(interactive
(list (completing-read "Version: " (agda2-get-agda-program-versions))))
(let*
((agda-buffers
(cl-mapcan (lambda (buf)
(with-current-buffer buf
(when (equal major-mode 'agda2-mode)
(list buf))))
(buffer-list)))
(default-hook (default-value 'agda2-mode-hook))
;; Sanitize version.
;; * Strip "agda-" prefix from version.
;; * Replace version "agda" by just "".
;;
;; Rationale:
;; The user might by accident enter "agda-2.9.0" instead of "2.9.0",
;; or "agda" instead of "".
(version
(cond
;; Strip "agda-" prefix from version.
((string-prefix-p "agda-" version) (substring version (length "agda-")))
;; Replace version "agda" by just "".
((equal version "agda") "")
;; Default.
(t version)))
(version-suffix (if (or (equal version "")
(equal version nil))
""
(concat "-" version)))
;; Run agda-mode<version-suffix> and make sure that it returns
;; successfully.
(coding-system-for-read 'utf-8)
(old-agda (agda2-old-version version))
(agda-mode-prog (concat (if old-agda "agda-mode" "agda") version-suffix))
(agda-mode-path
(condition-case nil
(with-temp-buffer
(unless
(equal 0
(if old-agda
(call-process agda-mode-prog nil (current-buffer) nil "locate")
(call-process agda-mode-prog nil (current-buffer) nil "--emacs-mode" "locate")))
(error "%s" (concat "Error when running "
agda-mode-prog)))
(buffer-string))
(file-error
(error "%s" (concat "Could not find " agda-mode-prog))))))
;; Make sure that agda-mode<version-suffix> returns a valid file.
(unless (file-readable-p agda-mode-path)
(error "%s" (concat "Could not read " agda-mode-path)))
;; Turn off the Agda mode.
(agda2-quit)
;; Kill some buffers related to Agda.
(when (buffer-live-p agda2-info-buffer)
(kill-buffer agda2-info-buffer))
(when (buffer-live-p agda2-debug-buffer)
(kill-buffer agda2-debug-buffer))
;; Remove the Agda mode directory from the load path.
(setq load-path (delete agda2-directory load-path))
;; Unload the Agda mode and its dependencies.
(unload-feature 'agda2-mode 'force)
(unload-feature 'agda2 'force)
(unload-feature 'eri 'force)
(unload-feature 'annotation 'force)
(unload-feature 'agda-input 'force)
(unload-feature 'agda2-highlight 'force)
(unload-feature 'agda2-abbrevs 'force)
(unload-feature 'agda2-queue 'force)
;; Load the new version of Agda.
(load-file agda-mode-path)
(require 'agda2-mode)
(setq agda2-program-name (concat "agda" version-suffix))
;; Restore the Agda mode's default hook (if any).
(when default-hook
(set-default 'agda2-mode-hook default-hook))
;; Restart the Agda mode in all former Agda mode buffers.
(mapc (lambda (buf)
(with-current-buffer buf
(agda2-mode)))
agda-buffers)))
(provide 'agda2-mode)
;;; agda2-mode.el ends here