XEmacs 21.2-b1
[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-temp-file 'lisp-indent-function 1)
770 (put 'with-temp-buffer 'lisp-indent-function 0)
771 (put 'with-output-to-string 'lisp-indent-function 0)
772 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
773 (put 'eval-after-load 'lisp-indent-function 1)
774 (put 'display-message 'lisp-indent-function 1)
775 (put 'display-warning 'lisp-indent-function 1)
776 (put 'lmessage 'lisp-indent-function 2)
777 (put 'lwarn 'lisp-indent-function 2)
778 (put 'global-set-key 'lisp-indent-function 1)
779
780 (defun indent-sexp (&optional endpos)
781   "Indent each line of the list starting just after point.
782 If optional arg ENDPOS is given, indent each line, stopping when
783 ENDPOS is encountered."
784   (interactive)
785   (let ((indent-stack (list nil))
786         (next-depth 0)
787         ;; If ENDPOS is non-nil, use nil as STARTING-POINT
788         ;; so that calculate-lisp-indent will find the beginning of
789         ;; the defun we are in.
790         ;; If ENDPOS is nil, it is safe not to scan before point
791         ;; since every line we indent is more deeply nested than point is.
792         (starting-point (if endpos nil (point)))
793         (last-point (point))
794         last-depth bol outer-loop-done inner-loop-done state this-indent)
795     (or endpos
796         ;; Get error now if we don't have a complete sexp after point.
797         (save-excursion (forward-sexp 1)))
798     (save-excursion
799       (setq outer-loop-done nil)
800       (while (if endpos (< (point) endpos)
801                (not outer-loop-done))
802         (setq last-depth next-depth
803               inner-loop-done nil)
804         ;; Parse this line so we can learn the state
805         ;; to indent the next line.
806         ;; This inner loop goes through only once
807         ;; unless a line ends inside a string.
808         (while (and (not inner-loop-done)
809                     (not (setq outer-loop-done (eobp))))
810           (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
811                                           nil nil state))
812           (setq next-depth (car state))
813           ;; If the line contains a comment other than the sort
814           ;; that is indented like code,
815           ;; indent it now with indent-for-comment.
816           ;; Comments indented like code are right already.
817           ;; In any case clear the in-comment flag in the state
818           ;; because parse-partial-sexp never sees the newlines.
819           (if (car (nthcdr 4 state))
820               (progn (indent-for-comment)
821                      (end-of-line)
822                      (setcar (nthcdr 4 state) nil)))
823           ;; If this line ends inside a string,
824           ;; go straight to next line, remaining within the inner loop,
825           ;; and turn off the \-flag.
826           (if (car (nthcdr 3 state))
827               (progn
828                 (forward-line 1)
829                 (setcar (nthcdr 5 state) nil))
830             (setq inner-loop-done t)))
831         (and endpos
832              (<= next-depth 0)
833              (progn
834                (setq indent-stack (append indent-stack
835                                           (make-list (- next-depth) nil))
836                      last-depth (- last-depth next-depth)
837                      next-depth 0)))
838         (or outer-loop-done endpos
839             (setq outer-loop-done (<= next-depth 0)))
840         (if outer-loop-done
841             (forward-line 1)
842           (while (> last-depth next-depth)
843             (setq indent-stack (cdr indent-stack)
844                   last-depth (1- last-depth)))
845           (while (< last-depth next-depth)
846             (setq indent-stack (cons nil indent-stack)
847                   last-depth (1+ last-depth)))
848           ;; Now go to the next line and indent it according
849           ;; to what we learned from parsing the previous one.
850           (forward-line 1)
851           (setq bol (point))
852           (skip-chars-forward " \t")
853           ;; But not if the line is blank, or just a comment
854           ;; (except for double-semi comments; indent them as usual).
855           (if (or (eobp) (looking-at "\\s<\\|\n"))
856               nil
857             (if (and (car indent-stack)
858                      (>= (car indent-stack) 0))
859                 (setq this-indent (car indent-stack))
860               (let ((val (calculate-lisp-indent
861                           (if (car indent-stack) (- (car indent-stack))
862                             starting-point))))
863                 (if (integerp val)
864                     (setcar indent-stack
865                             (setq this-indent val))
866                   (setcar indent-stack (- (car (cdr val))))
867                   (setq this-indent (car val)))))
868             (if (/= (current-column) this-indent)
869                 (progn (delete-region bol (point))
870                        (indent-to this-indent)))))
871         (or outer-loop-done
872             (setq outer-loop-done (= (point) last-point))
873             (setq last-point (point)))))))
874
875 ;; Indent every line whose first char is between START and END inclusive.
876 (defun lisp-indent-region (start end)
877   (save-excursion
878     (let ((endmark (copy-marker end)))
879       (goto-char start)
880       (and (bolp) (not (eolp))
881            (lisp-indent-line))
882       (indent-sexp endmark)
883       (set-marker endmark nil))))
884 \f
885 ;;;; Lisp paragraph filling commands.
886
887 (defun lisp-fill-paragraph (&optional justify)
888   "Like \\[fill-paragraph], but handle Emacs Lisp comments.
889 If any of the current line is a comment, fill the comment or the
890 paragraph of it that point is in, preserving the comment's indentation
891 and initial semicolons."
892   (interactive "P")
893   (let (
894         ;; Non-nil if the current line contains a comment.
895         has-comment
896
897         ;; Non-nil if the current line contains code and a comment.
898         has-code-and-comment
899
900         ;; If has-comment, the appropriate fill-prefix for the comment.
901         comment-fill-prefix
902         )
903
904     ;; Figure out what kind of comment we are looking at.
905     (save-excursion
906       (beginning-of-line)
907       (cond
908
909        ;; A line with nothing but a comment on it?
910        ((looking-at "[ \t]*;[; \t]*")
911         (setq has-comment t
912               comment-fill-prefix (buffer-substring (match-beginning 0)
913                                                     (match-end 0))))
914
915        ;; A line with some code, followed by a comment?  Remember that the
916        ;; semi which starts the comment shouldn't be part of a string or
917        ;; character.
918        ;; XEmacs Try this the FSF and see if it works.
919 ;       ((progn
920 ;         (while (not (looking-at ";\\|$"))
921 ;           (skip-chars-forward "^;\n\"\\\\?")
922 ;           (cond
923 ;            ((eq (char-after (point)) ?\\) (forward-char 2))
924 ;            ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
925 ;         (looking-at ";+[\t ]*"))
926 ;       (setq has-comment t)
927        ((condition-case nil
928             (save-restriction
929               (narrow-to-region (point-min)
930                                 (save-excursion (end-of-line) (point)))
931               (while (not (looking-at ";\\|$"))
932                 (skip-chars-forward "^;\n\"\\\\?")
933                 (cond
934                  ((eq (char-after (point)) ?\\) (forward-char 2))
935                  ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
936               (looking-at ";+[\t ]*"))
937           (error nil))
938         (setq has-comment t has-code-and-comment t)
939         (setq comment-fill-prefix
940               (concat (make-string (/ (current-column) 8) ?\t)
941                       (make-string (% (current-column) 8) ?\ )
942                       (buffer-substring (match-beginning 0) (match-end 0)))))))
943
944     (if (not has-comment)
945         (fill-paragraph justify)
946
947       ;; Narrow to include only the comment, and then fill the region.
948       (save-excursion
949         (save-restriction
950           (beginning-of-line)
951           (narrow-to-region
952            ;; Find the first line we should include in the region to fill.
953            (save-excursion
954              (while (and (zerop (forward-line -1))
955                          (looking-at "^[ \t]*;")))
956              ;; We may have gone too far.  Go forward again.
957              (or (looking-at ".*;")
958                  (forward-line 1))
959              (point))
960            ;; Find the beginning of the first line past the region to fill.
961            (save-excursion
962              (while (progn (forward-line 1)
963                            (looking-at "^[ \t]*;")))
964              (point)))
965
966           ;; Lines with only semicolons on them can be paragraph boundaries.
967           (let* ((paragraph-start (concat paragraph-start "\\|[ \t;]*$"))
968                  (paragraph-separate (concat paragraph-start "\\|[ \t;]*$"))
969                  (paragraph-ignore-fill-prefix nil)
970                  (fill-prefix comment-fill-prefix)
971                  (after-line (if has-code-and-comment
972                                  (save-excursion
973                                    (forward-line 1) (point))))
974                  (end (progn
975                         (forward-paragraph)
976                         (or (bolp) (newline 1))
977                         (point)))
978                  ;; If this comment starts on a line with code,
979                  ;; include that like in the filling.
980                  (beg (progn (backward-paragraph)
981                              (if (eq (point) after-line)
982                                  (forward-line -1))
983                              (point))))
984             (fill-region-as-paragraph beg end
985                                       justify nil
986                                       (save-excursion
987                                         (goto-char beg)
988                                         (if (looking-at fill-prefix)
989                                             nil
990                                           (re-search-forward comment-start-skip)
991                                           (point))))))))
992     t))
993 \f
994 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
995   "Indent all lines of code, starting in the region, sideways by ARG columns.
996 Does not affect lines starting inside comments or strings, assuming that
997 the start of the region is not inside them.
998
999 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1000 The last is a regexp which, if matched at the beginning of a line,
1001 means don't indent that line."
1002   (interactive "r\np")
1003   (let (state)
1004     (save-excursion
1005       (goto-char end)
1006       (setq end (point-marker))
1007       (goto-char start)
1008       (or (bolp)
1009           (setq state (parse-partial-sexp (point)
1010                                           (progn
1011                                             (forward-line 1) (point))
1012                                           nil nil state)))
1013       (while (< (point) end)
1014         (or (car (nthcdr 3 state))
1015             (and nochange-regexp
1016                  (looking-at nochange-regexp))
1017             ;; If line does not start in string, indent it
1018             (let ((indent (current-indentation)))
1019               (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1020               (or (eolp)
1021                   (indent-to (max 0 (+ indent arg)) 0))))
1022         (setq state (parse-partial-sexp (point)
1023                                         (progn
1024                                           (forward-line 1) (point))
1025                                         nil nil state))))))
1026
1027 (provide 'lisp-mode)
1028
1029 ;;; lisp-mode.el ends here