XEmacs 21.2.24 "Hecate".
[chise/xemacs-chise.git.1] / lisp / lisp-mode.el
1 ;;; lisp-mode.el --- Lisp mode, and its idiosyncratic commands.
2
3 ;; Copyright (C) 1985, 1996, 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995 Tinker Systems
5
6 ;; Maintainer: FSF
7 ;; Keywords: lisp, languages, dumped
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
23 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24 ;; 02111-1307, USA.
25
26 ;;; Synched up with: FSF 19.34 (but starting to diverge).
27
28 ;;; Commentary:
29
30 ;; This file is dumped with XEmacs.
31
32 ;; The base major mode for editing Lisp code (used also for Emacs Lisp).
33 ;; This mode is documented in the Emacs manual
34
35 ;; July/05/97 slb Converted to use easymenu.
36
37 ;;; Code:
38
39 (defgroup lisp nil
40   "Lisp support, including Emacs Lisp."
41   :group 'languages
42   :group 'development)
43
44 (defvar lisp-mode-syntax-table nil)
45 (defvar emacs-lisp-mode-syntax-table nil)
46 (defvar lisp-mode-abbrev-table nil)
47
48 ;; XEmacs change
49 (defvar lisp-interaction-mode-popup-menu nil)
50 (defvar lisp-interaction-mode-popup-menu-1
51   (purecopy '("Lisp-Interaction"
52               ["Evaluate Last S-expression" eval-last-sexp]
53               ["Evaluate Entire Buffer"     eval-current-buffer]
54               ["Evaluate Region"        eval-region
55                :active (region-exists-p)]
56               "---"
57               ["Evaluate This Defun"      eval-defun]
58               ;; FSF says "Instrument Function for Debugging"
59               ["Debug This Defun"         edebug-defun]
60               "---"
61               ["Trace a Function"   trace-function-background]
62               ["Untrace All Functions"    untrace-all
63                :active (fboundp 'untrace-all)]
64               "---"
65               ["Comment Out Region"     comment-region
66                :active (region-exists-p)]
67               ["Indent Region"          indent-region
68                :active (region-exists-p)]
69               ["Indent Line"            lisp-indent-line]
70               "---"
71               ["Debug On Error" (setq debug-on-error (not debug-on-error))
72                :style toggle :selected debug-on-error]
73               ["Debug On Quit" (setq debug-on-quit (not debug-on-quit))
74                :style toggle :selected debug-on-quit]
75               ["Debug on Signal" (setq debug-on-signal (not debug-on-signal))
76                :style toggle :selected debug-on-signal]
77               )))
78
79 (defvar emacs-lisp-mode-popup-menu nil)
80 (defvar emacs-lisp-mode-popup-menu-1
81   (purecopy
82    (nconc
83     '("Emacs-Lisp"
84       ["Byte-compile This File" emacs-lisp-byte-compile]
85       ["Byte-compile/load This" emacs-lisp-byte-compile-and-load]
86       ["Byte-recompile Directory..." byte-recompile-directory]
87       "---")
88     (cdr lisp-interaction-mode-popup-menu-1))))
89
90 ;Don't have a menubar entry in Lisp Interaction mode.  Otherwise, the
91 ;*scratch* buffer has a Lisp menubar item!  Very confusing.
92 ;(defvar lisp-interaction-mode-menubar-menu
93 ;  (purecopy (cons "Lisp" (cdr lisp-interaction-mode-popup-menu))))
94
95 (defvar emacs-lisp-mode-menubar-menu nil)
96 (defvar emacs-lisp-mode-menubar-menu-1
97   (purecopy (cons "Lisp" (cdr emacs-lisp-mode-popup-menu-1))))
98
99 (if (not emacs-lisp-mode-syntax-table)
100     (let ((i 0))
101       (setq emacs-lisp-mode-syntax-table (make-syntax-table))
102       (while (< i ?0)
103         (modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
104         (setq i (1+ i)))
105       (setq i (1+ ?9))
106       (while (< i ?A)
107         (modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
108         (setq i (1+ i)))
109       (setq i (1+ ?Z))
110       (while (< i ?a)
111         (modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
112         (setq i (1+ i)))
113       (setq i (1+ ?z))
114       (while (< i 128)
115         (modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
116         (setq i (1+ i)))
117       (modify-syntax-entry ?  "    " emacs-lisp-mode-syntax-table)
118       (modify-syntax-entry ?\t "    " emacs-lisp-mode-syntax-table)
119       (modify-syntax-entry ?\f "    " emacs-lisp-mode-syntax-table)
120       (modify-syntax-entry ?\n ">   " emacs-lisp-mode-syntax-table)
121       ;; Give CR the same syntax as newline, for selective-display.
122       (modify-syntax-entry ?\^m ">   " emacs-lisp-mode-syntax-table)
123       (modify-syntax-entry ?\; "<   " emacs-lisp-mode-syntax-table)
124       (modify-syntax-entry ?` "'   " emacs-lisp-mode-syntax-table)
125       (modify-syntax-entry ?' "'   " emacs-lisp-mode-syntax-table)
126       (modify-syntax-entry ?, "'   " emacs-lisp-mode-syntax-table)
127       ;; Used to be singlequote; changed for flonums.
128       (modify-syntax-entry ?. "_   " emacs-lisp-mode-syntax-table)
129       (modify-syntax-entry ?# "'   " emacs-lisp-mode-syntax-table)
130       (modify-syntax-entry ?\" "\"    " emacs-lisp-mode-syntax-table)
131       (modify-syntax-entry ?\\ "\\   " emacs-lisp-mode-syntax-table)
132       (modify-syntax-entry ?\( "()  " emacs-lisp-mode-syntax-table)
133       (modify-syntax-entry ?\) ")(  " emacs-lisp-mode-syntax-table)
134       (modify-syntax-entry ?\[ "(]  " emacs-lisp-mode-syntax-table)
135       (modify-syntax-entry ?\] ")[  " emacs-lisp-mode-syntax-table)))
136
137 (if (not lisp-mode-syntax-table)
138     (progn (setq lisp-mode-syntax-table
139                  (copy-syntax-table emacs-lisp-mode-syntax-table))
140            (modify-syntax-entry ?\| "\"   " lisp-mode-syntax-table)
141            (modify-syntax-entry ?\[ "_   " lisp-mode-syntax-table)
142            ;; XEmacs changes
143            (modify-syntax-entry ?\] "_   " lisp-mode-syntax-table)
144            ;;
145            ;; If emacs was compiled with NEW_SYNTAX, then do
146            ;;  CL's #| |# block comments.
147            (if (= 8 (length (parse-partial-sexp (point) (point))))
148                (progn
149                  (modify-syntax-entry ?#  "' 58" lisp-mode-syntax-table)
150                  (modify-syntax-entry ?|  ". 67" lisp-mode-syntax-table))
151              ;; else, old style
152              (modify-syntax-entry ?\| "\"   " lisp-mode-syntax-table))))
153
154 (define-abbrev-table 'lisp-mode-abbrev-table ())
155
156 (defvar lisp-imenu-generic-expression
157       '(
158         (nil 
159          "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\\s-+\\([-A-Za-z0-9+*|:]+\\)" 2)
160         ("Variables" 
161          "^\\s-*(def\\(var\\|const\\|custom\\)\\s-+\\([-A-Za-z0-9+*|:]+\\)" 2)
162         ("Types" 
163          "^\\s-*(def\\(group\\|type\\|struct\\|class\\|ine-condition\\)\\s-+\\([-A-Za-z0-9+*|:]+\\)" 
164          2))
165
166   "Imenu generic expression for Lisp mode.  See `imenu-generic-expression'.")
167
168 (defun lisp-mode-variables (lisp-syntax)
169   (cond (lisp-syntax
170          (set-syntax-table lisp-mode-syntax-table)))
171   (setq local-abbrev-table lisp-mode-abbrev-table)
172   (make-local-variable 'paragraph-start)
173   (setq paragraph-start (concat page-delimiter "\\|$" ))
174   (make-local-variable 'paragraph-separate)
175   (setq paragraph-separate paragraph-start)
176   (make-local-variable 'paragraph-ignore-fill-prefix)
177   (setq paragraph-ignore-fill-prefix t)
178   (make-local-variable 'fill-paragraph-function)
179   (setq fill-paragraph-function 'lisp-fill-paragraph)
180   ;; Adaptive fill mode gets in the way of auto-fill,
181   ;; and should make no difference for explicit fill
182   ;; because lisp-fill-paragraph should do the job.
183   (make-local-variable 'adaptive-fill-mode)
184   (setq adaptive-fill-mode nil)
185   (make-local-variable 'indent-line-function)
186   (setq indent-line-function 'lisp-indent-line)
187   (make-local-variable 'indent-region-function)
188   (setq indent-region-function 'lisp-indent-region)
189   (make-local-variable 'parse-sexp-ignore-comments)
190   (setq parse-sexp-ignore-comments t)
191   (make-local-variable 'outline-regexp)
192   (setq outline-regexp ";;; \\|(....")
193   (make-local-variable 'comment-start)
194   (setq comment-start ";")
195   ;; XEmacs change
196   (set (make-local-variable 'block-comment-start) ";;")
197   (make-local-variable 'comment-start-skip)
198   ;; Look within the line for a ; following an even number of backslashes
199   ;; after either a non-backslash or the line beginning.
200   (setq comment-start-skip "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\);+ *")
201   (make-local-variable 'comment-column)
202   (setq comment-column 40)
203   (make-local-variable 'comment-indent-function)
204   (setq comment-indent-function 'lisp-comment-indent)
205   ;; XEmacs change
206   (set (make-local-variable 'dabbrev-case-fold-search) nil)
207   (set (make-local-variable 'dabbrev-case-replace) nil)
208   (make-local-variable 'imenu-generic-expression)
209   (setq imenu-generic-expression lisp-imenu-generic-expression))
210 \f
211 (defvar shared-lisp-mode-map ()
212   "Keymap for commands shared by all sorts of Lisp modes.")
213
214 (if shared-lisp-mode-map
215     ()
216    (setq shared-lisp-mode-map (make-sparse-keymap))
217    ;; XEmacs changes
218    (set-keymap-name shared-lisp-mode-map 'shared-lisp-mode-map)
219    (define-key shared-lisp-mode-map "\M-;" 'lisp-indent-for-comment)
220    (define-key shared-lisp-mode-map "\e\C-q" 'indent-sexp))
221
222 (defvar emacs-lisp-mode-map ()
223   "Keymap for Emacs Lisp mode.
224 All commands in `shared-lisp-mode-map' are inherited by this map.")
225
226 (if emacs-lisp-mode-map
227     ()
228   ;; XEmacs:  Ignore FSF nconc stuff
229   (setq emacs-lisp-mode-map (make-sparse-keymap))
230   (set-keymap-name emacs-lisp-mode-map 'emacs-lisp-mode-map)
231   (set-keymap-parents emacs-lisp-mode-map (list shared-lisp-mode-map))
232   (define-key emacs-lisp-mode-map "\e\t" 'lisp-complete-symbol)
233   (define-key emacs-lisp-mode-map "\e\C-x" 'eval-defun)
234   ;; XEmacs: Not sure what the FSF menu bindings are.  I hope XEmacs
235   ;; doesn't need them.
236 )
237
238 (defun emacs-lisp-byte-compile ()
239   "Byte compile the file containing the current buffer."
240   (interactive)
241   (if buffer-file-name
242       ;; XEmacs change.  Force buffer save first
243       (progn
244         (save-buffer)
245         (byte-compile-file buffer-file-name))
246     (error "The buffer must be saved in a file first.")))
247
248 (defun emacs-lisp-byte-compile-and-load ()
249   "Byte-compile the current file (if it has changed), then load compiled code."
250   (interactive)
251   (or buffer-file-name
252       (error "The buffer must be saved in a file first"))
253   (require 'bytecomp)
254   ;; Recompile if file or buffer has changed since last compilation.
255   (if (and (buffer-modified-p)
256            (y-or-n-p (format "save buffer %s first? " (buffer-name))))
257       (save-buffer))
258   (let ((compiled-file-name (byte-compile-dest-file buffer-file-name)))
259     (if (file-newer-than-file-p compiled-file-name buffer-file-name)
260         (load-file compiled-file-name)
261       (byte-compile-file buffer-file-name t))))
262
263 (defun emacs-lisp-mode ()
264   "Major mode for editing Lisp code to run in Emacs.
265 Commands:
266 Delete converts tabs to spaces as it moves back.
267 Blank lines separate paragraphs.  Semicolons start comments.
268 \\{emacs-lisp-mode-map}
269 Entry to this mode calls the value of `emacs-lisp-mode-hook'
270 if that value is non-nil."
271   (interactive)
272   (kill-all-local-variables)
273   (use-local-map emacs-lisp-mode-map)
274   (set-syntax-table emacs-lisp-mode-syntax-table)
275   ;; XEmacs changes
276   (setq major-mode 'emacs-lisp-mode
277         ;; mode-popup-menu emacs-lisp-mode-popup-menu
278         mode-name "Emacs-Lisp")
279   ;; (if (and (featurep 'menubar)
280            ;; current-menubar)
281       ;; (progn
282         ;; make a local copy of the menubar, so our modes don't
283         ;; change the global menubar
284         ;; (set-buffer-menubar current-menubar)
285         ;; (add-submenu nil emacs-lisp-mode-menubar-menu)))
286   (unless emacs-lisp-mode-popup-menu
287     (easy-menu-define emacs-lisp-mode-popup-menu emacs-lisp-mode-map ""
288                       emacs-lisp-mode-popup-menu-1))
289   (easy-menu-add emacs-lisp-mode-popup-menu)
290   (lisp-mode-variables nil)
291   (run-hooks 'emacs-lisp-mode-hook))
292
293 (put 'emacs-lisp-mode 'font-lock-lisp-like t)
294
295 (defvar lisp-mode-map ()
296   "Keymap for ordinary Lisp mode.
297 All commands in `shared-lisp-mode-map' are inherited by this map.")
298
299 (if lisp-mode-map
300     ()
301   ;; XEmacs changes
302   (setq lisp-mode-map (make-sparse-keymap))
303   (set-keymap-name lisp-mode-map 'lisp-mode-map)
304   (set-keymap-parents lisp-mode-map (list shared-lisp-mode-map))
305   (define-key lisp-mode-map "\e\C-x" 'lisp-send-defun)
306   ;; gag, no.  use ilisp.  -jwz
307 ;;  (define-key lisp-mode-map "\C-c\C-z" 'run-lisp)
308   )
309
310 (defun lisp-mode ()
311   "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
312 Commands:
313 Delete converts tabs to spaces as it moves back.
314 Blank lines separate paragraphs.  Semicolons start comments.
315 \\{lisp-mode-map}
316 Note that `run-lisp' may be used either to start an inferior Lisp job
317 or to switch back to an existing one.
318
319 Entry to this mode calls the value of `lisp-mode-hook'
320 if that value is non-nil."
321   (interactive)
322   (kill-all-local-variables)
323   (use-local-map lisp-mode-map)
324   (setq major-mode 'lisp-mode)
325   (setq mode-name "Lisp")
326   (lisp-mode-variables t)
327   (set-syntax-table lisp-mode-syntax-table)
328   (run-hooks 'lisp-mode-hook))
329
330 ;; This will do unless shell.el is loaded.
331 ;; XEmacs change
332 (defun lisp-send-defun ()
333   "Send the current defun to the Lisp process made by \\[run-lisp]."
334   (interactive)
335   (error "Process lisp does not exist"))
336
337 ;; XEmacs change: emacs-lisp-mode-map is a more appropriate parent.
338 (defvar lisp-interaction-mode-map ()
339   "Keymap for Lisp Interaction mode.
340 All commands in `shared-lisp-mode-map' are inherited by this map.")
341
342 (if lisp-interaction-mode-map
343     ()
344   ;; XEmacs set keymap our way
345   (setq lisp-interaction-mode-map (make-sparse-keymap))
346   (set-keymap-name lisp-interaction-mode-map 'lisp-interaction-mode-map)
347   (set-keymap-parents lisp-interaction-mode-map (list emacs-lisp-mode-map))
348   (define-key lisp-interaction-mode-map "\e\C-x" 'eval-defun)
349   (define-key lisp-interaction-mode-map "\e\t" 'lisp-complete-symbol)
350   (define-key lisp-interaction-mode-map "\n" 'eval-print-last-sexp))
351
352 (defun lisp-interaction-mode ()
353   "Major mode for typing and evaluating Lisp forms.
354 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
355 before point, and prints its value into the buffer, advancing point.
356
357 Commands:
358 Delete converts tabs to spaces as it moves back.
359 Paragraphs are separated only by blank lines.
360 Semicolons start comments.
361 \\{lisp-interaction-mode-map}
362 Entry to this mode calls the value of `lisp-interaction-mode-hook'
363 if that value is non-nil."
364   (interactive)
365   (kill-all-local-variables)
366   (use-local-map lisp-interaction-mode-map)
367   (setq major-mode 'lisp-interaction-mode)
368   (setq mode-name "Lisp Interaction")
369   ;; XEmacs change
370   ;; (setq mode-popup-menu lisp-interaction-mode-popup-menu)
371   (unless lisp-interaction-mode-popup-menu
372     (easy-menu-define lisp-interaction-mode-popup-menu
373                       lisp-interaction-mode-map
374                       ""
375                       lisp-interaction-mode-popup-menu-1))
376   (easy-menu-add lisp-interaction-mode-popup-menu)
377
378   (set-syntax-table emacs-lisp-mode-syntax-table)
379   (lisp-mode-variables nil)
380   (run-hooks 'lisp-interaction-mode-hook))
381
382 (defun eval-print-last-sexp ()
383   "Evaluate sexp before point; print value into current buffer."
384   (interactive)
385   (let ((standard-output (current-buffer)))
386     (terpri)
387     (eval-last-sexp t)
388     (terpri)))
389 \f
390 ;; XEmacs change
391 (defcustom eval-interactive-verbose t
392   "*Non-nil means that interactive evaluation can print messages.
393 The messages are printed when the expression is treated differently
394 using `\\[eval-last-sexp]' and `\\[eval-defun]' than it than it would have been
395 treated noninteractively.
396
397 The printed messages are \"defvar treated as defconst\" and \"defcustom
398  evaluation forced\".  See `eval-interactive' for more details."
399   :type 'boolean
400   :group 'lisp)
401
402 (defun eval-interactive (expr)
403   "Like `eval' except that it transforms defvars to defconsts.
404 The evaluation of defcustom forms is forced."
405   (cond ((and (eq (car-safe expr) 'defvar)
406               (> (length expr) 2))
407          (eval (cons 'defconst (cdr expr)))
408          (when eval-interactive-verbose
409            (message "defvar treated as defconst")
410            (sit-for 1)
411            (message ""))
412          (nth 1 expr))
413         ((and (eq (car-safe expr) 'defcustom)
414               (> (length expr) 2)
415               (default-boundp (nth 1 expr)))
416          ;; Force variable to be bound
417          ;; #### defcustom might specify a different :set method.
418          (set-default (nth 1 expr) (eval (nth 2 expr)))
419          ;; And evaluate the defcustom
420          (eval expr)
421          (when eval-interactive-verbose
422            (message "defcustom evaluation forced")
423            (sit-for 1)
424            (message ""))
425          (nth 1 expr))
426         (t
427          (eval expr))))
428
429 ;; XEmacs change, based on Bob Weiner suggestion
430 (defun eval-last-sexp (eval-last-sexp-arg-internal) ;dynamic scoping wonderment
431   "Evaluate sexp before point; print value in minibuffer.
432 With argument, print output into current buffer."
433   (interactive "P")
434   (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t))
435         (opoint (point))
436         ignore-quotes)
437     (prin1 (eval-interactive
438             (letf (((syntax-table) emacs-lisp-mode-syntax-table))
439               (save-excursion
440                 ;; If this sexp appears to be enclosed in `...' then
441                 ;; ignore the surrounding quotes.
442                 (setq ignore-quotes (or (eq (char-after) ?\')
443                                         (eq (char-before) ?\')))
444                 (forward-sexp -1)
445                 ;; vladimir@cs.ualberta.ca 30-Jul-1997: skip ` in
446                 ;; `variable' so that the value is returned, not the
447                 ;; name.
448                 (if (and ignore-quotes
449                          (eq (char-after) ?\`))
450                     (forward-char))
451                 (save-restriction
452                   (narrow-to-region (point-min) opoint)
453                   (let ((expr (read (current-buffer))))
454                     (if (eq (car-safe expr) 'interactive)
455                         ;; If it's an (interactive ...) form, it's
456                         ;; more useful to show how an interactive call
457                         ;; would use it.
458                         `(call-interactively
459                           (lambda (&rest args)
460                             ,expr args))
461                       expr)))))))))
462
463 (defun eval-defun (eval-defun-arg-internal)
464   "Evaluate defun that point is in or before.
465 Print value in minibuffer.
466 With argument, insert value in current buffer after the defun."
467   (interactive "P")
468   (let ((standard-output (if eval-defun-arg-internal (current-buffer) t)))
469     (prin1 (eval-interactive (save-excursion
470                                (end-of-defun)
471                                (beginning-of-defun)
472                                (read (current-buffer)))))))
473
474 \f
475 (defun lisp-comment-indent ()
476   (if (looking-at "\\s<\\s<\\s<")
477       (current-column)
478     (if (looking-at "\\s<\\s<")
479         ;; #### FSF has:
480         ;; (let ((tem (or (calculate-lisp-indent) (current-column)))) ...
481         (let ((tem (calculate-lisp-indent)))
482           (if (listp tem) (car tem) tem))
483       (skip-chars-backward " \t")
484       (max (if (bolp) 0 (1+ (current-column)))
485            comment-column))))
486
487 ;; XEmacs change
488 (defun lisp-indent-for-comment ()
489   "Indent this line's comment appropriately, or insert an empty comment.
490 If adding a new comment on a blank line, use `block-comment-start' instead
491 of `comment-start' to open the comment."
492   ;; by Stig@hackvan.com
493   ;; #### - This functionality, the recognition of block-comment-{start,end},
494   ;; will perhaps be standardized across modes and move to indent-for-comment.
495   (interactive)
496   (if (and block-comment-start
497            (save-excursion (beginning-of-line) (looking-at "^[ \t]*$")))
498       (insert block-comment-start))
499   (indent-for-comment))
500
501 (defvar lisp-indent-offset nil)
502 (defvar lisp-indent-function 'lisp-indent-function)
503
504 (defun lisp-indent-line (&optional whole-exp)
505   "Indent current line as Lisp code.
506 With argument, indent any additional lines of the same expression
507 rigidly along with this one."
508   (interactive "P")
509   (let ((indent (calculate-lisp-indent)) shift-amt beg end
510         (pos (- (point-max) (point))))
511     (beginning-of-line)
512     (setq beg (point))
513     (skip-chars-forward " \t")
514     (if (looking-at "\\s<\\s<\\s<")
515         ;; Don't alter indentation of a ;;; comment line.
516         (goto-char (- (point-max) pos))
517       (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
518           ;; Single-semicolon comment lines should be indented
519           ;; as comment lines, not as code.
520           (progn (indent-for-comment) (forward-char -1))
521         (if (listp indent) (setq indent (car indent)))
522         (setq shift-amt (- indent (current-column)))
523         (if (zerop shift-amt)
524             nil
525           (delete-region beg (point))
526           (indent-to indent)))
527       ;; If initial point was within line's indentation,
528       ;; position after the indentation.  Else stay at same point in text.
529       (if (> (- (point-max) pos) (point))
530           (goto-char (- (point-max) pos)))
531       ;; If desired, shift remaining lines of expression the same amount.
532       (and whole-exp (not (zerop shift-amt))
533            (save-excursion
534              (goto-char beg)
535              (forward-sexp 1)
536              (setq end (point))
537              (goto-char beg)
538              (forward-line 1)
539              (setq beg (point))
540              (> end beg))
541            (indent-code-rigidly beg end shift-amt)))))
542
543 (defvar calculate-lisp-indent-last-sexp)
544
545 (defun calculate-lisp-indent (&optional parse-start)
546   "Return appropriate indentation for current line as Lisp code.
547 In usual case returns an integer: the column to indent to.
548 Can instead return a list, whose car is the column to indent to.
549 This means that following lines at the same level of indentation
550 should not necessarily be indented the same way.
551 The second element of the list is the buffer position
552 of the start of the containing expression."
553   (save-excursion
554     (beginning-of-line)
555     (let ((indent-point (point))
556           ;; XEmacs change (remove paren-depth)
557           state ;;paren-depth
558           ;; setting this to a number inhibits calling hook
559           (desired-indent nil)
560           (retry t)
561           calculate-lisp-indent-last-sexp containing-sexp)
562       (if parse-start
563           (goto-char parse-start)
564           (beginning-of-defun))
565       ;; Find outermost containing sexp
566       (while (< (point) indent-point)
567         (setq state (parse-partial-sexp (point) indent-point 0)))
568       ;; Find innermost containing sexp
569       (while (and retry
570                   state
571                   ;; XEmacs change (remove paren-depth)
572                   (> ;;(setq paren-depth (elt state 0))
573                      (elt state 0)
574                      0))
575         (setq retry nil)
576         (setq calculate-lisp-indent-last-sexp (elt state 2))
577         (setq containing-sexp (elt state 1))
578         ;; Position following last unclosed open.
579         (goto-char (1+ containing-sexp))
580         ;; Is there a complete sexp since then?
581         (if (and calculate-lisp-indent-last-sexp
582                  (> calculate-lisp-indent-last-sexp (point)))
583             ;; Yes, but is there a containing sexp after that?
584             (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
585                                             indent-point 0)))
586               (if (setq retry (car (cdr peek))) (setq state peek)))))
587       (if retry
588           nil
589         ;; Innermost containing sexp found
590         (goto-char (1+ containing-sexp))
591         (if (not calculate-lisp-indent-last-sexp)
592             ;; indent-point immediately follows open paren.
593             ;; Don't call hook.
594             (setq desired-indent (current-column))
595           ;; Find the start of first element of containing sexp.
596           (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
597           (cond ((looking-at "\\s(")
598                  ;; First element of containing sexp is a list.
599                  ;; Indent under that list.
600                  )
601                 ((> (save-excursion (forward-line 1) (point))
602                     calculate-lisp-indent-last-sexp)
603                  ;; This is the first line to start within the containing sexp.
604                  ;; It's almost certainly a function call.
605                  (if (= (point) calculate-lisp-indent-last-sexp)
606                      ;; Containing sexp has nothing before this line
607                      ;; except the first element.  Indent under that element.
608                      nil
609                    ;; Skip the first element, find start of second (the first
610                    ;; argument of the function call) and indent under.
611                    (progn (forward-sexp 1)
612                           (parse-partial-sexp (point)
613                                               calculate-lisp-indent-last-sexp
614                                               0 t)))
615                  (backward-prefix-chars))
616                 (t
617                  ;; Indent beneath first sexp on same line as
618                  ;; calculate-lisp-indent-last-sexp.  Again, it's
619                  ;; almost certainly a function call.
620                  (goto-char calculate-lisp-indent-last-sexp)
621                  (beginning-of-line)
622                  (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
623                                      0 t)
624                  (backward-prefix-chars)))))
625       ;; Point is at the point to indent under unless we are inside a string.
626       ;; Call indentation hook except when overridden by lisp-indent-offset
627       ;; or if the desired indentation has already been computed.
628       (let ((normal-indent (current-column)))
629         (cond ((elt state 3)
630                ;; Inside a string, don't change indentation.
631                (goto-char indent-point)
632                (skip-chars-forward " \t")
633                (current-column))
634               (desired-indent)
635               ((and (boundp 'lisp-indent-function)
636                     lisp-indent-function
637                     (not retry))
638                (or (funcall lisp-indent-function indent-point state)
639                    normal-indent))
640               ;; XEmacs change:
641               ;; lisp-indent-offset shouldn't override lisp-indent-function !
642               ((and (integerp lisp-indent-offset) containing-sexp)
643                ;; Indent by constant offset
644                (goto-char containing-sexp)
645                (+ normal-indent lisp-indent-offset))
646               (t
647                normal-indent))))))
648
649 (defun lisp-indent-function (indent-point state)
650   ;; free reference to `calculate-lisp-indent-last-sexp'
651   ;; in #'calculate-lisp-indent
652   (let ((normal-indent (current-column)))
653     (goto-char (1+ (elt state 1)))
654     (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
655     (if (and (elt state 2)
656              (not (looking-at "\\sw\\|\\s_")))
657         ;; car of form doesn't seem to be a a symbol
658         (progn
659           (if (not (> (save-excursion (forward-line 1) (point))
660                       calculate-lisp-indent-last-sexp))
661               (progn (goto-char calculate-lisp-indent-last-sexp)
662                      (beginning-of-line)
663                      (parse-partial-sexp (point)
664                                          calculate-lisp-indent-last-sexp 0 t)))
665           ;; Indent under the list or under the first sexp on the same
666           ;; line as calculate-lisp-indent-last-sexp.  Note that first
667           ;; thing on that line has to be complete sexp since we are
668           ;; inside the innermost containing sexp.
669           (backward-prefix-chars)
670           (current-column))
671       (let ((function (buffer-substring (point)
672                                         (progn (forward-sexp 1) (point))))
673             method)
674         (setq method (or (get (intern-soft function) 'lisp-indent-function)
675                          (get (intern-soft function) 'lisp-indent-hook)))
676         (cond ((or (eq method 'defun)
677                    (and (null method)
678                         (> (length function) 3)
679                         (string-match "\\`def" function)))
680                (lisp-indent-defform state indent-point))
681               ((integerp method)
682                (lisp-indent-specform method state
683                                      indent-point normal-indent))
684               (method
685                 (funcall method state indent-point)))))))
686
687 (defvar lisp-body-indent 2
688   "Number of columns to indent the second line of a `(def...)' form.")
689
690 (defun lisp-indent-specform (count state indent-point normal-indent)
691   (let ((containing-form-start (elt state 1))
692         (i count)
693         body-indent containing-form-column)
694     ;; Move to the start of containing form, calculate indentation
695     ;; to use for non-distinguished forms (> count), and move past the
696     ;; function symbol.  lisp-indent-function guarantees that there is at
697     ;; least one word or symbol character following open paren of containing
698     ;; form.
699     (goto-char containing-form-start)
700     (setq containing-form-column (current-column))
701     (setq body-indent (+ lisp-body-indent containing-form-column))
702     (forward-char 1)
703     (forward-sexp 1)
704     ;; Now find the start of the last form.
705     (parse-partial-sexp (point) indent-point 1 t)
706     (while (and (< (point) indent-point)
707                 (condition-case ()
708                     (progn
709                       (setq count (1- count))
710                       (forward-sexp 1)
711                       (parse-partial-sexp (point) indent-point 1 t))
712                   (error nil))))
713     ;; Point is sitting on first character of last (or count) sexp.
714     (if (> count 0)
715         ;; A distinguished form.  If it is the first or second form use double
716         ;; lisp-body-indent, else normal indent.  With lisp-body-indent bound
717         ;; to 2 (the default), this just happens to work the same with if as
718         ;; the older code, but it makes unwind-protect, condition-case,
719         ;; with-output-to-temp-buffer, et. al. much more tasteful.  The older,
720         ;; less hacked, behavior can be obtained by replacing below with
721         ;; (list normal-indent containing-form-start).
722         (if (<= (- i count) 1)
723             (list (+ containing-form-column (* 2 lisp-body-indent))
724                   containing-form-start)
725             (list normal-indent containing-form-start))
726       ;; A non-distinguished form.  Use body-indent if there are no
727       ;; distinguished forms and this is the first undistinguished form,
728       ;; or if this is the first undistinguished form and the preceding
729       ;; distinguished form has indentation at least as great as body-indent.
730       (if (or (and (= i 0) (= count 0))
731               (and (= count 0) (<= body-indent normal-indent)))
732           body-indent
733           normal-indent))))
734
735 (defun lisp-indent-defform (state indent-point)
736   (goto-char (car (cdr state)))
737   (forward-line 1)
738   (if (> (point) (car (cdr (cdr state))))
739       (progn
740         (goto-char (car (cdr state)))
741         (+ lisp-body-indent (current-column)))))
742
743 \f
744 ;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
745 ;; like defun if the first form is placed on the next line, otherwise
746 ;; it is indented like any other form (i.e. forms line up under first).
747
748 (put 'lambda 'lisp-indent-function 'defun)
749 (put 'autoload 'lisp-indent-function 'defun)
750 (put 'progn 'lisp-indent-function 0)
751 (put 'prog1 'lisp-indent-function 1)
752 (put 'prog2 'lisp-indent-function 2)
753 (put 'save-excursion 'lisp-indent-function 0)
754 (put 'save-window-excursion 'lisp-indent-function 0)
755 (put 'save-selected-window 'lisp-indent-function 0)
756 (put 'save-selected-frame 'lisp-indent-function 0)
757 (put 'with-selected-frame 'lisp-indent-function 1)
758 (put 'save-restriction 'lisp-indent-function 0)
759 (put 'save-match-data 'lisp-indent-function 0)
760 (put 'let 'lisp-indent-function 1)
761 (put 'let* 'lisp-indent-function 1)
762 (put 'let-specifier 'lisp-indent-function 1)
763 (put 'while 'lisp-indent-function 1)
764 (put 'if 'lisp-indent-function 2)
765 (put 'catch 'lisp-indent-function 1)
766 (put 'condition-case 'lisp-indent-function 2)
767 (put 'call-with-condition-handler 'lisp-indent-function 2)
768 (put 'unwind-protect 'lisp-indent-function 1)
769 (put 'save-current-buffer 'lisp-indent-function 0)
770 (put 'with-current-buffer 'lisp-indent-function 1)
771 (put 'with-string-as-buffer-contents 'lisp-indent-function 1)
772 (put 'with-temp-file 'lisp-indent-function 1)
773 (put 'with-temp-buffer 'lisp-indent-function 0)
774 (put 'with-output-to-string 'lisp-indent-function 0)
775 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
776 (put 'eval-after-load 'lisp-indent-function 1)
777 (put 'display-message 'lisp-indent-function 1)
778 (put 'display-warning 'lisp-indent-function 1)
779 (put 'lmessage 'lisp-indent-function 2)
780 (put 'lwarn 'lisp-indent-function 2)
781 (put 'global-set-key 'lisp-indent-function 1)
782
783 (defun indent-sexp (&optional endpos)
784   "Indent each line of the list starting just after point.
785 If optional arg ENDPOS is given, indent each line, stopping when
786 ENDPOS is encountered."
787   (interactive)
788   (let ((indent-stack (list nil))
789         (next-depth 0)
790         ;; If ENDPOS is non-nil, use nil as STARTING-POINT
791         ;; so that calculate-lisp-indent will find the beginning of
792         ;; the defun we are in.
793         ;; If ENDPOS is nil, it is safe not to scan before point
794         ;; since every line we indent is more deeply nested than point is.
795         (starting-point (if endpos nil (point)))
796         (last-point (point))
797         last-depth bol outer-loop-done inner-loop-done state this-indent)
798     (or endpos
799         ;; Get error now if we don't have a complete sexp after point.
800         (save-excursion (forward-sexp 1)))
801     (save-excursion
802       (setq outer-loop-done nil)
803       (while (if endpos (< (point) endpos)
804                (not outer-loop-done))
805         (setq last-depth next-depth
806               inner-loop-done nil)
807         ;; Parse this line so we can learn the state
808         ;; to indent the next line.
809         ;; This inner loop goes through only once
810         ;; unless a line ends inside a string.
811         (while (and (not inner-loop-done)
812                     (not (setq outer-loop-done (eobp))))
813           (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
814                                           nil nil state))
815           (setq next-depth (car state))
816           ;; If the line contains a comment other than the sort
817           ;; that is indented like code,
818           ;; indent it now with indent-for-comment.
819           ;; Comments indented like code are right already.
820           ;; In any case clear the in-comment flag in the state
821           ;; because parse-partial-sexp never sees the newlines.
822           (if (car (nthcdr 4 state))
823               (progn (indent-for-comment)
824                      (end-of-line)
825                      (setcar (nthcdr 4 state) nil)))
826           ;; If this line ends inside a string,
827           ;; go straight to next line, remaining within the inner loop,
828           ;; and turn off the \-flag.
829           (if (car (nthcdr 3 state))
830               (progn
831                 (forward-line 1)
832                 (setcar (nthcdr 5 state) nil))
833             (setq inner-loop-done t)))
834         (and endpos
835              (<= next-depth 0)
836              (progn
837                (setq indent-stack (append indent-stack
838                                           (make-list (- next-depth) nil))
839                      last-depth (- last-depth next-depth)
840                      next-depth 0)))
841         (or outer-loop-done endpos
842             (setq outer-loop-done (<= next-depth 0)))
843         (if outer-loop-done
844             (forward-line 1)
845           (while (> last-depth next-depth)
846             (setq indent-stack (cdr indent-stack)
847                   last-depth (1- last-depth)))
848           (while (< last-depth next-depth)
849             (setq indent-stack (cons nil indent-stack)
850                   last-depth (1+ last-depth)))
851           ;; Now go to the next line and indent it according
852           ;; to what we learned from parsing the previous one.
853           (forward-line 1)
854           (setq bol (point))
855           (skip-chars-forward " \t")
856           ;; But not if the line is blank, or just a comment
857           ;; (except for double-semi comments; indent them as usual).
858           (if (or (eobp) (looking-at "\\s<\\|\n"))
859               nil
860             (if (and (car indent-stack)
861                      (>= (car indent-stack) 0))
862                 (setq this-indent (car indent-stack))
863               (let ((val (calculate-lisp-indent
864                           (if (car indent-stack) (- (car indent-stack))
865                             starting-point))))
866                 (if (integerp val)
867                     (setcar indent-stack
868                             (setq this-indent val))
869                   (setcar indent-stack (- (car (cdr val))))
870                   (setq this-indent (car val)))))
871             (if (/= (current-column) this-indent)
872                 (progn (delete-region bol (point))
873                        (indent-to this-indent)))))
874         (or outer-loop-done
875             (setq outer-loop-done (= (point) last-point))
876             (setq last-point (point)))))))
877
878 ;; Indent every line whose first char is between START and END inclusive.
879 (defun lisp-indent-region (start end)
880   (save-excursion
881     (let ((endmark (copy-marker end)))
882       (goto-char start)
883       (and (bolp) (not (eolp))
884            (lisp-indent-line))
885       (indent-sexp endmark)
886       (set-marker endmark nil))))
887 \f
888 ;;;; Lisp paragraph filling commands.
889
890 (defun lisp-fill-paragraph (&optional justify)
891   "Like \\[fill-paragraph], but handle Emacs Lisp comments.
892 If any of the current line is a comment, fill the comment or the
893 paragraph of it that point is in, preserving the comment's indentation
894 and initial semicolons."
895   (interactive "P")
896   (let (
897         ;; Non-nil if the current line contains a comment.
898         has-comment
899
900         ;; Non-nil if the current line contains code and a comment.
901         has-code-and-comment
902
903         ;; If has-comment, the appropriate fill-prefix for the comment.
904         comment-fill-prefix
905         )
906
907     ;; Figure out what kind of comment we are looking at.
908     (save-excursion
909       (beginning-of-line)
910       (cond
911
912        ;; A line with nothing but a comment on it?
913        ((looking-at "[ \t]*;[; \t]*")
914         (setq has-comment t
915               comment-fill-prefix (buffer-substring (match-beginning 0)
916                                                     (match-end 0))))
917
918        ;; A line with some code, followed by a comment?  Remember that the
919        ;; semi which starts the comment shouldn't be part of a string or
920        ;; character.
921        ;; XEmacs Try this the FSF and see if it works.
922 ;       ((progn
923 ;         (while (not (looking-at ";\\|$"))
924 ;           (skip-chars-forward "^;\n\"\\\\?")
925 ;           (cond
926 ;            ((eq (char-after (point)) ?\\) (forward-char 2))
927 ;            ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
928 ;         (looking-at ";+[\t ]*"))
929 ;       (setq has-comment t)
930        ((condition-case nil
931             (save-restriction
932               (narrow-to-region (point-min)
933                                 (save-excursion (end-of-line) (point)))
934               (while (not (looking-at ";\\|$"))
935                 (skip-chars-forward "^;\n\"\\\\?")
936                 (cond
937                  ((eq (char-after (point)) ?\\) (forward-char 2))
938                  ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
939               (looking-at ";+[\t ]*"))
940           (error nil))
941         (setq has-comment t has-code-and-comment t)
942         (setq comment-fill-prefix
943               (concat (make-string (/ (current-column) 8) ?\t)
944                       (make-string (% (current-column) 8) ?\ )
945                       (buffer-substring (match-beginning 0) (match-end 0)))))))
946
947     (if (not has-comment)
948         (fill-paragraph justify)
949
950       ;; Narrow to include only the comment, and then fill the region.
951       (save-excursion
952         (save-restriction
953           (beginning-of-line)
954           (narrow-to-region
955            ;; Find the first line we should include in the region to fill.
956            (save-excursion
957              (while (and (zerop (forward-line -1))
958                          (looking-at "^[ \t]*;")))
959              ;; We may have gone too far.  Go forward again.
960              (or (looking-at ".*;")
961                  (forward-line 1))
962              (point))
963            ;; Find the beginning of the first line past the region to fill.
964            (save-excursion
965              (while (progn (forward-line 1)
966                            (looking-at "^[ \t]*;")))
967              (point)))
968
969           ;; Lines with only semicolons on them can be paragraph boundaries.
970           (let* ((paragraph-start (concat paragraph-start "\\|[ \t;]*$"))
971                  (paragraph-separate (concat paragraph-start "\\|[ \t;]*$"))
972                  (paragraph-ignore-fill-prefix nil)
973                  (fill-prefix comment-fill-prefix)
974                  (after-line (if has-code-and-comment
975                                  (save-excursion
976                                    (forward-line 1) (point))))
977                  (end (progn
978                         (forward-paragraph)
979                         (or (bolp) (newline 1))
980                         (point)))
981                  ;; If this comment starts on a line with code,
982                  ;; include that like in the filling.
983                  (beg (progn (backward-paragraph)
984                              (if (eq (point) after-line)
985                                  (forward-line -1))
986                              (point))))
987             (fill-region-as-paragraph beg end
988                                       justify nil
989                                       (save-excursion
990                                         (goto-char beg)
991                                         (if (looking-at fill-prefix)
992                                             nil
993                                           (re-search-forward comment-start-skip)
994                                           (point))))))))
995     t))
996 \f
997 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
998   "Indent all lines of code, starting in the region, sideways by ARG columns.
999 Does not affect lines starting inside comments or strings, assuming that
1000 the start of the region is not inside them.
1001
1002 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1003 The last is a regexp which, if matched at the beginning of a line,
1004 means don't indent that line."
1005   (interactive "r\np")
1006   (let (state)
1007     (save-excursion
1008       (goto-char end)
1009       (setq end (point-marker))
1010       (goto-char start)
1011       (or (bolp)
1012           (setq state (parse-partial-sexp (point)
1013                                           (progn
1014                                             (forward-line 1) (point))
1015                                           nil nil state)))
1016       (while (< (point) end)
1017         (or (car (nthcdr 3 state))
1018             (and nochange-regexp
1019                  (looking-at nochange-regexp))
1020             ;; If line does not start in string, indent it
1021             (let ((indent (current-indentation)))
1022               (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1023               (or (eolp)
1024                   (indent-to (max 0 (+ indent arg)) 0))))
1025         (setq state (parse-partial-sexp (point)
1026                                         (progn
1027                                           (forward-line 1) (point))
1028                                         nil nil state))))))
1029
1030 (provide 'lisp-mode)
1031
1032 ;;; lisp-mode.el ends here