view lisp/lisp-mode.el @ 5353:38e24b8be4ea

Improve the lexical scoping in #'block, #'return-from. lisp/ChangeLog addition: 2011-02-07 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el: * bytecomp.el (byte-compile-initial-macro-environment): Shadow `block', `return-from' here, we implement them differently when byte-compiling. * bytecomp.el (byte-compile-active-blocks): New. * bytecomp.el (byte-compile-block-1): New. * bytecomp.el (byte-compile-return-from-1): New. * bytecomp.el (return-from-1): New. * bytecomp.el (block-1): New. These are two aliases that exist to have their own associated byte-compile functions, which functions implement `block' and `return-from'. * cl-extra.el (cl-macroexpand-all): Fix a bug here when macros in the environment have been compiled. * cl-macs.el (block): * cl-macs.el (return): * cl-macs.el (return-from): Be more careful about lexical scope in these macros. * cl.el: * cl.el ('cl-block-wrapper): Removed. * cl.el ('cl-block-throw): Removed. These aren't needed in code generated by this XEmacs. They shouldn't be needed in code generated by XEmacs 21.4, but if it turns out the packages do need them, we can put them back. 2011-01-30 Mike Sperber <mike@xemacs.org> * font-lock.el (font-lock-fontify-pending-extents): Don't fail if `font-lock-mode' is unset, which can happen in the middle of `revert-buffer'. 2011-01-23 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (delete): * cl-macs.el (delq): * cl-macs.el (remove): * cl-macs.el (remq): Don't use the compiler macro if these functions were given the wrong number of arguments, as happens in lisp-tests.el. * cl-seq.el (remove, remq): Removed. I added these to subr.el, and forgot to remove them from here. 2011-01-22 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-setq, byte-compile-set): Remove kludge allowing keywords' values to be set, all the code that does that is gone. * cl-compat.el (elt-satisfies-test-p): * faces.el (set-face-parent): * faces.el (face-doc-string): * gtk-font-menu.el: * gtk-font-menu.el (gtk-reset-device-font-menus): * msw-font-menu.el: * msw-font-menu.el (mswindows-reset-device-font-menus): * package-get.el (package-get-installedp): * select.el (select-convert-from-image-data): * sound.el: * sound.el (load-sound-file): * x-font-menu.el (x-reset-device-font-menus-core): Don't quote keywords, they're self-quoting, and the win from backward-compatibility is sufficiently small now that the style problem overrides it. 2011-01-22 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (block, return-from): Require that NAME be a symbol in these macros, as always documented in the #'block docstring and as required by Common Lisp. * descr-text.el (unidata-initialize-unihan-database): Correct the use of non-symbols in #'block and #'return-from in this function. 2011-01-15 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (concatenate): Accept more complicated TYPEs in this function, handing the sequences over to #'coerce if we don't understand them here. * cl-macs.el (inline): Don't proclaim #'concatenate as inline, its compiler macro is more useful than doing that. 2011-01-11 Aidan Kehoe <kehoea@parhasard.net> * subr.el (delete, delq, remove, remq): Move #'remove, #'remq here, they don't belong in cl-seq.el; move #'delete, #'delq here from fns.c, implement them in terms of #'delete*, allowing support for sequences generally. * update-elc.el (do-autoload-commands): Use #'delete*, not #'delq here, now the latter's no longer dumped. * cl-macs.el (delete, delq): Add compiler macros transforming #'delete and #'delq to #'delete* calls. 2011-01-10 Aidan Kehoe <kehoea@parhasard.net> * dialog.el (make-dialog-box): Correct a misplaced parenthesis here, thank you Mats Lidell in 87zkr9gqrh.fsf@mail.contactor.se ! 2011-01-02 Aidan Kehoe <kehoea@parhasard.net> * dialog.el (make-dialog-box): * list-mode.el (display-completion-list): These functions used to use cl-parsing-keywords; change them to use defun* instead, fixing the build. (Not sure what led to me not including this change in d1b17a33450b!) 2011-01-02 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (define-star-compiler-macros): Make sure the form has ITEM and LIST specified before attempting to change to calls with explicit tests; necessary for some tests in lisp-tests.el to compile correctly. (stable-union, stable-intersection): Add compiler macros for these functions, in the same way we do for most of the other functions in cl-seq.el. 2011-01-01 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (dolist, dotimes, do-symbols, macrolet) (symbol-macrolet): Define these macros with defmacro* instead of parsing the argument list by hand, for the sake of style and readability; use backquote where appropriate, instead of calling #'list and and friends, for the same reason. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * x-misc.el (device-x-display): Provide this function, documented in the Lispref for years, but not existing previously. Thank you Julian Bradfield, thank you Jeff Mincy. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * cl-seq.el: Move the heavy lifting from this file to C. Dump the cl-parsing-keywords macro, but don't use defun* for the functions we define that do take keywords, dynamic scope lossage makes that not practical. * subr.el (sort, fillarray): Move these aliases here. (map-plist): #'nsublis is now built-in, but at this point #'eql isn't necessarily available as a test; use #'eq. * obsolete.el (cl-delete-duplicates): Make this available for old compiler macros and old code. (memql): Document that this is equivalent to #'member*, and worse. * cl.el (adjoin, subst): Removed. These are in C. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * simple.el (assoc-ignore-case): Remove a duplicate definition of this function (it's already in subr.el). * iso8859-1.el (char-width): On non-Mule, make this function equivalent to that produced by (constantly 1), but preserve its docstring. * subr.el (subst-char-in-string): Define this in terms of #'substitute, #'nsubstitute. (string-width): Define this using #'reduce and #'char-width. (char-width): Give this a simpler definition, it makes far more sense to check for mule at load time and redefine, as we do in iso8859-1.el. (store-substring): Implement this in terms of #'replace, now #'replace is cheap. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * update-elc.el (lisp-files-needed-for-byte-compilation) (lisp-files-needing-early-byte-compilation): cl-macs belongs in the former, not the latter, it is as fundamental as bytecomp.el. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * cl.el: Provde the Common Lisp program-error, type-error as error symbols. This doesn't nearly go far enough for anyone using the Common Lisp errors. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (delete-duplicates): If the form has an incorrect number of arguments, don't attempt a compiler macroexpansion. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (cl-safe-expr-p): Forms that start with the symbol lambda are also safe. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (= < > <= >=): For these functions' compiler macros, the optimisation is safe even if the first and the last arguments have side effects, since they're only used the once. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (inline-side-effect-free-compiler-macros): Unroll a loop here at macro-expansion time, so these compiler macros are compiled. Use #'eql instead of #'eq in a couple of places for better style. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (notany, notevery): Avoid some dynamic scope stupidity with local variable names in these functions, when they weren't prefixed with cl-; go into some more detail in the doc strings. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (side-effect-free-fns): #'remove, #'remq are free of side-effects. (side-effect-and-error-free-fns): Drop dot, dot-marker from the list. 2010-11-17 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (coerce): In the argument list, name the first argument OBJECT, not X; the former name was always used in the doc string and is clearer. Handle vector type specifications which include the length of the target sequence, error if there's a mismatch. * cl-macs.el (cl-make-type-test): Handle type specifications starting with the symbol 'eql. 2010-11-14 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (eql): Don't remove the byte-compile property of this symbol. That was necessary to override a bug in bytecomp.el where #'eql was confused with #'eq, which bug we no longer have. If neither expression is constant, don't attempt to handle the expression in this compiler macro, leave it to byte-compile-eql, which produces better code anyway. * bytecomp.el (eq): #'eql is not the function associated with the byte-eq byte code. (byte-compile-eql): Add an explicit compile method for this function, for cases where the cl-macs compiler macro hasn't reduced it to #'eq or #'equal. 2010-10-25 Aidan Kehoe <kehoea@parhasard.net> Add compiler macros and compilation sanity-checking for various functions that take keywords. * byte-optimize.el (side-effect-free-fns): #'symbol-value is side-effect free and not error free. * bytecomp.el (byte-compile-normal-call): Check keyword argument lists for sanity; store information about the positions where keyword arguments start using the new byte-compile-keyword-start property. * cl-macs.el (cl-const-expr-val): Take a new optional argument, cl-not-constant, defaulting to nil, in this function; return it if the expression is not constant. (cl-non-fixnum-number-p): Make this into a separate function, we want to pass it to #'every. (eql): Use it. (define-star-compiler-macros): Use the same code to generate the member*, assoc* and rassoc* compiler macros; special-case some code in #'add-to-list in subr.el. (remove, remq): Add compiler macros for these two functions, in preparation for #'remove being in C. (define-foo-if-compiler-macros): Transform (remove-if-not ...) calls to (remove ... :if-not) at compile time, which will be a real win once the latter is in C. (define-substitute-if-compiler-macros) (define-subst-if-compiler-macros): Similarly for these functions. (delete-duplicates): Change this compiler macro to use #'plists-equal; if we don't have information about the type of SEQUENCE at compile time, don't bother attempting to inline the call, the function will be in C soon enough. (equalp): Remove an old commented-out compiler macro for this, if we want to see it it's in version control. (subst-char-in-string): Transform this to a call to nsubstitute or nsubstitute, if that is appropriate. * cl.el (ldiff): Don't call setf here, this makes for a load-time dependency problem in cl-macs.el 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * term/vt100.el: Refer to XEmacs, not GNU Emacs, in permissions. * term/bg-mouse.el: * term/sup-mouse.el: Put copyright notice in canonical "Copyright DATE AUTHOR" form. Refer to XEmacs, not GNU Emacs, in permissions. * site-load.el: Add permission boilerplate. * mule/canna-leim.el: * alist.el: Refer to XEmacs, not APEL/this program, in permissions. * mule/canna-leim.el: Remove my copyright, I've assigned it to the FSF. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * gtk.el: * gtk-widget-accessors.el: * gtk-package.el: * gtk-marshal.el: * gtk-compose.el: * gnome.el: Add copyright notice based on internal evidence. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * easymenu.el: Add reference to COPYING to permission notice. * gutter.el: * gutter-items.el: * menubar-items.el: Fix typo "Xmacs" in permissions notice. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * auto-save.el: * font.el: * fontconfig.el: * mule/kinsoku.el: Add "part of XEmacs" text to permission notice. 2010-10-14 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (side-effect-free-fns): * cl-macs.el (remf, getf): * cl-extra.el (tailp, cl-set-getf, cl-do-remf): * cl.el (ldiff, endp): Tighten up Common Lisp compatibility for #'ldiff, #'endp, #'tailp; add circularity checking for the first two. #'cl-set-getf and #'cl-do-remf were Lisp implementations of #'plist-put and #'plist-remprop; change the names to aliases, changes the macros that use them to using #'plist-put and #'plist-remprop directly. 2010-10-12 Aidan Kehoe <kehoea@parhasard.net> * abbrev.el (fundamental-mode-abbrev-table, global-abbrev-table): Create both these abbrev tables using the usual #'define-abbrev-table calls, rather than attempting to special-case them. * cl-extra.el: Force cl-macs to be loaded here, if cl-extra.el is being loaded interpreted. Previously other, later files would redundantly call (load "cl-macs") when interpreted, it's more reasonable to do it here, once. * cmdloop.el (read-quoted-char-radix): Use defcustom here, we don't have any dump-order dependencies that would prevent that. * custom.el (eval-when-compile): Don't load cl-macs when interpreted or when byte-compiling, rely on cl-extra.el in the former case and the appropriate entry in bytecomp-load-hook in the latter. Get rid of custom-declare-variable-list, we have no dump-time dependencies that would require it. * faces.el (eval-when-compile): Don't load cl-macs when interpreted or when byte-compiling. * packages.el: Remove some inaccurate comments. * post-gc.el (cleanup-simple-finalizers): Use #'delete-if-not here, now the order of preloaded-file-list has been changed to make it available. * subr.el (custom-declare-variable-list): Remove. No need for it. Also remove a stub define-abbrev-table from this file, given the current order of preloaded-file-list there's no need for it. 2010-10-10 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-constp) Forms quoted with FUNCTION are also constant. (byte-compile-initial-macro-environment): In #'the, if FORM is constant and does not match TYPE, warn at byte-compile time. 2010-10-10 Aidan Kehoe <kehoea@parhasard.net> * backquote.el (bq-vector-contents, bq-list*): Remove; the former is equivalent to (append VECTOR nil), the latter to (list* ...). (bq-process-2): Use (append VECTOR nil) instead of using #'bq-vector-contents to convert to a list. (bq-process-1): Now we use list* instead of bq-list * subr.el (list*): Moved from cl.el, since it is now required to be available the first time a backquoted form is encountered. * cl.el (list*): Move to subr.el. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * test-harness.el (Check-Message): Add an omitted comma here, thank you the buildbot. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * hash-table.el (hash-table-key-list, hash-table-value-list) (hash-table-key-value-alist, hash-table-key-value-plist): Remove some useless #'nreverse calls in these files; our hash tables have no order, it's not helpful to pretend they do. * behavior.el (read-behavior): Do the same in this file, in some code evidently copied from hash-table.el. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * info.el (Info-insert-dir): * format.el (format-deannotate-region): * files.el (cd, save-buffers-kill-emacs): Use #'some, #'every and related functions for applying boolean operations to lists, instead of rolling our own ones that cons and don't short-circuit. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-initial-macro-environment): * cl-macs.el (the): Rephrase the docstring, make its implementation when compiling files a little nicer. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * descr-text.el (unidata-initialize-unicodedata-database) (unidata-initialize-unihan-database, describe-char-unicode-data) (describe-char-unicode-data): Wrap calls to the database functions with (with-fboundp ...), avoiding byte compile warnings on builds without support for the database functions. (describe-char): (reduce #'max ...), not (apply #'max ...), no need to cons needlessly. (describe-char): Remove a redundant lambda wrapping #'extent-properties. (describe-char-unicode-data): Call #'nsubst when replacing "" with nil in the result of #'split-string, instead of consing inside mapcar. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * x-faces.el (x-available-font-sizes): * specifier.el (let-specifier): * package-ui.el (pui-add-required-packages): * msw-faces.el (mswindows-available-font-sizes): * modeline.el (modeline-minor-mode-menu): * minibuf.el (minibuf-directory-files): Replace the O2N (delq nil (mapcar (lambda (W) (and X Y)) Z)) with the ON (mapcan (lambda (W) (and X (list Y))) Z) in these files. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (= < > <= >=): When these functions are handed more than two arguments, and those arguments have no side effects, transform to a series of two argument calls, avoiding funcall in the byte-compiled code. * mule/mule-cmds.el (finish-set-language-environment): Take advantage of this change in a function called 256 times at startup. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-function-form, byte-compile-quote) (byte-compile-quote-form): Warn at compile time, and error at runtime, if a (quote ...) or a (function ...) form attempts to quote more than one object. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (byte-optimize-apply): Transform (apply 'nconc (mapcar ...)) to (mapcan ...); warn about use of the first idiom. * update-elc.el (do-autoload-commands): * packages.el (packages-find-package-library-path): * frame.el (frame-list): * extents.el (extent-descendants): * etags.el (buffer-tag-table-files): * dumped-lisp.el (preloaded-file-list): * device.el (device-list): * bytecomp-runtime.el (proclaim-inline, proclaim-notinline) Use #'mapcan, not (apply #'nconc (mapcar ...) in all these files. * bytecomp-runtime.el (eval-when-compile, eval-and-compile): In passing, mention that these macros also evaluate the body when interpreted. tests/ChangeLog addition: 2011-02-07 Aidan Kehoe <kehoea@parhasard.net> * automated/lisp-tests.el: Test lexical scope for `block', `return-from'; add a Known-Bug-Expect-Failure for a contorted example that fails when byte-compiled.
author Aidan Kehoe <kehoea@parhasard.net>
date Mon, 07 Feb 2011 12:01:24 +0000
parents 77907bd57d25
children 308d34e9f07d
line wrap: on
line source

;;; lisp-mode.el --- Lisp mode, and its idiosyncratic commands.

;; Copyright (C) 1985, 1996, 1997 Free Software Foundation, Inc.
;; Copyright (C) 1995 Tinker Systems.
;; Copyright (C) 2002, 2010 Ben Wing.

;; Maintainer: FSF
;; Keywords: lisp, languages, dumped

;; This file is part of XEmacs.

;; XEmacs is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; XEmacs is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with XEmacs; see the file COPYING.  If not, write to the Free
;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
;; 02111-1307, USA.

;;; Synched up with: FSF 19.34 (but starting to diverge).

;;; Commentary:

;; This file is dumped with XEmacs.

;; The base major mode for editing Lisp code (used also for Emacs Lisp).
;; This mode is documented in the Emacs manual

;;; Code:

(defgroup lisp nil
  "Lisp support, including Emacs Lisp."
  :group 'languages
  :group 'development)

(defvar lisp-mode-syntax-table nil)
(defvar emacs-lisp-mode-syntax-table nil)
(defvar lisp-mode-abbrev-table nil)

(defun construct-lisp-mode-menu (popup-p emacs-lisp-p)
  (flet ((popup-wrap (form)
	   (if popup-p `(menu-call-at-event ',form) form)))
    `(,@(if emacs-lisp-p
	  `(["%_Byte-Compile This File" ,(popup-wrap
					  'emacs-lisp-byte-compile)]
	    ["B%_yte-Compile/Load This File"
	     ,(popup-wrap 'emacs-lisp-byte-compile-and-load)]
	    ["Byte-%_Recompile Directory..."
	     ,(popup-wrap 'byte-recompile-directory)]
	    "---"))
	["%_Evaluate Region or Defun"
	 ,(popup-wrap '(if (region-exists-p)
			   (call-interactively 'eval-region)
			 (call-interactively 'eval-defun)))]
	["Evaluate %_Whole Buffer" ,(popup-wrap 'eval-current-buffer)]
	["Evaluate Last %_S-expression" ,(popup-wrap 'eval-last-sexp)]
	"---"
	["%_Indent Region or Balanced Expression"
	 ,(popup-wrap '(if (region-exists-p)
			   (call-interactively 'indent-region)
			 (call-interactively 'indent-sexp)))]
	["I%_ndent Defun"
	 ,(popup-wrap '(progn
			 (beginning-of-defun)
			 (indent-sexp)))]
	"---"
	["%_Comment Out Region" comment-region :active (region-exists-p)]
	["Unc%_omment Region" uncomment-region :active (region-exists-p)]
	"---"
	,@(if popup-p
	    '(["%_Find Function"
	       (find-function (menu-call-at-event '(function-at-point)))
	       :suffix (let ((fun (menu-call-at-event '(function-at-point))))
			 (if fun (symbol-name fun) ""))
	       :active (and (fboundp 'find-function)
			    (menu-call-at-event '(function-at-point)))]
	      ["%_Find Variable"
	       (find-variable (menu-call-at-event '(variable-at-point)))
	       :suffix (let ((fun (menu-call-at-event '(variable-at-point))))
			 (if fun (symbol-name fun) ""))
	       :active (and (fboundp 'find-variable)
			    (menu-call-at-event '(variable-at-point)))]
	      ["%_Help on Function"
	       (describe-function (menu-call-at-event '(function-at-point)))
	       :suffix (let ((fun (menu-call-at-event '(function-at-point))))
			 (if fun (symbol-name fun) ""))
	       :active (and (fboundp 'describe-function)
			    (menu-call-at-event '(function-at-point)))]
	      ["%_Help on Variable"
	       (describe-variable (menu-call-at-event '(variable-at-point)))
	       :suffix (let ((fun (menu-call-at-event '(variable-at-point))))
			 (if fun (symbol-name fun) ""))
	       :active (and (fboundp 'describe-variable)
			    (menu-call-at-event '(variable-at-point)))])
	    '(["Find %_Function..." find-function
	       :active (fboundp 'find-function)]
	      ["Find %_Variable..." find-variable
	       :active (fboundp 'find-variable)]
	      ["%_Help on Function..." describe-function
	       :active (fboundp 'describe-function)]
	      ["Hel%_p on Variable..." describe-variable
	       :active (fboundp 'describe-variable)]))
	"---"
	["Instrument This Defun for %_Debugging" ,(popup-wrap 'edebug-defun)]
	["%_Trace Function..." trace-function-background]
	["%_Untrace All Functions" untrace-all
	 :active (fboundp 'untrace-all)]
	"---"
	["Display %_Macro Expansion of Balanced Expression"
	 ,(popup-wrap 'macroexpand-sexp)]
	["Display Recursive Macro E%_xpansion of Balanced Expression"
	 ,(popup-wrap 'macroexpand-all-sexp)]
	"---"
	"Look for debug-on-error under Options->Troubleshooting"
	)))

(defvar lisp-interaction-mode-popup-menu
  (cons "Lisp-Interaction" (construct-lisp-mode-menu t nil)))

(defvar emacs-lisp-mode-popup-menu
  (cons "Emacs-Lisp" (construct-lisp-mode-menu t t)))

;Don't have a menubar entry in Lisp Interaction mode.  Otherwise, the
;*scratch* buffer has a Lisp menubar item!  Very confusing.
;Jan Vroonhof really wants this, so it's back.  --ben
(defvar lisp-interaction-mode-menubar-menu
  (cons "%_Lisp" (construct-lisp-mode-menu nil nil)))

(defvar emacs-lisp-mode-menubar-menu
  (cons "%_Lisp" (construct-lisp-mode-menu nil t)))

(if (not emacs-lisp-mode-syntax-table)
    (let ((i 0))
      (setq emacs-lisp-mode-syntax-table (make-syntax-table))
      (while (< i ?0)
	(modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
	(setq i (1+ i)))
      (setq i (1+ ?9))
      (while (< i ?A)
	(modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
	(setq i (1+ i)))
      (setq i (1+ ?Z))
      (while (< i ?a)
	(modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
	(setq i (1+ i)))
      (setq i (1+ ?z))
      (while (< i 128)
	(modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
	(setq i (1+ i)))
      (modify-syntax-entry ?  "    " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\t "    " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\f "    " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\n ">   " emacs-lisp-mode-syntax-table)
      ;; Give CR the same syntax as newline, for selective-display.
      (modify-syntax-entry ?\^m ">   " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\; "<   " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?` "'   " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?' "'   " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?, "'   " emacs-lisp-mode-syntax-table)
      ;; Used to be singlequote; changed for flonums.
      (modify-syntax-entry ?. "_   " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?# "'   " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\" "\"    " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\\ "\\   " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\( "()  " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\) ")(  " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\[ "(]  " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\] ")[  " emacs-lisp-mode-syntax-table)))

(if (not lisp-mode-syntax-table)
    (progn (setq lisp-mode-syntax-table
		 (copy-syntax-table emacs-lisp-mode-syntax-table))
	   (modify-syntax-entry ?\[ "_   " lisp-mode-syntax-table)
	   ;; XEmacs changes
	   (modify-syntax-entry ?\] "_   " lisp-mode-syntax-table)
	   (modify-syntax-entry ?#  "' 58" lisp-mode-syntax-table)
	   (modify-syntax-entry ?|  "\" 67" lisp-mode-syntax-table)))

(define-abbrev-table 'lisp-mode-abbrev-table ())

(defvar lisp-imenu-generic-expression
      '(
	(nil 
	 "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\\s-+\\([-A-Za-z0-9+*|:]+\\)" 2)
	("Variables" 
	 "^\\s-*(def\\(var\\|const\\|custom\\)\\s-+\\([-A-Za-z0-9+*|:]+\\)" 2)
	("Types" 
	 "^\\s-*(def\\(group\\|type\\|struct\\|class\\|ine-condition\\)\\s-+\\([-A-Za-z0-9+*|:]+\\)" 
	 2))

  "Imenu generic expression for Lisp mode.  See `imenu-generic-expression'.")

(defun lisp-mode-variables (lisp-syntax)
  (cond (lisp-syntax
	 (set-syntax-table lisp-mode-syntax-table)))
  (setq local-abbrev-table lisp-mode-abbrev-table)
  (make-local-variable 'paragraph-start)
  (setq paragraph-start (concat page-delimiter "\\|$" ))
  (make-local-variable 'paragraph-separate)
  (setq paragraph-separate paragraph-start)
  (make-local-variable 'paragraph-ignore-fill-prefix)
  (setq paragraph-ignore-fill-prefix t)
  (make-local-variable 'fill-paragraph-function)
  (setq fill-paragraph-function 'lisp-fill-paragraph)
  ;; Adaptive fill mode gets in the way of auto-fill,
  ;; and should make no difference for explicit fill
  ;; because lisp-fill-paragraph should do the job.
  (make-local-variable 'adaptive-fill-mode)
  (setq adaptive-fill-mode nil)
  (make-local-variable 'indent-line-function)
  (setq indent-line-function 'lisp-indent-line)
  (make-local-variable 'indent-region-function)
  (setq indent-region-function 'lisp-indent-region)
  (make-local-variable 'parse-sexp-ignore-comments)
  (setq parse-sexp-ignore-comments t)
  (make-local-variable 'outline-regexp)
  (setq outline-regexp ";;; \\|(....")
  (make-local-variable 'comment-start)
  (setq comment-start ";")
  ;; XEmacs change
  (set (make-local-variable 'block-comment-start) ";;")
  (make-local-variable 'comment-start-skip)
  ;; Look within the line for a ; following an even number of backslashes
  ;; after either a non-backslash or the line beginning.
  (setq comment-start-skip "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\);+ *")
  (make-local-variable 'comment-column)
  (setq comment-column 40)
  (make-local-variable 'comment-indent-function)
  (setq comment-indent-function 'lisp-comment-indent)
  ;; XEmacs change
  (set (make-local-variable 'dabbrev-case-fold-search) nil)
  (set (make-local-variable 'dabbrev-case-replace) nil)
  (make-local-variable 'imenu-generic-expression)
  (setq imenu-generic-expression lisp-imenu-generic-expression))

(defvar shared-lisp-mode-map ()
  "Keymap for commands shared by all sorts of Lisp modes.")

(if shared-lisp-mode-map
    ()
   (setq shared-lisp-mode-map (make-sparse-keymap))
   ;; XEmacs changes
   (set-keymap-name shared-lisp-mode-map 'shared-lisp-mode-map)
   (define-key shared-lisp-mode-map "\M-;" 'lisp-indent-for-comment)
   (define-key shared-lisp-mode-map "\e\C-q" 'indent-sexp))

(defvar emacs-lisp-mode-map ()
  "Keymap for Emacs Lisp mode.
All commands in `shared-lisp-mode-map' are inherited by this map.")

(if emacs-lisp-mode-map
    ()
  ;; XEmacs:  Ignore FSF nconc stuff
  (setq emacs-lisp-mode-map (make-sparse-keymap))
  (set-keymap-name emacs-lisp-mode-map 'emacs-lisp-mode-map)
  (set-keymap-parents emacs-lisp-mode-map (list shared-lisp-mode-map))
  (define-key emacs-lisp-mode-map "\e\t" 'lisp-complete-symbol)
  (define-key emacs-lisp-mode-map "\e\C-x" 'eval-defun)
  ;; XEmacs: Not sure what the FSF menu bindings are.  I hope XEmacs
  ;; doesn't need them.
)

;; XEmacs: add docstrings to the hooks
(defvar emacs-lisp-mode-hook nil
  "Hook to run when entering emacs-lisp-mode.")

(defvar lisp-mode-hook nil
  "Hook to run when entering lisp-mode.")

(defvar lisp-interaction-mode-hook nil
  "Hook to run when entering lisp-interaction-mode.")

(defun emacs-lisp-byte-compile ()
  "Byte compile the file containing the current buffer."
  (interactive)
  (if buffer-file-name
      ;; XEmacs change.  Force buffer save first
      (progn
	(save-buffer)
	(byte-compile-file buffer-file-name))
    (error "The buffer must be saved in a file first.")))

(defun emacs-lisp-byte-compile-and-load ()
  "Byte-compile the current file (if it has changed), then load compiled code."
  (interactive)
  (or buffer-file-name
      (error "The buffer must be saved in a file first"))
  (require 'bytecomp)
  ;; Recompile if file or buffer has changed since last compilation.
  (if (and (buffer-modified-p)
	   (y-or-n-p (format "save buffer %s first? " (buffer-name))))
      (save-buffer))
  (let ((compiled-file-name (byte-compile-dest-file buffer-file-name)))
    (if (file-newer-than-file-p compiled-file-name buffer-file-name)
	(load-file compiled-file-name)
      (byte-compile-file buffer-file-name t))))

(defun emacs-lisp-mode ()
  "Major mode for editing Lisp code to run in Emacs.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs.  Semicolons start comments.
\\{emacs-lisp-mode-map}
Entry to this mode calls the value of `emacs-lisp-mode-hook'
if that value is non-nil."
  (interactive)
  (kill-all-local-variables)
  (use-local-map emacs-lisp-mode-map)
  (set-syntax-table emacs-lisp-mode-syntax-table)
  ;; XEmacs changes
  (setq major-mode 'emacs-lisp-mode
	mode-popup-menu emacs-lisp-mode-popup-menu
	mode-name "Emacs-Lisp")
  (if (and (featurep 'menubar)
           current-menubar)
      (progn
	;; make a local copy of the menubar, so our modes don't
	;; change the global menubar
	(set-buffer-menubar current-menubar)
	(add-submenu nil emacs-lisp-mode-menubar-menu)))
  (lisp-mode-variables nil)
  (run-hooks 'emacs-lisp-mode-hook))

(put 'emacs-lisp-mode 'font-lock-lisp-like t)

(defvar lisp-mode-map ()
  "Keymap for ordinary Lisp mode.
All commands in `shared-lisp-mode-map' are inherited by this map.")

(if lisp-mode-map
    ()
  ;; XEmacs changes
  (setq lisp-mode-map (make-sparse-keymap))
  (set-keymap-name lisp-mode-map 'lisp-mode-map)
  (set-keymap-parents lisp-mode-map (list shared-lisp-mode-map))
  ;; gag, no.  use ilisp.  -jwz
;;  (define-key lisp-mode-map "\C-c\C-z" 'run-lisp)
  )

(defun lisp-mode ()
  "Major mode for editing Lisp code for Lisps other than Emacs Lisp.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs.  Semicolons start comments.
\\{lisp-mode-map}
Note that `run-lisp' may be used either to start an inferior Lisp job
or to switch back to an existing one.

Entry to this mode calls the value of `lisp-mode-hook'
if that value is non-nil."
  (interactive)
  (kill-all-local-variables)
  (use-local-map lisp-mode-map)
  (setq major-mode 'lisp-mode)
  (setq mode-name "Lisp")
  (lisp-mode-variables t)
  (set-syntax-table lisp-mode-syntax-table)
  (run-hooks 'lisp-mode-hook))

;; XEmacs change: emacs-lisp-mode-map is a more appropriate parent.
(defvar lisp-interaction-mode-map ()
  "Keymap for Lisp Interaction mode.
All commands in `shared-lisp-mode-map' are inherited by this map.")

(if lisp-interaction-mode-map
    ()
  ;; XEmacs set keymap our way
  (setq lisp-interaction-mode-map (make-sparse-keymap))
  (set-keymap-name lisp-interaction-mode-map 'lisp-interaction-mode-map)
  (set-keymap-parents lisp-interaction-mode-map (list emacs-lisp-mode-map))
  (define-key lisp-interaction-mode-map "\e\C-x" 'eval-defun)
  (define-key lisp-interaction-mode-map "\e\t" 'lisp-complete-symbol)
  (define-key lisp-interaction-mode-map "\n" 'eval-print-last-sexp))

(defun lisp-interaction-mode ()
  "Major mode for typing and evaluating Lisp forms.
Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
before point, and prints its value into the buffer, advancing point.

Commands:
Delete converts tabs to spaces as it moves back.
Paragraphs are separated only by blank lines.
Semicolons start comments.
\\{lisp-interaction-mode-map}
Entry to this mode calls the value of `lisp-interaction-mode-hook'
if that value is non-nil."
  (interactive)
  (kill-all-local-variables)
  (use-local-map lisp-interaction-mode-map)
  (setq major-mode 'lisp-interaction-mode)
  (setq mode-name "Lisp Interaction")
  (setq mode-popup-menu lisp-interaction-mode-popup-menu)
  (if (and (featurep 'menubar)
           current-menubar)
      (progn
	;; make a local copy of the menubar, so our modes don't
	;; change the global menubar
	(set-buffer-menubar current-menubar)
	(add-submenu nil lisp-interaction-mode-menubar-menu)))
  (set-syntax-table emacs-lisp-mode-syntax-table)
  (lisp-mode-variables nil)
  (run-hooks 'lisp-interaction-mode-hook))

(defun eval-print-last-sexp ()
  "Evaluate sexp before point; print value into current buffer."
  (interactive)
  (let ((standard-output (current-buffer)))
    (terpri)
    (eval-last-sexp t)
    (terpri)))

;; XEmacs change
(defcustom eval-interactive-verbose t
  "*Non-nil means that interactive evaluation can print messages.
The messages are printed when the expression is treated differently
using `\\[eval-last-sexp]' and `\\[eval-defun]' than it would have
been treated noninteractively.

The printed messages are \"defvar treated as defconst\" and \"defcustom
evaluation forced\".  See `eval-interactive' for more details."
  :type 'boolean
  :group 'lisp)

(defun eval-interactive (expr)
  "Evaluate EXPR; pass back multiple values, transform defvars to defconsts. 

Always returns a list.  The length of this list will be something other than
one if the form returned multiple values.  It will be zero if the form
returned a single zero-length multiple value."
  (cond ((and (eq (car-safe expr) 'defvar)
	      (> (length expr) 2))
	 (setq expr (multiple-value-list (eval (cons 'defconst (cdr expr)))))
	 (when eval-interactive-verbose
	   (message "defvar treated as defconst")
	   (sit-for 1)
	   (message ""))
         expr)
	((and (eq (car-safe expr) 'defcustom)
	      (> (length expr) 2)
	      (default-boundp (nth 1 expr)))
	 ;; Force variable to be bound
         (funcall 
          (or (plist-get expr :set) #'custom-set-default)
          (nth 1 expr) (eval (nth 2 expr)))
	 ;; And evaluate the defcustom
	 (setq expr (multiple-value-list (eval expr)))
	 (when eval-interactive-verbose
	   (message "defcustom evaluation forced")
	   (sit-for 1)
	   (message ""))
         expr)
	(t
	 (multiple-value-list (eval expr)))))

(defun prin1-list-as-multiple-values (multiple-value-list &optional stream)
  "Call `prin1' on each element of MULTIPLE-VALUE-LIST, separated by \" ;\\n\"

If MULTIPLE-VALUE-LIST is zero-length, print the text
\"#<zero length multiple value> ;\\n\".  Always returns nil."
  (loop for value in multiple-value-list
    with seen-first = nil
    do
    (if seen-first
        (princ " ;\n" stream)
      (setq seen-first t))
    (prin1 value stream)
    finally (unless seen-first
	      (princ "#<zero length multiple value> ;" stream))))

;; XEmacs change, based on Bob Weiner suggestion
(defun eval-last-sexp (eval-last-sexp-arg-internal) ;dynamic scoping wonderment
  "Evaluate sexp before point; print value in minibuffer.
With argument, print output into current buffer."
  (interactive "P")
  (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t))
	(opoint (point))
	ignore-quotes)
    (prin1-list-as-multiple-values
     (eval-interactive
      (letf (((syntax-table) emacs-lisp-mode-syntax-table))
        (save-excursion
          ;; If this sexp appears to be enclosed in `...' then
          ;; ignore the surrounding quotes.
          (setq ignore-quotes (or (eq (char-after) ?\')
                                  (eq (char-before) ?\')))
          (forward-sexp -1)
          ;; vladimir@cs.ualberta.ca 30-Jul-1997: skip ` in
          ;; `variable' so that the value is returned, not the
          ;; name.
          (if (and ignore-quotes
                   (eq (char-after) ?\`))
              (forward-char))
          (save-restriction
            (narrow-to-region (point-min) opoint)
            (let ((expr (read (current-buffer))))
              (if (eq (car-safe expr) 'interactive)
                  ;; If it's an (interactive ...) form, it's
                  ;; more useful to show how an interactive call
                  ;; would use it.
                  `(call-interactively
                    (lambda (&rest args)
                      ,expr args))
                expr)))))))))

(defun eval-defun (eval-defun-arg-internal)
  "Evaluate defun that point is in or before.
Print value in minibuffer.
With argument, insert value in current buffer after the defun."
  (interactive "P")
  (let ((standard-output (if eval-defun-arg-internal (current-buffer) t)))
    (prin1-list-as-multiple-values
     (eval-interactive
      (save-excursion
        (end-of-defun)
        (beginning-of-defun)
        (read (current-buffer)))))))

(defun lisp-comment-indent ()
  (if (looking-at "\\s<\\s<\\s<")
      (current-column)
    (if (looking-at "\\s<\\s<")
	;; #### FSF has:
	;; (let ((tem (or (calculate-lisp-indent) (current-column)))) ...
	(let ((tem (calculate-lisp-indent)))
	  (if (listp tem) (car tem) tem))
      (skip-chars-backward " \t")
      (max (if (bolp) 0 (1+ (current-column)))
	   comment-column))))

;; XEmacs change
(defun lisp-indent-for-comment ()
  "Indent this line's comment appropriately, or insert an empty comment.
If adding a new comment on a blank line, use `block-comment-start' instead
of `comment-start' to open the comment."
  ;; by Stig@hackvan.com
  ;; #### - This functionality, the recognition of block-comment-{start,end},
  ;; will perhaps be standardized across modes and move to indent-for-comment.
  (interactive)
  (if (and block-comment-start
	   (save-excursion (beginning-of-line) (looking-at "^[ \t]*$")))
      (insert block-comment-start))
  (indent-for-comment))

(defvar lisp-indent-offset nil)
(defvar lisp-indent-function 'lisp-indent-function)

(defun lisp-indent-line (&optional whole-exp)
  "Indent current line as Lisp code.
With argument, indent any additional lines of the same expression
rigidly along with this one."
  (interactive "P")
  (let ((indent (calculate-lisp-indent)) shift-amt beg end
	(pos (- (point-max) (point))))
    (beginning-of-line)
    (setq beg (point))
    (skip-chars-forward " \t")
    (if (looking-at "\\s<\\s<\\s<")
	;; Don't alter indentation of a ;;; comment line.
	(goto-char (- (point-max) pos))
      (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
	  ;; Single-semicolon comment lines should be indented
	  ;; as comment lines, not as code.
	  (progn (indent-for-comment) (backward-char 1))
	(if (listp indent) (setq indent (car indent)))
	(setq shift-amt (- indent (current-column)))
	(if (zerop shift-amt)
	    nil
	  (delete-region beg (point))
	  (indent-to indent)))
      ;; If initial point was within line's indentation,
      ;; position after the indentation.  Else stay at same point in text.
      (if (> (- (point-max) pos) (point))
	  (goto-char (- (point-max) pos)))
      ;; If desired, shift remaining lines of expression the same amount.
      (and whole-exp (not (zerop shift-amt))
	   (save-excursion
	     (goto-char beg)
	     (forward-sexp 1)
	     (setq end (point))
	     (goto-char beg)
	     (forward-line 1)
	     (setq beg (point))
	     (> end beg))
	   (indent-code-rigidly beg end shift-amt)))))

(defvar calculate-lisp-indent-last-sexp)

(defun calculate-lisp-indent (&optional parse-start)
  "Return appropriate indentation for current line as Lisp code.
In usual case returns an integer: the column to indent to.
Can instead return a list, whose car is the column to indent to.
This means that following lines at the same level of indentation
should not necessarily be indented the same way.
The second element of the list is the buffer position
of the start of the containing expression."
  (save-excursion
    (beginning-of-line)
    (let ((indent-point (point))
	  ;; XEmacs change (remove paren-depth)
          state ;;paren-depth
          ;; setting this to a number inhibits calling hook
          (desired-indent nil)
          (retry t)
          calculate-lisp-indent-last-sexp containing-sexp)
      (if parse-start
          (goto-char parse-start)
          (beginning-of-defun))
      ;; Find outermost containing sexp
      (while (< (point) indent-point)
        (setq state (parse-partial-sexp (point) indent-point 0)))
      ;; Find innermost containing sexp
      (while (and retry
		  state
		  ;; XEmacs change (remove paren-depth)
                  (> ;;(setq paren-depth (elt state 0))
		     (elt state 0)
		     0))
        (setq retry nil)
        (setq calculate-lisp-indent-last-sexp (elt state 2))
        (setq containing-sexp (elt state 1))
        ;; Position following last unclosed open.
        (goto-char (1+ containing-sexp))
        ;; Is there a complete sexp since then?
        (if (and calculate-lisp-indent-last-sexp
		 (> calculate-lisp-indent-last-sexp (point)))
            ;; Yes, but is there a containing sexp after that?
            (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
					    indent-point 0)))
              (if (setq retry (car (cdr peek))) (setq state peek)))))
      (if retry
          nil
        ;; Innermost containing sexp found
        (goto-char (1+ containing-sexp))
        (if (not calculate-lisp-indent-last-sexp)
	    ;; indent-point immediately follows open paren.
	    ;; Don't call hook.
            (setq desired-indent (current-column))
	  ;; Find the start of first element of containing sexp.
	  (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
	  (cond ((looking-at "\\s(")
		 ;; First element of containing sexp is a list.
		 ;; Indent under that list.
		 )
		((> (save-excursion (forward-line 1) (point))
		    calculate-lisp-indent-last-sexp)
		 ;; This is the first line to start within the containing sexp.
		 ;; It's almost certainly a function call.
		 (if (= (point) calculate-lisp-indent-last-sexp)
		     ;; Containing sexp has nothing before this line
		     ;; except the first element.  Indent under that element.
		     nil
		   ;; Skip the first element, find start of second (the first
		   ;; argument of the function call) and indent under.
		   (progn (forward-sexp 1)
			  (parse-partial-sexp (point)
					      calculate-lisp-indent-last-sexp
					      0 t)))
		 (backward-prefix-chars))
		(t
		 ;; Indent beneath first sexp on same line as
		 ;; calculate-lisp-indent-last-sexp.  Again, it's
		 ;; almost certainly a function call.
		 (goto-char calculate-lisp-indent-last-sexp)
		 (beginning-of-line)
		 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
				     0 t)
		 (backward-prefix-chars)))))
      ;; Point is at the point to indent under unless we are inside a string.
      ;; Call indentation hook except when overridden by lisp-indent-offset
      ;; or if the desired indentation has already been computed.
      (let ((normal-indent (current-column)))
        (cond ((elt state 3)
               ;; Inside a string, don't change indentation.
               (goto-char indent-point)
               (skip-chars-forward " \t")
               (current-column))
              (desired-indent)
              ((and (boundp 'lisp-indent-function)
                    lisp-indent-function
                    (not retry))
               (or (funcall lisp-indent-function indent-point state)
                   normal-indent))
	      ;; XEmacs change:
              ;; lisp-indent-offset shouldn't override lisp-indent-function !
              ((and (integerp lisp-indent-offset) containing-sexp)
               ;; Indent by constant offset
               (goto-char containing-sexp)
               (+ normal-indent lisp-indent-offset))
              (t
               normal-indent))))))

(defvar lisp-function-and-type-regexp
  (concat "def\\("
	  ;; def but not define-.
	  "\\(un\\*?\\|advice\\|alias\\|macro\\*?\\|setf\\|subst\\*?\\|"
	  "-edebug-spec\\|"
	  ;; CLOS
	  "method\\|generic\\|"
	  ;; define-*
	  "ine-\\(?:"
	  ;; basic Lisp stuff
	  "compiler-macro\\|function\\|function-when-void\\|modify-macro\\|"
	  "setf-method\\|"
	  ;; obsolete/compatible support, XEmacs-specific
	  "compatible-function-alias\\|obsolete-function-alias\\|"
	  ;; XEmacs-specific, supporting stuff inside of XEmacs
	  "ccl-program\\|device-method\\*?\\|prefix-command\\|skeleton"
          "\\)\\)\\|"
	  ;; Structure declarations.
	  "\\(class\\|struct\\|type\\)\\)\\>")
  "Regular expression to match the function and type keywords used in Lisp.
This matches, for example, the string \"defun\", as well as defsetf,
defsubst*, define-prefix-command, etc.  Match string 1 matches everything
but the three-letter \"def\" string at the beginning.  Match string 2
matches everything after that, when it's *NOT* a \"type\" declaration --
which includes defclass, defstruct, and deftype.  Match string 3 is similar
to match string 2 in that it matches everything after the \"def\", when
\(and only when) the keyword matched *IS* a type declaration.  You can use
match strings 2 and 3 to easily determine whether a function or type was
matched.  The regex is terminated with a \\\> so that there must be a
word-end; i.e. defunbbb won't match.")

(defvar lisp-flet-regexp
  "(\\(flet\\|macrolet\\|labels\\)\\(\\s-\\|\n\\)")

(defun lisp-indent-function (indent-point state)
  ;; free reference to `calculate-lisp-indent-last-sexp'
  ;; in #'calculate-lisp-indent
  (let ((normal-indent (current-column)))
    (goto-char (1+ (elt state 1)))
    (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
    (if (and (elt state 2)
             (not (looking-at "\\sw\\|\\s_")))
        ;; car of form doesn't seem to be a symbol
        (progn
          (if (not (> (save-excursion (forward-line 1) (point))
                      calculate-lisp-indent-last-sexp))
              (progn (goto-char calculate-lisp-indent-last-sexp)
                     (beginning-of-line)
                     (parse-partial-sexp (point)
					 calculate-lisp-indent-last-sexp 0 t)))
          ;; Indent under the list or under the first sexp on the same
          ;; line as calculate-lisp-indent-last-sexp.  Note that first
          ;; thing on that line has to be complete sexp since we are
          ;; inside the innermost containing sexp.
          (backward-prefix-chars)
          (current-column))

      ;; Now come a bunch of ad-hoc checks to see if we're in particular
      ;; places (defining an flet function, in the argument list of a
      ;; regular or flet function, in a quoted list, etc.) where the
      ;; regular indenting doesn't work well.

      ;; #### All this stuff here should be generalized so that
      ;; you can specify, for various functions, how you want
      ;; particular arguments handled -- in some way that works
      ;; recursively, so it can handle flet and such.
      
      (let* ((function (buffer-substring (point)
					(progn (forward-sexp 1) (point))))
	     (quote (condition-case nil
			(save-excursion
			  (backward-up-list 1)
			  (memq (char-before (point)) '(?' ?`)))))
	     method)
	(cond
	 ;; if we're indenting a quoted list, and the first word is not
	 ;; lambda, line up second line below first with no indentation,
	 ;; so that property lists indent correctly.
	 ((and quote (not (equal function "lambda")))
	  (setq method 'lisp-indent-quoteform))
	 ;; do the same if we're indenting the arg list of a def* form.
	 ((let ((p (point)))
	    (condition-case nil
		(save-excursion
		  (backward-up-list 2)
		  ;; make sure we're indeed the second argument of the
		  ;; def* form.
		  (and (eq (point) (save-excursion
				     (goto-char p)
				     (backward-up-list 1)
				     (backward-sexp 2)
				     (1- (point))))
		       ;; check to see that the function is a def* type
		       (eq (char-after) ?\()
		       (progn (forward-char 1) t)
		       (looking-at lisp-function-and-type-regexp)
		       ;; defstruct may have slot option specs, which
		       ;; should probably be reverse-indented like
		       ;; normal, because the slot name is the first
		       ;; in the list. #### Review this.
		       (not (equal (match-string 0) "defstruct"))))
	      (error nil)))
	  (setq method 'lisp-indent-quoteform))

	 ;; handle functions in flet forms
	 ((let ((p (point)))
	    (condition-case nil
		(save-excursion
		  (backward-up-list 3)
		  ;; make sure we're indeed a function, i.e. inside the
		  ;; first form after the flet.
		  (and (eq (point) (save-excursion
				     (goto-char p)
				     (backward-up-list 2)
				     (backward-sexp 1)
				     (1- (point))))
		       (looking-at lisp-flet-regexp)))
	      (error nil)))
	  (setq method 'defun))

	 ;; handle the arg lists in functions in flet forms
	 ((let ((p (point)))
	    (condition-case nil
		(save-excursion
		  (backward-up-list 2)
		  ;; make sure we're indeed the arg list -- i.e. the first
		  ;; element after the function name.
		  (and (eq (point) (save-excursion
				     (goto-char p)
				     (backward-up-list 1)
				     (backward-sexp 1)
				     (1- (point))))
		       (progn
			 (backward-up-list 2)
			 (looking-at lisp-flet-regexp))))
	      (error nil)))
	  (setq method 'lisp-indent-quoteform))
	 (t
	  (setq method
		(or (get (intern-soft function) 'lisp-indent-function)
		    (get (intern-soft function) 'lisp-indent-hook)))))
	(cond ((or (eq method 'defun)
		   (and (null method)
			(> (length function) 3)
			(string-match "\\`def" function)))
	       (lisp-indent-defform state indent-point))
	      ((integerp method)
	       (lisp-indent-specform method state
				     indent-point normal-indent))
	      (method
		(funcall method state indent-point))
	      ((and (> (length function) 5)
		    (string-match "\\`with-" function))
	       (lisp-indent-specform 0 state indent-point normal-indent
				     t)))))))

(defun lisp-indent-quoteform (state indent-point)
  (goto-char (car (cdr state)))
  (forward-line 1)
  (if (> (point) (car (cdr (cdr state))))
      (progn
	(goto-char (car (cdr state)))
	(+ 1 (current-column)))))

(defvar lisp-body-indent 2
  "Number of columns to indent the second line of a `(def...)' form.")

;; Calculate the appropriate indentation for a special form (e.g. defun) or
;; a macro that behaves like a special form (e.g. with-temp-buffer).
;; Return value is as for `calculate-lisp-indent' (q.v.).
;;
;; COUNT is the number of "distinguished" forms (e.g. arguments before the
;; "body", in a macro taking a body as its last argument).
;;
;; INDENT-POINT is usually the value of (point) at the beginning of the
;; line containing the form to be indented.
;;
;; STATE is the result of calling (parse-partial-sexp (point) INDENT-POINT)
;; when (point) is sitting on (i.e. just before) the outermost containing
;; left paren for the form to be indented.
;;
;; NORMAL-INDENT is the amount of "full" indentation used for arguments
;; that aren't given some special indentation (usually less), and normally
;; it lines up with the first word after the function name.  forms are
;; indented as follows:
;;
;; -- The first and second distinguished forms are given 2 times body indent
;;    (determined by `lisp-body-indent')
;; -- Other distinguished forms are given normal indent
;; -- The first nondistinguished form (the body, usually) is given body indent
;; -- Normally, any further nondistinguished forms are given normal indent
;; -- However, if INDENT-REMAINING-AS-BODY was specified, any further
;;    nondistinguished forms are given body indent.  This is useful when the
;;    number of distinguished forms isn't known or may vary.

(defun lisp-indent-specform (count state indent-point normal-indent
			     &optional indent-remaining-as-body)
  (let ((containing-form-start (elt state 1))
        (i count)
        body-indent containing-form-column)
    ;; Move to the start of containing form, calculate indentation
    ;; to use for non-distinguished forms (> count), and move past the
    ;; function symbol.  lisp-indent-function guarantees that there is at
    ;; least one word or symbol character following open paren of containing
    ;; form.
    (goto-char containing-form-start)
    (setq containing-form-column (current-column))
    (setq body-indent (+ lisp-body-indent containing-form-column))
    (forward-char 1)
    (forward-sexp 1)
    ;; Now find the start of the last form.
    (parse-partial-sexp (point) indent-point 1 t)
    (while (and (< (point) indent-point)
                (condition-case ()
                    (progn
                      (setq count (1- count))
                      (forward-sexp 1)
                      (parse-partial-sexp (point) indent-point 1 t))
                  (error nil))))
    ;; Point is sitting on first character of last (or count) sexp.
    (if (> count 0)
        ;; A distinguished form.  If it is the first or second form use double
        ;; lisp-body-indent, else normal indent.  With lisp-body-indent bound
        ;; to 2 (the default), this just happens to work the same with if as
        ;; the older code, but it makes unwind-protect, condition-case,
        ;; with-output-to-temp-buffer, et. al. much more tasteful.  The older,
        ;; less hacked, behavior can be obtained by replacing below with
        ;; (list normal-indent containing-form-start).
        (if (<= (- i count) 1)
            (list (+ containing-form-column (* 2 lisp-body-indent))
                  containing-form-start)
            (list normal-indent containing-form-start))
      ;; A non-distinguished form.  Use body-indent if there are no
      ;; distinguished forms and this is the first undistinguished form,
      ;; or if this is the first undistinguished form and the preceding
      ;; distinguished form has indentation at least as great as body-indent.
      (if (or (and (= i 0) (= count 0))
              (and (or (= count 0) indent-remaining-as-body)
		   (<= body-indent normal-indent)))
          body-indent
          normal-indent))))

(defun lisp-indent-defform (state indent-point)
  (goto-char (car (cdr state)))
  (forward-line 1)
  (if (> (point) (car (cdr (cdr state))))
      (progn
	(goto-char (car (cdr state)))
	(+ lisp-body-indent (current-column)))))


;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
;; like defun if the first form is placed on the next line, otherwise
;; it is indented like any other form (i.e. forms line up under first).

;; NOTE: All def* functions are handled specially, no need to put them here.
;; NOTE: All cl-* constructs are handled in cl.el.

(put 'lambda 'lisp-indent-function 'defun)
(put 'autoload 'lisp-indent-function 'defun)
(put 'progn 'lisp-indent-function 0)
(put 'prog1 'lisp-indent-function 1)
(put 'prog2 'lisp-indent-function 2)
(put 'save-excursion 'lisp-indent-function 0)
(put 'save-window-excursion 'lisp-indent-function 0)
(put 'save-selected-window 'lisp-indent-function 0)
(put 'with-selected-window 'lisp-indent-function 1)
(put 'save-selected-frame 'lisp-indent-function 0)
(put 'with-selected-frame 'lisp-indent-function 1)
(put 'save-selected-device 'lisp-indent-function 0)
(put 'with-selected-device 'lisp-indent-function 1)
(put 'save-restriction 'lisp-indent-function 0)
(put 'save-match-data 'lisp-indent-function 0)
(put 'let 'lisp-indent-function 1)
(put 'let* 'lisp-indent-function 1)
(put 'let-specifier 'lisp-indent-function 1)
(put 'while 'lisp-indent-function 1)
(put 'if 'lisp-indent-function 2)
(put 'catch 'lisp-indent-function 1)
(put 'condition-case 'lisp-indent-function 2)
(put 'handler-case 'lisp-indent-function 1)
(put 'handler-bind 'lisp-indent-function 1)
(put 'call-with-condition-handler 'lisp-indent-function 2)
(put 'unwind-protect 'lisp-indent-function 1)
(put 'save-current-buffer 'lisp-indent-function 0)
(put 'with-current-buffer 'lisp-indent-function 1)
(put 'with-string-as-buffer-contents 'lisp-indent-function 1)
(put 'with-temp-file 'lisp-indent-function 1)
(put 'with-temp-buffer 'lisp-indent-function 0)
(put 'with-output-to-string 'lisp-indent-function 0)
(put 'with-output-to-temp-buffer 'lisp-indent-function 1)
(put 'with-slots 'lisp-indent-function 2)
(put 'with-open-file 'lisp-indent-function 1)
(put 'with-open-stream 'lisp-indent-function 1)
(put 'eval-after-load 'lisp-indent-function 1)
(put 'display-message 'lisp-indent-function 1)
(put 'display-warning 'lisp-indent-function 1)
(put 'lmessage 'lisp-indent-function 2)
(put 'lwarn 'lisp-indent-function 2)
(put 'global-set-key 'lisp-indent-function 1)
(put 'print-unreadable-object 'lisp-indent-function 1)

(defun indent-sexp (&optional endpos)
  "Indent each line of the list starting just after point.
If optional arg ENDPOS is given, indent each line, stopping when
ENDPOS is encountered."
  (interactive)
  (let ((indent-stack (list nil))
	(next-depth 0)
	;; If ENDPOS is non-nil, use nil as STARTING-POINT
	;; so that calculate-lisp-indent will find the beginning of
	;; the defun we are in.
	;; If ENDPOS is nil, it is safe not to scan before point
	;; since every line we indent is more deeply nested than point is.
	(starting-point (if endpos nil (point)))
	(last-point (point))
	last-depth bol outer-loop-done inner-loop-done state this-indent)
    (or endpos
	;; Get error now if we don't have a complete sexp after point.
	(save-excursion (forward-sexp 1)))
    (save-excursion
      (setq outer-loop-done nil)
      (while (if endpos (< (point) endpos)
	       (not outer-loop-done))
	(setq last-depth next-depth
	      inner-loop-done nil)
	;; Parse this line so we can learn the state
	;; to indent the next line.
	;; This inner loop goes through only once
	;; unless a line ends inside a string.
	(while (and (not inner-loop-done)
		    (not (setq outer-loop-done (eobp))))
	  (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
					  nil nil state))
	  (setq next-depth (car state))
	  ;; If the line contains a comment other than the sort
	  ;; that is indented like code,
	  ;; indent it now with indent-for-comment.
	  ;; Comments indented like code are right already.
	  ;; In any case clear the in-comment flag in the state
	  ;; because parse-partial-sexp never sees the newlines.
	  (if (car (nthcdr 4 state))
	      (progn (indent-for-comment)
		     (end-of-line)
		     (setcar (nthcdr 4 state) nil)))
	  ;; If this line ends inside a string,
	  ;; go straight to next line, remaining within the inner loop,
	  ;; and turn off the \-flag.
	  (if (car (nthcdr 3 state))
	      (progn
		(forward-line 1)
		(setcar (nthcdr 5 state) nil))
	    (setq inner-loop-done t)))
	(and endpos
	     (<= next-depth 0)
	     (progn
	       (setq indent-stack (append indent-stack
					  (make-list (- next-depth) nil))
		     last-depth (- last-depth next-depth)
		     next-depth 0)))
	(or outer-loop-done endpos
	    (setq outer-loop-done (<= next-depth 0)))
	(if outer-loop-done
	    (forward-line 1)
	  (while (> last-depth next-depth)
	    (setq indent-stack (cdr indent-stack)
		  last-depth (1- last-depth)))
	  (while (< last-depth next-depth)
	    (setq indent-stack (cons nil indent-stack)
		  last-depth (1+ last-depth)))
	  ;; Now go to the next line and indent it according
	  ;; to what we learned from parsing the previous one.
	  (forward-line 1)
	  (setq bol (point))
	  (skip-chars-forward " \t")
	  ;; But not if the line is blank, or just a comment
	  ;; (except for double-semi comments; indent them as usual).
	  (if (or (eobp) (looking-at "\\s<\\|\n"))
	      nil
	    (if (and (car indent-stack)
		     (>= (car indent-stack) 0))
		(setq this-indent (car indent-stack))
	      (let ((val (calculate-lisp-indent
			  (if (car indent-stack) (- (car indent-stack))
			    starting-point))))
		(if (integerp val)
		    (setcar indent-stack
			    (setq this-indent val))
		  (setcar indent-stack (- (car (cdr val))))
		  (setq this-indent (car val)))))
	    (if (/= (current-column) this-indent)
		(progn (delete-region bol (point))
		       (indent-to this-indent)))))
	(or outer-loop-done
	    (setq outer-loop-done (= (point) last-point))
	    (setq last-point (point)))))))

;; Indent every line whose first char is between START and END inclusive.
(defun lisp-indent-region (start end)
  (save-excursion
    (let ((endmark (copy-marker end)))
      (goto-char start)
      (and (bolp) (not (eolp))
	   (lisp-indent-line))
      (indent-sexp endmark)
      (set-marker endmark nil))))

;;;; Lisp paragraph filling commands.

(defun lisp-fill-paragraph (&optional justify)
  "Like \\[fill-paragraph], but handle Emacs Lisp comments.
If any of the current line is a comment, fill the comment or the
paragraph of it that point is in, preserving the comment's indentation
and initial semicolons."
  (interactive "P")
  (let (
	;; Non-nil if the current line contains a comment.
	has-comment

	;; Non-nil if the current line contains code and a comment.
	has-code-and-comment

	;; If has-comment, the appropriate fill-prefix for the comment.
	comment-fill-prefix
	)

    ;; Figure out what kind of comment we are looking at.
    (save-excursion
      (beginning-of-line)
      (cond

       ;; A line with nothing but a comment on it?
       ((looking-at "[ \t]*;[; \t]*")
	(setq has-comment t
	      comment-fill-prefix (buffer-substring (match-beginning 0)
						    (match-end 0))))

       ;; A line with some code, followed by a comment?  Remember that the
       ;; semi which starts the comment shouldn't be part of a string or
       ;; character.
       ;; XEmacs Try this the FSF and see if it works.
;       ((progn
;	  (while (not (looking-at ";\\|$"))
;	    (skip-chars-forward "^;\n\"\\\\?")
;	    (cond
;	     ((eq (char-after (point)) ?\\) (forward-char 2))
;	     ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
;	  (looking-at ";+[\t ]*"))
;	(setq has-comment t)
       ((condition-case nil
	    (save-restriction
	      (narrow-to-region (point-min)
				(save-excursion (end-of-line) (point)))
	      (while (not (looking-at ";\\|$"))
		(skip-chars-forward "^;\n\"\\\\?")
		(cond
		 ((eq (char-after (point)) ?\\) (forward-char 2))
		 ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
	      ;; don't do comment filling in a string, or we will mess up
	      ;; doc strings and other places where semicolons are used.
	      (and (not (eq 'string (buffer-syntactic-context)))
		   (looking-at ";+[\t ]*")))
	  (error nil))
	(setq has-comment t has-code-and-comment t)
	(setq comment-fill-prefix
	      (concat (make-string (/ (current-column) 8) ?\t)
		      (make-string (% (current-column) 8) ?\ )
		      (buffer-substring (match-beginning 0) (match-end 0)))))))

    (if (not has-comment)
	(fill-paragraph justify)

      ;; Narrow to include only the comment, and then fill the region.
      (save-excursion
	(save-restriction
	  (beginning-of-line)
	  (narrow-to-region
	   ;; Find the first line we should include in the region to fill.
	   (save-excursion
	     (while (and (zerop (forward-line -1))
			 (looking-at "^[ \t]*;")))
	     ;; We may have gone too far.  Go forward again.
	     (or (looking-at ".*;")
		 (forward-line 1))
	     (point))
	   ;; Find the beginning of the first line past the region to fill.
	   (save-excursion
	     (while (progn (forward-line 1)
			   (looking-at "^[ \t]*;")))
	     (point)))

	  ;; Lines with only semicolons on them can be paragraph boundaries.
	  (let* ((paragraph-start (concat paragraph-start "\\|[ \t;]*$"))
		 (paragraph-separate (concat paragraph-start "\\|[ \t;]*$"))
		 (paragraph-ignore-fill-prefix nil)
		 (fill-prefix comment-fill-prefix)
		 (after-line (if has-code-and-comment
				 (save-excursion
				   (forward-line 1) (point))))
		 (end (progn
			(forward-paragraph)
			(or (bolp) (newline 1))
			(point)))
		 ;; If this comment starts on a line with code,
		 ;; include that like in the filling.
		 (beg (progn (backward-paragraph)
			     (if (eq (point) after-line)
				 (forward-line -1))
			     (point))))
	    (fill-region-as-paragraph beg end
				      justify nil
				      (save-excursion
					(goto-char beg)
					(if (looking-at fill-prefix)
					    nil
					  (re-search-forward comment-start-skip)
					  (point))))))))
    t))

(defun indent-code-rigidly (start end arg &optional nochange-regexp)
  "Indent all lines of code, starting in the region, sideways by ARG columns.
Does not affect lines starting inside comments or strings, assuming that
the start of the region is not inside them.

Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
The last is a regexp which, if matched at the beginning of a line,
means don't indent that line."
  (interactive "r\np")
  (let (state)
    (save-excursion
      (goto-char end)
      (setq end (point-marker))
      (goto-char start)
      (or (bolp)
	  (setq state (parse-partial-sexp (point)
					  (progn
					    (forward-line 1) (point))
					  nil nil state)))
      (while (< (point) end)
	(or (car (nthcdr 3 state))
	    (and nochange-regexp
		 (looking-at nochange-regexp))
	    ;; If line does not start in string, indent it
	    (let ((indent (current-indentation)))
	      (delete-region (point) (progn (skip-chars-forward " \t") (point)))
	      (or (eolp)
		  (indent-to (max 0 (+ indent arg)) 0))))
	(setq state (parse-partial-sexp (point)
					(progn
					  (forward-line 1) (point))
					nil nil state))))))

(provide 'lisp-mode)

;;; lisp-mode.el ends here