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