]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/lisp-mode.el
Fix incorrect usage of @key in the User Manual (Bug#20135)
[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-2015 Free Software Foundation, Inc.
4
5 ;; Maintainer: emacs-devel@gnu.org
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 ?@ "_ p" 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 (setq-local comment-start-skip ";+ *")
453 (setq-local comment-add 1) ;default to `;;' in comment-region
454 (setq-local comment-column 40)
455 (setq-local comment-use-syntax t)
456 (setq-local imenu-generic-expression lisp-imenu-generic-expression)
457 (setq-local multibyte-syntax-as-symbol t)
458 ;; (setq-local syntax-begin-function 'beginning-of-defun) ;;Bug#16247.
459 (setq font-lock-defaults
460 `(,(if elisp '(lisp-el-font-lock-keywords
461 lisp-el-font-lock-keywords-1
462 lisp-el-font-lock-keywords-2)
463 '(lisp-cl-font-lock-keywords
464 lisp-cl-font-lock-keywords-1
465 lisp-cl-font-lock-keywords-2))
466 nil ,keywords-case-insensitive nil nil
467 (font-lock-mark-block-function . mark-defun)
468 (font-lock-syntactic-face-function
469 . lisp-font-lock-syntactic-face-function)))
470 (setq-local prettify-symbols-alist lisp--prettify-symbols-alist)
471 ;; electric
472 (when elisp
473 (setq-local electric-pair-text-pairs
474 (cons '(?\` . ?\') electric-pair-text-pairs)))
475 (setq-local electric-pair-skip-whitespace 'chomp)
476 (setq-local electric-pair-open-newline-between-pairs nil))
477
478 (defun lisp-outline-level ()
479 "Lisp mode `outline-level' function."
480 (let ((len (- (match-end 0) (match-beginning 0))))
481 (if (looking-at "(\\|;;;###autoload")
482 1000
483 len)))
484
485 (defun lisp-current-defun-name ()
486 "Return the name of the defun at point, or nil."
487 (save-excursion
488 (let ((location (point)))
489 ;; If we are now precisely at the beginning of a defun, make sure
490 ;; beginning-of-defun finds that one rather than the previous one.
491 (or (eobp) (forward-char 1))
492 (beginning-of-defun)
493 ;; Make sure we are really inside the defun found, not after it.
494 (when (and (looking-at "\\s(")
495 (progn (end-of-defun)
496 (< location (point)))
497 (progn (forward-sexp -1)
498 (>= location (point))))
499 (if (looking-at "\\s(")
500 (forward-char 1))
501 ;; Skip the defining construct name, typically "defun" or
502 ;; "defvar".
503 (forward-sexp 1)
504 ;; The second element is usually a symbol being defined. If it
505 ;; is not, use the first symbol in it.
506 (skip-chars-forward " \t\n'(")
507 (buffer-substring-no-properties (point)
508 (progn (forward-sexp 1)
509 (point)))))))
510
511 (defvar lisp-mode-shared-map
512 (let ((map (make-sparse-keymap)))
513 (set-keymap-parent map prog-mode-map)
514 (define-key map "\e\C-q" 'indent-sexp)
515 (define-key map "\177" 'backward-delete-char-untabify)
516 ;; This gets in the way when viewing a Lisp file in view-mode. As
517 ;; long as [backspace] is mapped into DEL via the
518 ;; function-key-map, this should remain disabled!!
519 ;;;(define-key map [backspace] 'backward-delete-char-untabify)
520 map)
521 "Keymap for commands shared by all sorts of Lisp modes.")
522
523 (defvar emacs-lisp-mode-map
524 (let ((map (make-sparse-keymap "Emacs-Lisp"))
525 (menu-map (make-sparse-keymap "Emacs-Lisp"))
526 (lint-map (make-sparse-keymap))
527 (prof-map (make-sparse-keymap))
528 (tracing-map (make-sparse-keymap)))
529 (set-keymap-parent map lisp-mode-shared-map)
530 (define-key map "\e\t" 'completion-at-point)
531 (define-key map "\e\C-x" 'eval-defun)
532 (define-key map "\e\C-q" 'indent-pp-sexp)
533 (bindings--define-key map [menu-bar emacs-lisp]
534 (cons "Emacs-Lisp" menu-map))
535 (bindings--define-key menu-map [eldoc]
536 '(menu-item "Auto-Display Documentation Strings" eldoc-mode
537 :button (:toggle . (bound-and-true-p eldoc-mode))
538 :help "Display the documentation string for the item under cursor"))
539 (bindings--define-key menu-map [checkdoc]
540 '(menu-item "Check Documentation Strings" checkdoc
541 :help "Check documentation strings for style requirements"))
542 (bindings--define-key menu-map [re-builder]
543 '(menu-item "Construct Regexp" re-builder
544 :help "Construct a regexp interactively"))
545 (bindings--define-key menu-map [tracing] (cons "Tracing" tracing-map))
546 (bindings--define-key tracing-map [tr-a]
547 '(menu-item "Untrace All" untrace-all
548 :help "Untrace all currently traced functions"))
549 (bindings--define-key tracing-map [tr-uf]
550 '(menu-item "Untrace Function..." untrace-function
551 :help "Untrace function, and possibly activate all remaining advice"))
552 (bindings--define-key tracing-map [tr-sep] menu-bar-separator)
553 (bindings--define-key tracing-map [tr-q]
554 '(menu-item "Trace Function Quietly..." trace-function-background
555 :help "Trace the function with trace output going quietly to a buffer"))
556 (bindings--define-key tracing-map [tr-f]
557 '(menu-item "Trace Function..." trace-function
558 :help "Trace the function given as an argument"))
559 (bindings--define-key menu-map [profiling] (cons "Profiling" prof-map))
560 (bindings--define-key prof-map [prof-restall]
561 '(menu-item "Remove Instrumentation for All Functions" elp-restore-all
562 :help "Restore the original definitions of all functions being profiled"))
563 (bindings--define-key prof-map [prof-restfunc]
564 '(menu-item "Remove Instrumentation for Function..." elp-restore-function
565 :help "Restore an instrumented function to its original definition"))
566
567 (bindings--define-key prof-map [sep-rem] menu-bar-separator)
568 (bindings--define-key prof-map [prof-resall]
569 '(menu-item "Reset Counters for All Functions" elp-reset-all
570 :help "Reset the profiling information for all functions being profiled"))
571 (bindings--define-key prof-map [prof-resfunc]
572 '(menu-item "Reset Counters for Function..." elp-reset-function
573 :help "Reset the profiling information for a function"))
574 (bindings--define-key prof-map [prof-res]
575 '(menu-item "Show Profiling Results" elp-results
576 :help "Display current profiling results"))
577 (bindings--define-key prof-map [prof-pack]
578 '(menu-item "Instrument Package..." elp-instrument-package
579 :help "Instrument for profiling all function that start with a prefix"))
580 (bindings--define-key prof-map [prof-func]
581 '(menu-item "Instrument Function..." elp-instrument-function
582 :help "Instrument a function for profiling"))
583 ;; Maybe this should be in a separate submenu from the ELP stuff?
584 (bindings--define-key prof-map [sep-natprof] menu-bar-separator)
585 (bindings--define-key prof-map [prof-natprof-stop]
586 '(menu-item "Stop Native Profiler" profiler-stop
587 :help "Stop recording profiling information"
588 :enable (and (featurep 'profiler)
589 (profiler-running-p))))
590 (bindings--define-key prof-map [prof-natprof-report]
591 '(menu-item "Show Profiler Report" profiler-report
592 :help "Show the current profiler report"
593 :enable (and (featurep 'profiler)
594 (profiler-running-p))))
595 (bindings--define-key prof-map [prof-natprof-start]
596 '(menu-item "Start Native Profiler..." profiler-start
597 :help "Start recording profiling information"))
598
599 (bindings--define-key menu-map [lint] (cons "Linting" lint-map))
600 (bindings--define-key lint-map [lint-di]
601 '(menu-item "Lint Directory..." elint-directory
602 :help "Lint a directory"))
603 (bindings--define-key lint-map [lint-f]
604 '(menu-item "Lint File..." elint-file
605 :help "Lint a file"))
606 (bindings--define-key lint-map [lint-b]
607 '(menu-item "Lint Buffer" elint-current-buffer
608 :help "Lint the current buffer"))
609 (bindings--define-key lint-map [lint-d]
610 '(menu-item "Lint Defun" elint-defun
611 :help "Lint the function at point"))
612 (bindings--define-key menu-map [edebug-defun]
613 '(menu-item "Instrument Function for Debugging" edebug-defun
614 :help "Evaluate the top level form point is in, stepping through with Edebug"
615 :keys "C-u C-M-x"))
616 (bindings--define-key menu-map [separator-byte] menu-bar-separator)
617 (bindings--define-key menu-map [disas]
618 '(menu-item "Disassemble Byte Compiled Object..." disassemble
619 :help "Print disassembled code for OBJECT in a buffer"))
620 (bindings--define-key menu-map [byte-recompile]
621 '(menu-item "Byte-recompile Directory..." byte-recompile-directory
622 :help "Recompile every `.el' file in DIRECTORY that needs recompilation"))
623 (bindings--define-key menu-map [emacs-byte-compile-and-load]
624 '(menu-item "Byte-compile and Load" emacs-lisp-byte-compile-and-load
625 :help "Byte-compile the current file (if it has changed), then load compiled code"))
626 (bindings--define-key menu-map [byte-compile]
627 '(menu-item "Byte-compile This File" emacs-lisp-byte-compile
628 :help "Byte compile the file containing the current buffer"))
629 (bindings--define-key menu-map [separator-eval] menu-bar-separator)
630 (bindings--define-key menu-map [ielm]
631 '(menu-item "Interactive Expression Evaluation" ielm
632 :help "Interactively evaluate Emacs Lisp expressions"))
633 (bindings--define-key menu-map [eval-buffer]
634 '(menu-item "Evaluate Buffer" eval-buffer
635 :help "Execute the current buffer as Lisp code"))
636 (bindings--define-key menu-map [eval-region]
637 '(menu-item "Evaluate Region" eval-region
638 :help "Execute the region as Lisp code"
639 :enable mark-active))
640 (bindings--define-key menu-map [eval-sexp]
641 '(menu-item "Evaluate Last S-expression" eval-last-sexp
642 :help "Evaluate sexp before point; print value in echo area"))
643 (bindings--define-key menu-map [separator-format] menu-bar-separator)
644 (bindings--define-key menu-map [comment-region]
645 '(menu-item "Comment Out Region" comment-region
646 :help "Comment or uncomment each line in the region"
647 :enable mark-active))
648 (bindings--define-key menu-map [indent-region]
649 '(menu-item "Indent Region" indent-region
650 :help "Indent each nonblank line in the region"
651 :enable mark-active))
652 (bindings--define-key menu-map [indent-line]
653 '(menu-item "Indent Line" lisp-indent-line))
654 map)
655 "Keymap for Emacs Lisp mode.
656 All commands in `lisp-mode-shared-map' are inherited by this map.")
657
658 (defun emacs-lisp-byte-compile ()
659 "Byte compile the file containing the current buffer."
660 (interactive)
661 (if buffer-file-name
662 (byte-compile-file buffer-file-name)
663 (error "The buffer must be saved in a file first")))
664
665 (defun emacs-lisp-byte-compile-and-load ()
666 "Byte-compile the current file (if it has changed), then load compiled code."
667 (interactive)
668 (or buffer-file-name
669 (error "The buffer must be saved in a file first"))
670 (require 'bytecomp)
671 ;; Recompile if file or buffer has changed since last compilation.
672 (if (and (buffer-modified-p)
673 (y-or-n-p (format "Save buffer %s first? " (buffer-name))))
674 (save-buffer))
675 (byte-recompile-file buffer-file-name nil 0 t))
676
677 (defcustom emacs-lisp-mode-hook nil
678 "Hook run when entering Emacs Lisp mode."
679 :options '(eldoc-mode imenu-add-menubar-index checkdoc-minor-mode)
680 :type 'hook
681 :group 'lisp)
682
683 (defcustom lisp-mode-hook nil
684 "Hook run when entering Lisp mode."
685 :options '(imenu-add-menubar-index)
686 :type 'hook
687 :group 'lisp)
688
689 (defcustom lisp-interaction-mode-hook nil
690 "Hook run when entering Lisp Interaction mode."
691 :options '(eldoc-mode)
692 :type 'hook
693 :group 'lisp)
694
695 (defconst lisp--prettify-symbols-alist
696 '(("lambda" . ?λ)))
697
698 (define-derived-mode emacs-lisp-mode prog-mode "Emacs-Lisp"
699 "Major mode for editing Lisp code to run in Emacs.
700 Commands:
701 Delete converts tabs to spaces as it moves back.
702 Blank lines separate paragraphs. Semicolons start comments.
703
704 \\{emacs-lisp-mode-map}"
705 :group 'lisp
706 (lisp-mode-variables nil nil 'elisp)
707 (setq imenu-case-fold-search nil)
708 (add-hook 'completion-at-point-functions
709 'lisp-completion-at-point nil 'local))
710
711 ;;; Emacs Lisp Byte-Code mode
712
713 (eval-and-compile
714 (defconst emacs-list-byte-code-comment-re
715 (concat "\\(#\\)@\\([0-9]+\\) "
716 ;; Make sure it's a docstring and not a lazy-loaded byte-code.
717 "\\(?:[^(]\\|([^\"]\\)")))
718
719 (defun emacs-lisp-byte-code-comment (end &optional _point)
720 "Try to syntactically mark the #@NNN ....^_ docstrings in byte-code files."
721 (let ((ppss (syntax-ppss)))
722 (when (and (nth 4 ppss)
723 (eq (char-after (nth 8 ppss)) ?#))
724 (let* ((n (save-excursion
725 (goto-char (nth 8 ppss))
726 (when (looking-at emacs-list-byte-code-comment-re)
727 (string-to-number (match-string 2)))))
728 ;; `maxdiff' tries to make sure the loop below terminates.
729 (maxdiff n))
730 (when n
731 (let* ((bchar (match-end 2))
732 (b (position-bytes bchar)))
733 (goto-char (+ b n))
734 (while (let ((diff (- (position-bytes (point)) b n)))
735 (unless (zerop diff)
736 (when (> diff maxdiff) (setq diff maxdiff))
737 (forward-char (- diff))
738 (setq maxdiff (if (> diff 0) diff
739 (max (1- maxdiff) 1)))
740 t))))
741 (if (<= (point) end)
742 (put-text-property (1- (point)) (point)
743 'syntax-table
744 (string-to-syntax "> b"))
745 (goto-char end)))))))
746
747 (defun emacs-lisp-byte-code-syntax-propertize (start end)
748 (emacs-lisp-byte-code-comment end (point))
749 (funcall
750 (syntax-propertize-rules
751 (emacs-list-byte-code-comment-re
752 (1 (prog1 "< b" (emacs-lisp-byte-code-comment end (point))))))
753 start end))
754
755 (add-to-list 'auto-mode-alist '("\\.elc\\'" . emacs-lisp-byte-code-mode))
756 (define-derived-mode emacs-lisp-byte-code-mode emacs-lisp-mode
757 "Elisp-Byte-Code"
758 "Major mode for *.elc files."
759 ;; TODO: Add way to disassemble byte-code under point.
760 (setq-local open-paren-in-column-0-is-defun-start nil)
761 (setq-local syntax-propertize-function
762 #'emacs-lisp-byte-code-syntax-propertize))
763
764 ;;; Generic Lisp mode.
765
766 (defvar lisp-mode-map
767 (let ((map (make-sparse-keymap))
768 (menu-map (make-sparse-keymap "Lisp")))
769 (set-keymap-parent map lisp-mode-shared-map)
770 (define-key map "\e\C-x" 'lisp-eval-defun)
771 (define-key map "\C-c\C-z" 'run-lisp)
772 (bindings--define-key map [menu-bar lisp] (cons "Lisp" menu-map))
773 (bindings--define-key menu-map [run-lisp]
774 '(menu-item "Run inferior Lisp" run-lisp
775 :help "Run an inferior Lisp process, input and output via buffer `*inferior-lisp*'"))
776 (bindings--define-key menu-map [ev-def]
777 '(menu-item "Eval defun" lisp-eval-defun
778 :help "Send the current defun to the Lisp process made by M-x run-lisp"))
779 (bindings--define-key menu-map [ind-sexp]
780 '(menu-item "Indent sexp" indent-sexp
781 :help "Indent each line of the list starting just after point"))
782 map)
783 "Keymap for ordinary Lisp mode.
784 All commands in `lisp-mode-shared-map' are inherited by this map.")
785
786 (define-derived-mode lisp-mode prog-mode "Lisp"
787 "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
788 Commands:
789 Delete converts tabs to spaces as it moves back.
790 Blank lines separate paragraphs. Semicolons start comments.
791
792 \\{lisp-mode-map}
793 Note that `run-lisp' may be used either to start an inferior Lisp job
794 or to switch back to an existing one."
795 (lisp-mode-variables nil t)
796 (setq-local find-tag-default-function 'lisp-find-tag-default)
797 (setq-local comment-start-skip
798 "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
799 (setq imenu-case-fold-search t))
800
801 (defun lisp-find-tag-default ()
802 (let ((default (find-tag-default)))
803 (when (stringp default)
804 (if (string-match ":+" default)
805 (substring default (match-end 0))
806 default))))
807
808 ;; Used in old LispM code.
809 (defalias 'common-lisp-mode 'lisp-mode)
810
811 ;; This will do unless inf-lisp.el is loaded.
812 (defun lisp-eval-defun (&optional _and-go)
813 "Send the current defun to the Lisp process made by \\[run-lisp]."
814 (interactive)
815 (error "Process lisp does not exist"))
816
817 (defvar lisp-interaction-mode-map
818 (let ((map (make-sparse-keymap))
819 (menu-map (make-sparse-keymap "Lisp-Interaction")))
820 (set-keymap-parent map lisp-mode-shared-map)
821 (define-key map "\e\C-x" 'eval-defun)
822 (define-key map "\e\C-q" 'indent-pp-sexp)
823 (define-key map "\e\t" 'completion-at-point)
824 (define-key map "\n" 'eval-print-last-sexp)
825 (bindings--define-key map [menu-bar lisp-interaction]
826 (cons "Lisp-Interaction" menu-map))
827 (bindings--define-key menu-map [eval-defun]
828 '(menu-item "Evaluate Defun" eval-defun
829 :help "Evaluate the top-level form containing point, or after point"))
830 (bindings--define-key menu-map [eval-print-last-sexp]
831 '(menu-item "Evaluate and Print" eval-print-last-sexp
832 :help "Evaluate sexp before point; print value into current buffer"))
833 (bindings--define-key menu-map [edebug-defun-lisp-interaction]
834 '(menu-item "Instrument Function for Debugging" edebug-defun
835 :help "Evaluate the top level form point is in, stepping through with Edebug"
836 :keys "C-u C-M-x"))
837 (bindings--define-key menu-map [indent-pp-sexp]
838 '(menu-item "Indent or Pretty-Print" indent-pp-sexp
839 :help "Indent each line of the list starting just after point, or prettyprint it"))
840 (bindings--define-key menu-map [complete-symbol]
841 '(menu-item "Complete Lisp Symbol" completion-at-point
842 :help "Perform completion on Lisp symbol preceding point"))
843 map)
844 "Keymap for Lisp Interaction mode.
845 All commands in `lisp-mode-shared-map' are inherited by this map.")
846
847 (define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
848 "Major mode for typing and evaluating Lisp forms.
849 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
850 before point, and prints its value into the buffer, advancing point.
851 Note that printing is controlled by `eval-expression-print-length'
852 and `eval-expression-print-level'.
853
854 Commands:
855 Delete converts tabs to spaces as it moves back.
856 Paragraphs are separated only by blank lines.
857 Semicolons start comments.
858
859 \\{lisp-interaction-mode-map}"
860 :abbrev-table nil)
861
862 (defun eval-print-last-sexp (&optional eval-last-sexp-arg-internal)
863 "Evaluate sexp before point; print value into current buffer.
864
865 Normally, this function truncates long output according to the value
866 of the variables `eval-expression-print-length' and
867 `eval-expression-print-level'. With a prefix argument of zero,
868 however, there is no such truncation. Such a prefix argument
869 also causes integers to be printed in several additional formats
870 \(octal, hexadecimal, and character).
871
872 If `eval-expression-debug-on-error' is non-nil, which is the default,
873 this command arranges for all errors to enter the debugger."
874 (interactive "P")
875 (let ((standard-output (current-buffer)))
876 (terpri)
877 (eval-last-sexp (or eval-last-sexp-arg-internal t))
878 (terpri)))
879
880
881 (defun last-sexp-setup-props (beg end value alt1 alt2)
882 "Set up text properties for the output of `eval-last-sexp-1'.
883 BEG and END are the start and end of the output in current-buffer.
884 VALUE is the Lisp value printed, ALT1 and ALT2 are strings for the
885 alternative printed representations that can be displayed."
886 (let ((map (make-sparse-keymap)))
887 (define-key map "\C-m" 'last-sexp-toggle-display)
888 (define-key map [down-mouse-2] 'mouse-set-point)
889 (define-key map [mouse-2] 'last-sexp-toggle-display)
890 (add-text-properties
891 beg end
892 `(printed-value (,value ,alt1 ,alt2)
893 mouse-face highlight
894 keymap ,map
895 help-echo "RET, mouse-2: toggle abbreviated display"
896 rear-nonsticky (mouse-face keymap help-echo
897 printed-value)))))
898
899
900 (defun last-sexp-toggle-display (&optional _arg)
901 "Toggle between abbreviated and unabbreviated printed representations."
902 (interactive "P")
903 (save-restriction
904 (widen)
905 (let ((value (get-text-property (point) 'printed-value)))
906 (when value
907 (let ((beg (or (previous-single-property-change (min (point-max) (1+ (point)))
908 'printed-value)
909 (point)))
910 (end (or (next-single-char-property-change (point) 'printed-value) (point)))
911 (standard-output (current-buffer))
912 (point (point)))
913 (delete-region beg end)
914 (insert (nth 1 value))
915 (or (= beg point)
916 (setq point (1- (point))))
917 (last-sexp-setup-props beg (point)
918 (nth 0 value)
919 (nth 2 value)
920 (nth 1 value))
921 (goto-char (min (point-max) point)))))))
922
923 (defun prin1-char (char)
924 "Return a string representing CHAR as a character rather than as an integer.
925 If CHAR is not a character, return nil."
926 (and (integerp char)
927 (eventp char)
928 (let ((c (event-basic-type char))
929 (mods (event-modifiers char))
930 string)
931 ;; Prevent ?A from turning into ?\S-a.
932 (if (and (memq 'shift mods)
933 (zerop (logand char ?\S-\^@))
934 (not (let ((case-fold-search nil))
935 (char-equal c (upcase c)))))
936 (setq c (upcase c) mods nil))
937 ;; What string are we considering using?
938 (condition-case nil
939 (setq string
940 (concat
941 "?"
942 (mapconcat
943 (lambda (modif)
944 (cond ((eq modif 'super) "\\s-")
945 (t (string ?\\ (upcase (aref (symbol-name modif) 0)) ?-))))
946 mods "")
947 (cond
948 ((memq c '(?\; ?\( ?\) ?\{ ?\} ?\[ ?\] ?\" ?\' ?\\)) (string ?\\ c))
949 ((eq c 127) "\\C-?")
950 (t
951 (string c)))))
952 (error nil))
953 ;; Verify the string reads a CHAR, not to some other character.
954 ;; If it doesn't, return nil instead.
955 (and string
956 (= (car (read-from-string string)) char)
957 string))))
958
959
960 (defun preceding-sexp ()
961 "Return sexp before the point."
962 (let ((opoint (point))
963 ignore-quotes
964 expr)
965 (save-excursion
966 (with-syntax-table emacs-lisp-mode-syntax-table
967 ;; If this sexp appears to be enclosed in `...'
968 ;; then ignore the surrounding quotes.
969 (setq ignore-quotes
970 (or (eq (following-char) ?\')
971 (eq (preceding-char) ?\')))
972 (forward-sexp -1)
973 ;; If we were after `?\e' (or similar case),
974 ;; use the whole thing, not just the `e'.
975 (when (eq (preceding-char) ?\\)
976 (forward-char -1)
977 (when (eq (preceding-char) ??)
978 (forward-char -1)))
979
980 ;; Skip over hash table read syntax.
981 (and (> (point) (1+ (point-min)))
982 (looking-back "#s" (- (point) 2))
983 (forward-char -2))
984
985 ;; Skip over `#N='s.
986 (when (eq (preceding-char) ?=)
987 (let (labeled-p)
988 (save-excursion
989 (skip-chars-backward "0-9#=")
990 (setq labeled-p (looking-at "\\(#[0-9]+=\\)+")))
991 (when labeled-p
992 (forward-sexp -1))))
993
994 (save-restriction
995 ;; vladimir@cs.ualberta.ca 30-Jul-1997: skip ` in
996 ;; `variable' so that the value is returned, not the
997 ;; name
998 (if (and ignore-quotes
999 (eq (following-char) ?`))
1000 (forward-char))
1001 (narrow-to-region (point-min) opoint)
1002 (setq expr (read (current-buffer)))
1003 ;; If it's an (interactive ...) form, it's more
1004 ;; useful to show how an interactive call would
1005 ;; use it.
1006 (and (consp expr)
1007 (eq (car expr) 'interactive)
1008 (setq expr
1009 (list 'call-interactively
1010 (list 'quote
1011 (list 'lambda
1012 '(&rest args)
1013 expr
1014 'args)))))
1015 expr)))))
1016
1017
1018 (defun eval-last-sexp-1 (eval-last-sexp-arg-internal)
1019 "Evaluate sexp before point; print value in the echo area.
1020 With argument, print output into current buffer.
1021 With a zero prefix arg, print output with no limit on the length
1022 and level of lists, and include additional formats for integers
1023 \(octal, hexadecimal, and character)."
1024 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
1025 ;; Setup the lexical environment if lexical-binding is enabled.
1026 (eval-last-sexp-print-value
1027 (eval (eval-sexp-add-defvars (preceding-sexp)) lexical-binding)
1028 eval-last-sexp-arg-internal)))
1029
1030
1031 (defun eval-last-sexp-print-value (value &optional eval-last-sexp-arg-internal)
1032 (let ((unabbreviated (let ((print-length nil) (print-level nil))
1033 (prin1-to-string value)))
1034 (print-length (and (not (zerop (prefix-numeric-value
1035 eval-last-sexp-arg-internal)))
1036 eval-expression-print-length))
1037 (print-level (and (not (zerop (prefix-numeric-value
1038 eval-last-sexp-arg-internal)))
1039 eval-expression-print-level))
1040 (beg (point))
1041 end)
1042 (prog1
1043 (prin1 value)
1044 (let ((str (eval-expression-print-format value)))
1045 (if str (princ str)))
1046 (setq end (point))
1047 (when (and (bufferp standard-output)
1048 (or (not (null print-length))
1049 (not (null print-level)))
1050 (not (string= unabbreviated
1051 (buffer-substring-no-properties beg end))))
1052 (last-sexp-setup-props beg end value
1053 unabbreviated
1054 (buffer-substring-no-properties beg end))
1055 ))))
1056
1057
1058 (defvar eval-last-sexp-fake-value (make-symbol "t"))
1059
1060 (defun eval-sexp-add-defvars (exp &optional pos)
1061 "Prepend EXP with all the `defvar's that precede it in the buffer.
1062 POS specifies the starting position where EXP was found and defaults to point."
1063 (setq exp (macroexpand-all exp)) ;Eager macro-expansion.
1064 (if (not lexical-binding)
1065 exp
1066 (save-excursion
1067 (unless pos (setq pos (point)))
1068 (let ((vars ()))
1069 (goto-char (point-min))
1070 (while (re-search-forward
1071 "(def\\(?:var\\|const\\|custom\\)[ \t\n]+\\([^; '()\n\t]+\\)"
1072 pos t)
1073 (let ((var (intern (match-string 1))))
1074 (and (not (special-variable-p var))
1075 (save-excursion
1076 (zerop (car (syntax-ppss (match-beginning 0)))))
1077 (push var vars))))
1078 `(progn ,@(mapcar (lambda (v) `(defvar ,v)) vars) ,exp)))))
1079
1080 (defun eval-last-sexp (eval-last-sexp-arg-internal)
1081 "Evaluate sexp before point; print value in the echo area.
1082 Interactively, with prefix argument, print output into current buffer.
1083
1084 Normally, this function truncates long output according to the value
1085 of the variables `eval-expression-print-length' and
1086 `eval-expression-print-level'. With a prefix argument of zero,
1087 however, there is no such truncation. Such a prefix argument
1088 also causes integers to be printed in several additional formats
1089 \(octal, hexadecimal, and character).
1090
1091 If `eval-expression-debug-on-error' is non-nil, which is the default,
1092 this command arranges for all errors to enter the debugger."
1093 (interactive "P")
1094 (if (null eval-expression-debug-on-error)
1095 (eval-last-sexp-1 eval-last-sexp-arg-internal)
1096 (let ((value
1097 (let ((debug-on-error eval-last-sexp-fake-value))
1098 (cons (eval-last-sexp-1 eval-last-sexp-arg-internal)
1099 debug-on-error))))
1100 (unless (eq (cdr value) eval-last-sexp-fake-value)
1101 (setq debug-on-error (cdr value)))
1102 (car value))))
1103
1104 (defun eval-defun-1 (form)
1105 "Treat some expressions specially.
1106 Reset the `defvar' and `defcustom' variables to the initial value.
1107 \(For `defcustom', use the :set function if there is one.)
1108 Reinitialize the face according to the `defface' specification."
1109 ;; The code in edebug-defun should be consistent with this, but not
1110 ;; the same, since this gets a macroexpanded form.
1111 (cond ((not (listp form))
1112 form)
1113 ((and (eq (car form) 'defvar)
1114 (cdr-safe (cdr-safe form))
1115 (boundp (cadr form)))
1116 ;; Force variable to be re-set.
1117 `(progn (defvar ,(nth 1 form) nil ,@(nthcdr 3 form))
1118 (setq-default ,(nth 1 form) ,(nth 2 form))))
1119 ;; `defcustom' is now macroexpanded to
1120 ;; `custom-declare-variable' with a quoted value arg.
1121 ((and (eq (car form) 'custom-declare-variable)
1122 (default-boundp (eval (nth 1 form) lexical-binding)))
1123 ;; Force variable to be bound, using :set function if specified.
1124 (let ((setfunc (memq :set form)))
1125 (when setfunc
1126 (setq setfunc (car-safe (cdr-safe setfunc)))
1127 (or (functionp setfunc) (setq setfunc nil)))
1128 (funcall (or setfunc 'set-default)
1129 (eval (nth 1 form) lexical-binding)
1130 ;; The second arg is an expression that evaluates to
1131 ;; an expression. The second evaluation is the one
1132 ;; normally performed not by normal execution but by
1133 ;; custom-initialize-set (for example), which does not
1134 ;; use lexical-binding.
1135 (eval (eval (nth 2 form) lexical-binding))))
1136 form)
1137 ;; `defface' is macroexpanded to `custom-declare-face'.
1138 ((eq (car form) 'custom-declare-face)
1139 ;; Reset the face.
1140 (let ((face-symbol (eval (nth 1 form) lexical-binding)))
1141 (setq face-new-frame-defaults
1142 (assq-delete-all face-symbol face-new-frame-defaults))
1143 (put face-symbol 'face-defface-spec nil)
1144 (put face-symbol 'face-override-spec nil))
1145 form)
1146 ((eq (car form) 'progn)
1147 (cons 'progn (mapcar 'eval-defun-1 (cdr form))))
1148 (t form)))
1149
1150 (defun eval-defun-2 ()
1151 "Evaluate defun that point is in or before.
1152 The value is displayed in the echo area.
1153 If the current defun is actually a call to `defvar',
1154 then reset the variable using the initial value expression
1155 even if the variable already has some other value.
1156 \(Normally `defvar' does not change the variable's value
1157 if it already has a value.\)
1158
1159 Return the result of evaluation."
1160 ;; FIXME: the print-length/level bindings should only be applied while
1161 ;; printing, not while evaluating.
1162 (let ((debug-on-error eval-expression-debug-on-error)
1163 (print-length eval-expression-print-length)
1164 (print-level eval-expression-print-level))
1165 (save-excursion
1166 ;; Arrange for eval-region to "read" the (possibly) altered form.
1167 ;; eval-region handles recording which file defines a function or
1168 ;; variable.
1169 (let ((standard-output t)
1170 beg end form)
1171 ;; Read the form from the buffer, and record where it ends.
1172 (save-excursion
1173 (end-of-defun)
1174 (beginning-of-defun)
1175 (setq beg (point))
1176 (setq form (read (current-buffer)))
1177 (setq end (point)))
1178 ;; Alter the form if necessary.
1179 (let ((form (eval-sexp-add-defvars
1180 (eval-defun-1 (macroexpand form)))))
1181 (eval-region beg end standard-output
1182 (lambda (_ignore)
1183 ;; Skipping to the end of the specified region
1184 ;; will make eval-region return.
1185 (goto-char end)
1186 form))))))
1187 (let ((str (eval-expression-print-format (car values))))
1188 (if str (princ str)))
1189 ;; The result of evaluation has been put onto VALUES. So return it.
1190 (car values))
1191
1192 (defun eval-defun (edebug-it)
1193 "Evaluate the top-level form containing point, or after point.
1194
1195 If the current defun is actually a call to `defvar' or `defcustom',
1196 evaluating it this way resets the variable using its initial value
1197 expression (using the defcustom's :set function if there is one), even
1198 if the variable already has some other value. \(Normally `defvar' and
1199 `defcustom' do not alter the value if there already is one.) In an
1200 analogous way, evaluating a `defface' overrides any customizations of
1201 the face, so that it becomes defined exactly as the `defface' expression
1202 says.
1203
1204 If `eval-expression-debug-on-error' is non-nil, which is the default,
1205 this command arranges for all errors to enter the debugger.
1206
1207 With a prefix argument, instrument the code for Edebug.
1208
1209 If acting on a `defun' for FUNCTION, and the function was
1210 instrumented, `Edebug: FUNCTION' is printed in the echo area. If not
1211 instrumented, just FUNCTION is printed.
1212
1213 If not acting on a `defun', the result of evaluation is displayed in
1214 the echo area. This display is controlled by the variables
1215 `eval-expression-print-length' and `eval-expression-print-level',
1216 which see."
1217 (interactive "P")
1218 (cond (edebug-it
1219 (require 'edebug)
1220 (eval-defun (not edebug-all-defs)))
1221 (t
1222 (if (null eval-expression-debug-on-error)
1223 (eval-defun-2)
1224 (let ((old-value (make-symbol "t")) new-value value)
1225 (let ((debug-on-error old-value))
1226 (setq value (eval-defun-2))
1227 (setq new-value debug-on-error))
1228 (unless (eq old-value new-value)
1229 (setq debug-on-error new-value))
1230 value)))))
1231
1232 ;; May still be used by some external Lisp-mode variant.
1233 (define-obsolete-function-alias 'lisp-comment-indent
1234 'comment-indent-default "22.1")
1235 (define-obsolete-function-alias 'lisp-mode-auto-fill 'do-auto-fill "23.1")
1236
1237 (defcustom lisp-indent-offset nil
1238 "If non-nil, indent second line of expressions that many more columns."
1239 :group 'lisp
1240 :type '(choice (const nil) integer))
1241 (put 'lisp-indent-offset 'safe-local-variable
1242 (lambda (x) (or (null x) (integerp x))))
1243
1244 (defcustom lisp-indent-function 'lisp-indent-function
1245 "A function to be called by `calculate-lisp-indent'.
1246 It indents the arguments of a Lisp function call. This function
1247 should accept two arguments: the indent-point, and the
1248 `parse-partial-sexp' state at that position. One option for this
1249 function is `common-lisp-indent-function'."
1250 :type 'function
1251 :group 'lisp)
1252
1253 (defun lisp-indent-line (&optional _whole-exp)
1254 "Indent current line as Lisp code.
1255 With argument, indent any additional lines of the same expression
1256 rigidly along with this one."
1257 (interactive "P")
1258 (let ((indent (calculate-lisp-indent)) shift-amt
1259 (pos (- (point-max) (point)))
1260 (beg (progn (beginning-of-line) (point))))
1261 (skip-chars-forward " \t")
1262 (if (or (null indent) (looking-at "\\s<\\s<\\s<"))
1263 ;; Don't alter indentation of a ;;; comment line
1264 ;; or a line that starts in a string.
1265 ;; FIXME: inconsistency: comment-indent moves ;;; to column 0.
1266 (goto-char (- (point-max) pos))
1267 (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
1268 ;; Single-semicolon comment lines should be indented
1269 ;; as comment lines, not as code.
1270 (progn (indent-for-comment) (forward-char -1))
1271 (if (listp indent) (setq indent (car indent)))
1272 (setq shift-amt (- indent (current-column)))
1273 (if (zerop shift-amt)
1274 nil
1275 (delete-region beg (point))
1276 (indent-to indent)))
1277 ;; If initial point was within line's indentation,
1278 ;; position after the indentation. Else stay at same point in text.
1279 (if (> (- (point-max) pos) (point))
1280 (goto-char (- (point-max) pos))))))
1281
1282 (defvar calculate-lisp-indent-last-sexp)
1283
1284 (defun calculate-lisp-indent (&optional parse-start)
1285 "Return appropriate indentation for current line as Lisp code.
1286 In usual case returns an integer: the column to indent to.
1287 If the value is nil, that means don't change the indentation
1288 because the line starts inside a string.
1289
1290 The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
1291 This means that following lines at the same level of indentation
1292 should not necessarily be indented the same as this line.
1293 Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
1294 is the buffer position of the start of the containing expression."
1295 (save-excursion
1296 (beginning-of-line)
1297 (let ((indent-point (point))
1298 state
1299 ;; setting this to a number inhibits calling hook
1300 (desired-indent nil)
1301 (retry t)
1302 calculate-lisp-indent-last-sexp containing-sexp)
1303 (if parse-start
1304 (goto-char parse-start)
1305 (beginning-of-defun))
1306 ;; Find outermost containing sexp
1307 (while (< (point) indent-point)
1308 (setq state (parse-partial-sexp (point) indent-point 0)))
1309 ;; Find innermost containing sexp
1310 (while (and retry
1311 state
1312 (> (elt state 0) 0))
1313 (setq retry nil)
1314 (setq calculate-lisp-indent-last-sexp (elt state 2))
1315 (setq containing-sexp (elt state 1))
1316 ;; Position following last unclosed open.
1317 (goto-char (1+ containing-sexp))
1318 ;; Is there a complete sexp since then?
1319 (if (and calculate-lisp-indent-last-sexp
1320 (> calculate-lisp-indent-last-sexp (point)))
1321 ;; Yes, but is there a containing sexp after that?
1322 (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
1323 indent-point 0)))
1324 (if (setq retry (car (cdr peek))) (setq state peek)))))
1325 (if retry
1326 nil
1327 ;; Innermost containing sexp found
1328 (goto-char (1+ containing-sexp))
1329 (if (not calculate-lisp-indent-last-sexp)
1330 ;; indent-point immediately follows open paren.
1331 ;; Don't call hook.
1332 (setq desired-indent (current-column))
1333 ;; Find the start of first element of containing sexp.
1334 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1335 (cond ((looking-at "\\s(")
1336 ;; First element of containing sexp is a list.
1337 ;; Indent under that list.
1338 )
1339 ((> (save-excursion (forward-line 1) (point))
1340 calculate-lisp-indent-last-sexp)
1341 ;; This is the first line to start within the containing sexp.
1342 ;; It's almost certainly a function call.
1343 (if (= (point) calculate-lisp-indent-last-sexp)
1344 ;; Containing sexp has nothing before this line
1345 ;; except the first element. Indent under that element.
1346 nil
1347 ;; Skip the first element, find start of second (the first
1348 ;; argument of the function call) and indent under.
1349 (progn (forward-sexp 1)
1350 (parse-partial-sexp (point)
1351 calculate-lisp-indent-last-sexp
1352 0 t)))
1353 (backward-prefix-chars))
1354 (t
1355 ;; Indent beneath first sexp on same line as
1356 ;; `calculate-lisp-indent-last-sexp'. Again, it's
1357 ;; almost certainly a function call.
1358 (goto-char calculate-lisp-indent-last-sexp)
1359 (beginning-of-line)
1360 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
1361 0 t)
1362 (backward-prefix-chars)))))
1363 ;; Point is at the point to indent under unless we are inside a string.
1364 ;; Call indentation hook except when overridden by lisp-indent-offset
1365 ;; or if the desired indentation has already been computed.
1366 (let ((normal-indent (current-column)))
1367 (cond ((elt state 3)
1368 ;; Inside a string, don't change indentation.
1369 nil)
1370 ((and (integerp lisp-indent-offset) containing-sexp)
1371 ;; Indent by constant offset
1372 (goto-char containing-sexp)
1373 (+ (current-column) lisp-indent-offset))
1374 ;; in this case calculate-lisp-indent-last-sexp is not nil
1375 (calculate-lisp-indent-last-sexp
1376 (or
1377 ;; try to align the parameters of a known function
1378 (and lisp-indent-function
1379 (not retry)
1380 (funcall lisp-indent-function indent-point state))
1381 ;; If the function has no special alignment
1382 ;; or it does not apply to this argument,
1383 ;; try to align a constant-symbol under the last
1384 ;; preceding constant symbol, if there is such one of
1385 ;; the last 2 preceding symbols, in the previous
1386 ;; uncommented line.
1387 (and (save-excursion
1388 (goto-char indent-point)
1389 (skip-chars-forward " \t")
1390 (looking-at ":"))
1391 ;; The last sexp may not be at the indentation
1392 ;; where it begins, so find that one, instead.
1393 (save-excursion
1394 (goto-char calculate-lisp-indent-last-sexp)
1395 ;; Handle prefix characters and whitespace
1396 ;; following an open paren. (Bug#1012)
1397 (backward-prefix-chars)
1398 (while (and (not (looking-back "^[ \t]*\\|([ \t]+"))
1399 (or (not containing-sexp)
1400 (< (1+ containing-sexp) (point))))
1401 (forward-sexp -1)
1402 (backward-prefix-chars))
1403 (setq calculate-lisp-indent-last-sexp (point)))
1404 (> calculate-lisp-indent-last-sexp
1405 (save-excursion
1406 (goto-char (1+ containing-sexp))
1407 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1408 (point)))
1409 (let ((parse-sexp-ignore-comments t)
1410 indent)
1411 (goto-char calculate-lisp-indent-last-sexp)
1412 (or (and (looking-at ":")
1413 (setq indent (current-column)))
1414 (and (< (line-beginning-position)
1415 (prog2 (backward-sexp) (point)))
1416 (looking-at ":")
1417 (setq indent (current-column))))
1418 indent))
1419 ;; another symbols or constants not preceded by a constant
1420 ;; as defined above.
1421 normal-indent))
1422 ;; in this case calculate-lisp-indent-last-sexp is nil
1423 (desired-indent)
1424 (t
1425 normal-indent))))))
1426
1427 (defun lisp-indent-function (indent-point state)
1428 "This function is the normal value of the variable `lisp-indent-function'.
1429 The function `calculate-lisp-indent' calls this to determine
1430 if the arguments of a Lisp function call should be indented specially.
1431
1432 INDENT-POINT is the position at which the line being indented begins.
1433 Point is located at the point to indent under (for default indentation);
1434 STATE is the `parse-partial-sexp' state for that position.
1435
1436 If the current line is in a call to a Lisp function that has a non-nil
1437 property `lisp-indent-function' (or the deprecated `lisp-indent-hook'),
1438 it specifies how to indent. The property value can be:
1439
1440 * `defun', meaning indent `defun'-style
1441 \(this is also the case if there is no property and the function
1442 has a name that begins with \"def\", and three or more arguments);
1443
1444 * an integer N, meaning indent the first N arguments specially
1445 (like ordinary function arguments), and then indent any further
1446 arguments like a body;
1447
1448 * a function to call that returns the indentation (or nil).
1449 `lisp-indent-function' calls this function with the same two arguments
1450 that it itself received.
1451
1452 This function returns either the indentation to use, or nil if the
1453 Lisp function does not specify a special indentation."
1454 (let ((normal-indent (current-column)))
1455 (goto-char (1+ (elt state 1)))
1456 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1457 (if (and (elt state 2)
1458 (not (looking-at "\\sw\\|\\s_")))
1459 ;; car of form doesn't seem to be a symbol
1460 (progn
1461 (if (not (> (save-excursion (forward-line 1) (point))
1462 calculate-lisp-indent-last-sexp))
1463 (progn (goto-char calculate-lisp-indent-last-sexp)
1464 (beginning-of-line)
1465 (parse-partial-sexp (point)
1466 calculate-lisp-indent-last-sexp 0 t)))
1467 ;; Indent under the list or under the first sexp on the same
1468 ;; line as calculate-lisp-indent-last-sexp. Note that first
1469 ;; thing on that line has to be complete sexp since we are
1470 ;; inside the innermost containing sexp.
1471 (backward-prefix-chars)
1472 (current-column))
1473 (let ((function (buffer-substring (point)
1474 (progn (forward-sexp 1) (point))))
1475 method)
1476 (setq method (or (function-get (intern-soft function)
1477 'lisp-indent-function)
1478 (get (intern-soft function) 'lisp-indent-hook)))
1479 (cond ((or (eq method 'defun)
1480 (and (null method)
1481 (> (length function) 3)
1482 (string-match "\\`def" function)))
1483 (lisp-indent-defform state indent-point))
1484 ((integerp method)
1485 (lisp-indent-specform method state
1486 indent-point normal-indent))
1487 (method
1488 (funcall method indent-point state)))))))
1489
1490 (defcustom lisp-body-indent 2
1491 "Number of columns to indent the second line of a `(def...)' form."
1492 :group 'lisp
1493 :type 'integer)
1494 (put 'lisp-body-indent 'safe-local-variable 'integerp)
1495
1496 (defun lisp-indent-specform (count state indent-point normal-indent)
1497 (let ((containing-form-start (elt state 1))
1498 (i count)
1499 body-indent containing-form-column)
1500 ;; Move to the start of containing form, calculate indentation
1501 ;; to use for non-distinguished forms (> count), and move past the
1502 ;; function symbol. lisp-indent-function guarantees that there is at
1503 ;; least one word or symbol character following open paren of containing
1504 ;; form.
1505 (goto-char containing-form-start)
1506 (setq containing-form-column (current-column))
1507 (setq body-indent (+ lisp-body-indent containing-form-column))
1508 (forward-char 1)
1509 (forward-sexp 1)
1510 ;; Now find the start of the last form.
1511 (parse-partial-sexp (point) indent-point 1 t)
1512 (while (and (< (point) indent-point)
1513 (condition-case ()
1514 (progn
1515 (setq count (1- count))
1516 (forward-sexp 1)
1517 (parse-partial-sexp (point) indent-point 1 t))
1518 (error nil))))
1519 ;; Point is sitting on first character of last (or count) sexp.
1520 (if (> count 0)
1521 ;; A distinguished form. If it is the first or second form use double
1522 ;; lisp-body-indent, else normal indent. With lisp-body-indent bound
1523 ;; to 2 (the default), this just happens to work the same with if as
1524 ;; the older code, but it makes unwind-protect, condition-case,
1525 ;; with-output-to-temp-buffer, et. al. much more tasteful. The older,
1526 ;; less hacked, behavior can be obtained by replacing below with
1527 ;; (list normal-indent containing-form-start).
1528 (if (<= (- i count) 1)
1529 (list (+ containing-form-column (* 2 lisp-body-indent))
1530 containing-form-start)
1531 (list normal-indent containing-form-start))
1532 ;; A non-distinguished form. Use body-indent if there are no
1533 ;; distinguished forms and this is the first undistinguished form,
1534 ;; or if this is the first undistinguished form and the preceding
1535 ;; distinguished form has indentation at least as great as body-indent.
1536 (if (or (and (= i 0) (= count 0))
1537 (and (= count 0) (<= body-indent normal-indent)))
1538 body-indent
1539 normal-indent))))
1540
1541 (defun lisp-indent-defform (state _indent-point)
1542 (goto-char (car (cdr state)))
1543 (forward-line 1)
1544 (if (> (point) (car (cdr (cdr state))))
1545 (progn
1546 (goto-char (car (cdr state)))
1547 (+ lisp-body-indent (current-column)))))
1548
1549
1550 ;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
1551 ;; like defun if the first form is placed on the next line, otherwise
1552 ;; it is indented like any other form (i.e. forms line up under first).
1553
1554 (put 'autoload 'lisp-indent-function 'defun)
1555 (put 'progn 'lisp-indent-function 0)
1556 (put 'prog1 'lisp-indent-function 1)
1557 (put 'prog2 'lisp-indent-function 2)
1558 (put 'save-excursion 'lisp-indent-function 0)
1559 (put 'save-restriction 'lisp-indent-function 0)
1560 (put 'save-current-buffer 'lisp-indent-function 0)
1561 (put 'let 'lisp-indent-function 1)
1562 (put 'let* 'lisp-indent-function 1)
1563 (put 'while 'lisp-indent-function 1)
1564 (put 'if 'lisp-indent-function 2)
1565 (put 'catch 'lisp-indent-function 1)
1566 (put 'condition-case 'lisp-indent-function 2)
1567 (put 'unwind-protect 'lisp-indent-function 1)
1568 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
1569
1570 (defun indent-sexp (&optional endpos)
1571 "Indent each line of the list starting just after point.
1572 If optional arg ENDPOS is given, indent each line, stopping when
1573 ENDPOS is encountered."
1574 (interactive)
1575 (let ((indent-stack (list nil))
1576 (next-depth 0)
1577 ;; If ENDPOS is non-nil, use nil as STARTING-POINT
1578 ;; so that calculate-lisp-indent will find the beginning of
1579 ;; the defun we are in.
1580 ;; If ENDPOS is nil, it is safe not to scan before point
1581 ;; since every line we indent is more deeply nested than point is.
1582 (starting-point (if endpos nil (point)))
1583 (last-point (point))
1584 last-depth bol outer-loop-done inner-loop-done state this-indent)
1585 (or endpos
1586 ;; Get error now if we don't have a complete sexp after point.
1587 (save-excursion (forward-sexp 1)))
1588 (save-excursion
1589 (setq outer-loop-done nil)
1590 (while (if endpos (< (point) endpos)
1591 (not outer-loop-done))
1592 (setq last-depth next-depth
1593 inner-loop-done nil)
1594 ;; Parse this line so we can learn the state
1595 ;; to indent the next line.
1596 ;; This inner loop goes through only once
1597 ;; unless a line ends inside a string.
1598 (while (and (not inner-loop-done)
1599 (not (setq outer-loop-done (eobp))))
1600 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
1601 nil nil state))
1602 (setq next-depth (car state))
1603 ;; If the line contains a comment other than the sort
1604 ;; that is indented like code,
1605 ;; indent it now with indent-for-comment.
1606 ;; Comments indented like code are right already.
1607 ;; In any case clear the in-comment flag in the state
1608 ;; because parse-partial-sexp never sees the newlines.
1609 (if (car (nthcdr 4 state))
1610 (progn (indent-for-comment)
1611 (end-of-line)
1612 (setcar (nthcdr 4 state) nil)))
1613 ;; If this line ends inside a string,
1614 ;; go straight to next line, remaining within the inner loop,
1615 ;; and turn off the \-flag.
1616 (if (car (nthcdr 3 state))
1617 (progn
1618 (forward-line 1)
1619 (setcar (nthcdr 5 state) nil))
1620 (setq inner-loop-done t)))
1621 (and endpos
1622 (<= next-depth 0)
1623 (progn
1624 (setq indent-stack (nconc indent-stack
1625 (make-list (- next-depth) nil))
1626 last-depth (- last-depth next-depth)
1627 next-depth 0)))
1628 (forward-line 1)
1629 ;; Decide whether to exit.
1630 (if endpos
1631 ;; If we have already reached the specified end,
1632 ;; give up and do not reindent this line.
1633 (if (<= endpos (point))
1634 (setq outer-loop-done t))
1635 ;; If no specified end, we are done if we have finished one sexp.
1636 (if (<= next-depth 0)
1637 (setq outer-loop-done t)))
1638 (unless outer-loop-done
1639 (while (> last-depth next-depth)
1640 (setq indent-stack (cdr indent-stack)
1641 last-depth (1- last-depth)))
1642 (while (< last-depth next-depth)
1643 (setq indent-stack (cons nil indent-stack)
1644 last-depth (1+ last-depth)))
1645 ;; Now indent the next line according
1646 ;; to what we learned from parsing the previous one.
1647 (setq bol (point))
1648 (skip-chars-forward " \t")
1649 ;; But not if the line is blank, or just a comment
1650 ;; (except for double-semi comments; indent them as usual).
1651 (if (or (eobp) (looking-at "\\s<\\|\n"))
1652 nil
1653 (if (and (car indent-stack)
1654 (>= (car indent-stack) 0))
1655 (setq this-indent (car indent-stack))
1656 (let ((val (calculate-lisp-indent
1657 (if (car indent-stack) (- (car indent-stack))
1658 starting-point))))
1659 (if (null val)
1660 (setq this-indent val)
1661 (if (integerp val)
1662 (setcar indent-stack
1663 (setq this-indent val))
1664 (setcar indent-stack (- (car (cdr val))))
1665 (setq this-indent (car val))))))
1666 (if (and this-indent (/= (current-column) this-indent))
1667 (progn (delete-region bol (point))
1668 (indent-to this-indent)))))
1669 (or outer-loop-done
1670 (setq outer-loop-done (= (point) last-point))
1671 (setq last-point (point)))))))
1672
1673 (defun indent-pp-sexp (&optional arg)
1674 "Indent each line of the list starting just after point, or prettyprint it.
1675 A prefix argument specifies pretty-printing."
1676 (interactive "P")
1677 (if arg
1678 (save-excursion
1679 (save-restriction
1680 (narrow-to-region (point) (progn (forward-sexp 1) (point)))
1681 (pp-buffer)
1682 (goto-char (point-max))
1683 (if (eq (char-before) ?\n)
1684 (delete-char -1)))))
1685 (indent-sexp))
1686
1687 ;;;; Lisp paragraph filling commands.
1688
1689 (defcustom emacs-lisp-docstring-fill-column 65
1690 "Value of `fill-column' to use when filling a docstring.
1691 Any non-integer value means do not use a different value of
1692 `fill-column' when filling docstrings."
1693 :type '(choice (integer)
1694 (const :tag "Use the current `fill-column'" t))
1695 :group 'lisp)
1696 (put 'emacs-lisp-docstring-fill-column 'safe-local-variable
1697 (lambda (x) (or (eq x t) (integerp x))))
1698
1699 (defun lisp-fill-paragraph (&optional justify)
1700 "Like \\[fill-paragraph], but handle Emacs Lisp comments and docstrings.
1701 If any of the current line is a comment, fill the comment or the
1702 paragraph of it that point is in, preserving the comment's indentation
1703 and initial semicolons."
1704 (interactive "P")
1705 (or (fill-comment-paragraph justify)
1706 ;; Since fill-comment-paragraph returned nil, that means we're not in
1707 ;; a comment: Point is on a program line; we are interested
1708 ;; particularly in docstring lines.
1709 ;;
1710 ;; We bind `paragraph-start' and `paragraph-separate' temporarily. They
1711 ;; are buffer-local, but we avoid changing them so that they can be set
1712 ;; to make `forward-paragraph' and friends do something the user wants.
1713 ;;
1714 ;; `paragraph-start': The `(' in the character alternative and the
1715 ;; left-singlequote plus `(' sequence after the \\| alternative prevent
1716 ;; sexps and backquoted sexps that follow a docstring from being filled
1717 ;; with the docstring. This setting has the consequence of inhibiting
1718 ;; filling many program lines that are not docstrings, which is sensible,
1719 ;; because the user probably asked to fill program lines by accident, or
1720 ;; expecting indentation (perhaps we should try to do indenting in that
1721 ;; case). The `;' and `:' stop the paragraph being filled at following
1722 ;; comment lines and at keywords (e.g., in `defcustom'). Left parens are
1723 ;; escaped to keep font-locking, filling, & paren matching in the source
1724 ;; file happy.
1725 ;;
1726 ;; `paragraph-separate': A clever regexp distinguishes the first line of
1727 ;; a docstring and identifies it as a paragraph separator, so that it
1728 ;; won't be filled. (Since the first line of documentation stands alone
1729 ;; in some contexts, filling should not alter the contents the author has
1730 ;; chosen.) Only the first line of a docstring begins with whitespace
1731 ;; and a quotation mark and ends with a period or (rarely) a comma.
1732 ;;
1733 ;; The `fill-column' is temporarily bound to
1734 ;; `emacs-lisp-docstring-fill-column' if that value is an integer.
1735 (let ((paragraph-start (concat paragraph-start
1736 "\\|\\s-*\\([(;:\"]\\|`(\\|#'(\\)"))
1737 (paragraph-separate
1738 (concat paragraph-separate "\\|\\s-*\".*[,\\.]$"))
1739 (fill-column (if (and (integerp emacs-lisp-docstring-fill-column)
1740 (derived-mode-p 'emacs-lisp-mode))
1741 emacs-lisp-docstring-fill-column
1742 fill-column)))
1743 (fill-paragraph justify))
1744 ;; Never return nil.
1745 t))
1746
1747 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
1748 "Indent all lines of code, starting in the region, sideways by ARG columns.
1749 Does not affect lines starting inside comments or strings, assuming that
1750 the start of the region is not inside them.
1751
1752 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1753 The last is a regexp which, if matched at the beginning of a line,
1754 means don't indent that line."
1755 (interactive "r\np")
1756 (let (state)
1757 (save-excursion
1758 (goto-char end)
1759 (setq end (point-marker))
1760 (goto-char start)
1761 (or (bolp)
1762 (setq state (parse-partial-sexp (point)
1763 (progn
1764 (forward-line 1) (point))
1765 nil nil state)))
1766 (while (< (point) end)
1767 (or (car (nthcdr 3 state))
1768 (and nochange-regexp
1769 (looking-at nochange-regexp))
1770 ;; If line does not start in string, indent it
1771 (let ((indent (current-indentation)))
1772 (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1773 (or (eolp)
1774 (indent-to (max 0 (+ indent arg)) 0))))
1775 (setq state (parse-partial-sexp (point)
1776 (progn
1777 (forward-line 1) (point))
1778 nil nil state))))))
1779
1780 (provide 'lisp-mode)
1781
1782 ;;; lisp-mode.el ends here