lisp/gnus/gnus-art.el (gnus-mime-buttonize-attachments-in-header): Improve criterion...
[bpt/emacs.git] / lisp / emacs-lisp / lisp-mode.el
CommitLineData
a5833280 1;;; lisp-mode.el --- Lisp mode, and its idiosyncratic commands -*- lexical-binding:t -*-
d6a3febd 2
ba318903 3;; Copyright (C) 1985-1986, 1999-2014 Free Software Foundation, Inc.
d6a3febd 4
34dc21db 5;; Maintainer: emacs-devel@gnu.org
d6a3febd 6;; Keywords: lisp, languages
bd78fa1d 7;; Package: emacs
d6a3febd
MR
8
9;; This file is part of GNU Emacs.
10
11;; GNU Emacs is free software: you can redistribute it and/or modify
12;; it under the terms of the GNU General Public License as published by
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
15
16;; GNU Emacs is distributed in the hope that it will be useful,
17;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19;; GNU General Public License for more details.
20
21;; You should have received a copy of the GNU General Public License
22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24;;; Commentary:
25
26;; The base major mode for editing Lisp code (used also for Emacs Lisp).
27;; This mode is documented in the Emacs manual.
28
29;;; Code:
30
31(defvar font-lock-comment-face)
32(defvar font-lock-doc-face)
33(defvar font-lock-keywords-case-fold-search)
34(defvar font-lock-string-face)
35
36(defvar lisp-mode-abbrev-table nil)
db174434
CY
37(define-abbrev-table 'lisp-mode-abbrev-table ()
38 "Abbrev table for Lisp mode.")
d6a3febd 39
db174434
CY
40(defvar emacs-lisp-mode-abbrev-table nil)
41(define-abbrev-table 'emacs-lisp-mode-abbrev-table ()
42 "Abbrev table for Emacs Lisp mode.
43It has `lisp-mode-abbrev-table' as its parent."
44 :parents (list lisp-mode-abbrev-table))
d6a3febd
MR
45
46(defvar emacs-lisp-mode-syntax-table
da68c4c8
DD
47 (let ((table (make-syntax-table))
48 (i 0))
49 (while (< i ?0)
50 (modify-syntax-entry i "_ " table)
51 (setq i (1+ i)))
52 (setq i (1+ ?9))
53 (while (< i ?A)
54 (modify-syntax-entry i "_ " table)
55 (setq i (1+ i)))
56 (setq i (1+ ?Z))
57 (while (< i ?a)
58 (modify-syntax-entry i "_ " table)
59 (setq i (1+ i)))
60 (setq i (1+ ?z))
61 (while (< i 128)
62 (modify-syntax-entry i "_ " table)
63 (setq i (1+ i)))
64 (modify-syntax-entry ?\s " " table)
65 ;; Non-break space acts as whitespace.
66 (modify-syntax-entry ?\x8a0 " " table)
67 (modify-syntax-entry ?\t " " table)
68 (modify-syntax-entry ?\f " " table)
69 (modify-syntax-entry ?\n "> " table)
70 ;; This is probably obsolete since nowadays such features use overlays.
71 ;; ;; Give CR the same syntax as newline, for selective-display.
72 ;; (modify-syntax-entry ?\^m "> " table)
73 (modify-syntax-entry ?\; "< " table)
74 (modify-syntax-entry ?` "' " table)
75 (modify-syntax-entry ?' "' " table)
76 (modify-syntax-entry ?, "' " table)
00104e59 77 (modify-syntax-entry ?@ "_ p" table)
da68c4c8
DD
78 ;; Used to be singlequote; changed for flonums.
79 (modify-syntax-entry ?. "_ " table)
80 (modify-syntax-entry ?# "' " table)
81 (modify-syntax-entry ?\" "\" " table)
82 (modify-syntax-entry ?\\ "\\ " table)
83 (modify-syntax-entry ?\( "() " table)
84 (modify-syntax-entry ?\) ")( " table)
85 (modify-syntax-entry ?\[ "(] " table)
86 (modify-syntax-entry ?\] ")[ " table)
e4a09a11
GM
87 table)
88 "Syntax table used in `emacs-lisp-mode'.")
d6a3febd
MR
89
90(defvar lisp-mode-syntax-table
91 (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
92 (modify-syntax-entry ?\[ "_ " table)
93 (modify-syntax-entry ?\] "_ " table)
c5683ceb 94 (modify-syntax-entry ?# "' 14" table)
d6a3febd 95 (modify-syntax-entry ?| "\" 23bn" table)
a8106aec
GM
96 table)
97 "Syntax table used in `lisp-mode'.")
d6a3febd
MR
98
99(defvar lisp-imenu-generic-expression
100 (list
101 (list nil
102 (purecopy (concat "^\\s-*("
103 (eval-when-compile
104 (regexp-opt
105 '("defun" "defun*" "defsubst" "defmacro"
106 "defadvice" "define-skeleton"
722237d5
LL
107 "define-compilation-mode" "define-minor-mode"
108 "define-global-minor-mode"
d6a3febd
MR
109 "define-globalized-minor-mode"
110 "define-derived-mode" "define-generic-mode"
111 "define-compiler-macro" "define-modify-macro"
112 "defsetf" "define-setf-expander"
113 "define-method-combination"
185e3b5a
JB
114 "defgeneric" "defmethod"
115 "cl-defun" "cl-defsubst" "cl-defmacro"
116 "cl-define-compiler-macro") t))
d6a3febd
MR
117 "\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"))
118 2)
119 (list (purecopy "Variables")
120 (purecopy (concat "^\\s-*("
121 (eval-when-compile
122 (regexp-opt
b7ccbdc2 123 '("defconst" "defconstant" "defcustom"
d6a3febd
MR
124 "defparameter" "define-symbol-macro") t))
125 "\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"))
126 2)
b7ccbdc2
CY
127 ;; For `defvar', we ignore (defvar FOO) constructs.
128 (list (purecopy "Variables")
129 (purecopy (concat "^\\s-*(defvar\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"
130 "[[:space:]\n]+[^)]"))
131 1)
d6a3febd
MR
132 (list (purecopy "Types")
133 (purecopy (concat "^\\s-*("
134 (eval-when-compile
135 (regexp-opt
136 '("defgroup" "deftheme" "deftype" "defstruct"
137 "defclass" "define-condition" "define-widget"
185e3b5a
JB
138 "defface" "defpackage" "cl-deftype"
139 "cl-defstruct") t))
d6a3febd
MR
140 "\\s-+'?\\(\\(\\sw\\|\\s_\\)+\\)"))
141 2))
142
143 "Imenu generic expression for Lisp mode. See `imenu-generic-expression'.")
144
145;; This was originally in autoload.el and is still used there.
146(put 'autoload 'doc-string-elt 3)
98449af8 147(put 'defmethod 'doc-string-elt 3)
d6a3febd 148(put 'defvar 'doc-string-elt 3)
d6a3febd 149(put 'defconst 'doc-string-elt 3)
d6a3febd
MR
150(put 'defalias 'doc-string-elt 3)
151(put 'defvaralias 'doc-string-elt 3)
152(put 'define-category 'doc-string-elt 2)
153
154(defvar lisp-doc-string-elt-property 'doc-string-elt
155 "The symbol property that holds the docstring position info.")
156
06286513
SM
157
158;;;; Font-lock support.
159
4f965793
SM
160(defun lisp--match-hidden-arg (limit)
161 (let ((res nil))
162 (while
163 (let ((ppss (parse-partial-sexp (line-beginning-position)
164 (line-end-position)
165 -1)))
17a873c5 166 (skip-syntax-forward " )")
4f965793 167 (if (or (>= (car ppss) 0)
17a873c5 168 (looking-at ";\\|$"))
4f965793
SM
169 (progn
170 (forward-line 1)
171 (< (point) limit))
172 (looking-at ".*") ;Set the match-data.
173 (forward-line 1)
174 (setq res (point))
175 nil)))
176 res))
177
06286513
SM
178(pcase-let
179 ((`(,vdefs ,tdefs
180 ,el-defs-re ,cl-defs-re
181 ,el-kws-re ,cl-kws-re
182 ,el-errs-re ,cl-errs-re)
183 (eval-when-compile
184 (let ((lisp-fdefs '("defmacro" "defsubst" "defun"))
185 (lisp-vdefs '("defvar"))
186 (lisp-kw '("cond" "if" "while" "let" "let*" "progn" "prog1"
187 "prog2" "lambda" "unwind-protect" "condition-case"
188 "when" "unless" "with-output-to-string"
189 "ignore-errors" "dotimes" "dolist" "declare"))
190 (lisp-errs '("warn" "error" "signal"))
191 ;; Elisp constructs. FIXME: update dynamically from obarray.
192 (el-fdefs '("defadvice" "defalias"
193 "define-derived-mode" "define-minor-mode"
194 "define-generic-mode" "define-global-minor-mode"
195 "define-globalized-minor-mode" "define-skeleton"
196 "define-widget"))
197 (el-vdefs '("defconst" "defcustom" "defvaralias" "defvar-local"
198 "defface"))
199 (el-tdefs '("defgroup" "deftheme"))
200 (el-kw '("while-no-input" "letrec" "pcase" "pcase-let"
201 "pcase-let*" "save-restriction" "save-excursion"
202 "save-selected-window"
203 ;; "eval-after-load" "eval-next-after-load"
204 "save-window-excursion" "save-current-buffer"
205 "save-match-data" "combine-after-change-calls"
206 "condition-case-unless-debug" "track-mouse"
207 "eval-and-compile" "eval-when-compile" "with-case-table"
208 "with-category-table" "with-coding-priority"
209 "with-current-buffer" "with-demoted-errors"
210 "with-electric-help" "with-eval-after-load"
d63d883a 211 "with-file-modes"
06286513
SM
212 "with-local-quit" "with-no-warnings"
213 "with-output-to-temp-buffer" "with-selected-window"
214 "with-selected-frame" "with-silent-modifications"
215 "with-syntax-table" "with-temp-buffer" "with-temp-file"
216 "with-temp-message" "with-timeout"
217 "with-timeout-handler"))
218 (el-errs '("user-error"))
219 ;; Common-Lisp constructs supported by EIEIO. FIXME: namespace.
220 (eieio-fdefs '("defgeneric" "defmethod"))
221 (eieio-tdefs '("defclass"))
222 (eieio-kw '("with-slots"))
223 ;; Common-Lisp constructs supported by cl-lib.
224 (cl-lib-fdefs '("defmacro" "defsubst" "defun"))
225 (cl-lib-tdefs '("defstruct" "deftype"))
226 (cl-lib-kw '("progv" "eval-when" "case" "ecase" "typecase"
227 "etypecase" "ccase" "ctypecase" "loop" "do" "do*"
228 "the" "locally" "proclaim" "declaim" "letf" "go"
229 ;; "lexical-let" "lexical-let*"
230 "symbol-macrolet" "flet" "destructuring-bind"
231 "labels" "macrolet" "tagbody" "multiple-value-bind"
232 "block" "return" "return-from"))
233 (cl-lib-errs '("assert" "check-type"))
234 ;; Common-Lisp constructs not supported by cl-lib.
235 (cl-fdefs '("defsetf" "define-method-combination"
236 "define-condition" "define-setf-expander"
237 ;; "define-function"??
238 "define-compiler-macro" "define-modify-macro"))
239 (cl-vdefs '("define-symbol-macro" "defconstant" "defparameter"))
240 (cl-tdefs '("defpackage" "defstruct" "deftype"))
241 (cl-kw '("prog" "prog*" "handler-case" "handler-bind"
242 "in-package" "restart-case" ;; "inline"
243 "restart-bind" "break" "multiple-value-prog1"
244 "compiler-let" "with-accessors" "with-compilation-unit"
245 "with-condition-restarts" "with-hash-table-iterator"
246 "with-input-from-string" "with-open-file"
247 "with-open-stream" "with-package-iterator"
248 "with-simple-restart" "with-standard-io-syntax"))
249 (cl-errs '("abort" "cerror")))
250
251 (list (append lisp-vdefs el-vdefs cl-vdefs)
252 (append el-tdefs eieio-tdefs cl-tdefs cl-lib-tdefs
253 (mapcar (lambda (s) (concat "cl-" s)) cl-lib-tdefs))
254
255 ;; Elisp and Common Lisp definers.
256 (regexp-opt (append lisp-fdefs lisp-vdefs
257 el-fdefs el-vdefs el-tdefs
258 (mapcar (lambda (s) (concat "cl-" s))
259 (append cl-lib-fdefs cl-lib-tdefs))
260 eieio-fdefs eieio-tdefs)
261 t)
262 (regexp-opt (append lisp-fdefs lisp-vdefs
263 cl-lib-fdefs cl-lib-tdefs
264 eieio-fdefs eieio-tdefs
265 cl-fdefs cl-vdefs cl-tdefs)
266 t)
267
268 ;; Elisp and Common Lisp keywords.
269 (regexp-opt (append
270 lisp-kw el-kw eieio-kw
271 (cons "go" (mapcar (lambda (s) (concat "cl-" s))
272 (remove "go" cl-lib-kw))))
273 t)
60db713e 274 (regexp-opt (append lisp-kw cl-kw eieio-kw cl-lib-kw)
06286513
SM
275 t)
276
277 ;; Elisp and Common Lisp "errors".
278 (regexp-opt (append (mapcar (lambda (s) (concat "cl-" s))
279 cl-lib-errs)
280 lisp-errs el-errs)
281 t)
282 (regexp-opt (append lisp-errs cl-lib-errs cl-errs) t))))))
283
284 (dolist (v vdefs)
285 (put (intern v) 'lisp-define-type 'var))
286 (dolist (v tdefs)
287 (put (intern v) 'lisp-define-type 'type))
288
289 (define-obsolete-variable-alias 'lisp-font-lock-keywords-1
290 'lisp-el-font-lock-keywords-1 "24.4")
291 (defconst lisp-el-font-lock-keywords-1
292 `( ;; Definitions.
293 (,(concat "(" el-defs-re "\\_>"
294 ;; Any whitespace and defined object.
295 "[ \t'\(]*"
296 "\\(\\(?:\\sw\\|\\s_\\)+\\)?")
297 (1 font-lock-keyword-face)
298 (2 (let ((type (get (intern-soft (match-string 1)) 'lisp-define-type)))
299 (cond ((eq type 'var) font-lock-variable-name-face)
300 ((eq type 'type) font-lock-type-face)
301 (t font-lock-function-name-face)))
302 nil t))
303 ;; Emacs Lisp autoload cookies. Supports the slightly different
304 ;; forms used by mh-e, calendar, etc.
305 ("^;;;###\\([-a-z]*autoload\\)" 1 font-lock-warning-face prepend))
306 "Subdued level highlighting for Emacs Lisp mode.")
307
308 (defconst lisp-cl-font-lock-keywords-1
309 `( ;; Definitions.
310 (,(concat "(" cl-defs-re "\\_>"
311 ;; Any whitespace and defined object.
312 "[ \t'\(]*"
313 "\\(setf[ \t]+\\(?:\\sw\\|\\s_\\)+\\|\\(?:\\sw\\|\\s_\\)+\\)?")
314 (1 font-lock-keyword-face)
315 (2 (let ((type (get (intern-soft (match-string 1)) 'lisp-define-type)))
316 (cond ((eq type 'var) font-lock-variable-name-face)
317 ((eq type 'type) font-lock-type-face)
318 (t font-lock-function-name-face)))
319 nil t)))
320 "Subdued level highlighting for Lisp modes.")
321
322 (define-obsolete-variable-alias 'lisp-font-lock-keywords-2
323 'lisp-el-font-lock-keywords-2 "24.4")
324 (defconst lisp-el-font-lock-keywords-2
325 (append
326 lisp-el-font-lock-keywords-1
327 `( ;; Regexp negated char group.
328 ("\\[\\(\\^\\)" 1 font-lock-negation-char-face prepend)
329 ;; Control structures. Common Lisp forms.
330 (,(concat "(" el-kws-re "\\_>") . 1)
331 ;; Exit/Feature symbols as constants.
332 (,(concat "(\\(catch\\|throw\\|featurep\\|provide\\|require\\)\\_>"
333 "[ \t']*\\(\\(?:\\sw\\|\\s_\\)+\\)?")
334 (1 font-lock-keyword-face)
335 (2 font-lock-constant-face nil t))
336 ;; Erroneous structures.
337 (,(concat "(" el-errs-re "\\_>")
338 (1 font-lock-warning-face))
339 ;; Words inside \\[] tend to be for `substitute-command-keys'.
340 ("\\\\\\\\\\[\\(\\(?:\\sw\\|\\s_\\)+\\)\\]"
341 (1 font-lock-constant-face prepend))
342 ;; Words inside `' tend to be symbol names.
343 ("`\\(\\(?:\\sw\\|\\s_\\)\\(?:\\sw\\|\\s_\\)+\\)'"
344 (1 font-lock-constant-face prepend))
345 ;; Constant values.
346 ("\\_<:\\(?:\\sw\\|\\s_\\)+\\_>" 0 font-lock-builtin-face)
347 ;; ELisp and CLisp `&' keywords as types.
348 ("\\_<\\&\\(?:\\sw\\|\\s_\\)+\\_>" . font-lock-type-face)
349 ;; ELisp regexp grouping constructs
350 (,(lambda (bound)
351 (catch 'found
352 ;; The following loop is needed to continue searching after matches
353 ;; that do not occur in strings. The associated regexp matches one
354 ;; of `\\\\' `\\(' `\\(?:' `\\|' `\\)'. `\\\\' has been included to
355 ;; avoid highlighting, for example, `\\(' in `\\\\('.
356 (while (re-search-forward "\\(\\\\\\\\\\)\\(?:\\(\\\\\\\\\\)\\|\\((\\(?:\\?[0-9]*:\\)?\\|[|)]\\)\\)" bound t)
357 (unless (match-beginning 2)
358 (let ((face (get-text-property (1- (point)) 'face)))
359 (when (or (and (listp face)
360 (memq 'font-lock-string-face face))
361 (eq 'font-lock-string-face face))
362 (throw 'found t)))))))
363 (1 'font-lock-regexp-grouping-backslash prepend)
364 (3 'font-lock-regexp-grouping-construct prepend))
365 ;; This is too general -- rms.
366 ;; A user complained that he has functions whose names start with `do'
367 ;; and that they get the wrong color.
368 ;; ;; CL `with-' and `do-' constructs
369 ;;("(\\(\\(do-\\|with-\\)\\(\\s_\\|\\w\\)*\\)" 1 font-lock-keyword-face)
4f965793
SM
370 (lisp--match-hidden-arg
371 (0 '(face font-lock-warning-face
372 help-echo "Hidden behind deeper element; move to another line?")))
06286513
SM
373 ))
374 "Gaudy level highlighting for Emacs Lisp mode.")
375
376 (defconst lisp-cl-font-lock-keywords-2
377 (append
378 lisp-cl-font-lock-keywords-1
379 `( ;; Regexp negated char group.
380 ("\\[\\(\\^\\)" 1 font-lock-negation-char-face prepend)
381 ;; Control structures. Common Lisp forms.
382 (,(concat "(" cl-kws-re "\\_>") . 1)
383 ;; Exit/Feature symbols as constants.
60db713e 384 (,(concat "(\\(catch\\|throw\\|provide\\|require\\)\\_>"
06286513
SM
385 "[ \t']*\\(\\(?:\\sw\\|\\s_\\)+\\)?")
386 (1 font-lock-keyword-face)
387 (2 font-lock-constant-face nil t))
388 ;; Erroneous structures.
389 (,(concat "(" cl-errs-re "\\_>")
390 (1 font-lock-warning-face))
391 ;; Words inside `' tend to be symbol names.
392 ("`\\(\\(?:\\sw\\|\\s_\\)\\(?:\\sw\\|\\s_\\)+\\)'"
393 (1 font-lock-constant-face prepend))
394 ;; Constant values.
395 ("\\_<:\\(?:\\sw\\|\\s_\\)+\\_>" 0 font-lock-builtin-face)
396 ;; ELisp and CLisp `&' keywords as types.
397 ("\\_<\\&\\(?:\\sw\\|\\s_\\)+\\_>" . font-lock-type-face)
398 ;; This is too general -- rms.
399 ;; A user complained that he has functions whose names start with `do'
400 ;; and that they get the wrong color.
401 ;; ;; CL `with-' and `do-' constructs
402 ;;("(\\(\\(do-\\|with-\\)\\(\\s_\\|\\w\\)*\\)" 1 font-lock-keyword-face)
4f965793
SM
403 (lisp--match-hidden-arg
404 (0 '(face font-lock-warning-face
405 help-echo "Hidden behind deeper element; move to another line?")))
06286513
SM
406 ))
407 "Gaudy level highlighting for Lisp modes."))
408
409(define-obsolete-variable-alias 'lisp-font-lock-keywords
410 'lisp-el-font-lock-keywords "24.4")
411(defvar lisp-el-font-lock-keywords lisp-el-font-lock-keywords-1
412 "Default expressions to highlight in Emacs Lisp mode.")
413(defvar lisp-cl-font-lock-keywords lisp-cl-font-lock-keywords-1
414 "Default expressions to highlight in Lisp modes.")
415
d6a3febd
MR
416(defun lisp-font-lock-syntactic-face-function (state)
417 (if (nth 3 state)
418 ;; This might be a (doc)string or a |...| symbol.
419 (let ((startpos (nth 8 state)))
420 (if (eq (char-after startpos) ?|)
421 ;; This is not a string, but a |...| symbol.
422 nil
423 (let* ((listbeg (nth 1 state))
424 (firstsym (and listbeg
425 (save-excursion
426 (goto-char listbeg)
427 (and (looking-at "([ \t\n]*\\(\\(\\sw\\|\\s_\\)+\\)")
428 (match-string 1)))))
7abaf5cc
SM
429 (docelt (and firstsym
430 (function-get (intern-soft firstsym)
d6a3febd
MR
431 lisp-doc-string-elt-property))))
432 (if (and docelt
433 ;; It's a string in a form that can have a docstring.
434 ;; Check whether it's in docstring position.
435 (save-excursion
436 (when (functionp docelt)
437 (goto-char (match-end 1))
438 (setq docelt (funcall docelt)))
439 (goto-char listbeg)
440 (forward-char 1)
441 (condition-case nil
442 (while (and (> docelt 0) (< (point) startpos)
443 (progn (forward-sexp 1) t))
444 (setq docelt (1- docelt)))
445 (error nil))
446 (and (zerop docelt) (<= (point) startpos)
447 (progn (forward-comment (point-max)) t)
448 (= (point) (nth 8 state)))))
449 font-lock-doc-face
450 font-lock-string-face))))
451 font-lock-comment-face))
452
06286513
SM
453(defun lisp-mode-variables (&optional lisp-syntax keywords-case-insensitive
454 elisp)
94686171
DN
455 "Common initialization routine for lisp modes.
456The LISP-SYNTAX argument is used by code in inf-lisp.el and is
5249a62d
MR
457\(uselessly) passed from pp.el, chistory.el, gnus-kill.el and
458score-mode.el. KEYWORDS-CASE-INSENSITIVE non-nil means that for
913274cb 459font-lock keywords will not be case sensitive."
d6a3febd
MR
460 (when lisp-syntax
461 (set-syntax-table lisp-mode-syntax-table))
92eadba5
CY
462 (setq-local paragraph-ignore-fill-prefix t)
463 (setq-local fill-paragraph-function 'lisp-fill-paragraph)
d6a3febd
MR
464 ;; Adaptive fill mode gets the fill wrong for a one-line paragraph made of
465 ;; a single docstring. Let's fix it here.
92eadba5
CY
466 (setq-local adaptive-fill-function
467 (lambda () (if (looking-at "\\s-+\"[^\n\"]+\"\\s-*$") "")))
d6a3febd
MR
468 ;; Adaptive fill mode gets in the way of auto-fill,
469 ;; and should make no difference for explicit fill
470 ;; because lisp-fill-paragraph should do the job.
471 ;; I believe that newcomment's auto-fill code properly deals with it -stef
472 ;;(set (make-local-variable 'adaptive-fill-mode) nil)
92eadba5
CY
473 (setq-local indent-line-function 'lisp-indent-line)
474 (setq-local outline-regexp ";;;\\(;* [^ \t\n]\\|###autoload\\)\\|(")
475 (setq-local outline-level 'lisp-outline-level)
ba03d0d9 476 (setq-local add-log-current-defun-function #'lisp-current-defun-name)
92eadba5 477 (setq-local comment-start ";")
4f8aeb84 478 (setq-local comment-start-skip ";+ *")
92eadba5
CY
479 (setq-local comment-add 1) ;default to `;;' in comment-region
480 (setq-local comment-column 40)
4f8aeb84 481 (setq-local comment-use-syntax t)
92eadba5
CY
482 (setq-local imenu-generic-expression lisp-imenu-generic-expression)
483 (setq-local multibyte-syntax-as-symbol t)
e18b70fc 484 ;; (setq-local syntax-begin-function 'beginning-of-defun) ;;Bug#16247.
d6a3febd 485 (setq font-lock-defaults
06286513
SM
486 `(,(if elisp '(lisp-el-font-lock-keywords
487 lisp-el-font-lock-keywords-1
488 lisp-el-font-lock-keywords-2)
489 '(lisp-cl-font-lock-keywords
490 lisp-cl-font-lock-keywords-1
491 lisp-cl-font-lock-keywords-2))
913274cb 492 nil ,keywords-case-insensitive nil nil
d6a3febd 493 (font-lock-mark-block-function . mark-defun)
4f965793 494 (font-lock-extra-managed-props help-echo)
d6a3febd 495 (font-lock-syntactic-face-function
7de135d0 496 . lisp-font-lock-syntactic-face-function)))
3b8d5131 497 (setq-local prettify-symbols-alist lisp--prettify-symbols-alist)
f1a85e52
GM
498 (when elisp
499 (setq-local electric-pair-text-pairs
500 (cons '(?\` . ?\') electric-pair-text-pairs)))
3b8d5131
JT
501 (setq-local electric-pair-skip-whitespace 'chomp)
502 (setq-local electric-pair-open-newline-between-pairs nil))
d6a3febd
MR
503
504(defun lisp-outline-level ()
505 "Lisp mode `outline-level' function."
506 (let ((len (- (match-end 0) (match-beginning 0))))
507 (if (looking-at "(\\|;;;###autoload")
508 1000
509 len)))
510
ba03d0d9
CY
511(defun lisp-current-defun-name ()
512 "Return the name of the defun at point, or nil."
9dffb5b6
CY
513 (save-excursion
514 (let ((location (point)))
515 ;; If we are now precisely at the beginning of a defun, make sure
516 ;; beginning-of-defun finds that one rather than the previous one.
517 (or (eobp) (forward-char 1))
518 (beginning-of-defun)
519 ;; Make sure we are really inside the defun found, not after it.
520 (when (and (looking-at "\\s(")
521 (progn (end-of-defun)
522 (< location (point)))
523 (progn (forward-sexp -1)
524 (>= location (point))))
525 (if (looking-at "\\s(")
526 (forward-char 1))
527 ;; Skip the defining construct name, typically "defun" or
528 ;; "defvar".
529 (forward-sexp 1)
530 ;; The second element is usually a symbol being defined. If it
531 ;; is not, use the first symbol in it.
532 (skip-chars-forward " \t\n'(")
533 (buffer-substring-no-properties (point)
534 (progn (forward-sexp 1)
535 (point)))))))
ba03d0d9 536
d6a3febd
MR
537(defvar lisp-mode-shared-map
538 (let ((map (make-sparse-keymap)))
33e249a2 539 (set-keymap-parent map prog-mode-map)
d6a3febd
MR
540 (define-key map "\e\C-q" 'indent-sexp)
541 (define-key map "\177" 'backward-delete-char-untabify)
542 ;; This gets in the way when viewing a Lisp file in view-mode. As
543 ;; long as [backspace] is mapped into DEL via the
544 ;; function-key-map, this should remain disabled!!
545 ;;;(define-key map [backspace] 'backward-delete-char-untabify)
546 map)
547 "Keymap for commands shared by all sorts of Lisp modes.")
548
549(defvar emacs-lisp-mode-map
550 (let ((map (make-sparse-keymap "Emacs-Lisp"))
551 (menu-map (make-sparse-keymap "Emacs-Lisp"))
a707eb05 552 (lint-map (make-sparse-keymap))
d6a3febd
MR
553 (prof-map (make-sparse-keymap))
554 (tracing-map (make-sparse-keymap)))
555 (set-keymap-parent map lisp-mode-shared-map)
51ef56c4 556 (define-key map "\e\t" 'completion-at-point)
d6a3febd
MR
557 (define-key map "\e\C-x" 'eval-defun)
558 (define-key map "\e\C-q" 'indent-pp-sexp)
1ec4b7b2
SM
559 (bindings--define-key map [menu-bar emacs-lisp]
560 (cons "Emacs-Lisp" menu-map))
561 (bindings--define-key menu-map [eldoc]
562 '(menu-item "Auto-Display Documentation Strings" eldoc-mode
d6a3febd 563 :button (:toggle . (bound-and-true-p eldoc-mode))
1ec4b7b2
SM
564 :help "Display the documentation string for the item under cursor"))
565 (bindings--define-key menu-map [checkdoc]
566 '(menu-item "Check Documentation Strings" checkdoc
567 :help "Check documentation strings for style requirements"))
568 (bindings--define-key menu-map [re-builder]
569 '(menu-item "Construct Regexp" re-builder
570 :help "Construct a regexp interactively"))
571 (bindings--define-key menu-map [tracing] (cons "Tracing" tracing-map))
572 (bindings--define-key tracing-map [tr-a]
573 '(menu-item "Untrace All" untrace-all
574 :help "Untrace all currently traced functions"))
575 (bindings--define-key tracing-map [tr-uf]
576 '(menu-item "Untrace Function..." untrace-function
577 :help "Untrace function, and possibly activate all remaining advice"))
578 (bindings--define-key tracing-map [tr-sep] menu-bar-separator)
579 (bindings--define-key tracing-map [tr-q]
580 '(menu-item "Trace Function Quietly..." trace-function-background
581 :help "Trace the function with trace output going quietly to a buffer"))
582 (bindings--define-key tracing-map [tr-f]
583 '(menu-item "Trace Function..." trace-function
584 :help "Trace the function given as an argument"))
585 (bindings--define-key menu-map [profiling] (cons "Profiling" prof-map))
586 (bindings--define-key prof-map [prof-restall]
587 '(menu-item "Remove Instrumentation for All Functions" elp-restore-all
588 :help "Restore the original definitions of all functions being profiled"))
589 (bindings--define-key prof-map [prof-restfunc]
590 '(menu-item "Remove Instrumentation for Function..." elp-restore-function
591 :help "Restore an instrumented function to its original definition"))
592
593 (bindings--define-key prof-map [sep-rem] menu-bar-separator)
594 (bindings--define-key prof-map [prof-resall]
595 '(menu-item "Reset Counters for All Functions" elp-reset-all
596 :help "Reset the profiling information for all functions being profiled"))
597 (bindings--define-key prof-map [prof-resfunc]
598 '(menu-item "Reset Counters for Function..." elp-reset-function
599 :help "Reset the profiling information for a function"))
600 (bindings--define-key prof-map [prof-res]
601 '(menu-item "Show Profiling Results" elp-results
602 :help "Display current profiling results"))
603 (bindings--define-key prof-map [prof-pack]
604 '(menu-item "Instrument Package..." elp-instrument-package
605 :help "Instrument for profiling all function that start with a prefix"))
606 (bindings--define-key prof-map [prof-func]
607 '(menu-item "Instrument Function..." elp-instrument-function
608 :help "Instrument a function for profiling"))
a576cc76
GM
609 ;; Maybe this should be in a separate submenu from the ELP stuff?
610 (bindings--define-key prof-map [sep-natprof] menu-bar-separator)
611 (bindings--define-key prof-map [prof-natprof-stop]
612 '(menu-item "Stop Native Profiler" profiler-stop
613 :help "Stop recording profiling information"
614 :enable (and (featurep 'profiler)
615 (profiler-running-p))))
616 (bindings--define-key prof-map [prof-natprof-report]
617 '(menu-item "Show Profiler Report" profiler-report
618 :help "Show the current profiler report"
619 :enable (and (featurep 'profiler)
620 (profiler-running-p))))
621 (bindings--define-key prof-map [prof-natprof-start]
622 '(menu-item "Start Native Profiler..." profiler-start
623 :help "Start recording profiling information"))
624
1ec4b7b2
SM
625 (bindings--define-key menu-map [lint] (cons "Linting" lint-map))
626 (bindings--define-key lint-map [lint-di]
627 '(menu-item "Lint Directory..." elint-directory
628 :help "Lint a directory"))
629 (bindings--define-key lint-map [lint-f]
630 '(menu-item "Lint File..." elint-file
631 :help "Lint a file"))
632 (bindings--define-key lint-map [lint-b]
633 '(menu-item "Lint Buffer" elint-current-buffer
634 :help "Lint the current buffer"))
635 (bindings--define-key lint-map [lint-d]
636 '(menu-item "Lint Defun" elint-defun
637 :help "Lint the function at point"))
638 (bindings--define-key menu-map [edebug-defun]
639 '(menu-item "Instrument Function for Debugging" edebug-defun
640 :help "Evaluate the top level form point is in, stepping through with Edebug"
641 :keys "C-u C-M-x"))
642 (bindings--define-key menu-map [separator-byte] menu-bar-separator)
643 (bindings--define-key menu-map [disas]
644 '(menu-item "Disassemble Byte Compiled Object..." disassemble
645 :help "Print disassembled code for OBJECT in a buffer"))
646 (bindings--define-key menu-map [byte-recompile]
647 '(menu-item "Byte-recompile Directory..." byte-recompile-directory
648 :help "Recompile every `.el' file in DIRECTORY that needs recompilation"))
649 (bindings--define-key menu-map [emacs-byte-compile-and-load]
650 '(menu-item "Byte-compile and Load" emacs-lisp-byte-compile-and-load
651 :help "Byte-compile the current file (if it has changed), then load compiled code"))
652 (bindings--define-key menu-map [byte-compile]
653 '(menu-item "Byte-compile This File" emacs-lisp-byte-compile
654 :help "Byte compile the file containing the current buffer"))
655 (bindings--define-key menu-map [separator-eval] menu-bar-separator)
656 (bindings--define-key menu-map [ielm]
657 '(menu-item "Interactive Expression Evaluation" ielm
658 :help "Interactively evaluate Emacs Lisp expressions"))
659 (bindings--define-key menu-map [eval-buffer]
660 '(menu-item "Evaluate Buffer" eval-buffer
661 :help "Execute the current buffer as Lisp code"))
662 (bindings--define-key menu-map [eval-region]
663 '(menu-item "Evaluate Region" eval-region
664 :help "Execute the region as Lisp code"
d6a3febd 665 :enable mark-active))
1ec4b7b2
SM
666 (bindings--define-key menu-map [eval-sexp]
667 '(menu-item "Evaluate Last S-expression" eval-last-sexp
32985194 668 :help "Evaluate sexp before point; print value in echo area"))
1ec4b7b2
SM
669 (bindings--define-key menu-map [separator-format] menu-bar-separator)
670 (bindings--define-key menu-map [comment-region]
671 '(menu-item "Comment Out Region" comment-region
672 :help "Comment or uncomment each line in the region"
d6a3febd 673 :enable mark-active))
1ec4b7b2
SM
674 (bindings--define-key menu-map [indent-region]
675 '(menu-item "Indent Region" indent-region
676 :help "Indent each nonblank line in the region"
d6a3febd 677 :enable mark-active))
1ec4b7b2
SM
678 (bindings--define-key menu-map [indent-line]
679 '(menu-item "Indent Line" lisp-indent-line))
d6a3febd
MR
680 map)
681 "Keymap for Emacs Lisp mode.
682All commands in `lisp-mode-shared-map' are inherited by this map.")
683
684(defun emacs-lisp-byte-compile ()
685 "Byte compile the file containing the current buffer."
686 (interactive)
687 (if buffer-file-name
688 (byte-compile-file buffer-file-name)
689 (error "The buffer must be saved in a file first")))
690
691(defun emacs-lisp-byte-compile-and-load ()
692 "Byte-compile the current file (if it has changed), then load compiled code."
693 (interactive)
694 (or buffer-file-name
695 (error "The buffer must be saved in a file first"))
696 (require 'bytecomp)
697 ;; Recompile if file or buffer has changed since last compilation.
698 (if (and (buffer-modified-p)
699 (y-or-n-p (format "Save buffer %s first? " (buffer-name))))
700 (save-buffer))
430e7297 701 (byte-recompile-file buffer-file-name nil 0 t))
d6a3febd
MR
702
703(defcustom emacs-lisp-mode-hook nil
704 "Hook run when entering Emacs Lisp mode."
ad78f432 705 :options '(eldoc-mode imenu-add-menubar-index checkdoc-minor-mode)
d6a3febd
MR
706 :type 'hook
707 :group 'lisp)
708
709(defcustom lisp-mode-hook nil
710 "Hook run when entering Lisp mode."
711 :options '(imenu-add-menubar-index)
712 :type 'hook
713 :group 'lisp)
714
715(defcustom lisp-interaction-mode-hook nil
716 "Hook run when entering Lisp Interaction mode."
ad78f432 717 :options '(eldoc-mode)
d6a3febd
MR
718 :type 'hook
719 :group 'lisp)
720
3ca0d0b4
TZ
721(defconst lisp--prettify-symbols-alist
722 '(("lambda" . ?λ)))
723
10dcc561 724(define-derived-mode emacs-lisp-mode prog-mode "Emacs-Lisp"
d6a3febd
MR
725 "Major mode for editing Lisp code to run in Emacs.
726Commands:
727Delete converts tabs to spaces as it moves back.
728Blank lines separate paragraphs. Semicolons start comments.
a3c40f60 729
ae1f1ce1 730\\{emacs-lisp-mode-map}"
51ef56c4 731 :group 'lisp
06286513 732 (lisp-mode-variables nil nil 'elisp)
d6a3febd 733 (setq imenu-case-fold-search nil)
51ef56c4
SM
734 (add-hook 'completion-at-point-functions
735 'lisp-completion-at-point nil 'local))
d6a3febd 736
9b851e25
SM
737;;; Emacs Lisp Byte-Code mode
738
739(eval-and-compile
740 (defconst emacs-list-byte-code-comment-re
741 (concat "\\(#\\)@\\([0-9]+\\) "
742 ;; Make sure it's a docstring and not a lazy-loaded byte-code.
743 "\\(?:[^(]\\|([^\"]\\)")))
744
745(defun emacs-lisp-byte-code-comment (end &optional _point)
746 "Try to syntactically mark the #@NNN ....^_ docstrings in byte-code files."
747 (let ((ppss (syntax-ppss)))
748 (when (and (nth 4 ppss)
749 (eq (char-after (nth 8 ppss)) ?#))
750 (let* ((n (save-excursion
751 (goto-char (nth 8 ppss))
752 (when (looking-at emacs-list-byte-code-comment-re)
753 (string-to-number (match-string 2)))))
754 ;; `maxdiff' tries to make sure the loop below terminates.
755 (maxdiff n))
756 (when n
757 (let* ((bchar (match-end 2))
758 (b (position-bytes bchar)))
759 (goto-char (+ b n))
760 (while (let ((diff (- (position-bytes (point)) b n)))
761 (unless (zerop diff)
762 (when (> diff maxdiff) (setq diff maxdiff))
763 (forward-char (- diff))
764 (setq maxdiff (if (> diff 0) diff
765 (max (1- maxdiff) 1)))
766 t))))
767 (if (<= (point) end)
768 (put-text-property (1- (point)) (point)
769 'syntax-table
770 (string-to-syntax "> b"))
771 (goto-char end)))))))
772
773(defun emacs-lisp-byte-code-syntax-propertize (start end)
774 (emacs-lisp-byte-code-comment end (point))
775 (funcall
776 (syntax-propertize-rules
777 (emacs-list-byte-code-comment-re
778 (1 (prog1 "< b" (emacs-lisp-byte-code-comment end (point))))))
779 start end))
780
781(add-to-list 'auto-mode-alist '("\\.elc\\'" . emacs-lisp-byte-code-mode))
782(define-derived-mode emacs-lisp-byte-code-mode emacs-lisp-mode
783 "Elisp-Byte-Code"
784 "Major mode for *.elc files."
785 ;; TODO: Add way to disassemble byte-code under point.
786 (setq-local open-paren-in-column-0-is-defun-start nil)
787 (setq-local syntax-propertize-function
788 #'emacs-lisp-byte-code-syntax-propertize))
789
790;;; Generic Lisp mode.
791
d6a3febd
MR
792(defvar lisp-mode-map
793 (let ((map (make-sparse-keymap))
794 (menu-map (make-sparse-keymap "Lisp")))
795 (set-keymap-parent map lisp-mode-shared-map)
796 (define-key map "\e\C-x" 'lisp-eval-defun)
797 (define-key map "\C-c\C-z" 'run-lisp)
1ec4b7b2
SM
798 (bindings--define-key map [menu-bar lisp] (cons "Lisp" menu-map))
799 (bindings--define-key menu-map [run-lisp]
800 '(menu-item "Run inferior Lisp" run-lisp
801 :help "Run an inferior Lisp process, input and output via buffer `*inferior-lisp*'"))
802 (bindings--define-key menu-map [ev-def]
803 '(menu-item "Eval defun" lisp-eval-defun
804 :help "Send the current defun to the Lisp process made by M-x run-lisp"))
805 (bindings--define-key menu-map [ind-sexp]
806 '(menu-item "Indent sexp" indent-sexp
807 :help "Indent each line of the list starting just after point"))
d6a3febd
MR
808 map)
809 "Keymap for ordinary Lisp mode.
810All commands in `lisp-mode-shared-map' are inherited by this map.")
811
10dcc561 812(define-derived-mode lisp-mode prog-mode "Lisp"
d6a3febd
MR
813 "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
814Commands:
815Delete converts tabs to spaces as it moves back.
816Blank lines separate paragraphs. Semicolons start comments.
a3c40f60 817
d6a3febd
MR
818\\{lisp-mode-map}
819Note that `run-lisp' may be used either to start an inferior Lisp job
ae1f1ce1 820or to switch back to an existing one."
913274cb 821 (lisp-mode-variables nil t)
92eadba5
CY
822 (setq-local find-tag-default-function 'lisp-find-tag-default)
823 (setq-local comment-start-skip
824 "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
f3a47002 825 (setq imenu-case-fold-search t))
d6a3febd
MR
826
827(defun lisp-find-tag-default ()
828 (let ((default (find-tag-default)))
829 (when (stringp default)
830 (if (string-match ":+" default)
831 (substring default (match-end 0))
832 default))))
833
834;; Used in old LispM code.
835(defalias 'common-lisp-mode 'lisp-mode)
836
837;; This will do unless inf-lisp.el is loaded.
9d3aa82c 838(defun lisp-eval-defun (&optional _and-go)
d6a3febd
MR
839 "Send the current defun to the Lisp process made by \\[run-lisp]."
840 (interactive)
841 (error "Process lisp does not exist"))
842
843(defvar lisp-interaction-mode-map
844 (let ((map (make-sparse-keymap))
845 (menu-map (make-sparse-keymap "Lisp-Interaction")))
846 (set-keymap-parent map lisp-mode-shared-map)
847 (define-key map "\e\C-x" 'eval-defun)
848 (define-key map "\e\C-q" 'indent-pp-sexp)
51ef56c4 849 (define-key map "\e\t" 'completion-at-point)
d6a3febd 850 (define-key map "\n" 'eval-print-last-sexp)
1ec4b7b2
SM
851 (bindings--define-key map [menu-bar lisp-interaction]
852 (cons "Lisp-Interaction" menu-map))
853 (bindings--define-key menu-map [eval-defun]
854 '(menu-item "Evaluate Defun" eval-defun
855 :help "Evaluate the top-level form containing point, or after point"))
856 (bindings--define-key menu-map [eval-print-last-sexp]
857 '(menu-item "Evaluate and Print" eval-print-last-sexp
858 :help "Evaluate sexp before point; print value into current buffer"))
859 (bindings--define-key menu-map [edebug-defun-lisp-interaction]
860 '(menu-item "Instrument Function for Debugging" edebug-defun
861 :help "Evaluate the top level form point is in, stepping through with Edebug"
862 :keys "C-u C-M-x"))
863 (bindings--define-key menu-map [indent-pp-sexp]
864 '(menu-item "Indent or Pretty-Print" indent-pp-sexp
865 :help "Indent each line of the list starting just after point, or prettyprint it"))
866 (bindings--define-key menu-map [complete-symbol]
867 '(menu-item "Complete Lisp Symbol" completion-at-point
868 :help "Perform completion on Lisp symbol preceding point"))
d6a3febd
MR
869 map)
870 "Keymap for Lisp Interaction mode.
871All commands in `lisp-mode-shared-map' are inherited by this map.")
872
d6a3febd
MR
873(define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
874 "Major mode for typing and evaluating Lisp forms.
875Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
876before point, and prints its value into the buffer, advancing point.
877Note that printing is controlled by `eval-expression-print-length'
878and `eval-expression-print-level'.
879
880Commands:
881Delete converts tabs to spaces as it moves back.
882Paragraphs are separated only by blank lines.
883Semicolons start comments.
a3c40f60 884
ae1f1ce1 885\\{lisp-interaction-mode-map}"
db174434 886 :abbrev-table nil)
d6a3febd 887
b41594fd 888(defun eval-print-last-sexp (&optional eval-last-sexp-arg-internal)
d6a3febd
MR
889 "Evaluate sexp before point; print value into current buffer.
890
1670e27f
GM
891Normally, this function truncates long output according to the value
892of the variables `eval-expression-print-length' and
893`eval-expression-print-level'. With a prefix argument of zero,
894however, there is no such truncation. Such a prefix argument
895also causes integers to be printed in several additional formats
896\(octal, hexadecimal, and character).
d6a3febd 897
1670e27f
GM
898If `eval-expression-debug-on-error' is non-nil, which is the default,
899this command arranges for all errors to enter the debugger."
b41594fd 900 (interactive "P")
d6a3febd
MR
901 (let ((standard-output (current-buffer)))
902 (terpri)
b41594fd 903 (eval-last-sexp (or eval-last-sexp-arg-internal t))
d6a3febd
MR
904 (terpri)))
905
906
907(defun last-sexp-setup-props (beg end value alt1 alt2)
908 "Set up text properties for the output of `eval-last-sexp-1'.
909BEG and END are the start and end of the output in current-buffer.
910VALUE is the Lisp value printed, ALT1 and ALT2 are strings for the
911alternative printed representations that can be displayed."
912 (let ((map (make-sparse-keymap)))
913 (define-key map "\C-m" 'last-sexp-toggle-display)
914 (define-key map [down-mouse-2] 'mouse-set-point)
915 (define-key map [mouse-2] 'last-sexp-toggle-display)
916 (add-text-properties
917 beg end
918 `(printed-value (,value ,alt1 ,alt2)
919 mouse-face highlight
920 keymap ,map
921 help-echo "RET, mouse-2: toggle abbreviated display"
922 rear-nonsticky (mouse-face keymap help-echo
923 printed-value)))))
924
925
9d3aa82c 926(defun last-sexp-toggle-display (&optional _arg)
d6a3febd
MR
927 "Toggle between abbreviated and unabbreviated printed representations."
928 (interactive "P")
929 (save-restriction
930 (widen)
931 (let ((value (get-text-property (point) 'printed-value)))
932 (when value
933 (let ((beg (or (previous-single-property-change (min (point-max) (1+ (point)))
934 'printed-value)
935 (point)))
936 (end (or (next-single-char-property-change (point) 'printed-value) (point)))
937 (standard-output (current-buffer))
938 (point (point)))
939 (delete-region beg end)
940 (insert (nth 1 value))
941 (or (= beg point)
942 (setq point (1- (point))))
943 (last-sexp-setup-props beg (point)
944 (nth 0 value)
945 (nth 2 value)
946 (nth 1 value))
947 (goto-char (min (point-max) point)))))))
948
949(defun prin1-char (char)
950 "Return a string representing CHAR as a character rather than as an integer.
951If CHAR is not a character, return nil."
952 (and (integerp char)
953 (eventp char)
954 (let ((c (event-basic-type char))
955 (mods (event-modifiers char))
956 string)
957 ;; Prevent ?A from turning into ?\S-a.
958 (if (and (memq 'shift mods)
959 (zerop (logand char ?\S-\^@))
960 (not (let ((case-fold-search nil))
961 (char-equal c (upcase c)))))
962 (setq c (upcase c) mods nil))
963 ;; What string are we considering using?
964 (condition-case nil
965 (setq string
966 (concat
967 "?"
968 (mapconcat
969 (lambda (modif)
970 (cond ((eq modif 'super) "\\s-")
971 (t (string ?\\ (upcase (aref (symbol-name modif) 0)) ?-))))
972 mods "")
973 (cond
974 ((memq c '(?\; ?\( ?\) ?\{ ?\} ?\[ ?\] ?\" ?\' ?\\)) (string ?\\ c))
975 ((eq c 127) "\\C-?")
976 (t
977 (string c)))))
978 (error nil))
979 ;; Verify the string reads a CHAR, not to some other character.
980 ;; If it doesn't, return nil instead.
981 (and string
982 (= (car (read-from-string string)) char)
983 string))))
984
985
986(defun preceding-sexp ()
987 "Return sexp before the point."
988 (let ((opoint (point))
989 ignore-quotes
990 expr)
991 (save-excursion
992 (with-syntax-table emacs-lisp-mode-syntax-table
993 ;; If this sexp appears to be enclosed in `...'
994 ;; then ignore the surrounding quotes.
995 (setq ignore-quotes
996 (or (eq (following-char) ?\')
997 (eq (preceding-char) ?\')))
998 (forward-sexp -1)
999 ;; If we were after `?\e' (or similar case),
1000 ;; use the whole thing, not just the `e'.
1001 (when (eq (preceding-char) ?\\)
1002 (forward-char -1)
1003 (when (eq (preceding-char) ??)
1004 (forward-char -1)))
1005
7346a407
CY
1006 ;; Skip over hash table read syntax.
1007 (and (> (point) (1+ (point-min)))
1008 (looking-back "#s" (- (point) 2))
1009 (forward-char -2))
1010
d6a3febd
MR
1011 ;; Skip over `#N='s.
1012 (when (eq (preceding-char) ?=)
1013 (let (labeled-p)
1014 (save-excursion
1015 (skip-chars-backward "0-9#=")
1016 (setq labeled-p (looking-at "\\(#[0-9]+=\\)+")))
1017 (when labeled-p
1018 (forward-sexp -1))))
1019
1020 (save-restriction
4eb43682
SM
1021 (if (and ignore-quotes (eq (following-char) ?`))
1022 ;; vladimir@cs.ualberta.ca 30-Jul-1997: Skip ` in `variable' so
1023 ;; that the value is returned, not the name.
d6a3febd 1024 (forward-char))
4eb43682 1025 (when (looking-at ",@?") (goto-char (match-end 0)))
d6a3febd
MR
1026 (narrow-to-region (point-min) opoint)
1027 (setq expr (read (current-buffer)))
4eb43682
SM
1028 ;; If it's an (interactive ...) form, it's more useful to show how an
1029 ;; interactive call would use it.
1030 ;; FIXME: Is it really the right place for this?
1031 (when (eq (car-safe expr) 'interactive)
d6a3febd 1032 (setq expr
4eb43682
SM
1033 `(call-interactively
1034 (lambda (&rest args) ,expr args))))
d6a3febd
MR
1035 expr)))))
1036
1037
1038(defun eval-last-sexp-1 (eval-last-sexp-arg-internal)
32985194 1039 "Evaluate sexp before point; print value in the echo area.
b41594fd
JL
1040With argument, print output into current buffer.
1041With a zero prefix arg, print output with no limit on the length
1042and level of lists, and include additional formats for integers
1043\(octal, hexadecimal, and character)."
a0ee6f27 1044 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
b9598260 1045 ;; Setup the lexical environment if lexical-binding is enabled.
06788a55 1046 (eval-last-sexp-print-value
b41594fd
JL
1047 (eval (eval-sexp-add-defvars (preceding-sexp)) lexical-binding)
1048 eval-last-sexp-arg-internal)))
d6a3febd
MR
1049
1050
b41594fd 1051(defun eval-last-sexp-print-value (value &optional eval-last-sexp-arg-internal)
d6a3febd
MR
1052 (let ((unabbreviated (let ((print-length nil) (print-level nil))
1053 (prin1-to-string value)))
b41594fd
JL
1054 (print-length (and (not (zerop (prefix-numeric-value
1055 eval-last-sexp-arg-internal)))
1056 eval-expression-print-length))
1057 (print-level (and (not (zerop (prefix-numeric-value
1058 eval-last-sexp-arg-internal)))
1059 eval-expression-print-level))
d6a3febd
MR
1060 (beg (point))
1061 end)
1062 (prog1
1063 (prin1 value)
1064 (let ((str (eval-expression-print-format value)))
1065 (if str (princ str)))
1066 (setq end (point))
1067 (when (and (bufferp standard-output)
1068 (or (not (null print-length))
1069 (not (null print-level)))
1070 (not (string= unabbreviated
1071 (buffer-substring-no-properties beg end))))
1072 (last-sexp-setup-props beg end value
1073 unabbreviated
1074 (buffer-substring-no-properties beg end))
1075 ))))
1076
1077
1078(defvar eval-last-sexp-fake-value (make-symbol "t"))
1079
06788a55
SM
1080(defun eval-sexp-add-defvars (exp &optional pos)
1081 "Prepend EXP with all the `defvar's that precede it in the buffer.
1082POS specifies the starting position where EXP was found and defaults to point."
1f8fdd53 1083 (setq exp (macroexpand-all exp)) ;Eager macro-expansion.
06788a55
SM
1084 (if (not lexical-binding)
1085 exp
1086 (save-excursion
1087 (unless pos (setq pos (point)))
1088 (let ((vars ()))
1089 (goto-char (point-min))
1090 (while (re-search-forward
9b851e25 1091 "(def\\(?:var\\|const\\|custom\\)[ \t\n]+\\([^; '()\n\t]+\\)"
06788a55
SM
1092 pos t)
1093 (let ((var (intern (match-string 1))))
9b851e25
SM
1094 (and (not (special-variable-p var))
1095 (save-excursion
1096 (zerop (car (syntax-ppss (match-beginning 0)))))
06788a55
SM
1097 (push var vars))))
1098 `(progn ,@(mapcar (lambda (v) `(defvar ,v)) vars) ,exp)))))
7200d79c 1099
d6a3febd 1100(defun eval-last-sexp (eval-last-sexp-arg-internal)
32985194 1101 "Evaluate sexp before point; print value in the echo area.
d6a3febd 1102Interactively, with prefix argument, print output into current buffer.
1670e27f
GM
1103
1104Normally, this function truncates long output according to the value
1105of the variables `eval-expression-print-length' and
1106`eval-expression-print-level'. With a prefix argument of zero,
1107however, there is no such truncation. Such a prefix argument
1108also causes integers to be printed in several additional formats
b41594fd 1109\(octal, hexadecimal, and character).
d6a3febd
MR
1110
1111If `eval-expression-debug-on-error' is non-nil, which is the default,
1112this command arranges for all errors to enter the debugger."
1113 (interactive "P")
1114 (if (null eval-expression-debug-on-error)
1115 (eval-last-sexp-1 eval-last-sexp-arg-internal)
1116 (let ((value
1117 (let ((debug-on-error eval-last-sexp-fake-value))
1118 (cons (eval-last-sexp-1 eval-last-sexp-arg-internal)
1119 debug-on-error))))
1120 (unless (eq (cdr value) eval-last-sexp-fake-value)
1121 (setq debug-on-error (cdr value)))
1122 (car value))))
1123
1124(defun eval-defun-1 (form)
1125 "Treat some expressions specially.
1126Reset the `defvar' and `defcustom' variables to the initial value.
c6c08d3f 1127\(For `defcustom', use the :set function if there is one.)
d6a3febd
MR
1128Reinitialize the face according to the `defface' specification."
1129 ;; The code in edebug-defun should be consistent with this, but not
53964682 1130 ;; the same, since this gets a macroexpanded form.
d6a3febd
MR
1131 (cond ((not (listp form))
1132 form)
1133 ((and (eq (car form) 'defvar)
1134 (cdr-safe (cdr-safe form))
1135 (boundp (cadr form)))
1136 ;; Force variable to be re-set.
1137 `(progn (defvar ,(nth 1 form) nil ,@(nthcdr 3 form))
1138 (setq-default ,(nth 1 form) ,(nth 2 form))))
1139 ;; `defcustom' is now macroexpanded to
1140 ;; `custom-declare-variable' with a quoted value arg.
1141 ((and (eq (car form) 'custom-declare-variable)
a0ee6f27 1142 (default-boundp (eval (nth 1 form) lexical-binding)))
c6c08d3f
GM
1143 ;; Force variable to be bound, using :set function if specified.
1144 (let ((setfunc (memq :set form)))
1145 (when setfunc
1146 (setq setfunc (car-safe (cdr-safe setfunc)))
1147 (or (functionp setfunc) (setq setfunc nil)))
1148 (funcall (or setfunc 'set-default)
1149 (eval (nth 1 form) lexical-binding)
1150 ;; The second arg is an expression that evaluates to
1151 ;; an expression. The second evaluation is the one
1152 ;; normally performed not by normal execution but by
1153 ;; custom-initialize-set (for example), which does not
1154 ;; use lexical-binding.
1155 (eval (eval (nth 2 form) lexical-binding))))
d6a3febd
MR
1156 form)
1157 ;; `defface' is macroexpanded to `custom-declare-face'.
1158 ((eq (car form) 'custom-declare-face)
1159 ;; Reset the face.
f4f73198
LMI
1160 (let ((face-symbol (eval (nth 1 form) lexical-binding)))
1161 (setq face-new-frame-defaults
1162 (assq-delete-all face-symbol face-new-frame-defaults))
1163 (put face-symbol 'face-defface-spec nil)
1c4f115d
CY
1164 (put face-symbol 'face-override-spec nil))
1165 form)
d6a3febd
MR
1166 ((eq (car form) 'progn)
1167 (cons 'progn (mapcar 'eval-defun-1 (cdr form))))
1168 (t form)))
1169
1170(defun eval-defun-2 ()
1171 "Evaluate defun that point is in or before.
32985194 1172The value is displayed in the echo area.
d6a3febd
MR
1173If the current defun is actually a call to `defvar',
1174then reset the variable using the initial value expression
1175even if the variable already has some other value.
1176\(Normally `defvar' does not change the variable's value
1177if it already has a value.\)
1178
d6a3febd 1179Return the result of evaluation."
d6a3febd
MR
1180 ;; FIXME: the print-length/level bindings should only be applied while
1181 ;; printing, not while evaluating.
1182 (let ((debug-on-error eval-expression-debug-on-error)
1183 (print-length eval-expression-print-length)
1184 (print-level eval-expression-print-level))
1185 (save-excursion
1186 ;; Arrange for eval-region to "read" the (possibly) altered form.
1187 ;; eval-region handles recording which file defines a function or
a5833280
SM
1188 ;; variable.
1189 (let ((standard-output t)
1190 beg end form)
1191 ;; Read the form from the buffer, and record where it ends.
1192 (save-excursion
1193 (end-of-defun)
1194 (beginning-of-defun)
1195 (setq beg (point))
1196 (setq form (read (current-buffer)))
1197 (setq end (point)))
1198 ;; Alter the form if necessary.
1199 (let ((form (eval-sexp-add-defvars
1200 (eval-defun-1 (macroexpand form)))))
1201 (eval-region beg end standard-output
1202 (lambda (_ignore)
1203 ;; Skipping to the end of the specified region
1204 ;; will make eval-region return.
1205 (goto-char end)
1206 form))))))
b41594fd
JL
1207 (let ((str (eval-expression-print-format (car values))))
1208 (if str (princ str)))
d6a3febd
MR
1209 ;; The result of evaluation has been put onto VALUES. So return it.
1210 (car values))
1211
1212(defun eval-defun (edebug-it)
1213 "Evaluate the top-level form containing point, or after point.
1214
1215If the current defun is actually a call to `defvar' or `defcustom',
1216evaluating it this way resets the variable using its initial value
c6c08d3f
GM
1217expression (using the defcustom's :set function if there is one), even
1218if the variable already has some other value. \(Normally `defvar' and
1219`defcustom' do not alter the value if there already is one.) In an
1220analogous way, evaluating a `defface' overrides any customizations of
1221the face, so that it becomes defined exactly as the `defface' expression
1222says.
d6a3febd
MR
1223
1224If `eval-expression-debug-on-error' is non-nil, which is the default,
1225this command arranges for all errors to enter the debugger.
1226
1227With a prefix argument, instrument the code for Edebug.
1228
1229If acting on a `defun' for FUNCTION, and the function was
32985194 1230instrumented, `Edebug: FUNCTION' is printed in the echo area. If not
d6a3febd
MR
1231instrumented, just FUNCTION is printed.
1232
1233If not acting on a `defun', the result of evaluation is displayed in
32985194 1234the echo area. This display is controlled by the variables
d6a3febd
MR
1235`eval-expression-print-length' and `eval-expression-print-level',
1236which see."
1237 (interactive "P")
1238 (cond (edebug-it
1239 (require 'edebug)
1240 (eval-defun (not edebug-all-defs)))
1241 (t
1242 (if (null eval-expression-debug-on-error)
1243 (eval-defun-2)
1244 (let ((old-value (make-symbol "t")) new-value value)
1245 (let ((debug-on-error old-value))
1246 (setq value (eval-defun-2))
1247 (setq new-value debug-on-error))
1248 (unless (eq old-value new-value)
1249 (setq debug-on-error new-value))
1250 value)))))
1251
1252;; May still be used by some external Lisp-mode variant.
1253(define-obsolete-function-alias 'lisp-comment-indent
1254 'comment-indent-default "22.1")
1255(define-obsolete-function-alias 'lisp-mode-auto-fill 'do-auto-fill "23.1")
1256
1257(defcustom lisp-indent-offset nil
1258 "If non-nil, indent second line of expressions that many more columns."
1259 :group 'lisp
1260 :type '(choice (const nil) integer))
3fde45af 1261(put 'lisp-indent-offset 'safe-local-variable
d6a3febd
MR
1262 (lambda (x) (or (null x) (integerp x))))
1263
3fde45af 1264(defcustom lisp-indent-function 'lisp-indent-function
c4ea8f00
GM
1265 "A function to be called by `calculate-lisp-indent'.
1266It indents the arguments of a Lisp function call. This function
1267should accept two arguments: the indent-point, and the
1268`parse-partial-sexp' state at that position. One option for this
3fde45af
GM
1269function is `common-lisp-indent-function'."
1270 :type 'function
1271 :group 'lisp)
d6a3febd 1272
9d3aa82c 1273(defun lisp-indent-line (&optional _whole-exp)
d6a3febd
MR
1274 "Indent current line as Lisp code.
1275With argument, indent any additional lines of the same expression
1276rigidly along with this one."
1277 (interactive "P")
9d3aa82c 1278 (let ((indent (calculate-lisp-indent)) shift-amt
d6a3febd
MR
1279 (pos (- (point-max) (point)))
1280 (beg (progn (beginning-of-line) (point))))
1281 (skip-chars-forward " \t")
1282 (if (or (null indent) (looking-at "\\s<\\s<\\s<"))
1283 ;; Don't alter indentation of a ;;; comment line
1284 ;; or a line that starts in a string.
9b851e25 1285 ;; FIXME: inconsistency: comment-indent moves ;;; to column 0.
d6a3febd
MR
1286 (goto-char (- (point-max) pos))
1287 (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
1288 ;; Single-semicolon comment lines should be indented
1289 ;; as comment lines, not as code.
1290 (progn (indent-for-comment) (forward-char -1))
1291 (if (listp indent) (setq indent (car indent)))
1292 (setq shift-amt (- indent (current-column)))
1293 (if (zerop shift-amt)
1294 nil
1295 (delete-region beg (point))
1296 (indent-to indent)))
1297 ;; If initial point was within line's indentation,
1298 ;; position after the indentation. Else stay at same point in text.
1299 (if (> (- (point-max) pos) (point))
9b851e25 1300 (goto-char (- (point-max) pos))))))
d6a3febd
MR
1301
1302(defvar calculate-lisp-indent-last-sexp)
1303
1304(defun calculate-lisp-indent (&optional parse-start)
1305 "Return appropriate indentation for current line as Lisp code.
1306In usual case returns an integer: the column to indent to.
1307If the value is nil, that means don't change the indentation
1308because the line starts inside a string.
1309
1310The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
1311This means that following lines at the same level of indentation
1312should not necessarily be indented the same as this line.
1313Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
1314is the buffer position of the start of the containing expression."
1315 (save-excursion
1316 (beginning-of-line)
1317 (let ((indent-point (point))
9d3aa82c 1318 state
d6a3febd
MR
1319 ;; setting this to a number inhibits calling hook
1320 (desired-indent nil)
1321 (retry t)
1322 calculate-lisp-indent-last-sexp containing-sexp)
1323 (if parse-start
1324 (goto-char parse-start)
1325 (beginning-of-defun))
1326 ;; Find outermost containing sexp
1327 (while (< (point) indent-point)
1328 (setq state (parse-partial-sexp (point) indent-point 0)))
1329 ;; Find innermost containing sexp
1330 (while (and retry
1331 state
9d3aa82c 1332 (> (elt state 0) 0))
d6a3febd
MR
1333 (setq retry nil)
1334 (setq calculate-lisp-indent-last-sexp (elt state 2))
1335 (setq containing-sexp (elt state 1))
1336 ;; Position following last unclosed open.
1337 (goto-char (1+ containing-sexp))
1338 ;; Is there a complete sexp since then?
1339 (if (and calculate-lisp-indent-last-sexp
1340 (> calculate-lisp-indent-last-sexp (point)))
1341 ;; Yes, but is there a containing sexp after that?
1342 (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
1343 indent-point 0)))
1344 (if (setq retry (car (cdr peek))) (setq state peek)))))
1345 (if retry
1346 nil
1347 ;; Innermost containing sexp found
1348 (goto-char (1+ containing-sexp))
1349 (if (not calculate-lisp-indent-last-sexp)
1350 ;; indent-point immediately follows open paren.
1351 ;; Don't call hook.
1352 (setq desired-indent (current-column))
1353 ;; Find the start of first element of containing sexp.
1354 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1355 (cond ((looking-at "\\s(")
1356 ;; First element of containing sexp is a list.
1357 ;; Indent under that list.
1358 )
1359 ((> (save-excursion (forward-line 1) (point))
1360 calculate-lisp-indent-last-sexp)
1361 ;; This is the first line to start within the containing sexp.
1362 ;; It's almost certainly a function call.
1363 (if (= (point) calculate-lisp-indent-last-sexp)
1364 ;; Containing sexp has nothing before this line
1365 ;; except the first element. Indent under that element.
1366 nil
1367 ;; Skip the first element, find start of second (the first
1368 ;; argument of the function call) and indent under.
1369 (progn (forward-sexp 1)
1370 (parse-partial-sexp (point)
1371 calculate-lisp-indent-last-sexp
1372 0 t)))
1373 (backward-prefix-chars))
1374 (t
1375 ;; Indent beneath first sexp on same line as
1376 ;; `calculate-lisp-indent-last-sexp'. Again, it's
1377 ;; almost certainly a function call.
1378 (goto-char calculate-lisp-indent-last-sexp)
1379 (beginning-of-line)
1380 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
1381 0 t)
1382 (backward-prefix-chars)))))
1383 ;; Point is at the point to indent under unless we are inside a string.
1384 ;; Call indentation hook except when overridden by lisp-indent-offset
1385 ;; or if the desired indentation has already been computed.
1386 (let ((normal-indent (current-column)))
1387 (cond ((elt state 3)
1388 ;; Inside a string, don't change indentation.
1389 nil)
1390 ((and (integerp lisp-indent-offset) containing-sexp)
1391 ;; Indent by constant offset
1392 (goto-char containing-sexp)
1393 (+ (current-column) lisp-indent-offset))
1394 ;; in this case calculate-lisp-indent-last-sexp is not nil
1395 (calculate-lisp-indent-last-sexp
1396 (or
1397 ;; try to align the parameters of a known function
1398 (and lisp-indent-function
1399 (not retry)
1400 (funcall lisp-indent-function indent-point state))
1401 ;; If the function has no special alignment
1402 ;; or it does not apply to this argument,
1403 ;; try to align a constant-symbol under the last
1404 ;; preceding constant symbol, if there is such one of
1405 ;; the last 2 preceding symbols, in the previous
1406 ;; uncommented line.
1407 (and (save-excursion
1408 (goto-char indent-point)
1409 (skip-chars-forward " \t")
1410 (looking-at ":"))
1411 ;; The last sexp may not be at the indentation
1412 ;; where it begins, so find that one, instead.
1413 (save-excursion
1414 (goto-char calculate-lisp-indent-last-sexp)
1415 ;; Handle prefix characters and whitespace
1416 ;; following an open paren. (Bug#1012)
1417 (backward-prefix-chars)
1418 (while (and (not (looking-back "^[ \t]*\\|([ \t]+"))
1419 (or (not containing-sexp)
1420 (< (1+ containing-sexp) (point))))
1421 (forward-sexp -1)
1422 (backward-prefix-chars))
1423 (setq calculate-lisp-indent-last-sexp (point)))
1424 (> calculate-lisp-indent-last-sexp
1425 (save-excursion
1426 (goto-char (1+ containing-sexp))
1427 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1428 (point)))
1429 (let ((parse-sexp-ignore-comments t)
1430 indent)
1431 (goto-char calculate-lisp-indent-last-sexp)
1432 (or (and (looking-at ":")
1433 (setq indent (current-column)))
5ed619e0 1434 (and (< (line-beginning-position)
d6a3febd
MR
1435 (prog2 (backward-sexp) (point)))
1436 (looking-at ":")
1437 (setq indent (current-column))))
1438 indent))
1439 ;; another symbols or constants not preceded by a constant
1440 ;; as defined above.
1441 normal-indent))
1442 ;; in this case calculate-lisp-indent-last-sexp is nil
1443 (desired-indent)
1444 (t
1445 normal-indent))))))
1446
1447(defun lisp-indent-function (indent-point state)
1448 "This function is the normal value of the variable `lisp-indent-function'.
b7556719
GM
1449The function `calculate-lisp-indent' calls this to determine
1450if the arguments of a Lisp function call should be indented specially.
d6a3febd 1451
f8a42ad6 1452INDENT-POINT is the position at which the line being indented begins.
d6a3febd
MR
1453Point is located at the point to indent under (for default indentation);
1454STATE is the `parse-partial-sexp' state for that position.
1455
b7556719
GM
1456If the current line is in a call to a Lisp function that has a non-nil
1457property `lisp-indent-function' (or the deprecated `lisp-indent-hook'),
1458it specifies how to indent. The property value can be:
1459
1460* `defun', meaning indent `defun'-style
1461 \(this is also the case if there is no property and the function
1462 has a name that begins with \"def\", and three or more arguments);
1463
d6a3febd 1464* an integer N, meaning indent the first N arguments specially
b7556719 1465 (like ordinary function arguments), and then indent any further
d6a3febd 1466 arguments like a body;
d6a3febd 1467
b7556719
GM
1468* a function to call that returns the indentation (or nil).
1469 `lisp-indent-function' calls this function with the same two arguments
1470 that it itself received.
1471
1472This function returns either the indentation to use, or nil if the
1473Lisp function does not specify a special indentation."
d6a3febd
MR
1474 (let ((normal-indent (current-column)))
1475 (goto-char (1+ (elt state 1)))
1476 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1477 (if (and (elt state 2)
1478 (not (looking-at "\\sw\\|\\s_")))
1479 ;; car of form doesn't seem to be a symbol
1480 (progn
1481 (if (not (> (save-excursion (forward-line 1) (point))
1482 calculate-lisp-indent-last-sexp))
1483 (progn (goto-char calculate-lisp-indent-last-sexp)
1484 (beginning-of-line)
1485 (parse-partial-sexp (point)
1486 calculate-lisp-indent-last-sexp 0 t)))
1487 ;; Indent under the list or under the first sexp on the same
1488 ;; line as calculate-lisp-indent-last-sexp. Note that first
1489 ;; thing on that line has to be complete sexp since we are
1490 ;; inside the innermost containing sexp.
1491 (backward-prefix-chars)
1492 (current-column))
1493 (let ((function (buffer-substring (point)
1494 (progn (forward-sexp 1) (point))))
1495 method)
7abaf5cc
SM
1496 (setq method (or (function-get (intern-soft function)
1497 'lisp-indent-function)
d6a3febd
MR
1498 (get (intern-soft function) 'lisp-indent-hook)))
1499 (cond ((or (eq method 'defun)
1500 (and (null method)
1501 (> (length function) 3)
1502 (string-match "\\`def" function)))
1503 (lisp-indent-defform state indent-point))
1504 ((integerp method)
1505 (lisp-indent-specform method state
1506 indent-point normal-indent))
1507 (method
1508 (funcall method indent-point state)))))))
1509
1510(defcustom lisp-body-indent 2
1511 "Number of columns to indent the second line of a `(def...)' form."
1512 :group 'lisp
1513 :type 'integer)
1514(put 'lisp-body-indent 'safe-local-variable 'integerp)
1515
1516(defun lisp-indent-specform (count state indent-point normal-indent)
1517 (let ((containing-form-start (elt state 1))
1518 (i count)
1519 body-indent containing-form-column)
1520 ;; Move to the start of containing form, calculate indentation
1521 ;; to use for non-distinguished forms (> count), and move past the
1522 ;; function symbol. lisp-indent-function guarantees that there is at
1523 ;; least one word or symbol character following open paren of containing
1524 ;; form.
1525 (goto-char containing-form-start)
1526 (setq containing-form-column (current-column))
1527 (setq body-indent (+ lisp-body-indent containing-form-column))
1528 (forward-char 1)
1529 (forward-sexp 1)
1530 ;; Now find the start of the last form.
1531 (parse-partial-sexp (point) indent-point 1 t)
1532 (while (and (< (point) indent-point)
1533 (condition-case ()
1534 (progn
1535 (setq count (1- count))
1536 (forward-sexp 1)
1537 (parse-partial-sexp (point) indent-point 1 t))
1538 (error nil))))
1539 ;; Point is sitting on first character of last (or count) sexp.
1540 (if (> count 0)
1541 ;; A distinguished form. If it is the first or second form use double
1542 ;; lisp-body-indent, else normal indent. With lisp-body-indent bound
1543 ;; to 2 (the default), this just happens to work the same with if as
1544 ;; the older code, but it makes unwind-protect, condition-case,
1545 ;; with-output-to-temp-buffer, et. al. much more tasteful. The older,
1546 ;; less hacked, behavior can be obtained by replacing below with
1547 ;; (list normal-indent containing-form-start).
1548 (if (<= (- i count) 1)
1549 (list (+ containing-form-column (* 2 lisp-body-indent))
1550 containing-form-start)
1551 (list normal-indent containing-form-start))
1552 ;; A non-distinguished form. Use body-indent if there are no
1553 ;; distinguished forms and this is the first undistinguished form,
1554 ;; or if this is the first undistinguished form and the preceding
1555 ;; distinguished form has indentation at least as great as body-indent.
1556 (if (or (and (= i 0) (= count 0))
1557 (and (= count 0) (<= body-indent normal-indent)))
1558 body-indent
1559 normal-indent))))
1560
9d3aa82c 1561(defun lisp-indent-defform (state _indent-point)
d6a3febd
MR
1562 (goto-char (car (cdr state)))
1563 (forward-line 1)
1564 (if (> (point) (car (cdr (cdr state))))
1565 (progn
1566 (goto-char (car (cdr state)))
1567 (+ lisp-body-indent (current-column)))))
1568
1569
1570;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
1571;; like defun if the first form is placed on the next line, otherwise
1572;; it is indented like any other form (i.e. forms line up under first).
1573
d6a3febd
MR
1574(put 'autoload 'lisp-indent-function 'defun)
1575(put 'progn 'lisp-indent-function 0)
1576(put 'prog1 'lisp-indent-function 1)
1577(put 'prog2 'lisp-indent-function 2)
1578(put 'save-excursion 'lisp-indent-function 0)
d6a3febd 1579(put 'save-restriction 'lisp-indent-function 0)
d6a3febd 1580(put 'save-current-buffer 'lisp-indent-function 0)
d6a3febd
MR
1581(put 'let 'lisp-indent-function 1)
1582(put 'let* 'lisp-indent-function 1)
1583(put 'while 'lisp-indent-function 1)
1584(put 'if 'lisp-indent-function 2)
d6a3febd
MR
1585(put 'catch 'lisp-indent-function 1)
1586(put 'condition-case 'lisp-indent-function 2)
1587(put 'unwind-protect 'lisp-indent-function 1)
1588(put 'with-output-to-temp-buffer 'lisp-indent-function 1)
d6a3febd
MR
1589
1590(defun indent-sexp (&optional endpos)
1591 "Indent each line of the list starting just after point.
1592If optional arg ENDPOS is given, indent each line, stopping when
1593ENDPOS is encountered."
1594 (interactive)
1595 (let ((indent-stack (list nil))
1596 (next-depth 0)
1597 ;; If ENDPOS is non-nil, use nil as STARTING-POINT
1598 ;; so that calculate-lisp-indent will find the beginning of
1599 ;; the defun we are in.
1600 ;; If ENDPOS is nil, it is safe not to scan before point
1601 ;; since every line we indent is more deeply nested than point is.
1602 (starting-point (if endpos nil (point)))
1603 (last-point (point))
1604 last-depth bol outer-loop-done inner-loop-done state this-indent)
1605 (or endpos
1606 ;; Get error now if we don't have a complete sexp after point.
1607 (save-excursion (forward-sexp 1)))
1608 (save-excursion
1609 (setq outer-loop-done nil)
1610 (while (if endpos (< (point) endpos)
1611 (not outer-loop-done))
1612 (setq last-depth next-depth
1613 inner-loop-done nil)
1614 ;; Parse this line so we can learn the state
1615 ;; to indent the next line.
1616 ;; This inner loop goes through only once
1617 ;; unless a line ends inside a string.
1618 (while (and (not inner-loop-done)
1619 (not (setq outer-loop-done (eobp))))
1620 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
1621 nil nil state))
1622 (setq next-depth (car state))
1623 ;; If the line contains a comment other than the sort
1624 ;; that is indented like code,
1625 ;; indent it now with indent-for-comment.
1626 ;; Comments indented like code are right already.
1627 ;; In any case clear the in-comment flag in the state
1628 ;; because parse-partial-sexp never sees the newlines.
1629 (if (car (nthcdr 4 state))
1630 (progn (indent-for-comment)
1631 (end-of-line)
1632 (setcar (nthcdr 4 state) nil)))
1633 ;; If this line ends inside a string,
1634 ;; go straight to next line, remaining within the inner loop,
1635 ;; and turn off the \-flag.
1636 (if (car (nthcdr 3 state))
1637 (progn
1638 (forward-line 1)
1639 (setcar (nthcdr 5 state) nil))
1640 (setq inner-loop-done t)))
1641 (and endpos
1642 (<= next-depth 0)
1643 (progn
1644 (setq indent-stack (nconc indent-stack
1645 (make-list (- next-depth) nil))
1646 last-depth (- last-depth next-depth)
1647 next-depth 0)))
1648 (forward-line 1)
1649 ;; Decide whether to exit.
1650 (if endpos
1651 ;; If we have already reached the specified end,
1652 ;; give up and do not reindent this line.
1653 (if (<= endpos (point))
1654 (setq outer-loop-done t))
1655 ;; If no specified end, we are done if we have finished one sexp.
1656 (if (<= next-depth 0)
1657 (setq outer-loop-done t)))
1658 (unless outer-loop-done
1659 (while (> last-depth next-depth)
1660 (setq indent-stack (cdr indent-stack)
1661 last-depth (1- last-depth)))
1662 (while (< last-depth next-depth)
1663 (setq indent-stack (cons nil indent-stack)
1664 last-depth (1+ last-depth)))
1665 ;; Now indent the next line according
1666 ;; to what we learned from parsing the previous one.
1667 (setq bol (point))
1668 (skip-chars-forward " \t")
1669 ;; But not if the line is blank, or just a comment
1670 ;; (except for double-semi comments; indent them as usual).
1671 (if (or (eobp) (looking-at "\\s<\\|\n"))
1672 nil
1673 (if (and (car indent-stack)
1674 (>= (car indent-stack) 0))
1675 (setq this-indent (car indent-stack))
1676 (let ((val (calculate-lisp-indent
1677 (if (car indent-stack) (- (car indent-stack))
1678 starting-point))))
1679 (if (null val)
1680 (setq this-indent val)
1681 (if (integerp val)
1682 (setcar indent-stack
1683 (setq this-indent val))
1684 (setcar indent-stack (- (car (cdr val))))
1685 (setq this-indent (car val))))))
1686 (if (and this-indent (/= (current-column) this-indent))
1687 (progn (delete-region bol (point))
1688 (indent-to this-indent)))))
1689 (or outer-loop-done
1690 (setq outer-loop-done (= (point) last-point))
1691 (setq last-point (point)))))))
1692
d6a3febd
MR
1693(defun indent-pp-sexp (&optional arg)
1694 "Indent each line of the list starting just after point, or prettyprint it.
1695A prefix argument specifies pretty-printing."
1696 (interactive "P")
1697 (if arg
1698 (save-excursion
1699 (save-restriction
1700 (narrow-to-region (point) (progn (forward-sexp 1) (point)))
1701 (pp-buffer)
1702 (goto-char (point-max))
1703 (if (eq (char-before) ?\n)
1704 (delete-char -1)))))
1705 (indent-sexp))
1706
1707;;;; Lisp paragraph filling commands.
1708
1709(defcustom emacs-lisp-docstring-fill-column 65
1710 "Value of `fill-column' to use when filling a docstring.
1711Any non-integer value means do not use a different value of
1712`fill-column' when filling docstrings."
1713 :type '(choice (integer)
1714 (const :tag "Use the current `fill-column'" t))
1715 :group 'lisp)
bde73d27
DG
1716(put 'emacs-lisp-docstring-fill-column 'safe-local-variable
1717 (lambda (x) (or (eq x t) (integerp x))))
d6a3febd
MR
1718
1719(defun lisp-fill-paragraph (&optional justify)
1720 "Like \\[fill-paragraph], but handle Emacs Lisp comments and docstrings.
1721If any of the current line is a comment, fill the comment or the
1722paragraph of it that point is in, preserving the comment's indentation
1723and initial semicolons."
1724 (interactive "P")
1725 (or (fill-comment-paragraph justify)
1726 ;; Since fill-comment-paragraph returned nil, that means we're not in
1727 ;; a comment: Point is on a program line; we are interested
1728 ;; particularly in docstring lines.
1729 ;;
1730 ;; We bind `paragraph-start' and `paragraph-separate' temporarily. They
1731 ;; are buffer-local, but we avoid changing them so that they can be set
1732 ;; to make `forward-paragraph' and friends do something the user wants.
1733 ;;
1734 ;; `paragraph-start': The `(' in the character alternative and the
1735 ;; left-singlequote plus `(' sequence after the \\| alternative prevent
1736 ;; sexps and backquoted sexps that follow a docstring from being filled
1737 ;; with the docstring. This setting has the consequence of inhibiting
1738 ;; filling many program lines that are not docstrings, which is sensible,
1739 ;; because the user probably asked to fill program lines by accident, or
1740 ;; expecting indentation (perhaps we should try to do indenting in that
1741 ;; case). The `;' and `:' stop the paragraph being filled at following
1742 ;; comment lines and at keywords (e.g., in `defcustom'). Left parens are
1743 ;; escaped to keep font-locking, filling, & paren matching in the source
1744 ;; file happy.
1745 ;;
1746 ;; `paragraph-separate': A clever regexp distinguishes the first line of
1747 ;; a docstring and identifies it as a paragraph separator, so that it
1748 ;; won't be filled. (Since the first line of documentation stands alone
1749 ;; in some contexts, filling should not alter the contents the author has
1750 ;; chosen.) Only the first line of a docstring begins with whitespace
1751 ;; and a quotation mark and ends with a period or (rarely) a comma.
1752 ;;
1753 ;; The `fill-column' is temporarily bound to
1754 ;; `emacs-lisp-docstring-fill-column' if that value is an integer.
1755 (let ((paragraph-start (concat paragraph-start
1756 "\\|\\s-*\\([(;:\"]\\|`(\\|#'(\\)"))
1757 (paragraph-separate
1758 (concat paragraph-separate "\\|\\s-*\".*[,\\.]$"))
1759 (fill-column (if (and (integerp emacs-lisp-docstring-fill-column)
1760 (derived-mode-p 'emacs-lisp-mode))
1761 emacs-lisp-docstring-fill-column
1762 fill-column)))
1763 (fill-paragraph justify))
1764 ;; Never return nil.
1765 t))
1766
1767(defun indent-code-rigidly (start end arg &optional nochange-regexp)
1768 "Indent all lines of code, starting in the region, sideways by ARG columns.
1769Does not affect lines starting inside comments or strings, assuming that
1770the start of the region is not inside them.
1771
1772Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1773The last is a regexp which, if matched at the beginning of a line,
1774means don't indent that line."
1775 (interactive "r\np")
1776 (let (state)
1777 (save-excursion
1778 (goto-char end)
1779 (setq end (point-marker))
1780 (goto-char start)
1781 (or (bolp)
1782 (setq state (parse-partial-sexp (point)
1783 (progn
1784 (forward-line 1) (point))
1785 nil nil state)))
1786 (while (< (point) end)
1787 (or (car (nthcdr 3 state))
1788 (and nochange-regexp
1789 (looking-at nochange-regexp))
1790 ;; If line does not start in string, indent it
1791 (let ((indent (current-indentation)))
1792 (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1793 (or (eolp)
1794 (indent-to (max 0 (+ indent arg)) 0))))
1795 (setq state (parse-partial-sexp (point)
1796 (progn
1797 (forward-line 1) (point))
1798 nil nil state))))))
1799
1800(provide 'lisp-mode)
1801
d6a3febd 1802;;; lisp-mode.el ends here