Contents in 1999-06-04-13 of release-21-2.
[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 (defvar lisp-mode-map ()
294   "Keymap for ordinary Lisp mode.
295 All commands in `shared-lisp-mode-map' are inherited by this map.")
296
297 (if lisp-mode-map
298     ()
299   ;; XEmacs changes
300   (setq lisp-mode-map (make-sparse-keymap))
301   (set-keymap-name lisp-mode-map 'lisp-mode-map)
302   (set-keymap-parents lisp-mode-map (list shared-lisp-mode-map))
303   (define-key lisp-mode-map "\e\C-x" 'lisp-send-defun)
304   ;; gag, no.  use ilisp.  -jwz
305 ;;  (define-key lisp-mode-map "\C-c\C-z" 'run-lisp)
306   )
307
308 (defun lisp-mode ()
309   "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
310 Commands:
311 Delete converts tabs to spaces as it moves back.
312 Blank lines separate paragraphs.  Semicolons start comments.
313 \\{lisp-mode-map}
314 Note that `run-lisp' may be used either to start an inferior Lisp job
315 or to switch back to an existing one.
316
317 Entry to this mode calls the value of `lisp-mode-hook'
318 if that value is non-nil."
319   (interactive)
320   (kill-all-local-variables)
321   (use-local-map lisp-mode-map)
322   (setq major-mode 'lisp-mode)
323   (setq mode-name "Lisp")
324   (lisp-mode-variables t)
325   (set-syntax-table lisp-mode-syntax-table)
326   (run-hooks 'lisp-mode-hook))
327
328 ;; This will do unless shell.el is loaded.
329 ;; XEmacs change
330 (defun lisp-send-defun ()
331   "Send the current defun to the Lisp process made by \\[run-lisp]."
332   (interactive)
333   (error "Process lisp does not exist"))
334
335 ;; XEmacs change: emacs-lisp-mode-map is a more appropriate parent.
336 (defvar lisp-interaction-mode-map ()
337   "Keymap for Lisp Interaction mode.
338 All commands in `shared-lisp-mode-map' are inherited by this map.")
339
340 (if lisp-interaction-mode-map
341     ()
342   ;; XEmacs set keymap our way
343   (setq lisp-interaction-mode-map (make-sparse-keymap))
344   (set-keymap-name lisp-interaction-mode-map 'lisp-interaction-mode-map)
345   (set-keymap-parents lisp-interaction-mode-map (list emacs-lisp-mode-map))
346   (define-key lisp-interaction-mode-map "\e\C-x" 'eval-defun)
347   (define-key lisp-interaction-mode-map "\e\t" 'lisp-complete-symbol)
348   (define-key lisp-interaction-mode-map "\n" 'eval-print-last-sexp))
349
350 (defun lisp-interaction-mode ()
351   "Major mode for typing and evaluating Lisp forms.
352 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
353 before point, and prints its value into the buffer, advancing point.
354
355 Commands:
356 Delete converts tabs to spaces as it moves back.
357 Paragraphs are separated only by blank lines.
358 Semicolons start comments.
359 \\{lisp-interaction-mode-map}
360 Entry to this mode calls the value of `lisp-interaction-mode-hook'
361 if that value is non-nil."
362   (interactive)
363   (kill-all-local-variables)
364   (use-local-map lisp-interaction-mode-map)
365   (setq major-mode 'lisp-interaction-mode)
366   (setq mode-name "Lisp Interaction")
367   ;; XEmacs change
368   ;; (setq mode-popup-menu lisp-interaction-mode-popup-menu)
369   (unless lisp-interaction-mode-popup-menu
370     (easy-menu-define lisp-interaction-mode-popup-menu
371                       lisp-interaction-mode-map
372                       ""
373                       lisp-interaction-mode-popup-menu-1))
374   (easy-menu-add lisp-interaction-mode-popup-menu)
375
376   (set-syntax-table emacs-lisp-mode-syntax-table)
377   (lisp-mode-variables nil)
378   (run-hooks 'lisp-interaction-mode-hook))
379
380 (defun eval-print-last-sexp ()
381   "Evaluate sexp before point; print value into current buffer."
382   (interactive)
383   (let ((standard-output (current-buffer)))
384     (terpri)
385     (eval-last-sexp t)
386     (terpri)))
387 \f
388 ;; XEmacs change
389 (defcustom eval-interactive-verbose t
390   "*Non-nil means that interactive evaluation can print messages.
391 The messages are printed when the expression is treated differently
392 using `\\[eval-last-sexp]' and `\\[eval-defun]' than it than it would have been
393 treated noninteractively.
394
395 The printed messages are \"defvar treated as defconst\" and \"defcustom
396  evaluation forced\".  See `eval-interactive' for more details."
397   :type 'boolean
398   :group 'lisp)
399
400 (defun eval-interactive (expr)
401   "Like `eval' except that it transforms defvars to defconsts.
402 The evaluation of defcustom forms is forced."
403   (cond ((and (eq (car-safe expr) 'defvar)
404               (> (length expr) 2))
405          (eval (cons 'defconst (cdr expr)))
406          (when eval-interactive-verbose
407            (message "defvar treated as defconst")
408            (sit-for 1)
409            (message ""))
410          (nth 1 expr))
411         ((and (eq (car-safe expr) 'defcustom)
412               (> (length expr) 2)
413               (default-boundp (nth 1 expr)))
414          ;; Force variable to be bound
415          ;; #### defcustom might specify a different :set method.
416          (set-default (nth 1 expr) (eval (nth 2 expr)))
417          ;; And evaluate the defcustom
418          (eval expr)
419          (when eval-interactive-verbose
420            (message "defcustom evaluation forced")
421            (sit-for 1)
422            (message ""))
423          (nth 1 expr))
424         (t
425          (eval expr))))
426
427 ;; XEmacs change, based on Bob Weiner suggestion
428 (defun eval-last-sexp (eval-last-sexp-arg-internal) ;dynamic scoping wonderment
429   "Evaluate sexp before point; print value in minibuffer.
430 With argument, print output into current buffer."
431   (interactive "P")
432   (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t))
433         (opoint (point))
434         ignore-quotes)
435     (prin1 (eval-interactive
436             (letf (((syntax-table) emacs-lisp-mode-syntax-table))
437               (save-excursion
438                 ;; If this sexp appears to be enclosed in `...' then
439                 ;; ignore the surrounding quotes.
440                 (setq ignore-quotes (or (eq (char-after) ?\')
441                                         (eq (char-before) ?\')))
442                 (forward-sexp -1)
443                 ;; vladimir@cs.ualberta.ca 30-Jul-1997: skip ` in
444                 ;; `variable' so that the value is returned, not the
445                 ;; name.
446                 (if (and ignore-quotes
447                          (eq (char-after) ?\`))
448                     (forward-char))
449                 (save-restriction
450                   (narrow-to-region (point-min) opoint)
451                   (let ((expr (read (current-buffer))))
452                     (if (eq (car-safe expr) 'interactive)
453                         ;; If it's an (interactive ...) form, it's
454                         ;; more useful to show how an interactive call
455                         ;; would use it.
456                         `(call-interactively
457                           (lambda (&rest args)
458                             ,expr args))
459                       expr)))))))))
460
461 (defun eval-defun (eval-defun-arg-internal)
462   "Evaluate defun that point is in or before.
463 Print value in minibuffer.
464 With argument, insert value in current buffer after the defun."
465   (interactive "P")
466   (let ((standard-output (if eval-defun-arg-internal (current-buffer) t)))
467     (prin1 (eval-interactive (save-excursion
468                                (end-of-defun)
469                                (beginning-of-defun)
470                                (read (current-buffer)))))))
471
472 \f
473 (defun lisp-comment-indent ()
474   (if (looking-at "\\s<\\s<\\s<")
475       (current-column)
476     (if (looking-at "\\s<\\s<")
477         ;; #### FSF has:
478         ;; (let ((tem (or (calculate-lisp-indent) (current-column)))) ...
479         (let ((tem (calculate-lisp-indent)))
480           (if (listp tem) (car tem) tem))
481       (skip-chars-backward " \t")
482       (max (if (bolp) 0 (1+ (current-column)))
483            comment-column))))
484
485 ;; XEmacs change
486 (defun lisp-indent-for-comment ()
487   "Indent this line's comment appropriately, or insert an empty comment.
488 If adding a new comment on a blank line, use `block-comment-start' instead
489 of `comment-start' to open the comment."
490   ;; by Stig@hackvan.com
491   ;; #### - This functionality, the recognition of block-comment-{start,end},
492   ;; will perhaps be standardized across modes and move to indent-for-comment.
493   (interactive)
494   (if (and block-comment-start
495            (save-excursion (beginning-of-line) (looking-at "^[ \t]*$")))
496       (insert block-comment-start))
497   (indent-for-comment))
498
499 (defvar lisp-indent-offset nil)
500 (defvar lisp-indent-function 'lisp-indent-function)
501
502 (defun lisp-indent-line (&optional whole-exp)
503   "Indent current line as Lisp code.
504 With argument, indent any additional lines of the same expression
505 rigidly along with this one."
506   (interactive "P")
507   (let ((indent (calculate-lisp-indent)) shift-amt beg end
508         (pos (- (point-max) (point))))
509     (beginning-of-line)
510     (setq beg (point))
511     (skip-chars-forward " \t")
512     (if (looking-at "\\s<\\s<\\s<")
513         ;; Don't alter indentation of a ;;; comment line.
514         (goto-char (- (point-max) pos))
515       (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
516           ;; Single-semicolon comment lines should be indented
517           ;; as comment lines, not as code.
518           (progn (indent-for-comment) (forward-char -1))
519         (if (listp indent) (setq indent (car indent)))
520         (setq shift-amt (- indent (current-column)))
521         (if (zerop shift-amt)
522             nil
523           (delete-region beg (point))
524           (indent-to indent)))
525       ;; If initial point was within line's indentation,
526       ;; position after the indentation.  Else stay at same point in text.
527       (if (> (- (point-max) pos) (point))
528           (goto-char (- (point-max) pos)))
529       ;; If desired, shift remaining lines of expression the same amount.
530       (and whole-exp (not (zerop shift-amt))
531            (save-excursion
532              (goto-char beg)
533              (forward-sexp 1)
534              (setq end (point))
535              (goto-char beg)
536              (forward-line 1)
537              (setq beg (point))
538              (> end beg))
539            (indent-code-rigidly beg end shift-amt)))))
540
541 (defvar calculate-lisp-indent-last-sexp)
542
543 (defun calculate-lisp-indent (&optional parse-start)
544   "Return appropriate indentation for current line as Lisp code.
545 In usual case returns an integer: the column to indent to.
546 Can instead return a list, whose car is the column to indent to.
547 This means that following lines at the same level of indentation
548 should not necessarily be indented the same way.
549 The second element of the list is the buffer position
550 of the start of the containing expression."
551   (save-excursion
552     (beginning-of-line)
553     (let ((indent-point (point))
554           ;; XEmacs change (remove paren-depth)
555           state ;;paren-depth
556           ;; setting this to a number inhibits calling hook
557           (desired-indent nil)
558           (retry t)
559           calculate-lisp-indent-last-sexp containing-sexp)
560       (if parse-start
561           (goto-char parse-start)
562           (beginning-of-defun))
563       ;; Find outermost containing sexp
564       (while (< (point) indent-point)
565         (setq state (parse-partial-sexp (point) indent-point 0)))
566       ;; Find innermost containing sexp
567       (while (and retry
568                   state
569                   ;; XEmacs change (remove paren-depth)
570                   (> ;;(setq paren-depth (elt state 0))
571                      (elt state 0)
572                      0))
573         (setq retry nil)
574         (setq calculate-lisp-indent-last-sexp (elt state 2))
575         (setq containing-sexp (elt state 1))
576         ;; Position following last unclosed open.
577         (goto-char (1+ containing-sexp))
578         ;; Is there a complete sexp since then?
579         (if (and calculate-lisp-indent-last-sexp
580                  (> calculate-lisp-indent-last-sexp (point)))
581             ;; Yes, but is there a containing sexp after that?
582             (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
583                                             indent-point 0)))
584               (if (setq retry (car (cdr peek))) (setq state peek)))))
585       (if retry
586           nil
587         ;; Innermost containing sexp found
588         (goto-char (1+ containing-sexp))
589         (if (not calculate-lisp-indent-last-sexp)
590             ;; indent-point immediately follows open paren.
591             ;; Don't call hook.
592             (setq desired-indent (current-column))
593           ;; Find the start of first element of containing sexp.
594           (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
595           (cond ((looking-at "\\s(")
596                  ;; First element of containing sexp is a list.
597                  ;; Indent under that list.
598                  )
599                 ((> (save-excursion (forward-line 1) (point))
600                     calculate-lisp-indent-last-sexp)
601                  ;; This is the first line to start within the containing sexp.
602                  ;; It's almost certainly a function call.
603                  (if (= (point) calculate-lisp-indent-last-sexp)
604                      ;; Containing sexp has nothing before this line
605                      ;; except the first element.  Indent under that element.
606                      nil
607                    ;; Skip the first element, find start of second (the first
608                    ;; argument of the function call) and indent under.
609                    (progn (forward-sexp 1)
610                           (parse-partial-sexp (point)
611                                               calculate-lisp-indent-last-sexp
612                                               0 t)))
613                  (backward-prefix-chars))
614                 (t
615                  ;; Indent beneath first sexp on same line as
616                  ;; calculate-lisp-indent-last-sexp.  Again, it's
617                  ;; almost certainly a function call.
618                  (goto-char calculate-lisp-indent-last-sexp)
619                  (beginning-of-line)
620                  (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
621                                      0 t)
622                  (backward-prefix-chars)))))
623       ;; Point is at the point to indent under unless we are inside a string.
624       ;; Call indentation hook except when overridden by lisp-indent-offset
625       ;; or if the desired indentation has already been computed.
626       (let ((normal-indent (current-column)))
627         (cond ((elt state 3)
628                ;; Inside a string, don't change indentation.
629                (goto-char indent-point)
630                (skip-chars-forward " \t")
631                (current-column))
632               (desired-indent)
633               ((and (boundp 'lisp-indent-function)
634                     lisp-indent-function
635                     (not retry))
636                (or (funcall lisp-indent-function indent-point state)
637                    normal-indent))
638               ;; XEmacs change:
639               ;; lisp-indent-offset shouldn't override lisp-indent-function !
640               ((and (integerp lisp-indent-offset) containing-sexp)
641                ;; Indent by constant offset
642                (goto-char containing-sexp)
643                (+ normal-indent lisp-indent-offset))
644               (t
645                normal-indent))))))
646
647 (defun lisp-indent-function (indent-point state)
648   ;; free reference to `calculate-lisp-indent-last-sexp'
649   ;; in #'calculate-lisp-indent
650   (let ((normal-indent (current-column)))
651     (goto-char (1+ (elt state 1)))
652     (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
653     (if (and (elt state 2)
654              (not (looking-at "\\sw\\|\\s_")))
655         ;; car of form doesn't seem to be a a symbol
656         (progn
657           (if (not (> (save-excursion (forward-line 1) (point))
658                       calculate-lisp-indent-last-sexp))
659               (progn (goto-char calculate-lisp-indent-last-sexp)
660                      (beginning-of-line)
661                      (parse-partial-sexp (point)
662                                          calculate-lisp-indent-last-sexp 0 t)))
663           ;; Indent under the list or under the first sexp on the same
664           ;; line as calculate-lisp-indent-last-sexp.  Note that first
665           ;; thing on that line has to be complete sexp since we are
666           ;; inside the innermost containing sexp.
667           (backward-prefix-chars)
668           (current-column))
669       (let ((function (buffer-substring (point)
670                                         (progn (forward-sexp 1) (point))))
671             method)
672         (setq method (or (get (intern-soft function) 'lisp-indent-function)
673                          (get (intern-soft function) 'lisp-indent-hook)))
674         (cond ((or (eq method 'defun)
675                    (and (null method)
676                         (> (length function) 3)
677                         (string-match "\\`def" function)))
678                (lisp-indent-defform state indent-point))
679               ((integerp method)
680                (lisp-indent-specform method state
681                                      indent-point normal-indent))
682               (method
683                 (funcall method state indent-point)))))))
684
685 (defvar lisp-body-indent 2
686   "Number of columns to indent the second line of a `(def...)' form.")
687
688 (defun lisp-indent-specform (count state indent-point normal-indent)
689   (let ((containing-form-start (elt state 1))
690         (i count)
691         body-indent containing-form-column)
692     ;; Move to the start of containing form, calculate indentation
693     ;; to use for non-distinguished forms (> count), and move past the
694     ;; function symbol.  lisp-indent-function guarantees that there is at
695     ;; least one word or symbol character following open paren of containing
696     ;; form.
697     (goto-char containing-form-start)
698     (setq containing-form-column (current-column))
699     (setq body-indent (+ lisp-body-indent containing-form-column))
700     (forward-char 1)
701     (forward-sexp 1)
702     ;; Now find the start of the last form.
703     (parse-partial-sexp (point) indent-point 1 t)
704     (while (and (< (point) indent-point)
705                 (condition-case ()
706                     (progn
707                       (setq count (1- count))
708                       (forward-sexp 1)
709                       (parse-partial-sexp (point) indent-point 1 t))
710                   (error nil))))
711     ;; Point is sitting on first character of last (or count) sexp.
712     (if (> count 0)
713         ;; A distinguished form.  If it is the first or second form use double
714         ;; lisp-body-indent, else normal indent.  With lisp-body-indent bound
715         ;; to 2 (the default), this just happens to work the same with if as
716         ;; the older code, but it makes unwind-protect, condition-case,
717         ;; with-output-to-temp-buffer, et. al. much more tasteful.  The older,
718         ;; less hacked, behavior can be obtained by replacing below with
719         ;; (list normal-indent containing-form-start).
720         (if (<= (- i count) 1)
721             (list (+ containing-form-column (* 2 lisp-body-indent))
722                   containing-form-start)
723             (list normal-indent containing-form-start))
724       ;; A non-distinguished form.  Use body-indent if there are no
725       ;; distinguished forms and this is the first undistinguished form,
726       ;; or if this is the first undistinguished form and the preceding
727       ;; distinguished form has indentation at least as great as body-indent.
728       (if (or (and (= i 0) (= count 0))
729               (and (= count 0) (<= body-indent normal-indent)))
730           body-indent
731           normal-indent))))
732
733 (defun lisp-indent-defform (state indent-point)
734   (goto-char (car (cdr state)))
735   (forward-line 1)
736   (if (> (point) (car (cdr (cdr state))))
737       (progn
738         (goto-char (car (cdr state)))
739         (+ lisp-body-indent (current-column)))))
740
741 \f
742 ;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
743 ;; like defun if the first form is placed on the next line, otherwise
744 ;; it is indented like any other form (i.e. forms line up under first).
745
746 (put 'lambda 'lisp-indent-function 'defun)
747 (put 'autoload 'lisp-indent-function 'defun)
748 (put 'progn 'lisp-indent-function 0)
749 (put 'prog1 'lisp-indent-function 1)
750 (put 'prog2 'lisp-indent-function 2)
751 (put 'save-excursion 'lisp-indent-function 0)
752 (put 'save-window-excursion 'lisp-indent-function 0)
753 (put 'save-selected-window 'lisp-indent-function 0)
754 (put 'save-selected-frame 'lisp-indent-function 0)
755 (put 'with-selected-frame 'lisp-indent-function 1)
756 (put 'save-restriction 'lisp-indent-function 0)
757 (put 'save-match-data 'lisp-indent-function 0)
758 (put 'let 'lisp-indent-function 1)
759 (put 'let* 'lisp-indent-function 1)
760 (put 'let-specifier 'lisp-indent-function 1)
761 (put 'while 'lisp-indent-function 1)
762 (put 'if 'lisp-indent-function 2)
763 (put 'catch 'lisp-indent-function 1)
764 (put 'condition-case 'lisp-indent-function 2)
765 (put 'call-with-condition-handler 'lisp-indent-function 2)
766 (put 'unwind-protect 'lisp-indent-function 1)
767 (put 'save-current-buffer 'lisp-indent-function 0)
768 (put 'with-current-buffer 'lisp-indent-function 1)
769 (put 'with-string-as-buffer-contents 'lisp-indent-function 1)
770 (put 'with-temp-file 'lisp-indent-function 1)
771 (put 'with-temp-buffer 'lisp-indent-function 0)
772 (put 'with-output-to-string 'lisp-indent-function 0)
773 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
774 (put 'eval-after-load 'lisp-indent-function 1)
775 (put 'display-message 'lisp-indent-function 1)
776 (put 'display-warning 'lisp-indent-function 1)
777 (put 'lmessage 'lisp-indent-function 2)
778 (put 'lwarn 'lisp-indent-function 2)
779 (put 'global-set-key 'lisp-indent-function 1)
780
781 (defun indent-sexp (&optional endpos)
782   "Indent each line of the list starting just after point.
783 If optional arg ENDPOS is given, indent each line, stopping when
784 ENDPOS is encountered."
785   (interactive)
786   (let ((indent-stack (list nil))
787         (next-depth 0)
788         ;; If ENDPOS is non-nil, use nil as STARTING-POINT
789         ;; so that calculate-lisp-indent will find the beginning of
790         ;; the defun we are in.
791         ;; If ENDPOS is nil, it is safe not to scan before point
792         ;; since every line we indent is more deeply nested than point is.
793         (starting-point (if endpos nil (point)))
794         (last-point (point))
795         last-depth bol outer-loop-done inner-loop-done state this-indent)
796     (or endpos
797         ;; Get error now if we don't have a complete sexp after point.
798         (save-excursion (forward-sexp 1)))
799     (save-excursion
800       (setq outer-loop-done nil)
801       (while (if endpos (< (point) endpos)
802                (not outer-loop-done))
803         (setq last-depth next-depth
804               inner-loop-done nil)
805         ;; Parse this line so we can learn the state
806         ;; to indent the next line.
807         ;; This inner loop goes through only once
808         ;; unless a line ends inside a string.
809         (while (and (not inner-loop-done)
810                     (not (setq outer-loop-done (eobp))))
811           (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
812                                           nil nil state))
813           (setq next-depth (car state))
814           ;; If the line contains a comment other than the sort
815           ;; that is indented like code,
816           ;; indent it now with indent-for-comment.
817           ;; Comments indented like code are right already.
818           ;; In any case clear the in-comment flag in the state
819           ;; because parse-partial-sexp never sees the newlines.
820           (if (car (nthcdr 4 state))
821               (progn (indent-for-comment)
822                      (end-of-line)
823                      (setcar (nthcdr 4 state) nil)))
824           ;; If this line ends inside a string,
825           ;; go straight to next line, remaining within the inner loop,
826           ;; and turn off the \-flag.
827           (if (car (nthcdr 3 state))
828               (progn
829                 (forward-line 1)
830                 (setcar (nthcdr 5 state) nil))
831             (setq inner-loop-done t)))
832         (and endpos
833              (<= next-depth 0)
834              (progn
835                (setq indent-stack (append indent-stack
836                                           (make-list (- next-depth) nil))
837                      last-depth (- last-depth next-depth)
838                      next-depth 0)))
839         (or outer-loop-done endpos
840             (setq outer-loop-done (<= next-depth 0)))
841         (if outer-loop-done
842             (forward-line 1)
843           (while (> last-depth next-depth)
844             (setq indent-stack (cdr indent-stack)
845                   last-depth (1- last-depth)))
846           (while (< last-depth next-depth)
847             (setq indent-stack (cons nil indent-stack)
848                   last-depth (1+ last-depth)))
849           ;; Now go to the next line and indent it according
850           ;; to what we learned from parsing the previous one.
851           (forward-line 1)
852           (setq bol (point))
853           (skip-chars-forward " \t")
854           ;; But not if the line is blank, or just a comment
855           ;; (except for double-semi comments; indent them as usual).
856           (if (or (eobp) (looking-at "\\s<\\|\n"))
857               nil
858             (if (and (car indent-stack)
859                      (>= (car indent-stack) 0))
860                 (setq this-indent (car indent-stack))
861               (let ((val (calculate-lisp-indent
862                           (if (car indent-stack) (- (car indent-stack))
863                             starting-point))))
864                 (if (integerp val)
865                     (setcar indent-stack
866                             (setq this-indent val))
867                   (setcar indent-stack (- (car (cdr val))))
868                   (setq this-indent (car val)))))
869             (if (/= (current-column) this-indent)
870                 (progn (delete-region bol (point))
871                        (indent-to this-indent)))))
872         (or outer-loop-done
873             (setq outer-loop-done (= (point) last-point))
874             (setq last-point (point)))))))
875
876 ;; Indent every line whose first char is between START and END inclusive.
877 (defun lisp-indent-region (start end)
878   (save-excursion
879     (let ((endmark (copy-marker end)))
880       (goto-char start)
881       (and (bolp) (not (eolp))
882            (lisp-indent-line))
883       (indent-sexp endmark)
884       (set-marker endmark nil))))
885 \f
886 ;;;; Lisp paragraph filling commands.
887
888 (defun lisp-fill-paragraph (&optional justify)
889   "Like \\[fill-paragraph], but handle Emacs Lisp comments.
890 If any of the current line is a comment, fill the comment or the
891 paragraph of it that point is in, preserving the comment's indentation
892 and initial semicolons."
893   (interactive "P")
894   (let (
895         ;; Non-nil if the current line contains a comment.
896         has-comment
897
898         ;; Non-nil if the current line contains code and a comment.
899         has-code-and-comment
900
901         ;; If has-comment, the appropriate fill-prefix for the comment.
902         comment-fill-prefix
903         )
904
905     ;; Figure out what kind of comment we are looking at.
906     (save-excursion
907       (beginning-of-line)
908       (cond
909
910        ;; A line with nothing but a comment on it?
911        ((looking-at "[ \t]*;[; \t]*")
912         (setq has-comment t
913               comment-fill-prefix (buffer-substring (match-beginning 0)
914                                                     (match-end 0))))
915
916        ;; A line with some code, followed by a comment?  Remember that the
917        ;; semi which starts the comment shouldn't be part of a string or
918        ;; character.
919        ;; XEmacs Try this the FSF and see if it works.
920 ;       ((progn
921 ;         (while (not (looking-at ";\\|$"))
922 ;           (skip-chars-forward "^;\n\"\\\\?")
923 ;           (cond
924 ;            ((eq (char-after (point)) ?\\) (forward-char 2))
925 ;            ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
926 ;         (looking-at ";+[\t ]*"))
927 ;       (setq has-comment t)
928        ((condition-case nil
929             (save-restriction
930               (narrow-to-region (point-min)
931                                 (save-excursion (end-of-line) (point)))
932               (while (not (looking-at ";\\|$"))
933                 (skip-chars-forward "^;\n\"\\\\?")
934                 (cond
935                  ((eq (char-after (point)) ?\\) (forward-char 2))
936                  ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
937               (looking-at ";+[\t ]*"))
938           (error nil))
939         (setq has-comment t has-code-and-comment t)
940         (setq comment-fill-prefix
941               (concat (make-string (/ (current-column) 8) ?\t)
942                       (make-string (% (current-column) 8) ?\ )
943                       (buffer-substring (match-beginning 0) (match-end 0)))))))
944
945     (if (not has-comment)
946         (fill-paragraph justify)
947
948       ;; Narrow to include only the comment, and then fill the region.
949       (save-excursion
950         (save-restriction
951           (beginning-of-line)
952           (narrow-to-region
953            ;; Find the first line we should include in the region to fill.
954            (save-excursion
955              (while (and (zerop (forward-line -1))
956                          (looking-at "^[ \t]*;")))
957              ;; We may have gone too far.  Go forward again.
958              (or (looking-at ".*;")
959                  (forward-line 1))
960              (point))
961            ;; Find the beginning of the first line past the region to fill.
962            (save-excursion
963              (while (progn (forward-line 1)
964                            (looking-at "^[ \t]*;")))
965              (point)))
966
967           ;; Lines with only semicolons on them can be paragraph boundaries.
968           (let* ((paragraph-start (concat paragraph-start "\\|[ \t;]*$"))
969                  (paragraph-separate (concat paragraph-start "\\|[ \t;]*$"))
970                  (paragraph-ignore-fill-prefix nil)
971                  (fill-prefix comment-fill-prefix)
972                  (after-line (if has-code-and-comment
973                                  (save-excursion
974                                    (forward-line 1) (point))))
975                  (end (progn
976                         (forward-paragraph)
977                         (or (bolp) (newline 1))
978                         (point)))
979                  ;; If this comment starts on a line with code,
980                  ;; include that like in the filling.
981                  (beg (progn (backward-paragraph)
982                              (if (eq (point) after-line)
983                                  (forward-line -1))
984                              (point))))
985             (fill-region-as-paragraph beg end
986                                       justify nil
987                                       (save-excursion
988                                         (goto-char beg)
989                                         (if (looking-at fill-prefix)
990                                             nil
991                                           (re-search-forward comment-start-skip)
992                                           (point))))))))
993     t))
994 \f
995 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
996   "Indent all lines of code, starting in the region, sideways by ARG columns.
997 Does not affect lines starting inside comments or strings, assuming that
998 the start of the region is not inside them.
999
1000 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1001 The last is a regexp which, if matched at the beginning of a line,
1002 means don't indent that line."
1003   (interactive "r\np")
1004   (let (state)
1005     (save-excursion
1006       (goto-char end)
1007       (setq end (point-marker))
1008       (goto-char start)
1009       (or (bolp)
1010           (setq state (parse-partial-sexp (point)
1011                                           (progn
1012                                             (forward-line 1) (point))
1013                                           nil nil state)))
1014       (while (< (point) end)
1015         (or (car (nthcdr 3 state))
1016             (and nochange-regexp
1017                  (looking-at nochange-regexp))
1018             ;; If line does not start in string, indent it
1019             (let ((indent (current-indentation)))
1020               (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1021               (or (eolp)
1022                   (indent-to (max 0 (+ indent arg)) 0))))
1023         (setq state (parse-partial-sexp (point)
1024                                         (progn
1025                                           (forward-line 1) (point))
1026                                         nil nil state))))))
1027
1028 (provide 'lisp-mode)
1029
1030 ;;; lisp-mode.el ends here