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