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