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