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