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