changeset 91239:2fcaae6177a5

Merge from emacs--devo--0 Revision: emacs@sv.gnu.org/emacs--unicode--0--patch-300
author Miles Bader <miles@gnu.org>
date Sun, 16 Dec 2007 05:08:49 +0000
parents 5cf14a2107b5 (current diff) 1d6e3255f024 (diff)
children b2febf77e71c
files ChangeLog admin/ChangeLog admin/FOR-RELEASE configure configure.in etc/ChangeLog etc/NEWS etc/NEWS.22 etc/TODO etc/images/icons/macemacs_16.png etc/images/icons/macemacs_24.png etc/images/icons/macemacs_256.png etc/images/icons/macemacs_32.png etc/images/icons/macemacs_48.png etc/images/icons/macemacs_512.png etc/schema/docbook-dyntbl.rnc etc/schema/docbook-soextbl.rnc etc/schema/xhtml-basic-form.rnc etc/schema/xhtml-basic-table.rnc etc/schema/xhtml-list.rnc etc/schema/xhtml-style.rnc etc/schema/xhtml-target.rnc leim/ChangeLog leim/quail/lao.el leim/quail/latin-post.el lib-src/ChangeLog lisp/ChangeLog lisp/bindings.el lisp/calc/calc-aent.el lisp/calc/calc-ext.el lisp/calc/calc-lang.el lisp/calc/calc-mode.el lisp/calc/calc.el lisp/calc/calcalg2.el lisp/calc/calcalg3.el lisp/calendar/calendar.el lisp/dired.el lisp/ediff-init.el lisp/emacs-lisp/checkdoc.el lisp/emacs-lisp/edebug.el lisp/emacs-lisp/lisp-mnt.el lisp/emulation/viper-init.el lisp/emulation/viper-util.el lisp/files.el lisp/generic-x.el lisp/gnus/ChangeLog lisp/gnus/gnus-art.el lisp/gnus/gnus-cache.el lisp/gnus/gnus-ems.el lisp/gnus/gnus-group.el lisp/gnus/gnus-int.el lisp/gnus/gnus-spec.el lisp/gnus/gnus-start.el lisp/gnus/gnus-sum.el lisp/gnus/gnus-util.el lisp/gnus/gnus-uu.el lisp/gnus/gnus.el lisp/gnus/mail-source.el lisp/gnus/message.el lisp/gnus/mm-bodies.el lisp/gnus/mm-decode.el lisp/gnus/mm-util.el lisp/gnus/mm-uu.el lisp/gnus/mm-view.el lisp/gnus/mml.el lisp/gnus/nnfolder.el lisp/gnus/nnheader.el lisp/gnus/nnmail.el lisp/gnus/pop3.el lisp/gnus/rfc1843.el lisp/help-fns.el lisp/ibuffer.el lisp/indent.el lisp/international/ja-dic-cnv.el lisp/isearch.el lisp/kmacro.el lisp/mail/feedmail.el lisp/mail/reporter.el lisp/mail/rmailout.el lisp/mail/uce.el lisp/makefile.w32-in lisp/man.el lisp/mouse.el lisp/net/rcirc.el lisp/net/trampver.el lisp/play/mpuz.el lisp/progmodes/ada-xref.el lisp/progmodes/antlr-mode.el lisp/progmodes/cc-cmds.el lisp/progmodes/cc-vars.el lisp/progmodes/cperl-mode.el lisp/progmodes/ebrowse.el lisp/progmodes/idlw-shell.el lisp/progmodes/idlwave.el lisp/progmodes/perl-mode.el lisp/progmodes/vhdl-mode.el lisp/replace.el lisp/server.el lisp/startup.el lisp/term/mac-win.el lisp/textmodes/artist.el lisp/textmodes/org-publish.el lisp/textmodes/org.el lisp/textmodes/reftex-index.el lisp/textmodes/reftex-toc.el lisp/textmodes/reftex.el lisp/textmodes/texinfmt.el lisp/vc-cvs.el lisp/vc-mcvs.el lisp/vc.el lisp/whitespace.el src/ChangeLog src/buffer.c src/dispextern.h src/keyboard.c src/w32fns.c src/w32term.c
diffstat 178 files changed, 12562 insertions(+), 921 deletions(-) [+]
line wrap: on
line diff
--- a/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,7 @@
+2007-12-09  Andreas Schwab  <schwab@suse.de>
+
+	* configure.in: D-Bus is not enabled by default.
+
 2007-12-06  Jan Dj,Ad(Brv  <jan.h.d@swipnet.se>
 
 	* configure.in: Add AC_CONFIG_SRCDIR which was lost in the previous
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/admin/CPP-DEFINES	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,46 @@
+Here are some of the cpp macros used, together with some short explanation
+of their use.  Feel free to add more macros and more categories.
+
+** Distinguishing OSes **
+
+MAC_OS		Compiling for some version of Mac OS?
+MAC_OS8		Compiling for Mac OS version 8.  Requires MAC_OS?
+MAC_OSX		Compiling for Mac OS X?  Is that also valid for Darwin?
+MAC_OS_X	??  Apparently only used once in mac.c.
+CYGWIN		Compiling the Cygwin port.
+__CYGWIN__	Ditto
+MSDOS		Compiling the MS-DOS port.
+__MSDOS__	Ditto.
+__DJGPP__	Major version number of the DJGPP library for the DOS port.
+__DJGPP_MINOR__ Minor version number of the DJGPP library.
+__GO32__	Compiling the DOS port with DJGPP v1.x (obsolete).
+DOS_NT		Compiling for either the MS-DOS or native MS-Windows port.
+WINDOWSNT	Compiling the native MS-Windows (W32) port.
+__MINGW32__	Compiling the W32 port with the MinGW port of GCC.
+_MSC_VER	Compiling the W32 port with the Microsoft C compiler.
+
+** Distinguishing GUIs **
+
+HAVE_NTGUI	Use the native W32 GUI for windows, frames, menus&scrollbars.
+HAVE_CARBON	Compile support for the Carbon GUI.  Requires MAC_OS?
+HAVE_X11	Compile support for the X11 GUI.
+HAVE_X_WINDOWS	Compile support for X Window system
+X11		??  Makefile.in suggests it's equivalent to HAVE_X11
+USE_LUCID	Use the Lucid toolkit for menus&scrollbars.  Requires HAVE_X11.
+USE_MOTIF	Use the Motif toolkit for menus&scrollbars.  Requires HAVE_X11.
+USE_GTK		Use the Gtk   toolkit for menus&scrollbars.  Requires HAVE_X11.
+
+** Frame types **
+
+FRAME_TERMCAP_P	A tty (character terminal) frame.
+FRAME_X_P	A frame on X Window system.
+FRAME_MSDOS_P	An MS-DOS frame (used only by the DOS port).
+FRAME_MAC_P	A Mac frame.
+FRAME_W32_P	A frame using native MS-Windows GUI.
+FRAME_WINDOW_P	A GUI frame (like X, w32, etc.)
+
+** Compile-time options **
+REL_ALLOC	Compile in the relocatable memory allocator ralloc.c.
+SYSTEM_MALLOC	Use the system library's malloc.
+
+# arch-tag: bc80061a-1168-4911-9766-46aaf2640250
--- a/admin/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/admin/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,13 @@
+2007-12-10  Stefan Monnier  <monnier@iro.umontreal.ca>
+
+	* CPP-DEFINES: New file.
+
+2007-12-08  Reiner Steib  <Reiner.Steib@gmx.de>
+
+	* FOR-RELEASE: Remove "window-system in face definition" [of
+	gnus-treat-emphasize].  Remove "Gnus archive groups".  Add comment
+	on gnus-dired.el.
+
 2007-12-05  Glenn Morris  <rgm@gnu.org>
 
 	* admin.el (set-version): Handle configure.in.  Adapt for doc/
--- a/admin/FOR-RELEASE	Fri Dec 14 12:53:04 2007 +0000
+++ b/admin/FOR-RELEASE	Sun Dec 16 05:08:49 2007 +0000
@@ -91,16 +91,8 @@
 
 ** rms: gnus-dired.el is a mistake.  Those features should not
 be part of Gnus.  They should be moved to some other part of Emacs.
-
-** sdl.web@gmail.com, 28 Oct: window-system in face definition
-
-** Gnus archive groups are not shown at all if they are not at the default level. 
-Fixed in Gnus CVS, but the patch has not been synched to Emacs yet:
-http://thread.gmane.org/gmane.emacs.gnus.general/65622/focus=65757
-
-** Extra question asked when doing a reply in Gnus
-Fixed in Gnus CVS, but the patch has not been synched to Emacs yet:
-http://thread.gmane.org/gmane.emacs.gnus.general/65627/65768
+rsteib: Gnus dependencies in `gnus-dired.el' (and `mailcap.el') have been
+minimized.  I don't know what is left to do here.
 
 ** sdl.web@gmail.com, 30 Oct: ps-lpr-switches has no effect
 
@@ -115,6 +107,10 @@
 ** Fix or document the shortcoming of easymenu and :suffix.
 http://lists.gnu.org/archive/html/emacs-devel/2007-11/msg01857.html
 
+** Fix problem with mode-name in SGML mode.
+If mode-name stays non-string, add NEWS entry and doc fix.
+http://lists.gnu.org/archive/html/emacs-devel/2007-11/msg02048.html
+
 * DOCUMENTATION
 
 ** Check the Emacs Tutorial.
--- a/configure	Fri Dec 14 12:53:04 2007 +0000
+++ b/configure	Sun Dec 16 05:08:49 2007 +0000
@@ -1370,7 +1370,7 @@
   --without-xaw3d         don't use Xaw3d
   --without-xim           don't use X11 XIM
   --without-carbon        don't use Carbon GUI on Mac OS X
-  --without-dbus          don't use D-Bus
+  --with-dbus             use D-Bus
   --with-x                use the X Window System
 
 Some influential environment variables:
--- a/configure.in	Fri Dec 14 12:53:04 2007 +0000
+++ b/configure.in	Sun Dec 16 05:08:49 2007 +0000
@@ -121,7 +121,7 @@
 EMACS_ARG_N([xaw3d],[don't use Xaw3d])
 EMACS_ARG_N([xim],[don't use X11 XIM])
 EMACS_ARG_N([carbon],[don't use Carbon GUI on Mac OS X])
-EMACS_ARG_N([dbus],[don't use D-Bus])
+EMACS_ARG_Y([dbus],[use D-Bus])
 
 AC_ARG_ENABLE(carbon-app,
 [AS_HELP_STRING([--enable-carbon-app@<:@=DIR@:>@],
--- a/doc/lispref/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/doc/lispref/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,10 @@
+2007-12-14  Martin Rudalics  <rudalics@gmx.at>
+
+	* nonascii.texi (Encoding and I/O): Reword to avoid saying
+	"visit the current buffer".
+
+	* os.texi (System Interface): Fix typo.
+
 2007-12-04  Richard Stallman  <rms@gnu.org>
 
 	* objects.texi (Symbol Type): Fix typo.
--- a/doc/lispref/nonascii.texi	Fri Dec 14 12:53:04 2007 +0000
+++ b/doc/lispref/nonascii.texi	Sun Dec 16 05:08:49 2007 +0000
@@ -727,15 +727,15 @@
 you will want to find out afterwards which coding system was chosen.
 
 @defvar buffer-file-coding-system
-This buffer-local variable records the coding system that was used to visit
-the current buffer.  It is used for saving the buffer, and for writing part
-of the buffer with @code{write-region}.  If the text to be written
-cannot be safely encoded using the coding system specified by this
-variable, these operations select an alternative encoding by calling
-the function @code{select-safe-coding-system} (@pxref{User-Chosen
-Coding Systems}).  If selecting a different encoding requires to ask
-the user to specify a coding system, @code{buffer-file-coding-system}
-is updated to the newly selected coding system.
+This buffer-local variable records the coding system used for saving the
+buffer and for writing part of the buffer with @code{write-region}.  If
+the text to be written cannot be safely encoded using the coding system
+specified by this variable, these operations select an alternative
+encoding by calling the function @code{select-safe-coding-system}
+(@pxref{User-Chosen Coding Systems}).  If selecting a different encoding
+requires to ask the user to specify a coding system,
+@code{buffer-file-coding-system} is updated to the newly selected coding
+system.
 
 @code{buffer-file-coding-system} does @emph{not} affect sending text
 to a subprocess.
--- a/doc/lispref/os.texi	Fri Dec 14 12:53:04 2007 +0000
+++ b/doc/lispref/os.texi	Sun Dec 16 05:08:49 2007 +0000
@@ -21,8 +21,8 @@
 * System Environment::  Distinguish the name and kind of system.
 * User Identification:: Finding the name and user id of the user.
 * Time of Day::		Getting the current time.
-* Time Conversion::     Converting a time from numeric form
-                          to calendrical data, and vice versa).
+* Time Conversion::     Converting a time from numeric form to 
+                          calendrical data and vice versa.
 * Time Parsing::        Converting a time from numeric form to text
                           and vice versa.
 * Processor Run Time::  Getting the run time used by Emacs.
--- a/doc/misc/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/doc/misc/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,13 @@
+2007-12-14  Sven Joachim  <svenjoac@gmx.de>
+
+	* gnus.texi (Score Variables): Fix typo.
+
+2007-12-07  Michael Albinus  <michael.albinus@gmx.de>
+
+	* dbus.texi (Synchronous Methods): Adapt dbus-call-method.
+	(Signals): Adapt dbus-send-signal and dbus-register-signal.
+	(Errors and Events): Adapt dbus-event.
+
 2007-12-03  Lars Magne Ingebrigtsen  <larsi@gnus.org>
 
 	* gnus.texi (Other Files): Add the yenc command.
--- a/doc/misc/dbus.texi	Fri Dec 14 12:53:04 2007 +0000
+++ b/doc/misc/dbus.texi	Sun Dec 16 05:08:49 2007 +0000
@@ -318,7 +318,7 @@
 be called, and a reply message returning the resulting output
 parameters from the object.
 
-@defun dbus-call-method bus method service path interface &rest args
+@defun dbus-call-method bus service path interface method &rest args
 This function calls @var{method} on the D-Bus @var{bus}.  @var{bus} is
 either the symbol @code{:system} or the symbol @code{:session}.
 
@@ -336,8 +336,8 @@
 
 @example
 (dbus-call-method
-  :session "GetKeyField" "org.gnome.seahorse"
-  "/org/gnome/seahorse/keys/openpgp" "org.gnome.seahorse.Keys"
+  :session "org.gnome.seahorse" "/org/gnome/seahorse/keys/openpgp"
+  "org.gnome.seahorse.Keys" "GetKeyField"
   "openpgp:657984B8C7A966DD" "simple-name")
 
 @result{} (t ("Philip R. Zimmermann"))
@@ -349,8 +349,9 @@
 
 @example
 (dbus-call-method
-  :system "GetPropertyString" "org.freedesktop.Hal"
-  "/org/freedesktop/Hal/devices/computer" "org.freedesktop.Hal.Device"
+  :system "org.freedesktop.Hal"
+  "/org/freedesktop/Hal/devices/computer"
+  "org.freedesktop.Hal.Device" "GetPropertyString"
   "system.kernel.machine")
 
 @result{} "i686"
@@ -368,14 +369,14 @@
 @example
 (dolist (device
           (dbus-call-method
-            :system "GetAllDevices" "org.freedesktop.Hal"
+            :system "org.freedesktop.Hal"
             "/org/freedesktop/Hal/Manager"
-            "org.freedesktop.Hal.Manager"))
+            "org.freedesktop.Hal.Manager" "GetAllDevices"))
   (message "\nudi = %s" device)
   (dolist (properties
             (dbus-call-method
-              :system "GetAllProperties" "org.freedesktop.Hal"
-              device "org.freedesktop.Hal.Device"))
+              :system "org.freedesktop.Hal" device
+              "org.freedesktop.Hal.Device" "GetAllProperties"))
     (message "  %s = %S"
              (car properties) (or (caar (cdr properties)) ""))))
 
@@ -406,7 +407,7 @@
 Signals are broadcast messages.  They carry input parameters, which
 are received by all objects which have registered for such a signal.
 
-@defun dbus-send-signal bus signal service path interface &rest args
+@defun dbus-send-signal bus service path interface signal &rest args
 This function is similar to @code{dbus-call-method}.  The difference
 is, that there are no returning output parameters.
 
@@ -425,12 +426,12 @@
 
 @example
 (dbus-send-signal
-  :session "FileModified" "org.gnu.Emacs" "/org/gnu/Emacs"
-  "org.gnu.Emacs.FileManager" "/home/albinus/.emacs")
+  :session "org.gnu.Emacs" "/org/gnu/Emacs"
+  "org.gnu.Emacs.FileManager" "FileModified" "/home/albinus/.emacs")
 @end example
 @end defun
 
-@defun dbus-register-signal bus signal service path interface handler
+@defun dbus-register-signal bus service path interface signal handler
 With this function, an application registers for @var{signal} on the
 D-Bus @var{bus}.
 
@@ -461,13 +462,15 @@
 (defun my-dbus-signal-handler (device)
   (message "Device %s added" device))
 
+@result{} my-dbus-signal-handler
+
 (dbus-register-signal
-  :system "DeviceAdded"
-  (dbus-get-name-owner :system "org.freedesktop.Hal")
-  "/org/freedesktop/Hal/Manager" "org.freedesktop.Hal.Manager"
+  :system "org.freedesktop.Hal" "/org/freedesktop/Hal/Manager"
+  "org.freedesktop.Hal.Manager" "DeviceAdded"
   'my-dbus-signal-handler)
 
-@result{} (:system "org.freedesktop.Hal.Manager" "DeviceAdded")
+@result{} (:system ":1.3" "/org/freedesktop/Hal/Manager"
+    "org.freedesktop.Hal.Manager" "DeviceAdded")
 @end example
 
 As we know from the inspection data of interface
@@ -503,13 +506,9 @@
 Events, , , elisp}).  The generated event has this form:
 
 @example
-(dbus-event @var{handler} @var{bus} @var{service} @var{path} @var{interface} @var{member} &rest @var{args})
+(dbus-event @var{bus} @var{service} @var{path} @var{interface} @var{member} @var{handler} &rest @var{args})
 @end example
 
-@var{handler} is the callback function which has been registered for
-this signal (see @pxref{Signals}).  When a @code{dbus-event} event
-arrives, @var{handler} is called with @var{args} as arguments.
-
 @var{bus} identifies the D-Bus the signal is coming from.  It is
 either the symbol @code{:system} or the symbol @code{:session}.
 
@@ -517,6 +516,10 @@
 of the D-Bus object emitting the signal.  @var{interface} and
 @var{member} denote the signal which has been sent.
 
+@var{handler} is the callback function which has been registered for
+this signal (see @pxref{Signals}).  When a @code{dbus-event} event
+arrives, @var{handler} is called with @var{args} as arguments.
+
 In order to inspect the @code{dbus-event} data, you could extend the
 definition of the callback function in @ref{Signals}:
 
--- a/doc/misc/gnus.texi	Fri Dec 14 12:53:04 2007 +0000
+++ b/doc/misc/gnus.texi	Sun Dec 16 05:08:49 2007 +0000
@@ -20529,7 +20529,7 @@
 @vindex gnus-score-uncacheable-files
 @cindex score cache
 All score files are normally cached to avoid excessive re-loading of
-score files.  However, if this might make your Emacs grow big and
+score files.  However, this might make your Emacs grow big and
 bloated, so this regexp can be used to weed out score files unlikely
 to be needed again.  It would be a bad idea to deny caching of
 @file{all.SCORE}, while it might be a good idea to not cache
--- a/etc/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/etc/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,38 @@
+2007-12-15  Eli Zaretskii  <eliz@gnu.org>
+
+	The following files renamed to avoid file-name clashes in
+	8+3 (a.k.a. DOS) namespace:
+
+	* schema/xhtml-basic-form.rnc: Renamed to xhtml-bform.rnc.
+	* schema/xhtml-basic-table.rnc: Renamed to xhtml-btable.rnc.
+	* schema/xhtml-list.rnc: Renamed to xhtml-lst.rnc.
+	* schema/xhtml-target.rnc: Renamed to xhtml-tgt.rnc.
+	* schema/xhtml-style.rnc: Renamed to xhtml-xstyle.rnc.
+	* schema/xhtml-form.rnc, schema/xhtml-table.rnc, schema/xhtml.rnc:
+	Updated accordingly.
+
+	* schema/docbook-dyntbl.rnc, schema/docbook-dyntbl.rnc: Renamed to
+	docbk-dyntbl.rnc and docbk-soextbl.rnc, respectively.
+
+	* images/icons/macemacs_16.png, images/icons/macemacs_24.png:
+	* images/icons/macemacs_32.png, images/icons/macemacs_48.png:
+	* images/icons/macemacs_256.png, images/icons/macemacs_512.png:
+	Renamed to emacs16_mac.png, emacs24_mac.png, emacs32_mac.png,
+	emacs48_mac.png, emacs256_mac.png, and emacs512_mac.png,
+	respectively.
+
+2007-12-08  Ulrich Mueller <ulm@gentoo.org>  (tiny change)
+
+	* emacs.desktop (Exec, Icon, Categories): Fix entries.
+
+2007-12-08  Reiner Steib  <Reiner.Steib@gmx.de>
+
+	* NEWS: Add minimal Gnus item.
+
+2007-12-08  Dan Nicolaescu  <dann@ics.uci.edu>
+
+	* emacs.desktop: New file.
+
 2007-11-30  Kentaro Ohkouchi  <nanasess@fsm.ne.jp>
 
 	* images/icons/macemacs_16.png, images/icons/macemacs_24.png:
--- a/etc/NEWS	Fri Dec 14 12:53:04 2007 +0000
+++ b/etc/NEWS	Sun Dec 16 05:08:49 2007 +0000
@@ -55,7 +55,7 @@
 OS-X-style icons (an application icon and a relevant document icon)
 were contributed by Kentaro Ohkouchi.
 Source files for these icons can be found in Emacs.app/Contents/Resources.
-PNG versions are available as etc/images/icons/macemacs_*.png.
+PNG versions are available as etc/images/icons/emacs*_mac.png.
 
 ** Built-in functions (subr) can now have an interactive specification
 that is not a prompt string.  If the `intspec' parameter of a `DEFUN'
@@ -234,7 +234,12 @@
 ** view-remove-frame-by-deleting is now by default t
 since users found iconification of view-mode frames distracting.
 
-** isearch can now search through multiple ChangeLog files.
+** Isearch mode
+
+*** New command `isearch-occur' bound to `M-s o' in isearch mode
+runs `occur' with the current search string.
+
+*** isearch can now search through multiple ChangeLog files.
 When running isearch in a ChangeLog file, if the search fails,
 then another C-s tries searching the previous ChangeLog,
 if there is one (e.g. go from ChangeLog to ChangeLog.12).
@@ -347,6 +352,14 @@
 +++
 *** (The increasingly misnamed) F90 mode supports Fortran 2003 syntax.
 
+** Gnus package
+
+*** The Gnus package has been updated
+
+*** There are many news features, bug fixes and improvements.
+
+See the file GNUS-NEWS or the node "No Gnus" in the Gnus manual for details.
+
 ** Miscellaneous
 
 *** comint-mode uses `start-file-process' now (see Lisp Changes).
--- a/etc/NEWS.22	Fri Dec 14 12:53:04 2007 +0000
+++ b/etc/NEWS.22	Sun Dec 16 05:08:49 2007 +0000
@@ -88,6 +88,8 @@
 
 ** The new package vera-mode.el provides a major mode for editing Vera files.
 
+** The new package verilog-mode.el provides a major mode for editing Verilog files.
+
 ** The new package socks.el implements the SOCKS v5 protocol.
 
 ** VC
--- a/etc/TODO	Fri Dec 14 12:53:04 2007 +0000
+++ b/etc/TODO	Sun Dec 16 05:08:49 2007 +0000
@@ -25,10 +25,6 @@
 
 ** Compute the list of active keymaps *after* reading the first event.
 
-** mouse-autoselect-window should wait to select the window until
-the mouse is put to rest or after a delay or both, so that moving over
-a window doesn't select it.
-
 ** Distribute a bar cursor of width > 1 evenly between the two glyphs
    on each side of the bar (what to do at the edges?).
 
@@ -38,6 +34,8 @@
 ** buffer-offer-save should be a permanent local.
 
 ** revert-buffer should eliminate overlays and the mark.
+   For related problems consult the thread starting with
+   http://lists.gnu.org/archive/html/emacs-devel/2005-11/msg01346.html
 
 ** erase-buffer should perhaps disregard read-only properties of text.
 
@@ -570,7 +568,7 @@
    a derived mode of sendmail.el.  Or arrange for messages.el to be split
    into a small core and "the rest" so that we use less resources as long as
    we stick to the features provided in sendmail.el.
- 
+
 ** Replace gmalloc.c with the modified Doug Lea code from the current
    GNU libc so that the special mmapping of buffers can be removed --
    that apparently loses under Solaris, at least. [fx has mostly done
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/emacs.desktop	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,11 @@
+[Desktop Entry]
+Name=Emacs
+GenericName=Text Editor
+Comment=Edit text
+MimeType=text/english;text/plain;text/x-makefile;text/x-c++hdr;text/x-c++src;text/x-chdr;text/x-csrc;text/x-java;text/x-moc;text/x-pascal;text/x-tcl;text/x-tex;application/x-shellscript;text/x-c;text/x-c++;
+Exec=emacs %F
+Icon=emacs_32
+Type=Application
+Terminal=false
+Categories=Development;TextEditor;
+StartupWMClass=Emacs
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/images/icons/emacs16_mac.png	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,1 @@
+‰PNG
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/images/icons/emacs24_mac.png	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,1 @@
+‰PNG
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/images/icons/emacs256_mac.png	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,1 @@
+‰PNG
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/images/icons/emacs32_mac.png	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,1 @@
+‰PNG
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/images/icons/emacs48_mac.png	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,1 @@
+‰PNG
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/images/icons/emacs512_mac.png	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,1 @@
+‰PNG
Binary file etc/images/icons/macemacs_16.png has changed
Binary file etc/images/icons/macemacs_24.png has changed
Binary file etc/images/icons/macemacs_256.png has changed
Binary file etc/images/icons/macemacs_32.png has changed
Binary file etc/images/icons/macemacs_48.png has changed
Binary file etc/images/icons/macemacs_512.png has changed
--- a/etc/schema/dbdyntbl.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ b/etc/schema/dbdyntbl.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -2,7 +2,7 @@
 # allows the table model to be selected dynamically based on the
 # definitions of cals.table.module and exchange.table.module.
 #
-# To use this copy, docbook.rnc to docbook-dyntbl.rnc replacing
+# To use this, copy docbook.rnc to docbook-dyntbl.rnc replacing
 # "dbcalstbl.rnc" by "dbdyntbl.rnc".  Then, you can override the
 # choice of table model by doing
 #
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/schema/docbk-dyntbl.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,18 @@
+# Variant of docbook.rnc that allows the table model to be selected
+# dynamically based on the definitions of cals.table.module and
+# exchange.table.module.  See dbdyntbl.rnc.
+
+# Document (root) elements
+include "dbstart.rnc"
+
+# Notation declarations
+include "dbnotn.rnc"
+
+# Information pool
+include "dbpool.rnc"
+
+# Dynamic Table Model
+include "dbdyntbl.rnc"
+
+# Document hierarchy
+include "dbhier.rnc"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/schema/docbk-soextbl.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,17 @@
+# Variant of docbook.rnc that uses the OASIS XML Exchange Table Model
+# rather than the CALS Table Model.
+
+# Document (root) elements
+include "dbstart.rnc"
+
+# Notation declarations
+include "dbnotn.rnc"
+
+# Information pool
+include "dbpool.rnc"
+
+# OASIS XML Exchange Table Model
+include "dbsoextbl.rnc"
+
+# Document hierarchy
+include "dbhier.rnc"
--- a/etc/schema/docbook-dyntbl.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,18 +0,0 @@
-# Variant of docbook.rnc that allows the table model to be selected
-# dynamically based on the definitions of cals.table.module and
-# exchange.table.module.  See dbdyntbl.rnc.
-
-# Document (root) elements
-include "dbstart.rnc"
-
-# Notation declarations
-include "dbnotn.rnc"
-
-# Information pool
-include "dbpool.rnc"
-
-# Dynamic Table Model
-include "dbdyntbl.rnc"
-
-# Document hierarchy
-include "dbhier.rnc"
--- a/etc/schema/docbook-soextbl.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,17 +0,0 @@
-# Variant of docbook.rnc that uses the OASIS XML Exchange Table Model
-# rather than the CALS Table Model.
-
-# Document (root) elements
-include "dbstart.rnc"
-
-# Notation declarations
-include "dbnotn.rnc"
-
-# Information pool
-include "dbpool.rnc"
-
-# OASIS XML Exchange Table Model
-include "dbsoextbl.rnc"
-
-# Document hierarchy
-include "dbhier.rnc"
--- a/etc/schema/xhtml-basic-form.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-# Simplified Forms Module
-
-form =
-  element form {
-    form.attlist,
-    # Don't use Block.model, because this gets redefined by the
-    # legacy module.
-    Block.class+
-  }
-form.attlist =
-  Common.attrib,
-  attribute action { URI.datatype },
-  attribute method { "get" | "post" }?,
-  attribute enctype { ContentType.datatype }?
-label = element label { label.attlist, Inline.model }
-label.attlist =
-  Common.attrib,
-  attribute for { IDREF.datatype }?,
-  attribute accesskey { Character.datatype }?
-input = element input { input.attlist }
-input.attlist =
-  Common.attrib,
-  attribute type { InputType.class }?,
-  attribute name { text }?,
-  attribute value { text }?,
-  attribute checked { "checked" }?,
-  attribute size { text }?,
-  attribute maxlength { Number.datatype }?,
-  attribute src { URI.datatype }?,
-  attribute accesskey { Character.datatype }?
-InputType.class =
-  "text"
-  | "password"
-  | "checkbox"
-  | "radio"
-  | "submit"
-  | "reset"
-  | "hidden"
-select = element select { select.attlist, option+ }
-select.attlist =
-  Common.attrib,
-  attribute name { text }?,
-  attribute size { Number.datatype }?,
-  attribute multiple { "multiple" }?
-option =
-  element option {
-    Common.attrib,
-    attribute selected { "selected" }?,
-    attribute value { text }?,
-    text
-  }
-textarea = element textarea { textarea.attlist }
-textarea.attlist =
-  Common.attrib,
-  attribute name { text }?,
-  attribute rows { Number.datatype },
-  attribute cols { Number.datatype },
-  attribute accesskey { Character.datatype }?,
-  text
-Form.class = form
-Formctrl.class = input | label | select | textarea
-Block.class |= Form.class
-Inline.class |= Formctrl.class
--- a/etc/schema/xhtml-basic-table.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-# Basic Tables Module
-
-table = element table { table.attlist, caption?, tr+ }
-table.attlist =
-  Common.attrib,
-  attribute summary { Text.datatype }?
-caption = element caption { caption.attlist, Inline.model }
-caption.attlist = Common.attrib
-tr = element tr { tr.attlist, (th | td)+ }
-tr.attlist = Common.attrib, CellHAlign.attrib, CellVAlign.attrib
-th = element th { th.attlist, Flow.model }
-th.attlist = Cell.attrib
-td = element td { td.attlist, Flow.model }
-td.attlist = Cell.attrib
-Cell.attrib =
-  Common.attrib,
-  attribute abbr { Text.datatype }?,
-  attribute axis { text }?,
-  attribute headers { IDREFS.datatype }?,
-  scope.attrib,
-  attribute rowspan { Number.datatype }?,
-  attribute colspan { Number.datatype }?,
-  CellHAlign.attrib,
-  CellVAlign.attrib
-CellHAlign.attrib = attribute align { "left" | "center" | "right" }?
-CellVAlign.attrib = attribute valign { "top" | "middle" | "bottom" }?
-scope.attrib = attribute scope { "row" | "col" }?
-Block.class |= table
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/schema/xhtml-bform.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,63 @@
+# Simplified Forms Module
+
+form =
+  element form {
+    form.attlist,
+    # Don't use Block.model, because this gets redefined by the
+    # legacy module.
+    Block.class+
+  }
+form.attlist =
+  Common.attrib,
+  attribute action { URI.datatype },
+  attribute method { "get" | "post" }?,
+  attribute enctype { ContentType.datatype }?
+label = element label { label.attlist, Inline.model }
+label.attlist =
+  Common.attrib,
+  attribute for { IDREF.datatype }?,
+  attribute accesskey { Character.datatype }?
+input = element input { input.attlist }
+input.attlist =
+  Common.attrib,
+  attribute type { InputType.class }?,
+  attribute name { text }?,
+  attribute value { text }?,
+  attribute checked { "checked" }?,
+  attribute size { text }?,
+  attribute maxlength { Number.datatype }?,
+  attribute src { URI.datatype }?,
+  attribute accesskey { Character.datatype }?
+InputType.class =
+  "text"
+  | "password"
+  | "checkbox"
+  | "radio"
+  | "submit"
+  | "reset"
+  | "hidden"
+select = element select { select.attlist, option+ }
+select.attlist =
+  Common.attrib,
+  attribute name { text }?,
+  attribute size { Number.datatype }?,
+  attribute multiple { "multiple" }?
+option =
+  element option {
+    Common.attrib,
+    attribute selected { "selected" }?,
+    attribute value { text }?,
+    text
+  }
+textarea = element textarea { textarea.attlist }
+textarea.attlist =
+  Common.attrib,
+  attribute name { text }?,
+  attribute rows { Number.datatype },
+  attribute cols { Number.datatype },
+  attribute accesskey { Character.datatype }?,
+  text
+Form.class = form
+Formctrl.class = input | label | select | textarea
+Block.class |= Form.class
+Inline.class |= Formctrl.class
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/schema/xhtml-btable.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,28 @@
+# Basic Tables Module
+
+table = element table { table.attlist, caption?, tr+ }
+table.attlist =
+  Common.attrib,
+  attribute summary { Text.datatype }?
+caption = element caption { caption.attlist, Inline.model }
+caption.attlist = Common.attrib
+tr = element tr { tr.attlist, (th | td)+ }
+tr.attlist = Common.attrib, CellHAlign.attrib, CellVAlign.attrib
+th = element th { th.attlist, Flow.model }
+th.attlist = Cell.attrib
+td = element td { td.attlist, Flow.model }
+td.attlist = Cell.attrib
+Cell.attrib =
+  Common.attrib,
+  attribute abbr { Text.datatype }?,
+  attribute axis { text }?,
+  attribute headers { IDREFS.datatype }?,
+  scope.attrib,
+  attribute rowspan { Number.datatype }?,
+  attribute colspan { Number.datatype }?,
+  CellHAlign.attrib,
+  CellVAlign.attrib
+CellHAlign.attrib = attribute align { "left" | "center" | "right" }?
+CellVAlign.attrib = attribute valign { "top" | "middle" | "bottom" }?
+scope.attrib = attribute scope { "row" | "col" }?
+Block.class |= table
--- a/etc/schema/xhtml-form.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ b/etc/schema/xhtml-form.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -2,7 +2,7 @@
 
 # Unlike the DTD implementation, this builds on the basic-form module
 
-include "xhtml-basic-form.rnc" {
+include "xhtml-bform.rnc" {
   select = element select { select.attlist, (option | optgroup)+ }
 }
 form.attlist &=
--- a/etc/schema/xhtml-list.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,16 +0,0 @@
-# List Module
-
-dl = element dl { dl.attlist, (dt | dd)+ }
-dl.attlist = Common.attrib
-dt = element dt { dt.attlist, Inline.model }
-dt.attlist = Common.attrib
-dd = element dd { dd.attlist, Flow.model }
-dd.attlist = Common.attrib
-ol = element ol { ol.attlist, li+ }
-ol.attlist = Common.attrib
-ul = element ul { ul.attlist, li+ }
-ul.attlist = Common.attrib
-li = element li { li.attlist, Flow.model }
-li.attlist = Common.attrib
-List.class = ul | ol | dl
-Block.class |= List.class
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/schema/xhtml-lst.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,16 @@
+# List Module
+
+dl = element dl { dl.attlist, (dt | dd)+ }
+dl.attlist = Common.attrib
+dt = element dt { dt.attlist, Inline.model }
+dt.attlist = Common.attrib
+dd = element dd { dd.attlist, Flow.model }
+dd.attlist = Common.attrib
+ol = element ol { ol.attlist, li+ }
+ol.attlist = Common.attrib
+ul = element ul { ul.attlist, li+ }
+ul.attlist = Common.attrib
+li = element li { li.attlist, Flow.model }
+li.attlist = Common.attrib
+List.class = ul | ol | dl
+Block.class |= List.class
--- a/etc/schema/xhtml-style.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-# Style Module
-
-style = element style { style.attlist, text }
-style.attlist =
-  title.attrib,
-  I18n.attrib,
-  attribute type { ContentType.datatype },
-  attribute media { MediaDesc.datatype }?,
-  attribute xml:space { "preserve" }?
-head.content &= style*
--- a/etc/schema/xhtml-table.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ b/etc/schema/xhtml-table.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -3,7 +3,7 @@
 # This builds on the basic tables module, unlike with the DTD
 # implementation.
 
-include "xhtml-basic-table.rnc" {
+include "xhtml-btable.rnc" {
   table =
     element table {
       table.attlist,
--- a/etc/schema/xhtml-target.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,8 +0,0 @@
-# Target Module
-
-a.attlist &= target.attrib
-area.attlist &= target.attrib
-base.attlist &= target.attrib
-link.attrib &= target.attrib
-form.attlist &= target.attrib
-target.attrib = attribute target { text }?
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/schema/xhtml-tgt.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,8 @@
+# Target Module
+
+a.attlist &= target.attrib
+area.attlist &= target.attrib
+base.attlist &= target.attrib
+link.attrib &= target.attrib
+form.attlist &= target.attrib
+target.attrib = attribute target { text }?
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/etc/schema/xhtml-xstyle.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,10 @@
+# Style Module
+
+style = element style { style.attlist, text }
+style.attlist =
+  title.attrib,
+  I18n.attrib,
+  attribute type { ContentType.datatype },
+  attribute media { MediaDesc.datatype }?,
+  attribute xml:space { "preserve" }?
+head.content &= style*
--- a/etc/schema/xhtml.rnc	Fri Dec 14 12:53:04 2007 +0000
+++ b/etc/schema/xhtml.rnc	Sun Dec 16 05:08:49 2007 +0000
@@ -10,7 +10,7 @@
 include "xhtml-frames.rnc"
 include "xhtml-text.rnc"
 include "xhtml-hypertext.rnc"
-include "xhtml-list.rnc"
+include "xhtml-lst.rnc"
 include "xhtml-image.rnc"
 include "xhtml-ssismap.rnc"
 include "xhtml-base.rnc"
@@ -22,16 +22,16 @@
 include "xhtml-pres.rnc"
 include "xhtml-edit.rnc"
 include "xhtml-applet.rnc"
-# include "xhtml-basic-form.rnc"
+# include "xhtml-bform.rnc"
 include "xhtml-form.rnc"
-include "xhtml-style.rnc"
+include "xhtml-xstyle.rnc"
 include "xhtml-script.rnc"
-# include "xhtml-basic-table.rnc"
+# include "xhtml-btable.rnc"
 include "xhtml-table.rnc"
 include "xhtml-csismap.rnc"
 include "xhtml-events.rnc"
 include "xhtml-inlstyle.rnc"
-include "xhtml-target.rnc"
+include "xhtml-tgt.rnc"
 include "xhtml-iframe.rnc"
 include "xhtml-nameident.rnc"
 include "xhtml-legacy.rnc"
--- a/leim/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/leim/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,8 @@
+2007-12-07  Kenichi Handa  <handa@ni.aist.go.jp>
+
+	* quail/lao.el (quail-map-from-table): Allow a tone just after a
+	consonant.
+
 2007-11-17  Glenn Morris  <rgm@gnu.org>
 
 	* Makefile.in (check-declare): New target.
--- a/leim/quail/lao.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/leim/quail/lao.el	Sun Dec 16 05:08:49 2007 +0000
@@ -206,8 +206,9 @@
 		lao-tone-key-alist
 		lao-other-key-alist)
     (svt-state (lao-semivowel-key-alist . v-state)
-	      (lao-vowel-key-alist . t-state)
-	      lao-voweltone-key-alist)
+	       (lao-vowel-key-alist . t-state)
+	       lao-voweltone-key-alist
+	       lao-tone-key-alist)
     (v-state (lao-vowel-key-alist . t-state))
     (t-state lao-tone-key-alist))))
 
--- a/leim/quail/latin-post.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/leim/quail/latin-post.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1256,7 +1256,7 @@
 (quail-define-package
  "scandinavian-postfix" "Latin-1" "SC<" t
  "Scandinavian input method with postfix modifiers
-Supported languages are Swidish, Norwegian, Danish, and Finnish.
+Supported languages are Swedish, Norwegian, Danish, and Finnish.
 
 ae -> æ
 oe -> ø
--- a/lib-src/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/lib-src/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -17,7 +17,7 @@
 
 2007-11-22  Francesco Potort,Al(B  <pot@gnu.org>
 
-	* etags.c (default_C_help) [CTAGS]: differentiate the help string,
+	* etags.c (default_C_help) [CTAGS]: Differentiate the help string,
 	as the defaults in ctags are different from etags.
 
 2007-11-15  Francesco Potort,Al(B  <pot@gnu.org>
--- a/lisp/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,306 @@
+2007-12-12  Thien-Thi Nguyen  <ttn@gnuvola.org>
+
+	* progmodes/cc-vars.el (defcustom-c-stylevar): Rewrite.
+
+2007-12-11  Dan Nicolaescu  <dann@ics.uci.edu>
+
+	* progmodes/verilog-mode.el (set-buffer-menubar): Remove unused
+	function.
+	(add-submenu): Only define for XEmacs.
+	(verilog-regexp-words): Revert previous change, keep the other
+	definition.
+
+2007-12-09  Dan Nicolaescu  <dann@ics.uci.edu>
+
+	* progmodes/perl-mode.el (perl-continued-statement-offset)
+	(perl-continued-brace-offset, perl-brace-offset)
+	(perl-brace-imaginary-offset, perl-label-offset):
+	* progmodes/cperl-mode.el (cperl-brace-offset)
+	(cperl-continued-brace-offset, cperl-label-offset)
+	(cperl-continued-statement-offset)
+	(cperl-extra-newline-before-brace, cperl-merge-trailing-else): Add
+	safe-local-variable properties.
+
+2007-12-08  Dan Nicolaescu  <dann@ics.uci.edu>
+
+	* progmodes/verilog-mode.el (verilog-mode-map)
+	(verilog-template-map, verilog-mode-mouse-map): Fix typos.
+	(verilog-colorize-include-files): Use only overlay functions so
+	that it can work on both emacs and XEmacs.
+	(set-extent-keymap): Remove unused defun.
+	(verilog-kill-existing-comment, verilog-insert-date)
+	(verilog-insert-year): Rename in order not to pollute the global
+	namespace from kill-existing-comment, insert-date and
+	insert-year, respectively.
+	(verilog-set-auto-endcomments, verilog-header): Update callers.
+
+	* files.el (auto-mode-alist): Recognize verilog files.
+
+	* progmodes/verilog-mode.el (verilog-string-replace-matches)
+	(verilog-string-remove-spaces, verilog-re-search-forward)
+	(verilog-re-search-backward, verilog-re-search-forward-quick)
+	(verilog-re-search-backward-quick, verilog-get-beg-of-line)
+	(verilog-get-end-of-line, verilog-within-string): Move definitions
+	before first use. No code changes.
+
+2007-12-08  Dan Nicolaescu  <dann@ics.uci.edu>
+
+	* progmodes/verilog-mode.el (verilog-mode-version)
+	(verilog-mode-release-date): Don't use expanding keywords.
+	(provide): Move to the end of file.
+	(fboundp): Don't check if eval-when-compile is bound, it is used
+	later in the file without checking.
+	(when, unless): Copy definitions from subr.el.
+	(char-before, defcustom, defface, customize-group)
+	(verilog-batch-error-wrapper): Don't use old style backquotes.
+	(verilog-regexp-opt): Avoid using the cl function case.
+	(verilog-regexp-words): Remove duplicated definition.
+	(verilog-mode-abbrev-table): Remove, duplicate.
+	(verilog-mode-map, verilog-template-map, verilog-mode-mouse-map):
+	Declare and initialize in one step.
+	(verilog-declaration-prefix-re, verilog-declaration-re)
+	(verilog-end-of-statement, verilog-indent-declaration)
+	(verilog-get-lineup-indent): Remove trailing whitespace.
+	(verilog-mode): Fix autoload cookie. Set
+	beginning-of-defun-function and end-of-defun-function. Use when
+	instead of if.
+	(verilog-emacs-features, verilog-auto-ascii-enum)
+	(verilog-insert-indices): Escape braces in doc strings.
+
+2007-12-08  Michael McNamara <mac@verilog.com>
+	    Wilson Snyder <wsnyder@wsnyder.org>
+
+	* progmodes/verilog-mode.el: New file.
+
+2007-12-08  Eli Zaretskii  <eliz@fencepost.gnu.org>
+
+	* international/latexenc.el (latexenc-find-file-coding-system): If
+	both coding-system-for-write and buffer-file-coding-system of
+	latex-main-file are nil, use `undecided'.
+
+2007-12-06  Jason Rumney  <jasonr@gnu.org>
+
+	* mouse.el (mouse-buffer-menu-alist): Keep buffer names left aligned.
+
+2007-12-12  Yoni Rabkin Katzenell  <yoni-r@actcom.com>  (tiny change)
+
+	* files.el (revert-buffer): Docstring fix.
+
+2007-12-11  Glenn Morris  <rgm@gnu.org>
+
+	* emacs-lisp/check-declare.el (check-declare-verify): Handle deffoo.
+
+2007-12-11  Jay Belanger  <jay.p.belanger@gmail.com>
+
+	* calc/calc-aent.el (math-restore-underscores)
+	(math-string-restore-underscores): New functions.
+	(math-read-factor): Properly check variable names with underscores
+	for entries in `math-expr-variable-mapping'.
+
+	* calc/calc-lang.el (math-lang-name): New property name.
+
+	* calc/calc.el (calc-set-mode-line): Use `math-lang-name'
+	to set language name.
+
+2007-12-10  Katsumi Yamaoka  <yamaoka@jpl.org>
+
+	* pgg.el (pgg-run-at-time, pgg-cancel-timer): Use eval-and-compile.
+
+2007-12-10  Stefan Monnier  <monnier@iro.umontreal.ca>
+
+	* server.el (server-select-display): Fix important typo.
+	(server-process-filter): Turn a "" display into nil.
+
+2007-12-09  Juri Linkov  <juri@jurta.org>
+
+	* replace.el (keep-lines, flush-lines, how-many): Doc fix.
+	Check search-upper-case before calling isearch-no-upper-case-p
+	to set case-fold-search.
+	(occur): Doc fix.
+	(occur-1, perform-replace): Check search-upper-case before calling
+	isearch-no-upper-case-p to set case-fold-search.
+
+	* isearch.el (search-upper-case): Doc fix.
+	(isearch-mode-map): Bind `M-s o' to isearch-occur.
+	(isearch-query-replace): Doc fix.  Let-bind search-upper-case to nil.
+	(isearch-query-replace-regexp): Doc fix.
+	(isearch-occur): New function.
+
+2007-12-09  Reiner Steib  <Reiner.Steib@gmx.de>
+
+	* pgg.el, pgg-parse.el (declare-function): Add new no-op macro for
+	backward compatibility.
+
+	* net/imap.el (imap-string-to-integer): New function.
+
+2007-12-09  David Kastrup  <dak@gnu.org>
+
+	* emacs-lisp/lisp-mnt.el (lm-verify): Make it work with
+	directories.  Not sure anybody uses this anymore, though.
+
+2007-12-09  Vinicius Jose Latorre  <viniciusjl@ig.com.br>
+
+	* printing.el: Fix pr-interface-map initialization code.
+	(pr-version): New version 6.9.3.
+	(pr-f-set-keymap-parents): Replace by pr-set-keymap-parents.
+	(pr-f-set-keymap-name): Replace by pr-set-keymap-name.
+	(pr-f-read-string): Replace by pr-read-string.
+	(pr-set-keymap-parents, pr-set-keymap-name, pr-read-string): New fun
+	name.
+	(pr-interactive-n-up, pr-interactive-regexp): Code fix.
+
+2007-12-09  Glenn Morris  <rgm@gnu.org>
+
+	* emulation/viper-init.el (top-level): Use dolist rather than mapc
+	in make-variable-frame-local call.
+
+2007-12-08  Dan Nicolaescu  <dann@ics.uci.edu>
+
+	* mail/hashcash.el (declare-function):
+	* net/imap.el (declare-function): New no-op macro for backward
+	compatibility.
+
+2007-12-08  Eli Zaretskii  <eliz@gnu.org>
+
+	Sync makefile.w32-in with Makefile.in.
+
+	* makefile.w32-in (check-declare): New target.
+	(BYTE_COMPILE_EXTRA_FLAGS): New variable.
+	(.el.elc, compile-CMD, compile-SH, compile-always-CMD)
+	(compile-always-SH, compile-calc-CMD, compile-calc-SH)
+	($(lisp)/progmodes/cc-mode.elc): Use it.
+	($(lisp)/progmodes/cc-mode.elc): New rule.
+
+2007-12-08  Reiner Steib  <Reiner.Steib@gmx.de>
+
+	* indent.el (tab-stop-list): Mark as safe-local-variable.
+
+	* generic-x.el (etc-sudoers-generic-mode): New mode.
+	(generic-unix-modes): Add it.
+
+2007-12-08  Michael Albinus  <michael.albinus@gmx.de>
+
+	* net/dbus.el (dbus-hash-table=): Remove function.  We cannot
+	apply wildcards in a hash table key; there is no usable hash code then.
+	(dbus-registered-functions-table): Use `equal' as test function.
+	(dbus-name-owner-changed-handler): Rewrite due to new hash table
+	structure.
+
+2007-12-08  Martin Rudalics  <rudalics@gmx.at>
+
+	* progmodes/cc-cmds.el (c-mask-paragraph): Avoid invalid search
+	bound error in block comment branch.
+
+2007-12-08  David Kastrup  <dak@gnu.org>
+
+	* textmodes/reftex.el (reftex-select-with-char):
+	* textmodes/reftex-toc.el (reftex-toc-do-promote)
+	(reftex-toc-visit-location, reftex-toc-find-section):
+	* textmodes/reftex-index.el (reftex-index-show-entry):
+	* textmodes/org.el (org-cycle-hide-archived-subtrees)
+	(org-table-rotate-recalc-marks, org-mark-ring-push)
+	(org-follow-info-link, org-mhe-get-message-folder-from-index)
+	(org-auto-repeat-maybe, org-store-log-note, org-delete-property)
+	(org-evaluate-time-range, org-edit-agenda-file-list):
+	* textmodes/artist.el (artist-select-next-op-in-list)
+	(artist-select-prev-op-in-list):
+	* term/mac-win.el (mac-service-insert-text):
+	* startup.el (fancy-about-screen):
+	* progmodes/vhdl-mode.el (vhdl-decision-query):
+	* progmodes/idlwave.el (idlwave-template)
+	(idlwave-scroll-completions, idlwave-display-completion-list):
+	* progmodes/ebrowse.el (ebrowse-show-progress):
+	* progmodes/cperl-mode.el (cperl-find-pods-heres):
+	* progmodes/antlr-mode.el (antlr-insert-option-do):
+	* play/mpuz.el (mpuz-close-game):
+	* net/rcirc.el (rcirc-next-active-buffer):
+	* mail/reporter.el (reporter-update-status):
+	* kmacro.el (kmacro-display):
+	* international/ja-dic-cnv.el (skkdic-set-okuri-nasi):
+	* emulation/viper-util.el (viper-save-setting):
+	* emacs-lisp/lisp-mnt.el (lm-verify):
+	* emacs-lisp/edebug.el (edebug-set-mode):
+	* emacs-lisp/checkdoc.el (checkdoc-rogue-spaces, checkdoc-defun):
+	* calendar/calendar.el (calendar-print-day-of-year):
+	* calc/calcalg3.el (calc-curve-fit):
+	* calc/calcalg2.el (math-integral):
+	* calc/calc.el (calc-read-key-sequence, calc-version):
+	* calc/calc-mode.el (calc-set-simplify-mode):
+	* calc/calc-ext.el (calc-fancy-prefix): Fix buggy call to `message'.
+
+2007-12-07  D. Goel  <deego3@gmail.com>
+
+	* progmodes/idlw-shell.el (idlwave-shell-display-line)
+	* progmodes/ada-xref.el (ada-find-file, ada-get-all-references)
+	(ada-xref-find-in-modified-ali, ada-find-in-src-path)
+	* mail/uce.el (uce-reply-to-uce)
+	* progmodes/vhdl-mode.el (vhdl-template-modify)
+	* mail/feedmail.el (feedmail-dump-message-to-queue): Improve calls
+	to `error' (as suggested by RMS.)
+
+2007-12-07  Glenn Morris  <rgm@gnu.org>
+
+	* allout.el (allout-write-file-hook-handler):
+	* textmodes/reftex.el (reftex-TeX-master-file):
+	* textmodes/reftex-parse.el (reftex-short-context):
+	Revert previous change.
+
+2007-12-07  Michael Albinus  <michael.albinus@gmx.de>
+
+	* net/dbus.el (dbus-hash-table=): Fix for new hash table key structure.
+	(dbus-list-hash-table, dbus-name-owner-changed-handler): New defuns.
+	(dbus-check-event, dbus-handle-event, dbus-event-bus-name)
+	(dbus-event-service-name, dbus-event-path-name)
+	(dbus-event-interface-name, dbus-event-member-name): Fix for new
+	event structure.
+	(dbus-list-activatable-names, dbus-list-names)
+	(dbus-list-queued-owners, dbus-get-name-owner, dbus-introspect):
+	Reorder `dbus-call-method' arguments.
+
+2007-12-06  D. Goel  <deego3@gmail.com>
+
+	* allout.el (allout-write-file-hook-handler):
+	* textmodes/reftex.el (reftex-TeX-master-file):
+	* textmodes/org.el (org-paste-subtree):
+	* progmodes/vhdl-mode.el (vhdl-template-modify):
+	* progmodes/idlw-shell.el (idlwave-shell-send-command)
+	(idlwave-shell-display-line):
+	* progmodes/ada-xref.el (ada-find-file, ada-get-all-references)
+	(ada-xref-find-in-modified-ali, ada-find-in-src-path):
+	* net/trampver.el (x):
+	* mail/uce.el (uce-reply-to-uce):
+	* mail/rmailout.el (rmail-output):
+	* mail/feedmail.el (feedmail-dump-message-to-queue):
+	* whitespace.el (whitespace-write-file-hook):
+	* wdired.el (wdired-check-kill-buffer):
+	* vc.el (vc-update):
+	* vc-mcvs.el (vc-mcvs-checkin):
+	* vc-cvs.el (vc-cvs-checkin):
+	* man.el (Man-bgproc-sentinel, Man-goto-see-also-section):
+	* ibuffer.el (ibuffer-current-buffer):
+	* dired.el (dired-move-to-end-of-filename):
+	* bindings.el (complete-symbol):
+	* textmodes/org-publish.el (org-publish-file):
+	(org-publish-current-project):
+	* textmodes/reftex-parse.el (reftex-short-context):
+	* textmodes/texinfmt.el: Fix buggy calls to `error'.
+
+2007-12-06  Stefan Monnier  <monnier@iro.umontreal.ca>
+
+	* doc-view.el (doc-view-dvi->pdf-sentinel)
+	(doc-view-pdf/ps->png-sentinel, doc-view-pdf->txt-sentinel)
+	(doc-view-ps->pdf-sentinel, doc-view-display): Don't change buffer
+	within a sentinel or timer.
+	(doc-view-display): Don't try to display before the requested page
+	is available, unless told to do so explicitly.
+	(doc-view-pdf/ps->png-sentinel, doc-view-initiate-display):
+	Force display even if the requested page is not available.
+
+2007-12-06  Richard Stallman  <rms@gnu.org>
+
+	* help-fns.el (describe-function-1): Call ad-get-advice-info
+	only on symbols.
+
 2007-12-06  Glenn Morris  <rgm@gnu.org>
 
 	* progmodes/antlr-mode.el (antlr-keyword, antlr-syntax)
@@ -97,8 +400,8 @@
 
 	* eshell/esh-module.el (eshell-load-defgroups): Eval and compile.
 
-	* eshell/esh-util.el (top-level): Don't require pp.  Use
-	condition-case rather than ignore-errors.
+	* eshell/esh-util.el (top-level): Don't require pp.
+	Use condition-case rather than ignore-errors.
 
 	* eshell/eshell.el (eshell-buffer-name): Define for compiler.
 
@@ -120,8 +423,8 @@
 	esh-maint.  Collect any require statements.  Leave provide at start.
 	Move any commentary to start.
 
-	* emacs-lisp/bytecomp.el (byte-compile-declare-function): Remove
-	declared function from byte-compile-noruntime-functions.
+	* emacs-lisp/bytecomp.el (byte-compile-declare-function):
+	Remove declared function from byte-compile-noruntime-functions.
 
 	* ediff-util.el (ediff-version):
 	* progmodes/python.el (compilation-shell-minor-mode):
@@ -223,16 +526,16 @@
 
 2007-12-03  Richard Stallman  <rms@gnu.org>
 
-	* subr.el (declare-function): Moved from byte-run.el.
-
-	* emacs-lisp/byte-run.el (declare-function): Moved to subr.el
+	* subr.el (declare-function): Move from byte-run.el.
+
+	* emacs-lisp/byte-run.el (declare-function): Move to subr.el
 
 	* window.el (recenter-top-bottom): Don't use `ecase'.
 
 2007-12-02  Karl Fogel  <kfogel@red-bean.com>
 
-	* saveplace.el (save-place-alist-to-file): Set
-	coding-system-for-write once and refer to it throughout.
+	* saveplace.el (save-place-alist-to-file):
+	Set coding-system-for-write once and refer to it throughout.
 	Suggested by David Reitter <dreitter{_AT_}inf.ed.ac.uk>.
 
 2007-12-02  Karl Fogel  <kfogel@red-bean.com>
--- a/lisp/bindings.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/bindings.el	Sun Dec 16 05:08:49 2007 +0000
@@ -616,7 +616,7 @@
     (if (fboundp 'complete-tag)
 	(complete-tag)
       ;; Don't autoload etags if we have no tags table.
-      (error (substitute-command-keys
+      (error "%s" (substitute-command-keys
 	      "No tags table loaded; use \\[visit-tags-table] to load one")))))
 
 ;; Reduce total amount of space we must allocate during this function
--- a/lisp/calc/calc-aent.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/calc/calc-aent.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1015,6 +1015,19 @@
        (concat (math-match-substring x 1) "-" (math-match-substring x 2)))
     x))
 
+(defun math-restore-underscores (x)
+  "Replace pound signs by underscores in the symbol x.
+If the current Calc language does not allow underscores, return nil."
+  (if (memq calc-language calc-lang-allow-underscores)
+      (intern-soft (math-string-restore-underscores (symbol-name x)))))
+
+(defun math-string-restore-underscores (x)
+  "Replace pound signs by underscores in the string x."
+  (if (string-match "\\`\\(.*\\)#\\(.*\\)\\'" x)
+      (math-string-restore-underscores
+       (concat (math-match-substring x 1) "_" (math-match-substring x 2)))
+    x))
+
 (defun math-read-if (cond op)
   (let ((then (math-read-expr-level 0)))
     (or (equal math-expr-data ":")
@@ -1116,7 +1129,10 @@
 				      sym
 				    (intern (concat "var-"
 						    (symbol-name sym)))))))
-		   (let ((v (assq (nth 1 val) math-expr-variable-mapping)))
+		   (let ((v (or
+                             (assq (nth 1 val) math-expr-variable-mapping)
+                             (assq (math-restore-underscores (nth 1 val))
+                                   math-expr-variable-mapping))))
 		     (and v (setq val (if (consp (cdr v))
 					  (funcall (car (cdr v)) v val)
 					(list 'var
--- a/lisp/calc/calc-ext.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/calc/calc-ext.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1434,7 +1434,7 @@
      (calc-set-command-flag 'no-align)
      (setq prefix (set flag (not (symbol-value flag)))
 	   prefix-arg n)
-     (message (if prefix msg "")))
+     (message "%s" (if prefix msg "")))
     (and prefix
 	 (not calc-is-keypad-press)
 	 (if (boundp 'overriding-terminal-local-map)
--- a/lisp/calc/calc-lang.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/calc/calc-lang.el	Sun Dec 16 05:08:49 2007 +0000
@@ -408,6 +408,9 @@
           (message 
            "LaTeX language mode with \\func(\\text{var}) and multiline matrices")))))
 
+(put 'tex 'math-lang-name "TeX")
+(put 'latex 'math-lang-name "LaTeX")
+
 (put 'tex 'math-oper-table
   '( ( "\\hat"    calcFunc-hat     -1  950 )
      ( "\\check"  calcFunc-check   -1  950 )
--- a/lisp/calc/calc-mode.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/calc/calc-mode.el	Sun Dec 16 05:08:49 2007 +0000
@@ -505,7 +505,7 @@
 			     mode)
 		      (and (not (eq calc-simplify-mode mode))
 			   mode)))
-  (message (if (eq calc-simplify-mode mode)
+  (message "%s" (if (eq calc-simplify-mode mode)
 	       msg
 	     "Default simplifications enabled")))
 
--- a/lisp/calc/calc.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/calc/calc.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1228,7 +1228,7 @@
   (let ((prompt2 (format "%s " (key-description (this-command-keys))))
 	(glob (current-global-map))
 	(loc (current-local-map)))
-    (or (input-pending-p) (message prompt))
+    (or (input-pending-p) (message "%s" prompt))
     (let ((key (calc-read-key t)))
       (calc-unread-command (cdr key))
       (unwind-protect
@@ -1244,7 +1244,7 @@
 (defun calc-version ()
   "Return version of this version of Calc."
   (interactive)
-  (message (concat "Calc version " calc-version)))
+  (message "Calc version %s" calc-version))
 
 (defun calc-mode ()
   "Calculator major mode.
@@ -1675,8 +1675,8 @@
 			   (t (format "Radix%d " calc-number-radix)))
 		     (if calc-leading-zeros "Zero " "")
 		     (cond ((null calc-language) "")
-			   ((eq calc-language 'tex) "TeX ")
-			   ((eq calc-language 'latex) "LaTeX ")
+                           ((get calc-language 'math-lang-name)
+                            (concat (get calc-language 'math-lang-name) " "))
 			   (t (concat
 			       (capitalize (symbol-name calc-language))
 			       " ")))
--- a/lisp/calc/calcalg2.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/calc/calcalg2.el	Sun Dec 16 05:08:49 2007 +0000
@@ -746,7 +746,7 @@
 		      (setq math-integ-msg (format
 					    "Working... Integrating %s"
 					    (math-format-flat-expr expr 0)))
-		      (message math-integ-msg)))
+		      (message "%s" math-integ-msg)))
 		(if math-cur-record
 		    (setcar (cdr math-cur-record)
 			    (if same-as-above (vector simp) 'busy))
@@ -773,7 +773,7 @@
 						     "simplification...\n")
 			      (setq val (math-integral simp 'no t))))))))
 	      (if (eq calc-display-working-message 'lots)
-		  (message math-integ-msg)))
+		  (message "%s" math-integ-msg)))
 	  (setcar (cdr math-cur-record) (or val
 				       (if (or math-enable-subst
 					       (not math-any-substs))
--- a/lisp/calc/calcalg3.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/calc/calcalg3.el	Sun Dec 16 05:08:49 2007 +0000
@@ -416,7 +416,7 @@
              (calc-record (calc-normalize calc-fit-to-trail) "parm"))))
   (when plot
     (if (stringp plot)
-        (message plot)
+        (message "%s" plot)
       (let ((calc-graph-no-auto-view t))
         (calc-graph-delete t)
         (calc-graph-add-curve
--- a/lisp/calendar/calendar.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/calendar/calendar.el	Sun Dec 16 05:08:49 2007 +0000
@@ -3154,7 +3154,7 @@
 (defun calendar-print-day-of-year ()
   "Show day number in year/days remaining in year for date under the cursor."
   (interactive)
-  (message (calendar-day-of-year-string (calendar-cursor-to-date t))))
+  (message "%s" (calendar-day-of-year-string (calendar-cursor-to-date t))))
 
 (defun calendar-set-mode-line (str)
   "Set mode line to STR, centered, surrounded by dashes."
--- a/lisp/dired.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/dired.el	Sun Dec 16 05:08:49 2007 +0000
@@ -2009,7 +2009,7 @@
 	       (forward-char -1))))
       (or no-error
 	  (not (eq opoint (point)))
-	  (error (if hidden
+	  (error "%s" (if hidden
 		     (substitute-command-keys
 		      "File line is hidden, type \\[dired-hide-subdir] to unhide")
 		   "No file on this line")))
--- a/lisp/doc-view.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/doc-view.el	Sun Dec 16 05:08:49 2007 +0000
@@ -508,14 +508,14 @@
   "If DVI->PDF conversion was successful, convert the PDF to PNG now."
   (if (not (string-match "finished" event))
       (message "DocView: dvi->pdf process changed status to %s." event)
-    (set-buffer (process-get proc 'buffer))
-    (setq doc-view-current-converter-process nil
-	  mode-line-process nil)
-    ;; Now go on converting this PDF to a set of PNG files.
-    (let* ((pdf (process-get proc 'pdf-file))
-	   (png (expand-file-name "page-%d.png"
-                                  (doc-view-current-cache-dir))))
-      (doc-view-pdf/ps->png pdf png))))
+    (with-current-buffer (process-get proc 'buffer)
+      (setq doc-view-current-converter-process nil
+            mode-line-process nil)
+      ;; Now go on converting this PDF to a set of PNG files.
+      (let* ((pdf (process-get proc 'pdf-file))
+             (png (expand-file-name "page-%d.png"
+                                    (doc-view-current-cache-dir))))
+        (doc-view-pdf/ps->png pdf png)))))
 
 (defun doc-view-dvi->pdf (dvi pdf)
   "Convert DVI to PDF asynchronously."
@@ -533,14 +533,14 @@
   "If PDF/PS->PNG conversion was successful, update the display."
   (if (not (string-match "finished" event))
       (message "DocView: converter process changed status to %s." event)
-    (set-buffer (process-get proc 'buffer))
-    (setq doc-view-current-converter-process nil
-	  mode-line-process nil)
-    (when doc-view-current-timer
-      (cancel-timer doc-view-current-timer)
-      (setq doc-view-current-timer nil))
-    ;; Yippie, finished.  Update the display!
-    (doc-view-display buffer-file-name)))
+    (with-current-buffer (process-get proc 'buffer)
+      (setq doc-view-current-converter-process nil
+            mode-line-process nil)
+      (when doc-view-current-timer
+        (cancel-timer doc-view-current-timer)
+        (setq doc-view-current-timer nil))
+      ;; Yippie, finished.  Update the display!
+      (doc-view-display buffer-file-name 'force))))
 
 (defun doc-view-pdf/ps->png (pdf-ps png)
   "Convert PDF-PS to PNG asynchronously."
@@ -568,13 +568,13 @@
       (message "DocView: converter process changed status to %s." event)
     (let ((current-buffer (current-buffer))
 	  (proc-buffer    (process-get proc 'buffer)))
-      (set-buffer proc-buffer)
-      (setq doc-view-current-converter-process nil
-	    mode-line-process nil)
-      ;; If the user looks at the DocView buffer where the conversion was
-      ;; performed, search anew.  This time it will be queried for a regexp.
-      (when (eq current-buffer proc-buffer)
-	(doc-view-search nil)))))
+      (with-current-buffer proc-buffer
+        (setq doc-view-current-converter-process nil
+              mode-line-process nil)
+        ;; If the user looks at the DocView buffer where the conversion was
+        ;; performed, search anew.  This time it will be queried for a regexp.
+        (when (eq current-buffer proc-buffer)
+          (doc-view-search nil))))))
 
 (defun doc-view-pdf->txt (pdf txt)
   "Convert PDF to TXT asynchronously."
@@ -590,13 +590,13 @@
 (defun doc-view-ps->pdf-sentinel (proc event)
   (if (not (string-match "finished" event))
       (message "DocView: converter process changed status to %s." event)
-    (set-buffer (process-get proc 'buffer))
-    (setq doc-view-current-converter-process nil
-	  mode-line-process nil)
-    ;; Now we can transform to plain text.
-    (doc-view-pdf->txt (process-get proc 'pdf-file)
-		       (expand-file-name "doc.txt"
-                                         (doc-view-current-cache-dir)))))
+    (with-current-buffer (process-get proc 'buffer)
+      (setq doc-view-current-converter-process nil
+            mode-line-process nil)
+      ;; Now we can transform to plain text.
+      (doc-view-pdf->txt (process-get proc 'pdf-file)
+                         (expand-file-name "doc.txt"
+                                           (doc-view-current-cache-dir))))))
 
 (defun doc-view-ps->pdf (ps pdf)
   "Convert PS to PDF asynchronously."
@@ -707,15 +707,19 @@
       (and (= (length a) (length b))
            (string< a b))))
 
-(defun doc-view-display (doc)
-  "Start viewing the document DOC."
-  (set-buffer (get-file-buffer doc))
-  (setq doc-view-current-files
-	(sort (directory-files (doc-view-current-cache-dir) t
-			       "page-[0-9]+\\.png" t)
-	      'doc-view-sort))
-  (when (> (length doc-view-current-files) 0)
-    (doc-view-goto-page doc-view-current-page)))
+(defun doc-view-display (doc &optional force)
+  "Start viewing the document DOC.
+If FORCE is non-nil, start viewing even if the document does not
+have the page we want to view."
+  (with-current-buffer (get-file-buffer doc)
+    (setq doc-view-current-files
+          (sort (directory-files (doc-view-current-cache-dir) t
+                                 "page-[0-9]+\\.png" t)
+                'doc-view-sort))
+    (when (or force
+              (>= (length doc-view-current-files)
+                  (or doc-view-current-page 1)))
+      (doc-view-goto-page doc-view-current-page))))
 
 (defun doc-view-buffer-message ()
   ;; Only show this message initially, not when refreshing the buffer (in which
@@ -898,7 +902,7 @@
 	(if (file-exists-p (doc-view-current-cache-dir))
 	    (progn
 	      (message "DocView: using cached files!")
-	      (doc-view-display buffer-file-name))
+	      (doc-view-display buffer-file-name 'force))
 	  (doc-view-convert-current-doc))
 	(message
 	 "%s"
--- a/lisp/ediff-init.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/ediff-init.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1576,7 +1576,7 @@
 	 )
 	((ediff-key-press-event-p event)
 	 (point))
-	(t (error nil))))
+	(t (error "Error"))))
 
 (defun ediff-event-buffer (event)
   (cond ((ediff-mouse-event-p event)
@@ -1587,7 +1587,7 @@
 	 )
 	((ediff-key-press-event-p event)
 	 (current-buffer))
-	(t (error nil))))
+	(t (error "Error"))))
 
 (defun ediff-event-key (event-or-key)
   (ediff-cond-compile-for-xemacs-or-emacs
--- a/lisp/emacs-lisp/check-declare.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/emacs-lisp/check-declare.el	Sun Dec 16 05:08:49 2007 +0000
@@ -34,6 +34,9 @@
 
 ;;; TODO:
 
+;; 1. Warn about functions marked as obsolete, eg
+;; password-read-and-add in smime.el.
+
 ;;; Code:
 
 (defconst check-declare-warning-buffer "*Check Declarations Warnings*"
@@ -141,7 +144,8 @@
           ;; defsubst's don't _have_ to be known at compile time.
           (setq re (format (if cflag
                                "^[ \t]*\\(DEFUN\\)[ \t]*([ \t]*\"%s\""
-                             "^[ \t]*(\\(fset[ \t]+'\\|def\\(?:un\\|subst\\|\
+                             "^[ \t]*(\\(fset[ \t]+'\\|\
+def\\(?:un\\|subst\\|foo\\|\
 ine-\\(?:derived\\|generic\\|\\(?:global\\(?:ized\\)?-\\)?minor\\)-mode\
 \\|\\(?:ine-obsolete-function-\\)?alias[ \t]+'\\)\\)\
 \[ \t]*%s\\([ \t;]+\\|$\\)")
--- a/lisp/emacs-lisp/checkdoc.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/emacs-lisp/checkdoc.el	Sun Dec 16 05:08:49 2007 +0000
@@ -978,7 +978,7 @@
     (if (not (interactive-p))
 	e
       (if e
-	  (message (checkdoc-error-text e))
+	  (message "%s" (checkdoc-error-text e))
 	(checkdoc-show-diagnostics)
 	(message "Space Check: done.")))))
 
@@ -1038,15 +1038,15 @@
 	     (end (save-excursion (end-of-defun) (point)))
 	     (msg (checkdoc-this-string-valid)))
 	(if msg (if no-error
-		    (message (checkdoc-error-text msg))
+		    (message "%s" (checkdoc-error-text msg))
 		  (error "%s" (checkdoc-error-text msg)))
 	  (setq msg (checkdoc-message-text-search beg end))
 	  (if msg (if no-error
-		      (message (checkdoc-error-text msg))
+		      (message "%s" (checkdoc-error-text msg))
 		    (error "%s" (checkdoc-error-text msg)))
 	    (setq msg (checkdoc-rogue-space-check-engine beg end))
 	    (if msg (if no-error
-			(message (checkdoc-error-text msg))
+			(message "%s" (checkdoc-error-text msg))
 		      (error "%s" (checkdoc-error-text msg))))))
 	(if (interactive-p) (message "Checkdoc: done."))))))
 
--- a/lisp/emacs-lisp/edebug.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/emacs-lisp/edebug.el	Sun Dec 16 05:08:49 2007 +0000
@@ -3295,12 +3295,12 @@
   (if (eq (1+ edebug-recursion-depth) (recursion-depth))
       (progn
 	(setq edebug-execution-mode mode)
-	(message shortmsg)
+	(message "%s" shortmsg)
 	;; Continue execution
 	(exit-recursive-edit))
     ;; This is not terribly useful!!
     (setq edebug-next-execution-mode mode)
-    (message msg)))
+    (message "%s" msg)))
 
 
 (defalias 'edebug-step-through-mode 'edebug-step-mode)
--- a/lisp/emacs-lisp/lisp-mnt.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/emacs-lisp/lisp-mnt.el	Sun Dec 16 05:08:49 2007 +0000
@@ -511,18 +511,17 @@
     (if (and file (file-directory-p file))
 	(setq ret
 	      (with-temp-buffer
-		(mapcar
-		 (lambda (f)
-		   (if (string-match ".*\\.el\\'" f)
-		       (let ((status (lm-verify f)))
-			 (insert f ":")
-			 (if status
-			     (lm-insert-at-column lm-comment-column status
-						  "\n")
-			   (if showok
-			       (lm-insert-at-column lm-comment-column
-						    "OK\n"))))))
-		 (directory-files file))))
+		(dolist (f (directory-files file nil "\\.el\\'")
+			   (buffer-string))
+		  (when (file-regular-p f)
+		    (let ((status (lm-verify f)))
+		      (insert f ":")
+		      (if status
+			  (lm-insert-at-column lm-comment-column status
+					       "\n")
+			(if showok
+			    (lm-insert-at-column lm-comment-column
+						 "OK\n"))))))))
       (lm-with-file file
 	(setq name (lm-get-package-name))
 	(setq ret
@@ -562,7 +561,7 @@
 	       (t
 		ret)))))
     (if verbose
-	(message ret))
+	(message "%s" ret))
     ret))
 
 (defun lm-synopsis (&optional file showall)
--- a/lisp/emulation/viper-init.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/emulation/viper-init.el	Sun Dec 16 05:08:49 2007 +0000
@@ -445,12 +445,10 @@
 (defvar viper-vi-state-cursor-color nil)
 
 (if (fboundp 'make-variable-frame-local)
-    (mapc 'make-variable-frame-local
-          '(viper-replace-overlay-cursor-color
-            viper-insert-state-cursor-color
-            viper-emacs-state-cursor-color
-            viper-vi-state-cursor-color)))
-
+    (dolist (v '(viper-replace-overlay-cursor-color
+                 viper-insert-state-cursor-color viper-emacs-state-cursor-color
+                 viper-vi-state-cursor-color))
+      (make-variable-frame-local v)))
 
 (viper-deflocalvar viper-replace-overlay nil "")
 (put 'viper-replace-overlay 'permanent-local t)
--- a/lisp/emulation/viper-util.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/emulation/viper-util.el	Sun Dec 16 05:08:49 2007 +0000
@@ -636,7 +636,7 @@
 	 (regexp (format "^[^;]*%s[ \t\n]*[a-zA-Z---_']*[ \t\n)]" var-name))
 	 (buf (find-file-noselect (substitute-in-file-name custom-file)))
 	)
-    (message message)
+    (message "%s" (or message ""))
     (save-excursion
       (set-buffer buf)
       (goto-char (point-min))
--- a/lisp/erc/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/erc/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,37 @@
+2007-12-09  Michael Olson  <mwolson@gnu.org>
+
+	* erc-services.el (erc-nickserv-alist): Fix regexps for GRnet.
+
+2007-12-09  Giorgos Keramidas  <keramida@ceid.upatras.gr>  (tiny change)
+
+	* erc-backend.el, erc.el:
+	Parse 275 (secure connection) responses.
+
+	* erc-services.el: Add identification hooks for GRnet, the Greek
+	IRC network <http://www.irc.gr>.
+
+2007-12-08  David Kastrup  <dak@gnu.org>
+
+	* erc-stamp.el (erc-echo-timestamp):
+	* erc-lang.el (language):
+	* erc-backend.el (erc-server-connect): Fix buggy call to `message'.
+
+2007-12-07  Edward O'Connor  <ted@oconnor.cx>
+
+	* erc-services.el: Provide a hook that runs when nickserv confirms
+	that the user has successfully identified.
+	(services, erc-nickserv-identify-mode): Add and remove
+	erc-nickserv-identification-autodetect from
+	erc-server-NOTICE-functions.
+	(erc-nickserv-alist): Add SUCCESS-REGEXP to each entry.
+	(erc-nickserv-alist-identified-regexp)
+	(erc-nickserv-identification-autodetect): New functions.
+	(erc-nickserv-identified-hook): New hook.
+
+2007-12-06  D. Goel  <deego3@gmail.com>
+
+	* erc-match.el (erc-add-entry-to-list): Fix buggy call to `error'.
+
 2007-12-01  Glenn Morris  <rgm@gnu.org>
 
 	* erc-backend.el (erc-server-send-ping): Move after definition of
--- a/lisp/erc/erc-backend.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/erc/erc-backend.el	Sun Dec 16 05:08:49 2007 +0000
@@ -515,7 +515,7 @@
       (set-process-filter process 'erc-server-filter-function)
       (set-process-buffer process buffer)))
   (erc-log "\n\n\n********************************************\n")
-  (message (erc-format-message
+  (message "%s" (erc-format-message
             'login ?n
             (with-current-buffer buffer (erc-current-nick))))
   ;; wait with script loading until we receive a confirmation (first
@@ -1538,6 +1538,16 @@
 See `erc-display-server-message'." nil
   (erc-display-server-message proc parsed))
 
+(define-erc-response-handler (275)
+  "Display secure connection message." nil
+  (multiple-value-bind (nick user message)
+      (cdr (erc-response.command-args parsed))
+    (erc-display-message
+     parsed 'notice 'active 's275
+     ?n nick
+     ?m (mapconcat 'identity (cddr (erc-response.command-args parsed))
+                   " "))))
+
 (define-erc-response-handler (290)
   "Handle dancer-ircd CAPAB messages." nil nil)
 
--- a/lisp/erc/erc-lang.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/erc/erc-lang.el	Sun Dec 16 05:08:49 2007 +0000
@@ -197,7 +197,7 @@
   "Return the language name for the ISO CODE."
   (interactive (list (completing-read "ISO language code: "
 				      iso-638-languages)))
-  (message (cdr (assoc code iso-638-languages))))
+  (message "%s" (cdr (assoc code iso-638-languages))))
 
 (defun erc-cmd-LANG (language)
   "Display the language name for the language code given by LANGUAGE."
--- a/lisp/erc/erc-match.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/erc/erc-match.el	Sun Dec 16 05:08:49 2007 +0000
@@ -299,7 +299,7 @@
 		(lambda (x)
 		  (not (erc-member-ignore-case (car x) (symbol-value list)))))))
     (if (erc-member-ignore-case entry (symbol-value list))
-	(error (format "\"%s\" is already on the list" entry))
+	(error "\"%s\" is already on the list" entry)
       (set list (cons entry (symbol-value list))))))
 
 (defun erc-remove-entry-from-list (list prompt)
--- a/lisp/erc/erc-services.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/erc/erc-services.el	Sun Dec 16 05:08:49 2007 +0000
@@ -29,9 +29,10 @@
 ;; are made to test if NickServ is the real NickServ for a given network or
 ;; server.
 
-;; As a default, ERC has the data for the official nickname services on the
-;; networks Austnet, BrasNET, Dalnet, freenode, GalaxyNet, and Slashnet.
-;; You can add more by using M-x customize-variable RET erc-nickserv-alist.
+;; As a default, ERC has the data for the official nickname services on
+;; the networks Austnet, BrasNET, Dalnet, freenode, GalaxyNet, GRnet,
+;; and Slashnet.  You can add more by using M-x customize-variable RET
+;; erc-nickserv-alist.
 
 ;; Usage:
 ;;
@@ -109,7 +110,9 @@
    (remove-hook 'erc-after-connect
 		'erc-nickserv-identify-on-connect)
    (remove-hook 'erc-nick-changed-functions
-		'erc-nickserv-identify-on-nick-change)))
+		'erc-nickserv-identify-on-nick-change)
+   (remove-hook 'erc-server-NOTICE-functions
+		'erc-nickserv-identification-autodetect)))
 
 ;;;###autoload
 (defun erc-nickserv-identify-mode (mode)
@@ -118,6 +121,8 @@
    (list (intern (completing-read
 		  "Choose Nickserv identify mode (RET to disable): "
 		  '(("autodetect") ("nick-change") ("both")) nil t))))
+  (add-hook 'erc-server-NOTICE-functions
+	    'erc-nickserv-identification-autodetect)
   (cond ((eq mode 'autodetect)
 	 (setq erc-nickserv-identify-mode 'autodetect)
 	 (add-hook 'erc-server-NOTICE-functions
@@ -149,7 +154,9 @@
 	 (remove-hook 'erc-after-connect
 		      'erc-nickserv-identify-on-connect)
 	 (remove-hook 'erc-nick-changed-functions
-		      'erc-nickserv-identify-on-nick-change))))
+		      'erc-nickserv-identify-on-nick-change)
+	 (remove-hook 'erc-server-NOTICE-functions
+		      'erc-nickserv-identification-autodetect))))
 
 (defcustom erc-prompt-for-nickserv-password t
   "Ask for the password when identifying to NickServ."
@@ -176,6 +183,7 @@
 			(const DALnet)
 			(const freenode)
 			(const GalaxyNet)
+			(const GRnet)
 			(const iip)
 			(const OFTC)
 			(const QuakeNet)
@@ -192,63 +200,70 @@
   '((Ars
      nil nil
      "Census"
-     "IDENTIFY" nil nil)
+     "IDENTIFY" nil nil nil)
     (Austnet
      "NickOP!service@austnet.org"
      "/msg\\s-NickOP@austnet.org\\s-identify\\s-<password>"
      "nickop@austnet.org"
-     "identify" nil nil)
+     "identify" nil nil nil)
     (Azzurra
      "NickServ!service@azzurra.org"
      "/ns\\s-IDENTIFY\\s-password"
      "NickServ"
-     "IDENTIFY" nil nil)
+     "IDENTIFY" nil nil nil)
     (BitlBee
      nil nil
      "&bitlbee"
-     "identify" nil nil)
+     "identify" nil nil nil)
     (BRASnet
      "NickServ!services@brasnet.org"
      "/NickServ\\s-IDENTIFY\\s-senha"
      "NickServ"
-     "IDENTIFY" nil "")
+     "IDENTIFY" nil "" nil)
     (DALnet
      "NickServ!service@dal.net"
      "/msg\\s-NickServ@services.dal.net\\s-IDENTIFY\\s-<password>"
      "NickServ@services.dal.net"
-     "IDENTIFY" nil nil)
+     "IDENTIFY" nil nil nil)
     (freenode
      "NickServ!NickServ@services."
      "/msg\\s-NickServ\\s-IDENTIFY\\s-<password>"
      "NickServ"
-     "IDENTIFY" nil nil)
+     "IDENTIFY" nil nil
+     "Password\\s-accepted\\s--\\s-you\\s-are\\s-now\\s-recognized")
     (GalaxyNet
      "NS!nickserv@galaxynet.org"
      "Please\\s-change\\s-nicks\\s-or\\s-authenticate."
      "NS@services.galaxynet.org"
-     "AUTH" t nil)
+     "AUTH" t nil nil)
+    (GRnet
+     "NickServ!service@irc.gr"
+     "This\\s-nickname\\s-is\\s-registered\\s-and\\s-protected."
+     "NickServ"
+     "IDENTIFY" nil nil
+     "Password\\s-accepted\\s--\\s-you\\s-are\\s-now\\s-recognized.")
     (iip
      "Trent@anon.iip"
      "type\\s-/squery\\s-Trent\\s-identify\\s-<password>"
      "Trent@anon.iip"
-     "IDENTIFY" nil "SQUERY")
+     "IDENTIFY" nil "SQUERY" nil)
     (OFTC
      "NickServ!services@services.oftc.net"
      "type\\s-/msg\\s-NickServ\\s-IDENTIFY\\s-password."
      "NickServ"
-     "IDENTIFY" nil nil)
+     "IDENTIFY" nil nil nil)
     (QuakeNet
      nil nil
      "Q@CServe.quakenet.org"
-     "auth" t nil)
+     "auth" t nil nil)
     (SlashNET
      "NickServ!services@services.slashnet.org"
      "/msg\\s-NickServ\\s-IDENTIFY\\s-password"
      "NickServ@services.slashnet.org"
-     "IDENTIFY" nil nil))
+     "IDENTIFY" nil nil nil))
    "Alist of NickServer details, sorted by network.
 Every element in the list has the form
-  \(SYMBOL NICKSERV REGEXP NICK KEYWORD USE-CURRENT ANSWER)
+  \(SYMBOL NICKSERV REGEXP NICK KEYWORD USE-CURRENT ANSWER SUCCESS-REGEXP)
 
 SYMBOL is a network identifier, a symbol, as used in `erc-networks-alist'.
 NICKSERV is the description of the nickserv in the form nick!user@host.
@@ -258,7 +273,9 @@
 USE-CURRENT indicates whether the current nickname must be used when
   identifying.
 ANSWER is the command to use for the answer.  The default is 'privmsg.
-  This last element is optional."
+SUCCESS-REGEXP is a regular expression matching the message nickserv
+  sends when you've successfully identified.
+The last two elements are optional."
    :group 'erc-services
    :type '(repeat
 	   (list :tag "Nickserv data"
@@ -292,8 +309,36 @@
 (defsubst erc-nickserv-alist-ident-command (network &optional entry)
   (nth 6 (or entry (assoc network erc-nickserv-alist))))
 
+(defsubst erc-nickserv-alist-identified-regexp (network &optional entry)
+  (nth 7 (or entry (assoc network erc-nickserv-alist))))
+
 ;; Functions:
 
+(defcustom erc-nickserv-identified-hook nil
+  "Run this hook when NickServ acknowledged successful identification.
+Hooks are called with arguments (NETWORK NICK)."
+  :group 'erc-services
+  :type 'hook)
+
+(defun erc-nickserv-identification-autodetect (proc parsed)
+  "Check for NickServ's successful identification notice.
+Make sure it is the real NickServ for this network and that it has
+specifically confirmed a successful identification attempt.
+If this is the case, run `erc-nickserv-identified-hook'."
+  (let* ((network (erc-network))
+	 (sender (erc-nickserv-alist-sender network))
+	 (success-regex (erc-nickserv-alist-identified-regexp network))
+	 (sspec (erc-response.sender parsed))
+	 (nick (car (erc-response.command-args parsed)))
+	 (msg (erc-response.contents parsed)))
+    ;; continue only if we're sure it's the real nickserv for this network
+    ;; and it's told us we've successfully identified
+    (when (and sender (equal sspec sender)
+	       (string-match success-regex msg))
+      (erc-log "NickServ IDENTIFY success notification detected")
+      (run-hook-with-args 'erc-nickserv-identified-hook network nick)
+      nil)))
+
 (defun erc-nickserv-identify-autodetect (proc parsed)
   "Check for a NickServ identify request everytime a notice is received.
 Make sure it is the real NickServ for this network and that it has
--- a/lisp/erc/erc-stamp.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/erc/erc-stamp.el	Sun Dec 16 05:08:49 2007 +0000
@@ -412,8 +412,8 @@
   (when erc-echo-timestamps
     (let ((stamp (get-text-property now 'timestamp)))
       (when stamp
-	(message (format-time-string erc-echo-timestamp-format
-				     stamp))))))
+	(message "%s" (format-time-string erc-echo-timestamp-format
+					  stamp))))))
 
 (provide 'erc-stamp)
 
--- a/lisp/erc/erc.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/erc/erc.el	Sun Dec 16 05:08:49 2007 +0000
@@ -6213,6 +6213,7 @@
    (s252   . "%i operator(s) online")
    (s253   . "%i unknown connection(s)")
    (s254   . "%i channels formed")
+   (s275   . "%n %m")
    (s301   . "%n is AWAY: %r")
    (s303   . "Is online: %n")
    (s305   . "%m")
--- a/lisp/files.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/files.el	Sun Dec 16 05:08:49 2007 +0000
@@ -2054,6 +2054,8 @@
      ("\\.dtd\\'" . sgml-mode)
      ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
      ("\\.js\\'" . java-mode)		; javascript-mode would be better
+     ("\\.x[bp]m\\'" . c-mode)
+     ("\\.d?v\\'" . verilog-mode)
      ;; .emacs or .gnus or .viper following a directory delimiter in
      ;; Unix, MSDOG or VMS syntax.
      ("[]>:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode)
@@ -4204,10 +4206,12 @@
 With a prefix argument, offer to revert from latest auto-save file, if
 that is more recent than the visited file.
 
-This command also works for special buffers that contain text which
-doesn't come from a file, but reflects some other data base instead:
-for example, Dired buffers and `buffer-list' buffers.  In these cases,
-it reconstructs the buffer contents from the appropriate data base.
+This command also implements an interface for special buffers
+that contain text which doesn't come from a file, but reflects
+some other data instead (e.g. Dired buffers, `buffer-list'
+buffers).  This is done via the variable
+`revert-buffer-function'.  In these cases, it should reconstruct
+the buffer contents from the appropriate data.
 
 When called from Lisp, the first argument is IGNORE-AUTO; only offer
 to revert from the auto-save file when this is nil.  Note that the
--- a/lisp/generic-x.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/generic-x.el	Sun Dec 16 05:08:49 2007 +0000
@@ -221,6 +221,7 @@
     etc-modules-conf-generic-mode
     etc-passwd-generic-mode
     etc-services-generic-mode
+    etc-sudoers-generic-mode
     fvwm-generic-mode
     inetd-conf-generic-mode
     mailagent-rules-generic-mode
@@ -1736,6 +1737,21 @@
       (setq imenu-generic-expression
 	    '((nil "^\\([^# \t]+\\)\\s-+" 1))))))))
 
+;; /etc/sudoers
+(when (memq 'etc-sudoers-generic-mode generic-extras-enable-list)
+
+(define-generic-mode etc-sudoers-generic-mode
+  '(?#)
+  '("User_Alias" "Runas_Alias" "Host_Alias"  "Cmnd_Alias"
+    "NOPASSWD" "PASSWD" "NOEXEC" "EXEC"
+    "ALL")
+  '(("\\<\\(root\\|su\\)\\>" 1 font-lock-warning-face)
+    ("\\(\\*\\)" 1 font-lock-warning-face)
+    ("\\<\\(%[A-Za-z0-9_]+\\)\\>" 1 font-lock-variable-name-face))
+  '("/etc/sudoers\\'")
+  nil
+  "Generic mode for sudoers configuration files."))
+
 ;; From Jacques Duthen <jacques.duthen@sncf.fr>
 (when (memq 'show-tabs-generic-mode generic-extras-enable-list)
 
--- a/lisp/gnus/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,169 @@
+2007-12-15  Reiner Steib  <Reiner.Steib@gmx.de>
+
+	* gnus-art.el (article-verify-x-pgp-sig): Add reference to X-PGP-Sig
+	format document.
+	(gnus-mime-delete-part): Don't write description line if empty.
+	(gnus-article-encrypt-body): Add confirmation for gnus-novice-user.
+
+2007-12-14  Johan Bockg,Ae(Brd  <bojohan@gnu.org>
+
+	* gnus-sum.el (gnus-summary-mark-unread-as-read)
+	(gnus-summary-mark-read-and-unread-as-read)
+	(gnus-summary-mark-current-read-and-unread-as-read)
+	(gnus-summary-mark-unread-as-ticked): Doc fix.
+	`gnus-mark-article-hook', not `gnus-summary-mark-article-hook'.
+
+2007-12-14  Reiner Steib  <Reiner.Steib@gmx.de>
+
+	* gnus-sum.el (gnus-summary-prev-article): Fix doc string.  Reported by
+	Christoph Conrad <christoph.conrad@gmx.de>.
+
+2007-12-14  Reiner Steib  <Reiner.Steib@gmx.de>
+
+	* gnus-util.el (gnus-y-or-n-p, gnus-yes-or-no-p): Alias to y-or-n-p and
+	yes-or-no-p.
+
+2007-12-11  Katsumi Yamaoka  <yamaoka@jpl.org>
+
+	* mm-decode.el (mm-add-meta-html-tag): New function.
+	(mm-save-part-to-file, mm-pipe-part): Use it
+
+	* gnus-art.el (gnus-article-browse-delete-temp-files): Use
+	gnus-y-or-n-p instead of y-or-n-p.
+	(gnus-article-browse-html-parts): Work with message/external-body; use
+	mm-add-meta-html-tag.
+
+2007-12-11  Glenn Morris  <rgm@gnu.org>
+
+	* gnus-cache.el: Require gnus-sum not just when compiling.
+
+	* gnus-fun.el (gnus-display-x-face-in-from): Require gnus-art.
+
+	* gnus-int.el (gnus-server-opened, gnus-status-message): Move
+	definitions before use.
+
+	* mm-decode.el: Require gnus-util.
+	(mm-remove-part): Only call delete-annotation on XEmacs.
+
+	* mm-uu.el (gnus-original-article-buffer): Define for compiler.
+
+	* nnmail.el: Require gnus-int.
+
+	* spam.el: Move `require's before `eval-when-compile's.
+
+	* gnus-ems.el (gnus-alive-p):
+	* gnus-fun.el (message-goto-eoh):
+	* gnus-util.el (gnus-group-name-decode):
+	* mail-source.el (gnus-compress-sequence):
+	* message.el (Info-goto-node, format-spec):
+	* mm-bodies.el (message-options-get):
+	* mm-decode.el (mm-view-pkcs7):
+	* mm-util.el (gmm-write-region):
+	* mml-smime.el (mml-compute-boundary)
+	(gnus-completing-read-with-default):
+	* mml.el (widget-button-press, gnus-make-hashtable):
+	* mml1991.el (mm-decode-content-transfer-encoding)
+	(mm-encode-content-transfer-encoding)
+	(message-options-get, message-options-set):
+	* mml2015.el (gnus-buffer-live-p, gnus-get-buffer-create):
+	* nnfolder.el (gnus-request-group):
+	* nnheader.el (ietf-drums-unfold-fws):
+	* rfc1843.el (mail-header-parse-content-type, message-narrow-to-head):
+	* smime.el (gnus-run-mode-hooks):
+	* spam-stat.el (gnus-message): Autoload.
+
+	* gnus-cache.el, gnus-fun.el, gnus-group.el, gnus.el, mail-source.el:
+	* mm-bodies.el, mm-decode.el, mm-extern.el, mm-util.el:
+	* mml-smime.el, mml.el, mml1991.el, mml2015.el, nndb.el, nnfolder.el:
+	* nnmail.el, nnmaildir.el, nnrss.el, rfc1843.el, spam.el:
+	Add declare-function compatibility definition.
+
+	* gnus-cache.el (nnvirtual-find-group-art):
+	* gnus-fun.el (article-narrow-to-head, gnus-article-goto-header)
+	(gnus-add-image, gnus-add-wash-type):
+	* gnus-group.el (nnkiboze-score-file):
+	* gnus-sum.el (turn-on-gnus-mailing-list-mode)
+	(gnus-cache-write-active, mm-uu-dissect, idna-to-unicode):
+	* gnus-util.el (gnus-find-method-for-group, gnus-group-name-charset)
+	(message-tokenize-header, gnus-get-buffer-create)
+	(mm-enable-multibyte, gnus-put-text-property, gnus-overlay-put)
+	(gnus-make-overlay, mm-disable-multibyte, gnus-add-text-properties):
+	* gnus.el (gnus-group-decoded-name):
+	* mail-source.el (imap-capability):
+	* mm-bodies.el (message-options-set):
+	* mm-decode.el (gnus-configure-windows):
+	* mm-extern.el (message-goto-body):
+	* mm-util.el (mm-delete-duplicates, mm-detect-coding-region):
+	* mml-smime.el (epg-key-sub-key-list, epg-sub-key-capability)
+	(epg-sub-key-validity, message-options-set):
+	* mml.el (widget-event-point, gnus-configure-windows):
+	* mml1991.el (mc-encrypt-generic, gpg-sign-encrypt, gpg-encrypt):
+	* mml2015.el (epg-check-configuration, epg-configuration)
+	(message-options-set):
+	* nndb.el (nndb-request-article):
+	* nnfolder.el (gnus-request-create-group):
+	* nnmail.el (gnus-activate-group, gnus-group-mark-article-read):
+	* nnmaildir.el (gnus-group-mark-article-read):
+	* nnrss.el (w3-parse-buffer, gnus-group-make-rss-group):
+	* rfc1843.el (message-fetch-field):
+	* spam.el (gnus-extract-address-components):
+	Declare as functions.
+
+2007-12-10  Katsumi Yamaoka  <yamaoka@jpl.org>
+
+	* gnus-art.el (gnus-article-browse-html-parts): Decode CTE.
+
+2007-12-09  Glenn Morris  <rgm@gnu.org>
+
+	* gnus-uu.el (gnus-uu-yenc-article): Use insert-buffer-substring.
+
+	* gnus-art.el, gnus-spec.el, gnus-sum.el, gnus-util.el:
+	* message.el, mm-view.el, sieve-manage, smime.el:
+	Add declare-function compatibility definition.
+
+	* gnus-art.el (w3-region, w3m-region, Info-menu):
+	* gnus-spec.el (gnus-summary-from-or-to-or-newsgroups):
+	* gnus-sum.el (gnus-get-predicate):
+	* gnus-util.el (mm-append-to-file, w32-focus-frame):
+	* message.el (mail-abbrev-in-expansion-header-p):
+	* mm-view.el (w3-do-setup, w3-region, w3-prepare-buffer)
+	(w3m-detect-meta-charset, w3m-region):
+	* sieve-manage.el (password-read, password-cache-add)
+	(password-cache-remove):
+	* smime.el (password-read-and-add): Declare as functions.
+
+2007-12-08  David Kastrup  <dak@gnu.org>
+
+	* gnus-sum.el (gnus-summary-simplify-subject-query):
+	* ecomplete.el (ecomplete-display-matches): Fix buggy call to
+	`message'.
+
+2007-12-07  Glenn Morris  <rgm@gnu.org>
+
+	* gnus-art.el (article-make-date-line): Revert previous change.
+
+2007-12-06  Reiner Steib  <Reiner.Steib@gmx.de>
+
+	* gnus-start.el (gnus-load): Rename local variable to avoid confusion.
+
+2007-12-06  Christian Plate  <cplate@web.de>  (tiny change)
+
+	* nnmaildir.el (nnmaildir-request-update-info): Improved performance.
+	Call gnus-add-to-range ranges only once with a prepared article-list.
+
+2007-12-06  Paul Jarc  <prj@po.cwru.edu>
+
+	* nnmaildir.el (nnmaildir-request-list, nnmaildir-retrieve-groups,
+	nnmaildir-request-group, nnmaildir-retrieve-headers): Escape spaces in
+	group names with backslashes.  Reported by Tassilo Horn
+	<tassilo@member.fsf.org>.
+
+2007-12-06  D. Goel  <deego3@gmail.com>
+
+	* gnus-art.el (article-make-date-line):
+	* gnus-start.el (gnus-load):
+	* pop3.el (pop3-read-response): Fix buggy call to `error'.
+
 2007-12-05  Katsumi Yamaoka  <yamaoka@jpl.org>
 
 	* gnus-art.el (gnus-use-idna)
--- a/lisp/gnus/ecomplete.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/ecomplete.el	Sun Dec 16 05:08:49 2007 +0000
@@ -119,7 +119,7 @@
 	  nil)
       (if (not choose)
 	  (progn
-	    (message matches)
+	    (message "%s" matches)
 	    nil)
 	(setq highlight (ecomplete-highlight-match-line matches line))
 	(while (not (memq (setq command (read-event highlight)) '(? return)))
--- a/lisp/gnus/gnus-art.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-art.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,9 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 (eval-when-compile
   (require 'cl))
 (defvar tool-bar-map)
@@ -2705,6 +2708,9 @@
 	     (t
 	      (apply (car func) (cdr func))))))))))
 
+;; External.
+(declare-function w3-region "ext:w3-display" (st nd))
+
 (defun gnus-article-wash-html-with-w3 ()
   "Wash the current buffer with w3."
   (mm-setup-w3)
@@ -2716,6 +2722,9 @@
 	(w3-region (point-min) (point-max))
       (error))))
 
+;; External.
+(declare-function w3m-region "ext:w3m" (start end &optional url charset))
+
 (defun gnus-article-wash-html-with-w3m ()
   "Wash the current buffer with emacs-w3m."
   (mm-setup-w3m)
@@ -2773,9 +2782,9 @@
 	     (or how
 		 (setq how gnus-article-browse-delete-temp)))
     (when (and (eq how 'ask)
-	       (y-or-n-p (format
-			  "Delete all %s temporary HTML file(s)? "
-			  (length gnus-article-browse-html-temp-list)))
+	       (gnus-y-or-n-p (format
+			       "Delete all %s temporary HTML file(s)? "
+			       (length gnus-article-browse-html-temp-list)))
 	       (setq how t)))
     (dolist (file gnus-article-browse-html-temp-list)
       (when (and (file-exists-p file)
@@ -2793,61 +2802,63 @@
   "View all \"text/html\" parts from LIST.
 Recurse into multiparts."
   ;; Internal function used by `gnus-article-browse-html-article'.
-  (let ((showed))
+  (let (type file charset tmp-file showed)
     ;; Find and show the html-parts.
     (dolist (handle list)
       ;; If HTML, show it:
-      (when (listp handle)
-	(cond ((and (bufferp (car handle))
-		    (string-match "text/html" (car (mm-handle-type handle))))
-	       (let ((tmp-file (mm-make-temp-file
-				;; Do we need to care for 8.3 filenames?
-				"mm-" nil ".html"))
-		     (charset (mail-content-type-get (mm-handle-type handle)
-						     'charset)))
-		 (if charset
-		     ;; Add a meta html tag to specify charset.
-		     (mm-with-unibyte-buffer
-		       (insert (with-current-buffer (mm-handle-buffer handle)
-				 (if (eq charset 'gnus-decoded)
-				     (mm-encode-coding-string
-				      (buffer-string)
-				      (setq charset 'utf-8))
-				   (buffer-string))))
-		       (setq charset (format "\
-<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">"
-					     charset))
-		       (goto-char (point-min))
-		       (let ((case-fold-search t))
-			 (cond (;; Don't modify existing meta tag.
-				(re-search-forward "\
-<meta[\t\n\r ]+http-equiv=\"content-type\"[^>]+>"
-						   nil t))
-			       ((re-search-forward "<head>[\t\n\r ]*" nil t)
-				(insert charset "\n"))
-			       (t
-				(re-search-forward "\
-<html\\(?:[\t\n\r ]+[^>]+\\|[\t\n\r ]*\\)>[\t\n\r ]*"
-						   nil t)
-				(insert "<head>\n" charset "\n</head>\n"))))
+      (cond ((not (listp handle)))
+	    ((or (equal (car (setq type (mm-handle-type handle))) "text/html")
+		 (and (equal (car type) "message/external-body")
+		      (setq file (or (mail-content-type-get type 'name)
+				     (mail-content-type-get
+				      (mm-handle-disposition handle)
+				      'filename)))
+		      (or (mm-handle-cache handle)
+			  (condition-case code
+			      (progn (mm-extern-cache-contents handle) t)
+			    (error
+			     (gnus-message 3 "%s" (error-message-string code))
+			     (when (>= gnus-verbose 3) (sit-for 2))
+			     nil)))
+		      (progn
+			(setq handle (mm-handle-cache handle)
+			      type (mm-handle-type handle))
+			(equal (car type) "text/html"))))
+	     (when (or (setq charset (mail-content-type-get type 'charset))
+		       (not file))
+	       (setq tmp-file (mm-make-temp-file
+			       ;; Do we need to care for 8.3 filenames?
+			       "mm-" nil ".html")))
+	     (if charset
+		 ;; Add a meta html tag to specify charset.
+		 (mm-with-unibyte-buffer
+		   (insert (if (eq charset 'gnus-decoded)
+			       (mm-encode-coding-string (mm-get-part handle)
+							(setq charset 'utf-8))
+			     (mm-get-part handle)))
+		   (if (or (mm-add-meta-html-tag handle charset)
+			   (not file))
 		       (mm-write-region (point-min) (point-max)
-					tmp-file nil nil nil 'binary t))
-		   (mm-save-part-to-file handle tmp-file))
-		 (add-to-list 'gnus-article-browse-html-temp-list tmp-file)
-		 (add-hook 'gnus-summary-prepare-exit-hook
-			   'gnus-article-browse-delete-temp-files)
-		 (add-hook 'gnus-exit-gnus-hook
-			   (lambda  ()
-			     (gnus-article-browse-delete-temp-files t)))
-		 ;; FIXME: Warn if there's an <img> tag?
-		 (browse-url-of-file tmp-file)
-		 (setq showed t)))
-	      ;; If multipart, recurse
-	      ((and (stringp (car handle))
-		    (string-match "^multipart/" (car handle))
-		    (setq showed
-			  (or showed
-			      (gnus-article-browse-html-parts handle))))))))
+					tmp-file nil nil nil 'binary t)
+		     (setq tmp-file nil)))
+	       (when tmp-file
+		 (mm-save-part-to-file handle tmp-file)))
+	     (when tmp-file
+	       (add-to-list 'gnus-article-browse-html-temp-list tmp-file))
+	     (add-hook 'gnus-summary-prepare-exit-hook
+		       'gnus-article-browse-delete-temp-files)
+	     (add-hook 'gnus-exit-gnus-hook
+		       (lambda  ()
+			 (gnus-article-browse-delete-temp-files t)))
+	     ;; FIXME: Warn if there's an <img> tag?
+	     (browse-url-of-file (or tmp-file (expand-file-name file)))
+	     (setq showed t))
+	    ;; If multipart, recurse
+	    ((and (stringp (car handle))
+		  (string-match "^multipart/" (car handle))
+		  (setq showed
+			(or showed
+			    (gnus-article-browse-html-parts handle)))))))
     showed))
 
 ;; FIXME: Documentation in texi/gnus.texi missing.
@@ -3907,6 +3918,7 @@
 
 (defun article-verify-x-pgp-sig ()
   "Verify X-PGP-Sig."
+  ;; <ftp://ftp.isc.org/pub/pgpcontrol/FORMAT>
   (interactive)
   (if (gnus-buffer-live-p gnus-original-article-buffer)
       (let ((sig (with-current-buffer gnus-original-article-buffer
@@ -4715,8 +4727,9 @@
 	   (handles gnus-article-mime-handles)
 	   (none "(none)")
 	   (description
-	    (mail-decode-encoded-word-string (or (mm-handle-description data)
-						 none)))
+	    (let ((desc (mm-handle-description data)))
+	      (when desc
+		(mail-decode-encoded-word-string desc))))
 	   (filename
 	    (or (mail-content-type-get (mm-handle-disposition data) 'filename)
 		none))
@@ -4734,7 +4747,8 @@
 	    "| Type:           " type "\n"
 	    "| Filename:       " filename "\n"
 	    "| Size (encoded): " bsize " Byte\n"
-	    "| Description:    " description "\n"
+	    (when description
+	      (concat    "| Description:    " description "\n"))
 	    "`----\n"))
 	  (setcdr data
 		  (cdr (mm-make-handle
@@ -7682,6 +7696,9 @@
   "Fetch KDE style info URL."
   (gnus-info-find-node (gnus-url-unhex-string url)))
 
+;; (info) will autoload info.el
+(declare-function Info-menu "info" (menu-item &optional fork))
+
 (defun gnus-button-handle-info-keystrokes (url)
   "Call `info' when pushing the corresponding URL button."
   ;; For links like `C-h i d m gnus RET', `C-h i d m CC Mode RET'.
@@ -7991,6 +8008,11 @@
 			 gnus-article-encrypt-protocol-alist
 			 nil t))
     current-prefix-arg))
+  ;; User might hit `K E' instead of `K e', so prompt once.
+  (when (and gnus-article-encrypt-protocol
+	     gnus-novice-user)
+    (unless (gnus-y-or-n-p "Really encrypt article(s)? ")
+      (error "Encrypt aborted.")))
   (let ((func (cdr (assoc protocol gnus-article-encrypt-protocol-alist))))
     (unless func
       (error "Can't find the encrypt protocol %s" protocol))
--- a/lisp/gnus/gnus-cache.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-cache.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,13 +27,18 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 
 (require 'gnus)
+(require 'gnus-sum)
+
 (eval-when-compile
   (unless (fboundp 'gnus-agent-load-alist)
-      (defun gnus-agent-load-alist (group)))
-  (require 'gnus-sum))
+    (defun gnus-agent-load-alist (group))))
 
 (defcustom gnus-cache-active-file
   (expand-file-name "active" gnus-cache-directory)
@@ -91,6 +96,8 @@
 (defvar gnus-cache-active-altered nil)
 (defvar gnus-cache-total-fetched-hashtb nil)
 
+(declare-function nnvirtual-find-group-art "nnvirtual" (group article))
+
 (eval-and-compile
   (autoload 'nnml-generate-nov-databases-directory "nnml")
   (autoload 'nnvirtual-find-group-art "nnvirtual"))
--- a/lisp/gnus/gnus-ems.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-ems.el	Sun Dec 16 05:08:49 2007 +0000
@@ -161,6 +161,8 @@
   "Non-nil means the mark and region are currently active in this buffer."
   mark-active) ; aliased to region-exists-p in XEmacs.
 
+(autoload 'gnus-alive-p "gnus-util")
+
 (defun gnus-x-splash ()
   "Show a splash screen using a pixmap in the current buffer."
   (interactive)
--- a/lisp/gnus/gnus-fun.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-fun.el	Sun Dec 16 05:08:49 2007 +0000
@@ -26,6 +26,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile
   (require 'cl))
 
@@ -105,6 +109,8 @@
 	 (format gnus-convert-pbm-to-x-face-command
 		 (shell-quote-argument file)))))))
 
+(autoload 'message-goto-eoh "message" nil t)
+
 ;;;###autoload
 (defun gnus-insert-random-x-face-header ()
   "Insert a random X-Face header from `gnus-x-face-directory'."
@@ -203,8 +209,14 @@
 colors of the displayed X-Faces."
   :group 'gnus-article-headers)
 
+(declare-function article-narrow-to-head   "gnus-art" ())
+(declare-function gnus-article-goto-header "gnus-art" (header))
+(declare-function gnus-add-image           "gnus-art" (category image))
+(declare-function gnus-add-wash-type       "gnus-art" (type))
+
 (defun gnus-display-x-face-in-from (data)
   "Display the X-Face DATA in the From header."
+  (require 'gnus-art)
   (let ((default-enable-multibyte-characters nil)
 	pbm)
     (when (or (gnus-image-type-available-p 'xface)
--- a/lisp/gnus/gnus-group.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-group.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile
   (require 'cl))
 (defvar tool-bar-mode)
@@ -3004,6 +3008,8 @@
      (list 'nndir (gnus-group-real-name group) (list 'nndir-directory dir)))))
 
 (defvar nnkiboze-score-file)
+(declare-function nnkiboze-score-file "nnkiboze" (group))
+
 (defun gnus-group-make-kiboze-group (group address scores)
   "Create an nnkiboze group.
 The user will be prompted for a name, a regexp to match groups, and
--- a/lisp/gnus/gnus-int.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-int.el	Sun Dec 16 05:08:49 2007 +0000
@@ -58,6 +58,27 @@
 (defvar gnus-internal-registry-spool-current-method nil
   "The current method, for the registry.")
 
+
+(defun gnus-server-opened (gnus-command-method)
+  "Check whether a connection to GNUS-COMMAND-METHOD has been opened."
+  (unless (eq (gnus-server-status gnus-command-method)
+	      'denied)
+    (when (stringp gnus-command-method)
+      (setq gnus-command-method (gnus-server-to-method gnus-command-method)))
+    (funcall (inline (gnus-get-function gnus-command-method 'server-opened))
+	     (nth 1 gnus-command-method))))
+
+(defun gnus-status-message (gnus-command-method)
+  "Return the status message from GNUS-COMMAND-METHOD.
+If GNUS-COMMAND-METHOD is a string, it is interpreted as a group
+name.  The method this group uses will be queried."
+  (let ((gnus-command-method
+	 (if (stringp gnus-command-method)
+	     (gnus-find-method-for-group gnus-command-method)
+	   gnus-command-method)))
+    (funcall (gnus-get-function gnus-command-method 'status-message)
+	     (nth 1 gnus-command-method))))
+
 ;;;
 ;;; Server Communication
 ;;;
@@ -315,26 +336,6 @@
     (when func
       (funcall func date (nth 1 gnus-command-method)))))
 
-(defun gnus-server-opened (gnus-command-method)
-  "Check whether a connection to GNUS-COMMAND-METHOD has been opened."
-  (unless (eq (gnus-server-status gnus-command-method)
-	      'denied)
-    (when (stringp gnus-command-method)
-      (setq gnus-command-method (gnus-server-to-method gnus-command-method)))
-    (funcall (inline (gnus-get-function gnus-command-method 'server-opened))
-	     (nth 1 gnus-command-method))))
-
-(defun gnus-status-message (gnus-command-method)
-  "Return the status message from GNUS-COMMAND-METHOD.
-If GNUS-COMMAND-METHOD is a string, it is interpreted as a group
-name.  The method this group uses will be queried."
-  (let ((gnus-command-method
-	 (if (stringp gnus-command-method)
-	     (gnus-find-method-for-group gnus-command-method)
-	   gnus-command-method)))
-    (funcall (gnus-get-function gnus-command-method 'status-message)
-	     (nth 1 gnus-command-method))))
-
 (defun gnus-request-regenerate (gnus-command-method)
   "Request a data generation from GNUS-COMMAND-METHOD."
   (when (stringp gnus-command-method)
--- a/lisp/gnus/gnus-spec.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-spec.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,9 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 (eval-when-compile (require 'cl))
 (defvar gnus-newsrc-file-version)
 
@@ -87,6 +90,9 @@
 (defvar gnus-tmp-header)
 (defvar gnus-tmp-from)
 
+(declare-function gnus-summary-from-or-to-or-newsgroups "gnus-sum"
+                  (header gnus-tmp-from))
+
 (defun gnus-summary-line-format-spec ()
   (insert gnus-tmp-unread gnus-tmp-replied
 	  gnus-tmp-score-char gnus-tmp-indentation)
--- a/lisp/gnus/gnus-start.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-start.el	Sun Dec 16 05:08:49 2007 +0000
@@ -2394,11 +2394,11 @@
 	    (eval form))
 	(error
 	 (unless (eq (car type) 'end-of-file)
-	   (let ((error (format "Error in %s line %d" file
-				(count-lines (point-min) (point)))))
+	   (let ((errmsg (format "Error in %s line %d" file
+				 (count-lines (point-min) (point)))))
 	     (ding)
-	     (unless (gnus-yes-or-no-p (concat error "; continue? "))
-	       (error "%s" error)))))))))
+	     (unless (gnus-yes-or-no-p (concat errmsg "; continue? "))
+	       (error "%s" errmsg)))))))))
 
 (defun gnus-read-newsrc-el-file (file)
   (let ((ding-file (concat file "d")))
--- a/lisp/gnus/gnus-sum.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-sum.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,9 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 (eval-when-compile
   (require 'cl))
 
@@ -2959,6 +2962,9 @@
 	    (setq headers (cdr headers)))
 	  (list (nreverse outh))))))))
 
+
+(declare-function turn-on-gnus-mailing-list-mode "gnus-ml" ())
+
 
 
 (defun gnus-summary-mode (&optional group)
@@ -4028,7 +4034,7 @@
   "Query where the respool algorithm would put this article."
   (interactive)
   (gnus-summary-select-article)
-  (message (gnus-general-simplify-subject (gnus-summary-article-subject))))
+  (message "%s" (gnus-general-simplify-subject (gnus-summary-article-subject))))
 
 (defun gnus-gather-threads-by-subject (threads)
   "Gather threads by looking at Subject headers."
@@ -5576,6 +5582,8 @@
 	  (gnus-inverse-list-range-intersection
 	   gnus-newsgroup-articles gnus-newsgroup-seen))))
 
+(declare-function gnus-get-predicate "gnus-agent" (predicate))
+
 (defun gnus-summary-display-make-predicate (display)
   (require 'gnus-agent)
   (when (= (length display) 1)
@@ -6946,6 +6954,8 @@
       (gnus-save-newsrc-file)
     (gnus-dribble-save)))
 
+(declare-function gnus-cache-write-active "gnus-cache" (&optional force))
+
 (defun gnus-summary-exit (&optional temporary leave-hidden)
   "Exit reading current newsgroup, and then return to group selection mode.
 `gnus-exit-group-hook' is called with no arguments if that value is non-nil."
@@ -7648,7 +7658,7 @@
 	(gnus-summary-article-subject))))
 
 (defun gnus-summary-prev-article (&optional unread subject)
-  "Select the article after the current one.
+  "Select the article before the current one.
 If UNREAD is non-nil, only unread articles are selected."
   (interactive "P")
   (gnus-summary-next-article unread subject t))
@@ -9437,6 +9447,8 @@
   ;; Create buttons and stuff...
   (gnus-treat-article nil))
 
+(declare-function idna-to-unicode "ext:idna" (str))
+
 (defun gnus-summary-idna-message (&optional arg)
   "Decode IDNA encoded domain names in the current articles.
 IDNA encoded domain names looks like `xn--bar'.  If a string
@@ -10818,12 +10830,12 @@
   (gnus-summary-mark-forward (- n) gnus-unread-mark))
 
 (defun gnus-summary-mark-unread-as-read ()
-  "Intended to be used by `gnus-summary-mark-article-hook'."
+  "Intended to be used by `gnus-mark-article-hook'."
   (when (memq gnus-current-article gnus-newsgroup-unreads)
     (gnus-summary-mark-article gnus-current-article gnus-read-mark)))
 
 (defun gnus-summary-mark-read-and-unread-as-read (&optional new-mark)
-  "Intended to be used by `gnus-summary-mark-article-hook'."
+  "Intended to be used by `gnus-mark-article-hook'."
   (let ((mark (gnus-summary-article-mark)))
     (when (or (gnus-unread-mark-p mark)
 	      (gnus-read-mark-p mark))
@@ -10831,7 +10843,7 @@
 				 (or new-mark gnus-read-mark)))))
 
 (defun gnus-summary-mark-current-read-and-unread-as-read (&optional new-mark)
-  "Intended to be used by `gnus-summary-mark-article-hook'."
+  "Intended to be used by `gnus-mark-article-hook'."
   (let ((mark (gnus-summary-article-mark)))
     (when (or (gnus-unread-mark-p mark)
 	      (gnus-read-mark-p mark))
@@ -10839,7 +10851,7 @@
 				 (or new-mark gnus-read-mark)))))
 
 (defun gnus-summary-mark-unread-as-ticked ()
-  "Intended to be used by `gnus-summary-mark-article-hook'."
+  "Intended to be used by `gnus-mark-article-hook'."
   (when (memq gnus-current-article gnus-newsgroup-unreads)
     (gnus-summary-mark-article gnus-current-article gnus-ticked-mark)))
 
@@ -11792,6 +11804,7 @@
       encoded)))
 
 (defvar gnus-summary-save-parts-counter)
+(declare-function mm-uu-dissect "mm-uu" (&optional noheader mime-type))
 
 (defun gnus-summary-save-parts (type dir n &optional reverse)
   "Save parts matching TYPE to DIR.
--- a/lisp/gnus/gnus-util.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-util.el	Sun Dec 16 05:08:49 2007 +0000
@@ -35,6 +35,9 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 (eval-when-compile
   (require 'cl))
 ;; Fixme: this should be a gnus variable, not nnmail-.
@@ -214,6 +217,13 @@
 		   (search-forward ":" eol t)
 		   (point)))))
 
+(declare-function gnus-find-method-for-group "gnus" (group &optional info))
+(autoload 'gnus-group-name-decode "gnus-group")
+(declare-function gnus-group-name-charset "gnus-group" (method group))
+;; gnus-group requires gnus-int which requires message.
+(declare-function message-tokenize-header "message"
+                  (header &optional separator))
+
 (defun gnus-decode-newsgroups (newsgroups group &optional method)
   (let ((method (or method (gnus-find-method-for-group group))))
     (mapconcat (lambda (group)
@@ -327,15 +337,23 @@
 
 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
 ;; the echo area.
-(defun gnus-y-or-n-p (prompt)
-  (prog1
-      (y-or-n-p prompt)
-    (message "")))
+;;
+;; Do we really need these aliases?  Workarounds for bugs in the corresponding
+;; Emacs functions?  Maybe these bug are no longer present in any supported
+;; (X)Emacs version?  Alias them to the original functions and see if anyone
+;; reports a problem.  If not, replace with original functions.  --rsteib
+;;
+;; (defun gnus-y-or-n-p (prompt)
+;;   (prog1
+;;       (y-or-n-p prompt)
+;;     (message "")))
+;; (defun gnus-yes-or-no-p (prompt)
+;;   (prog1
+;;       (yes-or-no-p prompt)
+;;     (message "")))
 
-(defun gnus-yes-or-no-p (prompt)
-  (prog1
-      (yes-or-no-p prompt)
-    (message "")))
+(defalias 'gnus-y-or-n-p 'y-or-n-p)
+(defalias 'gnus-yes-or-no-p 'yes-or-no-p)
 
 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
 ;; age-depending date representations. (e.g. just the time if it's
@@ -654,6 +672,10 @@
 
 (defvar gnus-work-buffer " *gnus work*")
 
+(declare-function gnus-get-buffer-create "gnus" (name))
+;; gnus.el requires mm-util.
+(declare-function mm-enable-multibyte "mm-util")
+
 (defun gnus-set-work-buffer ()
   "Put point in the empty Gnus work buffer."
   (if (get-buffer gnus-work-buffer)
@@ -838,6 +860,9 @@
     (setq string (replace-match "" t t string)))
   string)
 
+(declare-function gnus-put-text-property "gnus"
+                  (start end property value &optional object))
+
 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
   "The same as `put-text-property', but don't put this prop on any newlines in the region."
   (save-match-data
@@ -849,6 +874,10 @@
 	  (setq beg (point)))
 	(gnus-put-text-property beg (point) prop val)))))
 
+(declare-function gnus-overlay-put  "gnus" (overlay prop value))
+(declare-function gnus-make-overlay "gnus"
+                  (beg end &optional buffer front-advance rear-advance))
+
 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
   "The same as `put-text-property', but don't put this prop on any newlines in the region."
   (save-match-data
@@ -987,6 +1016,9 @@
 (defvar rmail-default-rmail-file)
 (defvar mm-text-coding-system)
 
+(declare-function mm-append-to-file "mm-util"
+                  (start end filename &optional codesys inhibit))
+
 (defun gnus-output-to-rmail (filename &optional ask)
   "Append the current article to an Rmail file named FILENAME."
   (require 'rmail)
@@ -1199,6 +1231,9 @@
 	(throw 'found nil)))
     t))
 
+;; gnus.el requires mm-util.
+(declare-function mm-disable-multibyte "mm-util")
+
 (defun gnus-write-active-file (file hashtb &optional full-names)
   ;; `coding-system-for-write' should be `raw-text' or equivalent.
   (let ((coding-system-for-write nnmail-active-file-coding-system))
@@ -1266,6 +1301,9 @@
 	     (pop l2))
 	   l1))))
 
+(declare-function gnus-add-text-properties "gnus"
+                  (start end properties &optional object))
+
 (defun gnus-add-text-properties-when
   (property value start end properties &optional object)
   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
@@ -1515,6 +1553,8 @@
 	(kill-buffer buf))
     tchar))
 
+(declare-function w32-focus-frame "../term/w32-win" (frame))
+
 (defun gnus-select-frame-set-input-focus (frame)
   "Select FRAME, raise it, and set input focus, if possible."
   (cond ((featurep 'xemacs)
--- a/lisp/gnus/gnus-uu.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus-uu.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1051,7 +1051,7 @@
 	(unless state
 	  (push 'middle state))
 	(mm-with-unibyte-buffer
-	  (insert-buffer gnus-original-article-buffer)
+	  (insert-buffer-substring gnus-original-article-buffer)
 	  (yenc-decode-region (point-min) (point-max))
 	  (when (and (member 'begin state)
 		     (file-exists-p gnus-uu-yenc-article-name))
--- a/lisp/gnus/gnus.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/gnus.el	Sun Dec 16 05:08:49 2007 +0000
@@ -30,6 +30,10 @@
 
 (eval '(run-hooks 'gnus-load-hook))
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 (require 'wid-edit)
 (require 'mm-util)
@@ -3736,6 +3740,8 @@
   "Return the prefix of the current group name."
   (< 0 (length (gnus-group-real-prefix group))))
 
+(declare-function gnus-group-decoded-name "gnus-group" (string))
+
 (defun gnus-summary-buffer-name (group)
   "Return the summary buffer name of GROUP."
   (concat "*Summary " (gnus-group-decoded-name group) "*"))
--- a/lisp/gnus/mail-source.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mail-source.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (require 'format-spec)
 (eval-when-compile
   (require 'cl)
@@ -997,9 +1001,14 @@
   (autoload 'imap-range-to-message-set "imap")
   (autoload 'nnheader-ms-strip-cr "nnheader"))
 
+(autoload 'gnus-compress-sequence "gnus-range")
+
 (defvar mail-source-imap-file-coding-system 'binary
   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
 
+;; Autoloads will bring in imap before this is called.
+(declare-function imap-capability "imap" (&optional identifier buffer))
+
 (defun mail-source-fetch-imap (source callback)
   "Fetcher for imap sources."
   (mail-source-bind (imap source)
--- a/lisp/gnus/message.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/message.el	Sun Dec 16 05:08:49 2007 +0000
@@ -31,9 +31,11 @@
 
 ;;; Code:
 
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 (eval-when-compile
   (require 'cl))
-  
+
 (require 'hashcash)
 (require 'canlock)
 (require 'mailheader)
@@ -2469,6 +2471,8 @@
     (kill-region start (point))))
 
 
+(autoload 'Info-goto-node "info")
+
 (defun message-info (&optional arg)
   "Display the Message manual.
 
@@ -3696,6 +3700,8 @@
 
 (defvar gnus-extract-address-components)
 
+(autoload 'format-spec "format-spec")
+
 (defun message-insert-formatted-citation-line (&optional from date)
   "Function that inserts a formatted citation line.
 
@@ -7474,6 +7480,8 @@
   :type '(choice (const nil)
 		 function))
 
+(declare-function mail-abbrev-in-expansion-header-p "mailabbrev" ())
+
 (defun message-tab ()
   "Complete names according to `message-completion-alist'.
 Execute function specified by `message-tab-body-function' when not in
--- a/lisp/gnus/mm-bodies.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mm-bodies.el	Sun Dec 16 05:08:49 2007 +0000
@@ -26,6 +26,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (require 'mm-util)
 (require 'rfc2047)
 (require 'mm-encode)
@@ -67,6 +71,9 @@
 			       (const base64))))
   :group 'mime)
 
+(autoload 'message-options-get "message")
+(declare-function message-options-set "message" (symbol value))
+
 (defun mm-encode-body (&optional charset)
   "Encode a body.
 Should be called narrowed to the body that is to be encoded.
--- a/lisp/gnus/mm-decode.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mm-decode.el	Sun Dec 16 05:08:49 2007 +0000
@@ -26,9 +26,14 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (require 'mail-parse)
 (require 'mailcap)
 (require 'mm-bodies)
+(require 'gnus-util)
 (eval-when-compile (require 'cl)
 		   (require 'term))
 
@@ -733,6 +738,8 @@
 		(mm-display-external
 		 handle 'mailcap-save-binary-file)))))))))
 
+(declare-function gnus-configure-windows "gnus-win" (setting &optional force))
+
 (defun mm-display-external (handle method)
   "Display HANDLE using METHOD."
   (let ((outbuf (current-buffer)))
@@ -990,7 +997,8 @@
 	(cond
 	 ;; Internally displayed part.
 	 ((mm-annotationp object)
-	  (delete-annotation object))
+          (if (featurep 'xemacs)
+              (delete-annotation object)))
 	 ((or (functionp object)
 	      (and (listp object)
 		   (eq (car object) 'lambda)))
@@ -1231,9 +1239,39 @@
 	   (mm-save-part-to-file handle file)
 	   file))))
 
+(defun mm-add-meta-html-tag (handle &optional charset)
+  "Add meta html tag to specify CHARSET of HANDLE in the current buffer.
+CHARSET defaults to the one HANDLE specifies.  Existing meta tag that
+specifies charset will not be modified.  Return t if meta tag is added
+or replaced."
+  (when (equal (mm-handle-media-type handle) "text/html")
+    (when (or charset
+	      (setq charset (mail-content-type-get (mm-handle-type handle)
+						   'charset)))
+      (setq charset (format "\
+<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">" charset))
+      (let ((case-fold-search t))
+	(goto-char (point-min))
+	(if (re-search-forward "\
+<meta\\s-+http-equiv=[\"']?content-type[\"']?\\s-+content=[\"']\
+text/\\(\\sw+\\)\\(?:\;\\s-*charset=\\(.+?\\)\\)?[\"'][^>]*>" nil t)
+	    (if (and (match-beginning 2)
+		     (string-match "\\`html\\'" (match-string 1)))
+		;; Don't modify existing meta tag.
+		nil
+	      ;; Replace it with the one specifying charset.
+	      (replace-match charset)
+	      t)
+	  (if (re-search-forward "<head>\\s-*" nil t)
+	      (insert charset "\n")
+	    (re-search-forward "<html\\(?:\\s-+[^>]+\\|\\s-*\\)>\\s-*" nil t)
+	    (insert "<head>\n" charset "\n</head>\n"))
+	  t)))))
+
 (defun mm-save-part-to-file (handle file)
   (mm-with-unibyte-buffer
     (mm-insert-part handle)
+    (mm-add-meta-html-tag handle)
     (let ((current-file-modes (default-file-modes)))
       (set-default-file-modes mm-attachment-file-modes)
       (unwind-protect
@@ -1250,6 +1288,7 @@
 	  (read-string "Shell command on MIME part: " mm-last-shell-command)))
     (mm-with-unibyte-buffer
       (mm-insert-part handle)
+      (mm-add-meta-html-tag handle)
       (let ((coding-system-for-write 'binary))
 	(shell-command-on-region (point-min) (point-max) command nil)))))
 
@@ -1490,6 +1529,8 @@
     (put-text-property 0 (length (car handle)) parameter value
 		       (car handle))))
 
+(autoload 'mm-view-pkcs7 "mm-view")
+
 (defun mm-possibly-verify-or-decrypt (parts ctl)
   (let ((type (car ctl))
 	(subtype (cadr (split-string (car ctl) "/")))
--- a/lisp/gnus/mm-extern.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mm-extern.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 
 (require 'mm-util)
@@ -90,6 +94,8 @@
   (let (mm-extern-anonymous)
     (mm-extern-anon-ftp handle)))
 
+(declare-function message-goto-body "message" (&optional interactivep))
+
 (defun mm-extern-mail-server (handle)
   (require 'message)
   (let* ((params (cdr (mm-handle-type handle)))
--- a/lisp/gnus/mm-util.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mm-util.el	Sun Dec 16 05:08:49 2007 +0000
@@ -26,6 +26,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 (require 'mail-prsvr)
 
@@ -913,6 +917,8 @@
   (when (featurep 'xemacs)
     `(and (featurep 'mule) (mm-xemacs-find-mime-charset-1 ,begin ,end))))
 
+(declare-function mm-delete-duplicates "mm-util" (list))
+
 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
   "Return the MIME charsets needed to encode the region between B and E.
 nil means ASCII, a single-element list represents an appropriate MIME
@@ -1145,6 +1151,8 @@
 	   inhibit-file-name-handlers)))
     (write-region start end filename append visit lockname)))
 
+(autoload 'gmm-write-region "gmm-utils")
+
 ;; It is not a MIME function, but some MIME functions use it.
 (if (and (fboundp 'make-temp-file)
 	 (ignore-errors
@@ -1236,6 +1244,8 @@
 	  (if (eq (point) end) 'ascii (mm-guess-charset))
 	(goto-char point)))))
 
+(declare-function mm-detect-coding-region "mm-util" (start end))
+
 (if (fboundp 'coding-system-get)
     (defun mm-detect-mime-charset-region (start end)
       "Detect MIME charset of the text in the region between START and END."
--- a/lisp/gnus/mm-uu.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mm-uu.el	Sun Dec 16 05:08:49 2007 +0000
@@ -427,6 +427,8 @@
 		      (list mm-dissect-disposition
 			    (cons 'filename file-name)))))
 
+(defvar gnus-original-article-buffer)   ; gnus.el
+
 (defun mm-uu-yenc-extract ()
   ;; This might not be exactly correct, but we sure can't get the
   ;; binary data from the article buffer, since that's already in a
--- a/lisp/gnus/mm-view.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mm-view.el	Sun Dec 16 05:08:49 2007 +0000
@@ -24,7 +24,8 @@
 ;;; Commentary:
 
 ;;; Code:
-
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 (eval-when-compile (require 'cl))
 (require 'mail-parse)
 (require 'mailcap)
@@ -117,6 +118,11 @@
       (defalias 'mm-inline-image 'mm-inline-image-xemacs)
     (defalias 'mm-inline-image 'mm-inline-image-emacs)))
 
+;; External.
+(declare-function w3-do-setup       "ext:w3"         ())
+(declare-function w3-region         "ext:w3-display" (st nd))
+(declare-function w3-prepare-buffer "ext:w3-display" (&rest args))
+
 (defvar mm-w3-setup nil)
 (defun mm-setup-w3 ()
   (unless mm-w3-setup
@@ -201,6 +207,10 @@
 (defvar mm-w3m-setup nil
   "Whether gnus-article-mode has been setup to use emacs-w3m.")
 
+;; External.
+(declare-function w3m-detect-meta-charset "ext:w3m" ())
+(declare-function w3m-region "ext:w3m" (start end &optional url charset))
+
 (defun mm-setup-w3m ()
   "Setup gnus-article-mode to use emacs-w3m."
   (unless mm-w3m-setup
--- a/lisp/gnus/mml-smime.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mml-smime.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 
 (require 'smime)
@@ -216,6 +220,8 @@
       (quit))
     result))
 
+(autoload 'gnus-completing-read-with-default "gnus-util")
+
 (defun mml-smime-openssl-encrypt-query ()
   ;; todo: try dns/ldap automatically first, before prompting user
   (let (certs done)
@@ -346,6 +352,10 @@
 	      (cons key-id mml-smime-epg-secret-key-id-list))
 	(copy-sequence passphrase)))))
 
+(declare-function epg-key-sub-key-list   "ext:epg" (key))
+(declare-function epg-sub-key-capability "ext:epg" (sub-key))
+(declare-function epg-sub-key-validity   "ext:epg" (sub-key))
+
 (defun mml-smime-epg-find-usable-key (keys usage)
   (catch 'found
     (while keys
@@ -358,6 +368,12 @@
 	  (setq pointer (cdr pointer))))
       (setq keys (cdr keys)))))
 
+(autoload 'mml-compute-boundary "mml")
+
+;; We require mm-decode, which requires mm-bodies, which autoloads
+;; message-options-get (!).
+(declare-function message-options-set "message" (symbol value))
+
 (defun mml-smime-epg-sign (cont)
   (let* ((inhibit-redisplay t)
 	 (context (epg-make-context 'CMS))
--- a/lisp/gnus/mml.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mml.el	Sun Dec 16 05:08:49 2007 +0000
@@ -25,6 +25,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (require 'mm-util)
 (require 'mm-bodies)
 (require 'mm-encode)
@@ -1315,6 +1319,12 @@
 
 (defvar mml-preview-buffer nil)
 
+(autoload 'gnus-make-hashtable "gnus-util")
+(autoload 'widget-button-press "wid-edit" nil t)
+(declare-function widget-event-point "wid-edit" (event))
+;; If gnus-buffer-configuration is bound this is loaded.
+(declare-function gnus-configure-windows "gnus-win" (setting &optional force))
+
 (defun mml-preview (&optional raw)
   "Display current buffer with Gnus, in a new buffer.
 If RAW, display a raw encoded MIME message.
--- a/lisp/gnus/mml1991.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mml1991.el	Sun Dec 16 05:08:49 2007 +0000
@@ -28,6 +28,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile
   (require 'cl)
   (require 'mm-util))
@@ -39,6 +43,11 @@
 (autoload 'quoted-printable-decode-region "qp")
 (autoload 'quoted-printable-encode-region "qp")
 
+(autoload 'mm-decode-content-transfer-encoding "mm-bodies")
+(autoload 'mm-encode-content-transfer-encoding "mm-bodies")
+(autoload 'message-options-get "message")
+(autoload 'message-options-set "message")
+
 (defvar mml1991-use mml2015-use
   "The package used for PGP.")
 
@@ -111,6 +120,9 @@
       (insert-buffer-substring signature)
       (goto-char (point-max)))))
 
+(declare-function mc-encrypt-generic "ext:mc-toplev"
+                  (&optional recipients scheme start end from sign))
+
 (defun mml1991-mailcrypt-encrypt (cont &optional sign)
   (let ((text (current-buffer))
 	(mc-pgp-always-sign
@@ -161,6 +173,13 @@
 (eval-and-compile
   (autoload 'gpg-sign-cleartext "gpg"))
 
+(declare-function gpg-sign-encrypt "ext:gpg"
+                  (plaintext ciphertext result recipients &optional
+                             passphrase sign-with-key armor textmode))
+(declare-function gpg-encrypt "ext:gpg"
+                  (plaintext ciphertext result recipients &optional
+                             passphrase armor textmode))
+
 (defun mml1991-gpg-sign (cont)
   (let ((text (current-buffer))
 	headers signature
--- a/lisp/gnus/mml2015.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/mml2015.el	Sun Dec 16 05:08:49 2007 +0000
@@ -30,6 +30,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 (require 'mm-decode)
 (require 'mm-util)
@@ -38,6 +42,10 @@
 
 (defvar mc-pgp-always-sign)
 
+(declare-function epg-check-configuration "ext:epg-config"
+                  (config &optional minimum-version))
+(declare-function epg-configuration "ext:epg-config" ())
+
 (defvar mml2015-use (or
 		     (condition-case nil
 			 (progn
@@ -396,6 +404,10 @@
     (insert (format "--%s--\n" boundary))
     (goto-char (point-max))))
 
+;; We require mm-decode, which requires mm-bodies, which autoloads
+;; message-options-get (!).
+(declare-function message-options-set "message" (symbol value))
+
 (defun mml2015-mailcrypt-encrypt (cont &optional sign)
   (let ((mc-pgp-always-sign
 	 (or mc-pgp-always-sign
@@ -1329,6 +1341,9 @@
 
 ;;; General wrapper
 
+(autoload 'gnus-buffer-live-p "gnus-util")
+(autoload 'gnus-get-buffer-create "gnus")
+
 (defun mml2015-clean-buffer ()
   (if (gnus-buffer-live-p mml2015-result-buffer)
       (with-current-buffer mml2015-result-buffer
--- a/lisp/gnus/nndb.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/nndb.el	Sun Dec 16 05:08:49 2007 +0000
@@ -48,6 +48,12 @@
 ;; * make the backend TOUCH an article when marked as expireable (will
 ;;   make article expire 'expiry' days after that moment).
 
+;;; Code:
+
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 ;;-
 ;; Register nndb with known select methods.
 
@@ -55,8 +61,6 @@
 (unless (assoc "nndb" gnus-valid-select-methods)
   (gnus-declare-backend "nndb" 'mail 'respool 'address 'prompt-address))
 
-;;; Code:
-
 (require 'nnmail)
 (require 'nnheader)
 (require 'nntp)
@@ -240,6 +244,9 @@
       (nndb-request-expire-articles-remote articles group server force)
     (nndb-request-expire-articles-local articles group server force)))
 
+;; _Something_ defines it...
+(declare-function nndb-request-article "nndb" t t)
+
 (deffoo nndb-request-move-article
     (article group server accept-form &optional last move-is-internal)
   "Move ARTICLE (a number) from GROUP on SERVER.
--- a/lisp/gnus/nnfolder.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/nnfolder.el	Sun Dec 16 05:08:49 2007 +0000
@@ -31,6 +31,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (require 'nnheader)
 (require 'message)
 (require 'nnmail)
@@ -429,6 +433,10 @@
       ;; The article numbers are increasing, so this result is sorted.
 	(nreverse numbers)))))
 
+(autoload 'gnus-request-group "gnus-int")
+(declare-function gnus-request-create-group "gnus-int"
+                  (group &optional gnus-command-method args))
+
 (deffoo nnfolder-request-expire-articles (articles newsgroup
 						   &optional server force)
   (nnfolder-possibly-change-group newsgroup server)
--- a/lisp/gnus/nnheader.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/nnheader.el	Sun Dec 16 05:08:49 2007 +0000
@@ -251,6 +251,8 @@
   (skip-chars-forward " \t")
   (buffer-substring (point) (point-at-eol)))
 
+(autoload 'ietf-drums-unfold-fws "ietf-drums")
+
 (defun nnheader-parse-naked-head (&optional number)
   ;; This function unfolds continuation lines in this buffer
   ;; destructively.  When this side effect is unwanted, use
--- a/lisp/gnus/nnmail.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/nnmail.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 
 (require 'gnus)				; for macro gnus-kill-buffer, at least
@@ -35,6 +39,7 @@
 (require 'gnus-util)
 (require 'mail-source)
 (require 'mm-util)
+(require 'gnus-int)
 
 (eval-and-compile
   (autoload 'gnus-add-buffer "gnus")
@@ -1315,6 +1320,9 @@
 
 ;;; Utility functions
 
+(declare-function gnus-activate-group "gnus-start"
+                  (group &optional scan dont-check method))
+
 (defun nnmail-do-request-post (accept-func &optional server)
   "Utility function to directly post a message to an nnmail-derived group.
 Calls ACCEPT-FUNC (which should be `nnchoke-request-accept-article')
@@ -1854,6 +1862,8 @@
 	     ;; Compare the time with the current time.
 	     (ignore-errors (time-less-p days (time-since time))))))))
 
+(declare-function gnus-group-mark-article-read "gnus-group" (group article))
+
 (defun nnmail-expiry-target-group (target group)
   ;; Do not invoke this from nntp-server-buffer!  At least nnfolder clears
   ;; that buffer if the nnfolder group isn't selected.
--- a/lisp/gnus/nnmaildir.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/nnmaildir.el	Sun Dec 16 05:08:49 2007 +0000
@@ -61,6 +61,10 @@
    )
 ]
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-and-compile
   (require 'nnheader)
   (require 'gnus)
@@ -884,7 +888,9 @@
 			pgname (nnmaildir--pgname nnmaildir--cur-server pgname)
 			group (symbol-value group)
 			ro (nnmaildir--param pgname 'read-only))
-		  (insert (nnmaildir--grp-name group) " ")
+		  (insert (gnus-replace-in-string
+			   (nnmaildir--grp-name group) " " "\\ " t)
+			  " ")
                   (princ (nnmaildir--group-maxnum nnmaildir--cur-server group)
 			 nntp-server-buffer)
 		  (insert " ")
@@ -911,14 +917,17 @@
 	  (insert " ")
 	  (princ (nnmaildir--group-maxnum nnmaildir--cur-server group)
 		 nntp-server-buffer)
-	  (insert " " gname "\n")))))
+	  (insert " "
+		  (gnus-replace-in-string gname " " "\\ " t)
+		  "\n")))))
   'group)
 
 (defun nnmaildir-request-update-info (gname info &optional server)
   (let ((group (nnmaildir--prepare server gname))
 	pgname flist always-marks never-marks old-marks dotfile num dir
 	markdirs marks mark ranges markdir article read end new-marks ls
-	old-mmth new-mmth mtime mark-sym existing missing deactivate-mark)
+	old-mmth new-mmth mtime mark-sym existing missing deactivate-mark
+	article-list)
     (catch 'return
       (unless group
 	(setf (nnmaildir--srv-error nnmaildir--cur-server)
@@ -966,12 +975,13 @@
 	    (setq ranges (assq mark-sym old-marks))
 	    (if ranges (setq ranges (cdr ranges)))
 	    (throw 'got-ranges nil))
+	  (setq article-list nil)
 	  (dolist (prefix (funcall ls markdir nil "\\`[^.]" 'nosort))
 	    (setq article (nnmaildir--flist-art flist prefix))
 	    (if article
-		(setq ranges
-		      (gnus-add-to-range ranges
-					 `(,(nnmaildir--art-num article)))))))
+		(setq article-list
+		      (cons (nnmaildir--art-num article) article-list))))
+	  (setq ranges (gnus-add-to-range ranges (sort article-list '<))))
 	(if (eq mark-sym 'read) (setq read ranges)
 	  (if ranges (setq marks (cons (cons mark-sym ranges) marks)))))
       (gnus-info-set-read info (gnus-range-add read missing))
@@ -999,7 +1009,7 @@
 	(insert " ")
 	(princ (nnmaildir--group-maxnum nnmaildir--cur-server group)
 	       nntp-server-buffer)
-	(insert " " gname "\n")
+	(insert " " (gnus-replace-in-string gname " " "\\ " t) "\n")
 	t))))
 
 (defun nnmaildir-request-create-group (gname &optional server args)
@@ -1161,7 +1171,7 @@
 	      (insert "\t" (nnmaildir--nov-get-beg nov) "\t"
 		      (nnmaildir--art-msgid article) "\t"
 		      (nnmaildir--nov-get-mid nov) "\tXref: nnmaildir "
-		      gname ":")
+		      (gnus-replace-in-string gname " " "\\ " t) ":")
 	      (princ num nntp-server-buffer)
 	      (insert "\t" (nnmaildir--nov-get-end nov) "\n"))))
     (catch 'return
@@ -1433,6 +1443,8 @@
 (defun nnmaildir-active-number (gname)
   0)
 
+(declare-function gnus-group-mark-article-read "gnus-group" (group article))
+
 (defun nnmaildir-request-expire-articles (ranges &optional gname server force)
   (let ((no-force (not force))
 	(group (nnmaildir--prepare server gname))
--- a/lisp/gnus/nnrss.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/nnrss.el	Sun Dec 16 05:08:49 2007 +0000
@@ -27,6 +27,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 
 (require 'gnus)
@@ -418,6 +422,8 @@
 					 nnrss-compatible-encoding-alist)))))
     (mm-coding-system-p 'utf-8)))
 
+(declare-function w3-parse-buffer "ext:w3-parse" (&optional buff))
+
 (defun nnrss-fetch (url &optional local)
   "Fetch URL and put it in a the expected Lisp structure."
   (mm-with-unibyte-buffer
@@ -784,6 +790,8 @@
 	  (push (list group nnrss-group-max) nnrss-server-data)))
       (nnrss-save-server-data server))))
 
+(declare-function gnus-group-make-rss-group "gnus-group" (&optional url))
+
 (defun nnrss-opml-import (opml-file)
   "OPML subscriptions import.
 Read the file and attempt to subscribe to each Feed in the file."
--- a/lisp/gnus/pop3.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/pop3.el	Sun Dec 16 05:08:49 2007 +0000
@@ -314,7 +314,7 @@
       (setq match-end (point))
       (goto-char pop3-read-point)
       (if (looking-at "-ERR")
-	  (error (buffer-substring (point) (- match-end 2)))
+	  (error "%s" (buffer-substring (point) (- match-end 2)))
 	(if (not (looking-at "+OK"))
 	    (progn (setq pop3-read-point match-end) nil)
 	  (setq pop3-read-point match-end)
--- a/lisp/gnus/rfc1843.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/rfc1843.el	Sun Dec 16 05:08:49 2007 +0000
@@ -34,6 +34,10 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
 (require 'mm-util)
 
@@ -139,6 +143,10 @@
 	  (aset s (incf i) (+ v (if (< v 63) 64 98))))))
     s))
 
+(autoload 'mail-header-parse-content-type "mail-parse")
+(autoload 'message-narrow-to-head "message")
+(declare-function message-fetch-field "message" (header &optional not-all))
+
 (defun rfc1843-decode-article-body ()
   "Decode HZ encoded text in the article body."
   (if (string-match (concat "\\<\\(" rfc1843-newsgroups-regexp "\\)\\>")
--- a/lisp/gnus/sieve-manage.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/sieve-manage.el	Sun Dec 16 05:08:49 2007 +0000
@@ -76,6 +76,9 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 (or (require 'password-cache nil t)
     (require 'password))
 (eval-when-compile
@@ -193,6 +196,10 @@
   (when (fboundp 'set-buffer-multibyte)
     (set-buffer-multibyte nil)))
 
+(declare-function password-read         "password-cache" (prompt &optional key))
+(declare-function password-cache-add    "password-cache" (key password))
+(declare-function password-cache-remove "password-cache" (key))
+
 ;; Uses the dynamically bound `reason' variable.
 (defvar reason)
 (defun sieve-manage-interactive-login (buffer loginfunc)
--- a/lisp/gnus/smime.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/smime.el	Sun Dec 16 05:08:49 2007 +0000
@@ -121,6 +121,9 @@
 
 ;;; Code:
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 (require 'dig)
 (or (require 'password-cache nil t)
     (require 'password))
@@ -257,6 +260,7 @@
 	   temporary-file-directory))))))
 
 ;; Password dialog function
+(declare-function password-read-and-add "password-cache" (prompt &optional key))
 
 (defun smime-ask-passphrase (&optional cache-key)
   "Asks the passphrase to unlock the secret key.
@@ -654,6 +658,8 @@
   (define-key smime-mode-map "q" 'smime-exit)
   (define-key smime-mode-map "f" 'smime-certificate-info))
 
+(autoload 'gnus-run-mode-hooks "gnus-util")
+
 (defun smime-mode ()
   "Major mode for browsing, viewing and fetching certificates.
 
--- a/lisp/gnus/spam-stat.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/spam-stat.el	Sun Dec 16 05:08:49 2007 +0000
@@ -377,6 +377,8 @@
    (spam-stat-buffer-words))
   (setq spam-stat-dirty t))
 
+(autoload 'gnus-message "gnus-util")
+
 (defun spam-stat-buffer-change-to-spam ()
   "Consider current buffer no longer normal mail but spam."
   (setq spam-stat-nbad (1+ spam-stat-nbad)
--- a/lisp/gnus/spam.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/gnus/spam.el	Sun Dec 16 05:08:49 2007 +0000
@@ -40,16 +40,20 @@
 
 ;;{{{ compilation directives and autoloads/requires
 
+;; For Emacs < 22.2.
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (eval-when-compile (require 'cl))
-(eval-when-compile (require 'spam-report))
-(eval-when-compile (require 'hashcash))
-
+
+(require 'message)		;for the message-fetch-field functions
 (require 'gnus-sum)
-
 (require 'gnus-uu)			; because of key prefix issues
 ;;; for the definitions of group content classification and spam processors
 (require 'gnus)
-(require 'message)		;for the message-fetch-field functions
+
+(eval-when-compile (require 'spam-report))
+(eval-when-compile (require 'hashcash))
 
 ;; for nnimap-split-download-body-default
 (eval-when-compile (require 'nnimap))
@@ -2066,6 +2070,9 @@
   (autoload 'bbdb-create-internal "bbdb")
   (autoload 'bbdb-search-simple "bbdb"))
 
+;; Autoloaded in message, which we require.
+(declare-function gnus-extract-address-components "gnus-util" (from))
+
 (eval-and-compile
   (when (condition-case nil
 	    (progn
--- a/lisp/help-fns.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/help-fns.el	Sun Dec 16 05:08:49 2007 +0000
@@ -252,7 +252,8 @@
 
 ;;;###autoload
 (defun describe-function-1 (function)
-  (let* ((advised (and (featurep 'advice) (ad-get-advice-info function)))
+  (let* ((advised (and (symbolp function) (featurep 'advice)
+		       (ad-get-advice-info function)))
 	 ;; If the function is advised, use the symbol that has the
 	 ;; real definition, if that symbol is already set up.
 	 (real-function
--- a/lisp/ibuffer.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/ibuffer.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1392,7 +1392,7 @@
     (when must-be-live
       (if (bufferp buf)
 	  (unless (buffer-live-p buf)
-	    (error (substitute-command-keys "Buffer %s has been killed; use `\\[ibuffer-update]' to update") buf))
+	    (error "Buffer %s has been killed; %s" buf (substitute-command-keys "use `\\[ibuffer-update]' to update")))
 	(error "No buffer on this line")))
     buf))
 
--- a/lisp/indent.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/indent.el	Sun Dec 16 05:08:49 2007 +0000
@@ -454,6 +454,7 @@
 This should be a list of integers, ordered from smallest to largest."
   :group 'indent
   :type '(repeat integer))
+(put 'tab-stop-list 'safe-local-variable 'listp)
 
 (defvar edit-tab-stops-map
   (let ((map (make-sparse-keymap)))
--- a/lisp/international/ja-dic-cnv.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/international/ja-dic-cnv.el	Sun Dec 16 05:08:49 2007 +0000
@@ -559,7 +559,7 @@
 	 (while l
 	   (setq count (1+ count))
 	   (if (= (% count 10000) 0)
-	       (message (format "%d entries" count)))
+	       (message "%d entries" count))
 	   (setq entry (skkdic-extract-conversion-data (car l)))
 	   (set-nested-alist (car entry) (cdr entry) map)
 	   (setq l (cdr l)))
--- a/lisp/international/latexenc.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/international/latexenc.el	Sun Dec 16 05:08:49 2007 +0000
@@ -181,7 +181,8 @@
                         (find-file-noselect latexenc-main-file t)))
                   (coding-system-base   ;Disregard the EOL part of the CS.
                    (with-current-buffer latexenc-main-buffer
-                     (or coding-system-for-write buffer-file-coding-system))))
+                     (or coding-system-for-write buffer-file-coding-system
+			 'undecided))))
               'undecided))))
     'undecided))
 
--- a/lisp/isearch.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/isearch.el	Sun Dec 16 05:08:49 2007 +0000
@@ -96,7 +96,8 @@
 That is, upper and lower case chars must match exactly.
 This applies no matter where the chars come from, but does not
 apply to chars in regexps that are prefixed with `\\'.
-If this value is `not-yanks', yanked text is always downcased."
+If this value is `not-yanks', text yanked into the search string
+in Isearch mode is always downcased."
   :type '(choice (const :tag "off" nil)
 		 (const not-yanks)
 		 (other :tag "on" t))
@@ -407,6 +408,7 @@
 
     (define-key map [?\M-%] 'isearch-query-replace)
     (define-key map [?\C-\M-%] 'isearch-query-replace-regexp)
+    (define-key map "\M-so" 'isearch-occur)
 
     map)
   "Keymap for `isearch-mode'.")
@@ -1226,11 +1228,14 @@
   (isearch-update))
 
 (defun isearch-query-replace (&optional regexp-flag)
-  "Start query-replace with string to replace from last search string."
+  "Start `query-replace' with string to replace from last search string."
   (interactive)
   (barf-if-buffer-read-only)
   (if regexp-flag (setq isearch-regexp t))
-  (let ((case-fold-search isearch-case-fold-search))
+  (let ((case-fold-search isearch-case-fold-search)
+	;; set `search-upper-case' to nil to not call
+	;; `isearch-no-upper-case-p' in `perform-replace'
+	(search-upper-case nil))
     (isearch-done)
     (isearch-clean-overlays)
     (if (and isearch-other-end
@@ -1252,10 +1257,24 @@
      (if (and transient-mark-mode mark-active) (region-end)))))
 
 (defun isearch-query-replace-regexp ()
-  "Start query-replace-regexp with string to replace from last search string."
+  "Start `query-replace-regexp' with string to replace from last search string."
   (interactive)
   (isearch-query-replace t))
 
+(defun isearch-occur (regexp &optional nlines)
+  "Run `occur' with regexp to search from the current search string.
+Interactively, REGEXP is the current search regexp or a quoted search
+string.  NLINES has the same meaning as in `occur'."
+  (interactive
+   (list
+    (if isearch-regexp isearch-string (regexp-quote isearch-string))
+    (if current-prefix-arg (prefix-numeric-value current-prefix-arg))))
+  (let ((case-fold-search isearch-case-fold-search)
+	;; set `search-upper-case' to nil to not call
+	;; `isearch-no-upper-case-p' in `occur-1'
+	(search-upper-case nil))
+    (occur regexp nlines)))
+
 
 (defun isearch-delete-char ()
   "Discard last input item and move point back.
--- a/lisp/kmacro.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/kmacro.el	Sun Dec 16 05:08:49 2007 +0000
@@ -404,7 +404,7 @@
 		   (format " [%s]"
 			   (format kmacro-counter-format-start kmacro-counter)))
 		 (if z (substring m 0 (1- x)) m) (if z "..." "")))
-    (message (or empty "No keyboard macros defined"))))
+    (message "%s" (or empty "No keyboard macros defined"))))
 
 
 (defun kmacro-repeat-on-last-key (keys)
--- a/lisp/mail/feedmail.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/mail/feedmail.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1922,7 +1922,7 @@
       ;; progn to get nil result no matter what
       (progn (make-directory queue-directory t) nil)
       (file-accessible-directory-p queue-directory)
-      (error (concat "FQM: Message not queued; trouble with directory " queue-directory)))
+      (error "FQM: Message not queued; trouble with directory %s" queue-directory))
   (let ((filename)
 	(is-fqm)
 	(is-in-this-dir)
--- a/lisp/mail/hashcash.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/mail/hashcash.el	Sun Dec 16 05:08:49 2007 +0000
@@ -49,6 +49,9 @@
 
 ;;; Code:
 
+(eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
+
 (defgroup hashcash nil
   "Hashcash configuration."
   :group 'mail)
@@ -112,13 +115,15 @@
 (require 'mail-utils)
 
 (eval-and-compile
- (if (fboundp 'point-at-bol)
-     (defalias 'hashcash-point-at-bol 'point-at-bol)
-   (defalias 'hashcash-point-at-bol 'line-beginning-position))
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
 
- (if (fboundp 'point-at-eol)
-     (defalias 'hashcash-point-at-eol 'point-at-eol)
-   (defalias 'hashcash-point-at-eol 'line-end-position)))
+  (if (fboundp 'point-at-bol)
+      (defalias 'hashcash-point-at-bol 'point-at-bol)
+    (defalias 'hashcash-point-at-bol 'line-beginning-position))
+
+  (if (fboundp 'point-at-eol)
+      (defalias 'hashcash-point-at-eol 'point-at-eol)
+    (defalias 'hashcash-point-at-eol 'line-end-position)))
 
 (defun hashcash-strip-quoted-names (addr)
   (setq addr (mail-strip-quoted-names addr))
--- a/lisp/mail/reporter.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/mail/reporter.el	Sun Dec 16 05:08:49 2007 +0000
@@ -118,7 +118,7 @@
   "Periodically output a status message."
   (if (zerop (% reporter-status-count 10))
       (progn
-	(message reporter-status-message)
+	(message "%s" reporter-status-message)
 	(setq reporter-status-message (concat reporter-status-message "."))))
   (setq reporter-status-count (1+ reporter-status-count)))
 
--- a/lisp/mail/rmailout.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/mail/rmailout.el	Sun Dec 16 05:08:49 2007 +0000
@@ -380,7 +380,7 @@
 		  (rmail-toggle-header))
 	      (if (and (> count 0) (not next-message-p))
 		  (progn
-		    (error
+		    (error "%s"
 		     (save-excursion
 		       (set-buffer rmailbuf)
 		       (format "Only %d message%s appended" num-appended
--- a/lisp/mail/uce.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/mail/uce.el	Sun Dec 16 05:08:49 2007 +0000
@@ -239,7 +239,7 @@
 	(full-header-p (and (eq uce-mail-reader 'rmail)
 			    (not (rmail-msg-is-pruned)))))
     (or (get-buffer message-buffer)
-	(error (concat "No buffer " message-buffer ", cannot find UCE")))
+	(error "No buffer %s, cannot find UCE" message-buffer))
     (switch-to-buffer message-buffer)
     ;; We need the message with headers pruned.
     (if full-header-p
--- a/lisp/makefile.w32-in	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/makefile.w32-in	Sun Dec 16 05:08:49 2007 +0000
@@ -40,6 +40,12 @@
 
 EMACSOPT = -batch --no-init-file --no-site-file --multibyte
 
+# Extra flags to pass to the byte compiler
+BYTE_COMPILE_EXTRA_FLAGS =
+# For example to not display the undefined function warnings you can use this:
+# BYTE_COMPILE_EXTRA_FLAGS = --eval '(setq byte-compile-warnings (quote (not unresolved)))'
+# The example above is just for developers, it should not be used by default.
+
 # Set EMACSLOADPATH correctly (already defined in environment).
 EMACSLOADPATH=$(lisp)
 
@@ -201,7 +207,7 @@
 .SUFFIXES: .elc .el
 
 .el.elc:
-	-$(emacs) -f batch-byte-compile $<
+	-$(emacs) $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile $<
 
 # Compile all Lisp files, but don't recompile those that are up to
 # date.  Some files don't actually get compiled because they set the
@@ -221,22 +227,22 @@
 compile-CMD:
 #	-for %%f in ($(lisp) $(WINS)) do for %%g in (%%f\*.elc) do @attrib -r %%g
 	for %%f in ($(COMPILE_FIRST)) do \
-	  $(emacs) -l loaddefs -f batch-byte-compile-if-not-done %%f
+	  $(emacs) -l loaddefs $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile-if-not-done %%f
 	for %%f in (. $(WINS)) do for %%g in (%%f/*.el) do \
-	  $(emacs) -l loaddefs -f batch-byte-compile-if-not-done %%f/%%g
+	  $(emacs) -l loaddefs $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile-if-not-done %%f/%%g
 
 compile-SH:
 #	for elc in $(lisp)/*.elc $(lisp)/*/*.elc; do attrib -r $$elc; done
 	for el in $(COMPILE_FIRST); do \
 	  echo Compiling $$el; \
-	  $(emacs) -l loaddefs -f batch-byte-compile-if-not-done $$el; \
+	  $(emacs) -l loaddefs $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile-if-not-done $$el; \
 	done
 	for dir in $(lisp) $(WINS); do \
 	  for el in $$dir/*.el; do \
 	    if test -f $$el; \
 	    then \
 	      echo Compiling $$el; \
-	      $(emacs) -l loaddefs -f batch-byte-compile-if-not-done $$el; \
+	      $(emacs) -l loaddefs $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile-if-not-done $$el; \
 	    fi \
 	  done; \
 	done
@@ -249,31 +255,31 @@
 
 compile-always-CMD:
 #	-for %%f in ($(lisp) $(WINS)) do for %%g in (%%f\*.elc) do @attrib -r %%g
-	for %%f in ($(COMPILE_FIRST)) do $(emacs) -f batch-byte-compile %%f
-	for %%f in (. $(WINS)) do for %%g in (%%f/*.el) do $(emacs) -f batch-byte-compile %%f/%%g
+	for %%f in ($(COMPILE_FIRST)) do $(emacs) $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile %%f
+	for %%f in (. $(WINS)) do for %%g in (%%f/*.el) do $(emacs) $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile %%f/%%g
 
 compile-always-SH:
 #	for elc in $(lisp)/*.elc $(lisp)/*/*.elc; do attrib -r $$elc; done
 	for el in $(COMPILE_FIRST); do \
 	  echo Compiling $$el; \
-	  $(emacs) -f batch-byte-compile $$el || exit 1; \
+	  $(emacs) $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile $$el || exit 1; \
 	done
 	for dir in $(lisp) $(WINS); do \
 	  for el in $$dir/*.el; do \
 	    echo Compiling $$el; \
-	    $(emacs) -f batch-byte-compile $$el || exit 1; \
+	    $(emacs) $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile $$el || exit 1; \
 	  done; \
 	done
 
 compile-calc: compile-calc-$(SHELLTYPE)
 
 compile-calc-CMD:
-	for %%f in ($(lisp)/calc/*.el) do $(emacs) -f batch-byte-compile %%f
+	for %%f in ($(lisp)/calc/*.el) do $(emacs) $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile %%f
 
 compile-calc-SH:
 	for el in $(lisp)/calc/*.el; do \
 	  echo Compiling $$el; \
-	  $(emacs) -f batch-byte-compile $$el || exit 1; \
+	  $(emacs) $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile $$el || exit 1; \
 	done
 
 # Backup compiled Lisp files in elc.tar.gz.  If that file already
@@ -295,6 +301,15 @@
 recompile: mh-autoloads doit $(lisp)/progmodes/cc-mode.elc
 	$(emacs) --eval $(ARGQUOTE)(batch-byte-recompile-directory 0)$(ARGQUOTE) $(lisp)
 
+# CC Mode uses a compile time macro system which causes a compile time
+# dependency in cc-mode.elc on the macros in cc-langs.el and the
+# version string in cc-defs.el.
+$(lisp)/progmodes/cc-mode.elc: \
+	$(lisp)/progmodes/cc-mode.el \
+	$(lisp)/progmodes/cc-langs.el \
+	$(lisp)/progmodes/cc-defs.el
+	$(emacs) $(BYTE_COMPILE_EXTRA_FLAGS) -f batch-byte-compile $(lisp)/progmodes/cc-mode.el
+
 # Update MH-E internal autoloads. These are not to be confused with
 # the autoloads for the MH-E entry points, which are already in
 # loaddefs.el.
@@ -443,6 +458,11 @@
 	for %%f in ($(WINS)) do cp -f %%f/*.el "$(INSTALL_DIR)/lisp/%%f"
 	for %%f in (. $(WINS)) do cp -f %%f/*.elc "$(INSTALL_DIR)/lisp/%%f"
 
+# WARNING: Do NOT split the part inside $(ARGQUOTE)s into multiple lines as
+#          this can break with GNU Make 3.81 and later if sh.exe is used.
+check-declare:
+	$(emacs) -l $(lisp)/emacs-lisp/check-declare --eval $(ARGQUOTE)(check-declare-directory $(DQUOTE)$(lisp)$(DQUOTE))$(ARGQUOTE)
+
 #
 # Maintenance
 #
--- a/lisp/man.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/man.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1077,7 +1077,7 @@
 	    (Man-notify-when-ready Man-buffer))
 
 	(if err-mess
-	    (error err-mess))
+	    (error "%s" err-mess))
 	))))
 
 
@@ -1338,7 +1338,7 @@
 Actually the section moved to is described by `Man-see-also-regexp'."
   (interactive)
   (if (not (Man-find-section Man-see-also-regexp))
-      (error (concat "No " Man-see-also-regexp
+      (error "%s" (concat "No " Man-see-also-regexp
 		     " section found in the current manpage"))))
 
 (defun Man-possibly-hyphenated-word ()
--- a/lisp/mouse.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/mouse.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1933,7 +1933,7 @@
 		  (cons
 		   (cons
 		    (format
-		     (format "%%%ds  %%s%%s  %%s" maxlen)
+		     (format "%%-%ds  %%s%%s  %%s" maxlen)
 		     (buffer-name elt)
 		     (if (buffer-modified-p elt) "*" " ")
 		     (save-excursion
--- a/lisp/net/dbus.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/net/dbus.el	Sun Dec 16 05:08:49 2007 +0000
@@ -49,32 +49,63 @@
 
 ;;; Hash table of registered functions.
 
-(defun dbus-hash-table= (x y)
-  "Compares keys X and Y in the hash table of registered functions for D-Bus.
-See `dbus-registered-functions-table' for a description of the hash table."
-  (and
-   (listp x) (listp y)
-   ;; Bus symbol, either :system or :session.
-   (symbolp (car x)) (symbolp (car y)) (equal (car x) (car y))
-   ;; Interface.
-   (or
-    (null (cadr x)) (null (cadr y)) ; wildcard
-    (and
-     (stringp (cadr x)) (stringp (cadr y)) (string-equal (cadr x) (cadr y))))
-   ;; Member.
-   (or
-    (null (caddr x)) (null (caddr y)) ; wildcard
-    (and
-     (stringp (caddr x)) (stringp (caddr y))
-     (string-equal (caddr x) (caddr y))))))
+;; We create it here.  So we have a simple test in dbusbind.c, whether
+;; the Lisp code has been loaded.
+(setq dbus-registered-functions-table (make-hash-table :test 'equal))
+
+(defun dbus-list-hash-table ()
+  "Returns all registered signal registrations to D-Bus.
+The return value is a list, with elements of kind (KEY . VALUE).
+See `dbus-registered-functions-table' for a description of the
+hash table."
+  (let (result)
+    (maphash
+     '(lambda (key value) (add-to-list 'result (cons key value) 'append))
+     dbus-registered-functions-table)
+    result))
 
-(define-hash-table-test 'dbus-hash-table-test 'dbus-hash-table= 'sxhash)
+(defun dbus-name-owner-changed-handler (service old-owner new-owner)
+  "Reapplies all signal registrations to D-Bus.
+This handler is applied when a \"NameOwnerChanged\" signal has
+arrived.  SERVICE is the object name for which the name owner has
+been changed.  OLD-OWNER is the previous owner of SERVICE, or the
+empty string if SERVICE was not owned yet.  NEW-OWNER is the new
+owner of SERVICE, or the empty string if SERVICE looses any name owner."
+  (save-match-data
+    ;; Check whether SERVICE is a known name.
+    (when (and (stringp service) (not (string-match "^:" service))
+	       (stringp old-owner) (stringp new-owner))
+      (maphash
+       '(lambda (key value)
+	  (dolist (elt value)
+	    ;; key has the structure (BUS INTERFACE SIGNAL).
+	    ;; elt has the structure (SERVICE UNAME PATH HANDLER).
+	    (when (string-equal old-owner (cadr elt))
+	      ;; Remove old key, and add new entry with changed name.
+	      (when dbus-debug (message "Remove rule for %s %s" key elt))
+	      ;(dbus-unregister-signal key)
+	      (setcar (cdr elt) new-owner)
+	      (when dbus-debug (message "Add rule for %s %s" key elt))
+	      ;; Maybe we could arrange the lists a little bit better
+	      ;; that we don't need to extract every single element?
+	      (when (not (zerop (length new-owner)))
+		(dbus-register-signal
+		 ;; BUS      SERVICE     PATH
+		 (nth 0 key) (nth 0 elt) (nth 2 elt)
+		 ;; INTERFACE SIGNAL     HANDLER
+		 (nth 1 key) (nth 2 key) (nth 3 elt))))))
+       (copy-hash-table dbus-registered-functions-table)))))
 
-;; When we assume that interface and and member are always strings in
-;; the key, we could use `equal' as test function.  But we want to
-;; have also `nil' there, being a wildcard.
-(setq dbus-registered-functions-table
-      (make-hash-table :test 'dbus-hash-table-test))
+;; Register the handler.
+(condition-case nil
+    (progn
+      (dbus-register-signal
+       :system dbus-service-dbus dbus-path-dbus dbus-interface-dbus
+       "NameOwnerChanged" 'dbus-name-owner-changed-handler)
+      (dbus-register-signal
+       :session dbus-service-dbus dbus-path-dbus dbus-interface-dbus
+       "NameOwnerChanged" 'dbus-name-owner-changed-handler))
+  (dbus-error))
 
 
 ;;; D-Bus events.
@@ -83,33 +114,34 @@
   "Checks whether EVENT is a well formed D-Bus event.
 EVENT is a list which starts with symbol `dbus-event':
 
-     (dbus-event HANDLER BUS SERVICE PATH INTERFACE MEMBER &rest ARGS)
+     (dbus-event BUS SERVICE PATH INTERFACE MEMBER HANDLER &rest ARGS)
 
-HANDLER is the function which has been registered for this
-signal.  BUS identifies the D-Bus the signal is coming from.  It
-is either the symbol `:system' or the symbol `:session'.  SERVICE
-and PATH are the name and the object path of the D-Bus object
+BUS identifies the D-Bus the signal is coming from.  It is either
+the symbol `:system' or the symbol `:session'.  SERVICE and PATH
+are the unique name and the object path of the D-Bus object
 emitting the signal.  INTERFACE and MEMBER denote the signal
-which has been sent.  ARGS are the arguments passed to HANDLER,
-when it is called during event handling in `dbus-handle-event'.
+which has been sent.  HANDLER is the function which has been
+registered for this signal.  ARGS are the arguments passed to
+HANDLER, when it is called during event handling in
+`dbus-handle-event'.
 
 This function raises a `dbus-error' signal in case the event is
 not well formed."
   (when dbus-debug (message "DBus-Event %s" event))
   (unless (and (listp event)
 	       (eq (car event) 'dbus-event)
-	       ;; Handler.
-	       (functionp (nth 1 event))
 	       ;; Bus symbol.
-	       (symbolp (nth 2 event))
+	       (symbolp (nth 1 event))
 	       ;; Service.
+	       (stringp (nth 2 event))
+	       ;; Object path.
 	       (stringp (nth 3 event))
-	       ;; Object path.
+	       ;; Interface.
 	       (stringp (nth 4 event))
-	       ;; Interface.
+	       ;; Member.
 	       (stringp (nth 5 event))
-	       ;; Member.
-	       (stringp (nth 6 event)))
+	       ;; Handler.
+	       (functionp (nth 6 event)))
     (signal 'dbus-error (list "Not a valid D-Bus event" event))))
 
 ;;;###autoload
@@ -123,7 +155,7 @@
   (condition-case nil
       (progn
 	(dbus-check-event event)
-	(apply (cadr event) (nthcdr 7 event)))
+	(apply (nth 6 event) (nthcdr 7 event)))
     (dbus-error)))
 
 (defun dbus-event-bus-name (event)
@@ -133,7 +165,7 @@
 raises a `dbus-error' signal in case the event is not well
 formed."
   (dbus-check-event event)
-  (nth 2 event))
+  (nth 1 event))
 
 (defun dbus-event-service-name (event)
   "Return the name of the D-Bus object the event is coming from.
@@ -141,7 +173,7 @@
 This function raises a `dbus-error' signal in case the event is
 not well formed."
   (dbus-check-event event)
-  (nth 3 event))
+  (nth 2 event))
 
 (defun dbus-event-path-name (event)
   "Return the object path of the D-Bus object the event is coming from.
@@ -149,7 +181,7 @@
 This function raises a `dbus-error' signal in case the event is
 not well formed."
   (dbus-check-event event)
-  (nth 4 event))
+  (nth 3 event))
 
 (defun dbus-event-interface-name (event)
   "Return the interface name of the D-Bus object the event is coming from.
@@ -157,7 +189,7 @@
 This function raises a `dbus-error' signal in case the event is
 not well formed."
   (dbus-check-event event)
-  (nth 5 event))
+  (nth 4 event))
 
 (defun dbus-event-member-name (event)
   "Return the member name the event is coming from.
@@ -166,7 +198,7 @@
 function raises a `dbus-error' signal in case the event is not
 well formed."
   (dbus-check-event event)
-  (nth 6 event))
+  (nth 5 event))
 
 
 ;;; D-Bus registered names.
@@ -177,8 +209,8 @@
 activatable service names at all."
   (condition-case nil
       (dbus-call-method
-       :system "ListActivatableNames" dbus-service-dbus
-       dbus-path-dbus dbus-interface-dbus)
+       :system dbus-service-dbus
+       dbus-path-dbus dbus-interface-dbus "ListActivatableNames")
     (dbus-error)))
 
 (defun dbus-list-names (bus)
@@ -189,7 +221,7 @@
 for services."
   (condition-case nil
       (dbus-call-method
-       bus "ListNames" dbus-service-dbus dbus-path-dbus dbus-interface-dbus)
+       bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus "ListNames")
     (dbus-error)))
 
 (defun dbus-list-known-names (bus)
@@ -206,8 +238,8 @@
 owners service names at all."
   (condition-case nil
       (dbus-call-method
-       bus "ListQueuedOwners" dbus-service-dbus
-       dbus-path-dbus dbus-interface-dbus service)
+       bus dbus-service-dbus dbus-path-dbus
+       dbus-interface-dbus "ListQueuedOwners" service)
     (dbus-error)))
 
 (defun dbus-get-name-owner (bus service)
@@ -215,8 +247,8 @@
 The result is either a string, or nil if there is no name owner."
   (condition-case nil
       (dbus-call-method
-       bus "GetNameOwner" dbus-service-dbus
-       dbus-path-dbus dbus-interface-dbus service)
+       bus dbus-service-dbus dbus-path-dbus
+       dbus-interface-dbus "GetNameOwner" service)
     (dbus-error)))
 
 (defun dbus-introspect (bus service path)
@@ -227,10 +259,10 @@
 
 \(dbus-introspect
   :system \"org.freedesktop.Hal\"
-  \"/org/freedesktop/Hal/devices/computer\"))"
+  \"/org/freedesktop/Hal/devices/computer\")"
   (condition-case nil
       (dbus-call-method
-       bus "Introspect" service path dbus-interface-introspectable)
+       bus service path dbus-interface-introspectable "Introspect")
     (dbus-error)))
 
 (if nil ;; Must be reworked.  Shall we offer D-Bus signatures at all?
--- a/lisp/net/imap.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/net/imap.el	Sun Dec 16 05:08:49 2007 +0000
@@ -140,6 +140,7 @@
 
 (eval-when-compile (require 'cl))
 (eval-and-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
   (autoload 'starttls-open-stream "starttls")
   (autoload 'starttls-negotiate "starttls")
   (autoload 'sasl-find-mechanism "sasl")
@@ -1734,6 +1735,18 @@
 		  (concat "UID STORE " articles
 			  " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
 
+;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/65317/focus=65343
+;; Signal an error if we'd get an integer overflow.
+;;
+;; FIXME: Identify relevant calls to `string-to-number' and replace them with
+;; `imap-string-to-integer'.
+(defun imap-string-to-integer (string &optional base)
+  (let ((number (string-to-number string base)))
+    (if (> number most-positive-fixnum)
+	(error
+	 (format "String %s cannot be converted to a lisp integer" number))
+      number)))
+
 (defun imap-message-copyuid-1 (mailbox)
   (if (imap-capability 'UIDPLUS)
       (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
--- a/lisp/net/rcirc.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/net/rcirc.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1708,13 +1708,13 @@
 	    (recenter -1)))
       (if (eq major-mode 'rcirc-mode)
 	  (switch-to-buffer (rcirc-non-irc-buffer))
-	(message (concat
-		  "No IRC activity."
-		  (when lopri
-		    (concat
-		     "  Type C-u "
-		     (key-description (this-command-keys))
-		     " for low priority activity."))))))))
+	(message "%s" (concat
+		       "No IRC activity."
+		       (when lopri
+			 (concat
+			  "  Type C-u "
+			  (key-description (this-command-keys))
+			  " for low priority activity."))))))))
 
 (defvar rcirc-activity-hooks nil
   "Hook to be run when there is channel activity.
--- a/lisp/net/trampver.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/net/trampver.el	Sun Dec 16 05:08:49 2007 +0000
@@ -38,7 +38,7 @@
 
 ;; Check for (X)Emacs version.
 (let ((x (if (or (< emacs-major-version 21)	(and (featurep 'xemacs)	     (< emacs-minor-version 4)))    (format "Tramp 2.1.12-pre is not fit for %s"	    (when (string-match "^.*$" (emacs-version))	      (match-string 0 (emacs-version))))    "ok")))
-  (unless (string-match "\\`ok\\'" x) (error x)))
+  (unless (string-match "\\`ok\\'" x) (error "%s" x)))
 
 (provide 'trampver)
 
--- a/lisp/pgg-parse.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/pgg-parse.el	Sun Dec 16 05:08:49 2007 +0000
@@ -36,7 +36,9 @@
 
 ;;; Code:
 
-(eval-when-compile (require 'cl))
+(eval-when-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
+  (require 'cl))
 
 (defgroup pgg-parse ()
   "OpenPGP packet parsing."
--- a/lisp/pgg.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/pgg.el	Sun Dec 16 05:08:49 2007 +0000
@@ -35,18 +35,17 @@
 
 ;; Don't merge these two `eval-when-compile's.
 (eval-when-compile
+  (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
   (require 'cl))
 
 ;;; @ utility functions
 ;;;
 
 (eval-when-compile
-  (unless (featurep 'xemacs)
-    (defalias 'pgg-run-at-time 'run-at-time)
-    (defalias 'pgg-cancel-timer 'cancel-timer))
-
-  (when (featurep 'xemacs)
-    (defmacro pgg-run-at-time-1 (time repeat function args)
+  ;; Define it as a null macro for Emacs in order to suppress a byte
+  ;; compile warning that Emacs 21 issues.
+  (defmacro pgg-run-at-time-1 (time repeat function args)
+    (when (featurep 'xemacs)
       (if (condition-case nil
 	      (let ((delete-itimer 'delete-itimer)
 		    (itimer-driver-start 'itimer-driver-start)
@@ -104,19 +103,23 @@
 			itimer
 			(append (list itimer function) args)))))
 		 1e-9 (if time (max time 1e-9) 1e-9)
-		 nil t itimers ,repeat ,function ,args))))
+		 nil t itimers ,repeat ,function ,args))))))
 
-    (defun pgg-run-at-time (time repeat function &rest args)
-      "Emulating function run as `run-at-time'.
+(eval-and-compile
+  (if (featurep 'xemacs)
+      (progn
+	(defun pgg-run-at-time (time repeat function &rest args)
+	  "Emulating function run as `run-at-time'.
 TIME should be nil meaning now, or a number of seconds from now.
 Return an itimer object which can be used in either `delete-itimer'
 or `cancel-timer'."
-      (pgg-run-at-time-1 time repeat function args))
-    (defun pgg-cancel-timer (timer)
-      "Emulate cancel-timer for xemacs."
-      (let ((delete-itimer 'delete-itimer))
-        (funcall delete-itimer timer)))
-    ))
+	  (pgg-run-at-time-1 time repeat function args))
+	(defun pgg-cancel-timer (timer)
+	  "Emulate cancel-timer for xemacs."
+	  (let ((delete-itimer 'delete-itimer))
+	    (funcall delete-itimer timer))))
+    (defalias 'pgg-run-at-time 'run-at-time)
+    (defalias 'pgg-cancel-timer 'cancel-timer)))
 
 (defun pgg-invoke (func scheme &rest args)
   (progn
--- a/lisp/play/mpuz.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/play/mpuz.el	Sun Dec 16 05:08:49 2007 +0000
@@ -489,7 +489,7 @@
 			       ((< mpuz-nb-errors 10)	"bad!")
 			       ((< mpuz-nb-errors 15)	"awful.")
 			       (t			"not serious.")))))
-    (message message)
+    (message "%s" message)
     (sit-for 4)
     (if (y-or-n-p (concat message "  Start a new game? "))
 	(mpuz-start-new-game)
--- a/lisp/progmodes/ada-xref.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/ada-xref.el	Sun Dec 16 05:08:49 2007 +0000
@@ -564,7 +564,7 @@
   (let ((file (ada-find-src-file-in-dir filename)))
     (if file
 	(find-file file)
-      (error (concat filename " not found in src_dir")))))
+      (error "%s not found in src_dir" filename))))
 
 
 ;; ----- Utilities -------------------------------------------------
@@ -1722,8 +1722,8 @@
 	  ;; No more idea to find the declaration.  Give up
 	  (progn
 	    (kill-buffer ali-buffer)
-	    (error (concat "No declaration of " (ada-name-of identlist)
-			   " found."))
+
+	    (error "No declaration of %s found." (ada-name-of identlist))
 	    )))
       )
 
@@ -1808,10 +1808,8 @@
 	   ;; none => error
 	   ((= len 0)
 	    (kill-buffer (current-buffer))
-	    (error (concat "No declaration of "
-			   (ada-name-of identlist)
-			   " recorded in .ali file")))
-
+	    (error "No declaration of %s recorded in .ali file"
+		   (ada-name-of identlist)))
 	   ;; one => should be the right one
 	   ((= len 1)
 	    (goto-line (caar declist)))
@@ -2011,7 +2009,7 @@
 				  (string-to-number (nth 2 (car list)))
 				  identlist
 				  other-frame)
-	(error (concat (caar list) " not found in src_dir")))
+	(error "%s not found in src_dir"  (caar list)))
       (message "This is only a (good) guess at the cross-reference.")
       )
 
--- a/lisp/progmodes/antlr-mode.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/antlr-mode.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1875,7 +1875,7 @@
 					(read initial)
 				      initial))
 			       (cdr value))))
-	(message (cadr value))
+	(message "%s" (or (cadr value) ""))
 	(setq value nil)))
     ;; insert value ----------------------------------------------------------
     (if (consp old)
--- a/lisp/progmodes/cc-cmds.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/cc-cmds.el	Sun Dec 16 05:08:49 2007 +0000
@@ -3864,7 +3864,12 @@
 		  (save-excursion
 		    (goto-char (cdr c-lit-limits))
 		    (beginning-of-line)
-		    (and (search-forward-regexp
+		    ;; The following conjunct was added to avoid an
+		    ;; "Invalid search bound (wrong side of point)"
+		    ;; error in the subsequent re-search.  Maybe
+		    ;; another fix would be needed (2007-12-08).
+		    (and (> (- (cdr c-lit-limits) 2) (point))
+			 (search-forward-regexp
 			  (concat "\\=[ \t]*\\(" c-current-comment-prefix "\\)")
 			  (- (cdr c-lit-limits) 2) t)
 			 (not (search-forward-regexp
--- a/lisp/progmodes/cc-vars.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/cc-vars.el	Sun Dec 16 05:08:49 2007 +0000
@@ -156,34 +156,45 @@
   (setq c-fallback-style (cons (cons name val) c-fallback-style)))
 
 (defmacro defcustom-c-stylevar (name val doc &rest args)
-  "Defines a style variable."
-  `(let ((-value- ,val))
-     (c-set-stylevar-fallback ',name -value-)
-     (custom-declare-variable
-      ',name ''set-from-style
-      ,(concat doc "
+  "Define a style variable NAME with VAL and DOC.
+More precisely, convert the given `:type FOO', mined out of ARGS,
+to an aggregate `:type (radio STYLE (PREAMBLE FOO))', append some
+some boilerplate documentation to DOC, arrange for the fallback
+value of NAME to be VAL, and call `custom-declare-variable' to
+do the rest of the work.
+
+STYLE stands for the choice where the value is taken from some
+style setting.  PREAMBLE is optionally prepended to FOO; that is,
+if FOO contains :tag or :value, the respective two-element list
+component is ignored."
+  (declare (debug (symbolp form stringp &rest)))
+  (let* ((expanded-doc (concat doc "
 
 This is a style variable.  Apart from the valid values described
-above, it can be set to the symbol `set-from-style'.  In that case, it
-takes its value from the style system (see `c-default-style' and
+above, it can be set to the symbol `set-from-style'.  In that case,
+it takes its value from the style system (see `c-default-style' and
 `c-style-alist') when a CC Mode buffer is initialized.  Otherwise,
 the value set here overrides the style system (there is a variable
-`c-old-style-variable-behavior' that changes this, though).")
-      ,@(plist-put
-	 args ':type
-	 `(` (radio
-	      (const :tag "Use style settings"
-		     set-from-style)
-	      ,(, (let ((type (eval (plist-get args ':type))))
-		    (unless (consp type)
-		      (setq type (list type)))
-		    (unless (c-safe (plist-get (cdr type) ':value))
-		      (setcdr type (append '(:value (, -value-))
-					   (cdr type))))
-		    (unless (c-safe (plist-get (cdr type) ':tag))
-		      (setcdr type (append '(:tag "Override style settings")
-					   (cdr type))))
-		    (bq-process type)))))))))
+`c-old-style-variable-behavior' that changes this, though)."))
+         (typ (eval (plist-get args :type)))
+         (type (if (consp typ) typ (list typ)))
+         (head (car type))
+         (tail (cdr type))
+         (newt (append (unless (plist-get tail :tag)
+                         '(:tag "Override style settings"))
+                       (unless (plist-get tail :value)
+                         `(:value ,val))
+                       tail))
+         (aggregate `'(radio
+                       (const :tag "Use style settings" set-from-style)
+                       ,(cons head newt))))
+    (message "aggregate: %S" aggregate)
+    `(progn
+       (c-set-stylevar-fallback ',name ,val)
+       (custom-declare-variable
+        ',name ''set-from-style
+        ,expanded-doc
+        ,@(plist-put args :type aggregate)))))
 
 (defun c-valid-offset (offset)
   "Return non-nil if OFFSET is a valid offset for a syntactic symbol.
--- a/lisp/progmodes/cperl-mode.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/cperl-mode.el	Sun Dec 16 05:08:49 2007 +0000
@@ -231,12 +231,18 @@
   :type 'integer
   :group 'cperl-indentation-details)
 
-;; Is is not unusual to put both perl-indent-level and
+;; Is is not unusual to put both things like perl-indent-level and
 ;; cperl-indent-level in the local variable section of a file. If only
 ;; one of perl-mode and cperl-mode is in use, a warning will be issued
-;; about the variable. Autoload this here, so that no warning is
+;; about the variable. Autoload these here, so that no warning is
 ;; issued when using either perl-mode or cperl-mode.
 ;;;###autoload(put 'cperl-indent-level 'safe-local-variable 'integerp)
+;;;###autoload(put 'cperl-brace-offset 'safe-local-variable 'integerp)
+;;;###autoload(put 'cperl-continued-brace-offset 'safe-local-variable 'integerp)
+;;;###autoload(put 'cperl-label-offset 'safe-local-variable 'integerp)
+;;;###autoload(put 'cperl-continued-statement-offset 'safe-local-variable 'integerp)
+;;;###autoload(put 'cperl-extra-newline-before-brace 'safe-local-variable 'booleanp)
+;;;###autoload(put 'cperl-merge-trailing-else 'safe-local-variable 'booleanp)
 
 (defcustom cperl-lineup-step nil
   "*`cperl-lineup' will always lineup at multiple of this number.
@@ -4581,7 +4587,7 @@
 					   (setq qtag "Can't find })")))
 				  (progn
 				    (goto-char (1- e))
-				    (message qtag))
+				    (message "%s" qtag))
 				(cperl-postpone-fontification
 				 (1- tag) (1- (point))
 				 'face font-lock-variable-name-face)
--- a/lisp/progmodes/ebrowse.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/ebrowse.el	Sun Dec 16 05:08:49 2007 +0000
@@ -896,10 +896,10 @@
   (let (message-log-max)
     (when start (setq ebrowse-n-boxes 0))
     (setq ebrowse-n-boxes (mod (1+ ebrowse-n-boxes) ebrowse-max-boxes))
-    (message (concat title ": "
-		     (propertize (make-string ebrowse-n-boxes
-					      (if (display-color-p) ?\  ?+))
-				 'face 'ebrowse-progress)))))
+    (message "%s: %s" title
+	     (propertize (make-string ebrowse-n-boxes
+				      (if (display-color-p) ?\  ?+))
+			 'face 'ebrowse-progress))))
 
 
 ;;; Reading a tree from disk
--- a/lisp/progmodes/idlw-shell.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/idlw-shell.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1322,7 +1322,7 @@
     (if (or (not (setq buf (get-buffer (idlwave-shell-buffer))))
 	    (not (setq proc (get-buffer-process buf))))
 	(if (not idlwave-shell-automatic-start)
-	    (error
+	    (error "%s"
 	     (substitute-command-keys
 	      "You need to first start an IDL shell with \\[idlwave-shell]"))
 	  (idlwave-shell-recenter-shell-window)
@@ -2375,7 +2375,7 @@
     (if (not (idlwave-shell-valid-frame frame))
 	;; fixme: errors are dangerous in shell filters.  but i think i
 	;; have never encountered this one.
-        (error (concat "invalid frame - unable to access file: " (car frame)))
+        (error "invalid frame - unable to access file: %s" (car frame))
 ;;;
 ;;; buffer : the buffer to display a line in.
 ;;; select-shell: current buffer is the shell.
--- a/lisp/progmodes/idlwave.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/idlwave.el	Sun Dec 16 05:08:49 2007 +0000
@@ -3799,7 +3799,7 @@
       (if (not noindent)
 	  (indent-region beg end nil))
       (if (stringp prompt)
-	  (message prompt)))))
+	  (message "%s" prompt)))))
 
 (defun idlwave-rw-case (string)
   "Make STRING have the case required by `idlwave-reserved-word-upcase'."
@@ -7038,7 +7038,7 @@
 			 (select-window win)
 			 (eval idlwave-complete-after-success-form))
 		     (set-window-start cwin (point-min)))))
-	  (and message (message message)))
+	  (and message (message "%s" message)))
       (select-window win))))
 
 (defun idlwave-display-completion-list (list &optional message beg complete)
@@ -7069,7 +7069,7 @@
   (run-hooks 'idlwave-completion-setup-hook)
 
   ;; Display the message
-  (message (or message "Making completion list...done")))
+  (message "%s" (or message "Making completion list...done")))
 
 (defun idlwave-choose (function &rest args)
   "Call FUNCTION as a completion chooser and pass ARGS to it."
--- a/lisp/progmodes/perl-mode.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/perl-mode.el	Sun Dec 16 05:08:49 2007 +0000
@@ -402,12 +402,17 @@
   :type 'integer
   :group 'perl)
 
-;; Is is not unusual to put both perl-indent-level and
+;; Is is not unusual to put both things like perl-indent-level and
 ;; cperl-indent-level in the local variable section of a file. If only
 ;; one of perl-mode and cperl-mode is in use, a warning will be issued
-;; about the variable. Autoload this here, so that no warning is
+;; about the variable. Autoload these here, so that no warning is
 ;; issued when using either perl-mode or cperl-mode.
 ;;;###autoload(put 'perl-indent-level 'safe-local-variable 'integerp)
+;;;###autoload(put 'perl-continued-statement-offset 'safe-local-variable 'integerp)
+;;;###autoload(put 'perl-continued-brace-offset 'safe-local-variable 'integerp)
+;;;###autoload(put 'perl-brace-offset 'safe-local-variable 'integerp)
+;;;###autoload(put 'perl-brace-imaginary-offset 'safe-local-variable 'integerp)
+;;;###autoload(put 'perl-label-offset 'safe-local-variable 'integerp)
 
 (defcustom perl-continued-statement-offset 4
   "*Extra indent for lines not starting new statements."
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lisp/progmodes/verilog-mode.el	Sun Dec 16 05:08:49 2007 +0000
@@ -0,0 +1,10318 @@
+;; verilog-mode.el --- major mode for editing verilog source in Emacs
+
+;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+;;   2005, 2006, 2007  Free Software Foundation, Inc.
+
+;; Author: Michael McNamara (mac@verilog.com)
+;;  http://www.verilog.com
+;;
+;; AUTO features, signal, modsig; by: Wilson Snyder
+;;	(wsnyder@wsnyder.org)
+;;	http://www.veripool.com
+;; Keywords: languages
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs 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 3, or (at your option)
+;; any later version.
+
+;; GNU Emacs 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 GNU Emacs; see the file COPYING.  If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+
+;;; Commentary:
+
+;; This mode borrows heavily from the Pascal-mode and the cc-mode of emacs
+
+;; USAGE
+;; =====
+
+;; A major mode for editing Verilog HDL source code. When you have
+;; entered Verilog mode, you may get more info by pressing C-h m. You
+;; may also get online help describing various functions by: C-h f
+;; <Name of function you want described>
+
+;; KNOWN BUGS / BUG REPORTS
+;; =======================
+
+;; Verilog is a rapidly evolving language, and hence this mode is
+;; under continuous development. Hence this is beta code, and likely
+;; has bugs. Please report any and all bugs to me at mac@verilog.com.
+;; Please use verilog-submit-bug-report to submit a report; type C-c
+;; C-b to invoke this and as a result I will have a much easier time
+;; of reproducing the bug you find, and hence fixing it.
+
+;; INSTALLING THE MODE
+;; ===================
+
+;; An older version of this mode may be already installed as a part of
+;; your environment, and one method of updating would be to update
+;; your emacs environment.  Sometimes this is difficult for local
+;; political/control reasons, and hence you can always install a
+;; private copy (or even a shared copy) which overrides the system
+;; default.
+
+;; You can get step by step help in installing this file by going to
+;; <http://www.verilog.com/emacs_install.html>
+
+;; The short list of installation instructions are: To set up
+;; automatic verilog mode, put this file in your load path, and put
+;; the following in code (please un comment it first!) in your
+;; .emacs, or in your site's site-load.el
+
+; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
+; (setq auto-mode-alist (cons  '("\\.v\\'" . verilog-mode) auto-mode-alist))
+; (setq auto-mode-alist (cons  '("\\.dv\\'" . verilog-mode) auto-mode-alist))
+
+;; If you want to customize Verilog mode to fit your needs better,
+;; you may add these lines (the values of the variables presented
+;; here are the defaults). Note also that if you use an emacs that
+;; supports custom, it's probably better to use the custom menu to
+;; edit these.
+;;
+;; Be sure to examine at the help for verilog-auto, and the other
+;; verilog-auto-* functions for some major coding time savers.
+;;
+; ;; User customization for Verilog mode
+; (setq verilog-indent-level             3
+;       verilog-indent-level-module      3
+;       verilog-indent-level-declaration 3
+;       verilog-indent-level-behavioral  3
+;       verilog-indent-level-directive   1
+;       verilog-case-indent              2
+;       verilog-auto-newline             t
+;       verilog-auto-indent-on-newline   t
+;       verilog-tab-always-indent        t
+;       verilog-auto-endcomments         t
+;       verilog-minimum-comment-distance 40
+;       verilog-indent-begin-after-if    t
+;       verilog-auto-lineup              '(all)
+;       verilog-highlight-p1800-keywords nil
+;	verilog-linter			 "my_lint_shell_command"
+;	)
+
+;; 
+
+;;; History:
+;;
+;; 
+;;; Code:
+
+;; This variable will always hold the version number of the mode
+(defconst verilog-mode-version "377"
+  "Version of this verilog mode.")
+(defconst verilog-mode-release-date "2007-12-07"
+  "Version of this verilog mode.")
+
+(defun verilog-version ()
+  "Inform caller of the version of this file."
+  (interactive)
+  (message (concat "Using verilog-mode version " verilog-mode-version) ))
+
+;; Insure we have certain packages, and deal with it if we don't
+(eval-when-compile
+  (condition-case nil
+      (require 'imenu)
+    (error nil))
+  (condition-case nil
+      (require 'reporter)
+    (error nil))
+  (condition-case nil
+      (require 'easymenu)
+    (error nil))
+  (condition-case nil
+      (require 'regexp-opt)
+    (error nil))
+  (condition-case nil
+      (load "skeleton") ;; bug in 19.28 through 19.30 skeleton.el, not provided.
+    (error nil))
+  (condition-case nil
+      (require 'vc)
+    (error nil))
+  (condition-case nil
+      (if (fboundp 'when)
+	  nil ;; fab
+	(defmacro when (cond &rest body)
+	  (list 'if cond (cons 'progn body))))
+    (error nil))
+  (condition-case nil
+      (if (fboundp 'unless)
+	  nil ;; fab
+	(defmacro unless (cond &rest body)
+	  (cons 'if (cons cond (cons nil body)))))
+    (error nil))
+  (condition-case nil
+      (if (fboundp 'store-match-data)
+	  nil ;; fab
+	(defmacro store-match-data (&rest args) nil))
+    (error nil))
+  (if (featurep 'xemacs)
+      (condition-case nil
+	  (if (boundp 'current-menubar)
+	      nil ;; great
+	    (progn
+	      (defmacro add-submenu (&rest args) nil))
+	    )
+	(error nil)))
+  (condition-case nil
+      (if (fboundp 'zmacs-activate-region)
+	  nil ;; great
+	(defmacro zmacs-activate-region (&rest args) nil))
+    (error nil))
+  (condition-case nil
+      (if (fboundp 'char-before)
+	  nil ;; great
+	(defmacro char-before (&rest body)
+	  (char-after (1- (point)))))
+    (error nil))
+  ;; Requires to define variables that would be "free" warnings
+  (condition-case nil
+      (require 'font-lock)
+    (error nil))
+  (condition-case nil
+      (require 'compile)
+    (error nil))
+  (condition-case nil
+      (require 'custom)
+    (error nil))
+  (condition-case nil
+      (require 'dinotrace)
+    (error nil))
+  (condition-case nil
+      (if (fboundp 'dinotrace-unannotate-all)
+	  nil ;; great
+	(defun dinotrace-unannotate-all (&rest args) nil))
+    (error nil))
+  (condition-case nil
+      (if (fboundp 'customize-apropos)
+	  nil ;; great
+	(defun customize-apropos (&rest args) nil))
+    (error nil))
+  (condition-case nil
+      (if (fboundp 'match-string-no-properties)
+	  nil ;; great
+	(defsubst match-string-no-properties (num &optional string)
+	  "Return string of text matched by last search, without text properties.
+NUM specifies which parenthesized expression in the last regexp.
+ Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
+Zero means the entire text matched by the whole regexp or whole string.
+STRING should be given if the last search was by `string-match' on STRING."
+	  (if (match-beginning num)
+	      (if string
+		  (let ((result
+			 (substring string (match-beginning num) (match-end num))))
+		    (set-text-properties 0 (length result) nil result)
+		    result)
+		(buffer-substring-no-properties (match-beginning num)
+						(match-end num)
+						(current-buffer)
+						)))))
+    (error nil))
+  (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
+      nil ;; We've got what we needed
+    ;; We have the old custom-library, hack around it!
+    (defmacro defgroup (&rest args)  nil)
+    (defmacro customize (&rest args)
+      (message "Sorry, Customize is not available with this version of emacs"))
+    (defmacro defcustom (var value doc &rest args)
+      `(defvar ,var ,value ,doc))
+    )
+  (if (fboundp 'defface)
+      nil				; great!
+    (defmacro defface (var values doc &rest args)
+      `(make-face ,var))
+    )
+
+  (if (and (featurep 'custom) (fboundp 'customize-group))
+      nil ;; We've got what we needed
+    ;; We have an intermediate custom-library, hack around it!
+    (defmacro customize-group (var &rest args)
+      `(customize ,var))
+    )
+
+  )
+;; Provide a regular expression optimization routine, using regexp-opt
+;; if provided by the user's elisp libraries
+(eval-and-compile
+  (if (fboundp 'regexp-opt)
+      ;; regexp-opt is defined, does it take 3 or 2 arguments?
+      (if (fboundp 'function-max-args)
+	  (let ((args (function-max-args `regexp-opt)))
+	    (cond 
+	     ((eq args 3) ;; It takes 3
+	      (condition-case nil	; Hide this defun from emacses
+					;with just a two input regexp
+		  (defun verilog-regexp-opt (a b)
+		    "Deal with differing number of required arguments for  `regexp-opt'.
+         Call 'regexp-opt' on A and B."
+		    (regexp-opt a b 't)
+		    )
+		(error nil))
+	      )
+	      ((eq args 2) ;; It takes 2
+	      (defun verilog-regexp-opt (a b)
+		"Call 'regexp-opt' on A and B."
+		(regexp-opt a b))
+	      )
+	      (t nil)))
+	;; We can't tell; assume it takes 2
+	(defun verilog-regexp-opt (a b)
+	  "Call 'regexp-opt' on A and B."
+	  (regexp-opt a b))
+	)
+    ;; There is no regexp-opt, provide our own
+    (defun verilog-regexp-opt (strings &optional paren shy)
+      (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
+	(concat open (mapconcat 'regexp-quote strings "\\|") close)))
+    ))
+
+(eval-when-compile
+  (defun verilog-regexp-words (a)
+    "Call 'regexp-opt' with word delimiters for the words A."
+    (concat "\\<" (verilog-regexp-opt a t) "\\>")))
+
+(defun verilog-customize ()
+  "Link to customize screen for Verilog."
+  (interactive)
+  (customize-group 'verilog-mode))
+
+(defun verilog-font-customize ()
+  "Link to customize fonts used for Verilog."
+  (interactive)
+  (customize-apropos "font-lock-*" 'faces))
+
+(defgroup verilog-mode nil
+  "Facilitates easy editing of Verilog source text"
+  :group 'languages)
+
+; (defgroup verilog-mode-fonts nil
+;   "Facilitates easy customization fonts used in Verilog source text"
+;   :link '(customize-apropos "font-lock-*" 'faces)
+;  :group 'verilog-mode)
+
+(defgroup verilog-mode-indent nil
+  "Customize indentation and highlighting of verilog source text"
+  :group 'verilog-mode)
+
+(defgroup verilog-mode-actions nil
+  "Customize actions on verilog source text"
+  :group 'verilog-mode)
+
+(defgroup verilog-mode-auto nil
+  "Customize AUTO actions when expanding verilog source text"
+  :group 'verilog-mode)
+
+(defcustom verilog-linter
+  "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
+  "*Unix program and arguments to call to run a lint checker on verilog source.
+Depending on the `verilog-set-compile-command', this may be invoked when
+you type \\[compile].  When the compile completes, \\[next-error] will take
+you to the next lint error."
+  :type 'string
+  :group 'verilog-mode-actions)
+
+(defcustom verilog-coverage
+  "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
+  "*Program and arguments to use to annotate for coverage verilog source.
+Depending on the `verilog-set-compile-command', this may be invoked when
+you type \\[compile].  When the compile completes, \\[next-error] will take
+you to the next lint error."
+  :type 'string
+  :group 'verilog-mode-actions)
+
+(defcustom verilog-simulator
+  "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
+  "*Program and arguments to use to interpret verilog source.
+Depending on the `verilog-set-compile-command', this may be invoked when
+you type \\[compile].  When the compile completes, \\[next-error] will take
+you to the next lint error."
+  :type 'string
+  :group 'verilog-mode-actions)
+
+(defcustom verilog-compiler
+  "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
+  "*Program and arguments to use to compile verilog source.
+Depending on the `verilog-set-compile-command', this may be invoked when
+you type \\[compile].  When the compile completes, \\[next-error] will take
+you to the next lint error."
+  :type 'string
+  :group 'verilog-mode-actions)
+
+(defvar verilog-tool 'verilog-linter
+  "Which tool to use for building compiler-command.
+Either nil, `verilog-linter, `verilog-coverage, `verilog-simulator, or
+`verilog-compiler.  Alternatively use the \"Choose Compilation Action\"
+menu.  See `verilog-set-compile-command' for more information.")
+
+(defcustom verilog-highlight-translate-off nil
+  "*Non-nil means background-highlight code excluded from translation.
+That is, all code between \"// synopsys translate_off\" and
+\"// synopsys translate_on\" is highlighted using a different background color
+\(face `verilog-font-lock-translate-off-face').
+
+Note: This will slow down on-the-fly fontification (and thus editing).
+
+Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
+entry \"Fontify Buffer\").  XEmacs: turn off and on font locking."
+  :type 'boolean
+  :group 'verilog-mode-indent)
+
+(defcustom verilog-indent-level 3
+  "*Indentation of Verilog statements with respect to containing block."
+  :group 'verilog-mode-indent
+  :type 'integer)
+
+(defcustom verilog-indent-level-module 3
+  "*Indentation of Module level Verilog statements.  (eg always, initial)
+Set to 0 to get initial and always statements lined up on the left side of
+your screen."
+  :group 'verilog-mode-indent
+  :type 'integer)
+
+(defcustom verilog-indent-level-declaration 3
+  "*Indentation of declarations with respect to containing block.
+Set to 0 to get them list right under containing block."
+  :group 'verilog-mode-indent
+  :type 'integer)
+
+(defcustom verilog-indent-declaration-macros nil
+  "*How to treat macro expansions in a declaration.
+If nil, indent as:
+	input [31:0] a;
+	input        `CP;
+	output       c;
+If non nil, treat as:
+	input [31:0] a;
+	input `CP    ;
+	output       c;"
+  :group 'verilog-mode-indent
+  :type 'boolean)
+
+(defcustom verilog-indent-lists t
+  "*How to treat indenting items in a list.
+If t (the default), indent as:
+	always @( posedge a or
+	          reset ) begin
+
+If nil, treat as:
+	always @( posedge a or
+	   reset ) begin"
+  :group 'verilog-mode-indent
+  :type 'boolean)
+
+(defcustom verilog-indent-level-behavioral 3
+  "*Absolute indentation of first begin in a task or function block.
+Set to 0 to get such code to start at the left side of the screen."
+  :group 'verilog-mode-indent
+  :type 'integer)
+
+(defcustom verilog-indent-level-directive 1
+  "*Indentation to add to each level of `ifdef declarations.
+Set to 0 to have all directives start at the left side of the screen."
+  :group 'verilog-mode-indent
+  :type 'integer)
+
+(defcustom verilog-cexp-indent 2
+  "*Indentation of Verilog statements split across lines."
+  :group 'verilog-mode-indent
+  :type 'integer)
+
+(defcustom verilog-case-indent 2
+  "*Indentation for case statements."
+  :group 'verilog-mode-indent
+  :type 'integer)
+
+(defcustom verilog-auto-newline t
+  "*True means automatically newline after semicolons."
+  :group 'verilog-mode-indent
+  :type 'boolean)
+
+(defcustom verilog-auto-indent-on-newline t
+  "*True means automatically indent line after newline."
+  :group 'verilog-mode-indent
+  :type 'boolean)
+
+(defcustom verilog-tab-always-indent t
+  "*True means TAB should always re-indent the current line.
+Nil means TAB will only reindent when at the beginning of the line."
+  :group 'verilog-mode-indent
+  :type 'boolean)
+
+(defcustom verilog-tab-to-comment nil
+  "*True means TAB moves to the right hand column in preparation for a comment."
+  :group 'verilog-mode-actions
+  :type 'boolean)
+
+(defcustom verilog-indent-begin-after-if t
+  "*If true, indent begin statements following if, else, while, for and repeat.
+Otherwise, line them up."
+  :group 'verilog-mode-indent
+  :type 'boolean )
+
+
+(defcustom verilog-align-ifelse nil
+  "*If true, align `else' under matching `if'.
+Otherwise else is lined up with first character on line holding matching if."
+  :group 'verilog-mode-indent
+  :type 'boolean )
+
+(defcustom verilog-minimum-comment-distance 10
+  "*Minimum distance (in lines) between begin and end required before a comment.
+Setting this variable to zero results in every end acquiring a comment; the
+default avoids too many redundant comments in tight quarters"
+  :group 'verilog-mode-indent
+  :type 'integer)
+
+(defcustom verilog-auto-lineup '(declaration)
+  "*Algorithm for lining up statements on multiple lines.
+
+If this list contains the symbol 'all', then all line ups described below
+are done.
+
+If this list contains the symbol 'declaration', then declarations are lined up
+with any preceding declarations, taking into account widths and the like, so
+for example the code:
+	reg [31:0] a;
+	reg b;
+would become
+	reg [31:0] a;
+	reg        b;
+
+If this list contains the symbol 'assignment', then assignments are lined up
+with any preceding assignments, so for example the code
+	a_long_variable = b + c;
+	d = e + f;
+would become
+	a_long_variable = b + c;
+	d               = e + f;"
+
+;; The following is not implemented:
+;If this list contains the symbol 'case', then case items are lined up
+;with any preceding case items, so for example the code
+;	case (a) begin
+;	 a_long_state : a = 3;
+;	 b: a = 4;
+;	endcase
+;would become
+;	case (a) begin
+;	 a_long_state : a = 3;
+;	 b            : a = 4;
+;	endcase
+;
+
+  :group 'verilog-mode-indent
+  :type 'list )
+
+(defcustom verilog-highlight-p1800-keywords nil
+  "*If true highlight words newly reserved by IEEE-1800 in
+verilog-font-lock-p1800-face in order to gently suggest changing where
+these words are used as variables to something else.  Nil means highlight
+these words as appropriate for the SystemVerilog IEEE-1800 standard.  Note
+that changing this will require restarting emacs to see the effect as font
+color choices are cached by emacs"
+  :group 'verilog-mode-indent
+  :type 'boolean)
+
+(defcustom verilog-auto-endcomments t
+  "*True means insert a comment /* ... */ after 'end's.
+The name of the function or case will be set between the braces."
+  :group 'verilog-mode-actions
+  :type 'boolean )
+
+(defcustom verilog-auto-read-includes nil
+  "*True means to automatically read includes before AUTOs.
+This will do a `verilog-read-defines' and `verilog-read-includes' before
+each AUTO expansion.  This makes it easier to embed defines and includes,
+but can result in very slow reading times if there are many or large
+include files."
+  :group 'verilog-mode-actions
+  :type 'boolean )
+
+(defcustom verilog-auto-save-policy nil
+  "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
+A value of `force' will always do a \\[verilog-auto] automatically if
+needed on every save.  A value of `detect' will do \\[verilog-auto]
+automatically when it thinks necessary.  A value of `ask' will query the
+user when it thinks updating is needed.
+
+You should not rely on the 'ask or 'detect policies, they are safeguards
+only.  They do not detect when AUTOINSTs need to be updated because a
+sub-module's port list has changed."
+  :group 'verilog-mode-actions
+  :type '(choice (const nil) (const ask) (const detect) (const force)))
+
+(defcustom verilog-auto-star-expand t
+  "*Non-nil indicates to expand a SystemVerilog .* instance ports.
+They will be expanded in the same way as if there was a AUTOINST in the
+instantiation.  See also `verilog-auto-star' and `verilog-auto-star-save'."
+  :group 'verilog-mode-actions
+  :type 'boolean)
+
+(defcustom verilog-auto-star-save nil
+  "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
+Nil indicates direct connections will be removed before saving.  Only
+meaningful to those created due to `verilog-auto-star-expand' being set.
+
+Instead of setting this, you may want to use /*AUTOINST*/, which will
+always be saved."
+  :group 'verilog-mode-actions
+  :type 'boolean)
+
+(defvar verilog-auto-update-tick nil
+  "Modification tick at which autos were last performed.")
+
+(defvar verilog-auto-last-file-locals nil
+  "Text from file-local-variables during last evaluation.")
+
+(defvar verilog-error-regexp-add-didit nil)
+(defvar verilog-error-regexp nil)
+(setq verilog-error-regexp-add-didit nil
+ verilog-error-regexp
+  '(
+	; SureLint
+;;    ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
+	; Most SureFire tools
+    ("\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\), \\(line \\|\\)\\([0-9]+\\):" 2 4 )
+    ("\
+\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
+:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
+        ; xsim
+	; Error! in file /homes/mac/Axis/Xsim/test.v at line 13		[OBJ_NOT_DECLARED]
+    ("\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
+	; vcs
+    ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
+    ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
+    ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
+    ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
+        ; Verilator
+    ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
+    ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
+       ; vxl
+    ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
+    ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 2)	       ; vxl
+    ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 2)
+        ; nc-verilog
+    (".*\\*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 2)
+       ; Leda
+    ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 2)
+    )
+;  "*List of regexps for verilog compilers, like verilint. See compilation-error-regexp-alist for the formatting."
+)
+
+(defvar verilog-error-font-lock-keywords
+  '(
+    ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
+    ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
+
+    ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
+    ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
+
+    ("\
+\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
+:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
+    ("\
+\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
+:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
+
+    ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
+    ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
+
+    ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
+    ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
+
+    ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
+    ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
+
+    ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
+    ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
+
+    ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
+    ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
+       ; vxl
+    ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
+    ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
+
+    ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 bold t)
+    ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 2 bold t)
+
+    ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 bold t)
+    ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 2 bold t)
+        ; nc-verilog
+    (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 bold t)
+    (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
+       ; Leda
+    ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 bold t)
+    ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 2 bold t)
+    )
+  "*Keywords to also highlight in Verilog *compilation* buffers."
+  )
+
+(defcustom verilog-library-flags '("")
+  "*List of standard Verilog arguments to use for /*AUTOINST*/.
+These arguments are used to find files for `verilog-auto', and match
+the flags accepted by a standard Verilog-XL simulator.
+
+    -f filename     Reads more `verilog-library-flags' from the filename.
+    +incdir+dir     Adds the directory to `verilog-library-directories'.
+    -Idir           Adds the directory to `verilog-library-directories'.
+    -y dir          Adds the directory to `verilog-library-directories'.
+    +libext+.v      Adds the extensions to `verilog-library-extensions'.
+    -v filename     Adds the filename to `verilog-library-files'.
+
+    filename        Adds the filename to `verilog-library-files'.
+                    This is not recommended, -v is a better choice.
+
+You might want these defined in each file; put at the *END* of your file
+something like:
+
+    // Local Variables:
+    // verilog-library-flags:(\"-y dir -y otherdir\")
+    // End:
+
+Verilog-mode attempts to detect changes to this local variable, but they
+are only insured to be correct when the file is first visited. Thus if you
+have problems, use \\[find-alternate-file] RET to have these take effect.
+
+See also the variables mentioned above."
+  :group 'verilog-mode-auto
+  :type '(repeat string))
+
+(defcustom verilog-library-directories '(".")
+  "*List of directories when looking for files for /*AUTOINST*/.
+The directory may be relative to the current file, or absolute.
+Environment variables are also expanded in the directory names.
+Having at least the current directory is a good idea.
+
+You might want these defined in each file; put at the *END* of your file
+something like:
+
+    // Local Variables:
+    // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
+    // End:
+
+Verilog-mode attempts to detect changes to this local variable, but they
+are only insured to be correct when the file is first visited. Thus if you
+have problems, use \\[find-alternate-file] RET to have these take effect.
+
+See also `verilog-library-flags', `verilog-library-files'
+and `verilog-library-extensions'."
+  :group 'verilog-mode-auto
+  :type '(repeat file))
+
+(defcustom verilog-library-files '()
+  "*List of files to search for modules when looking for AUTOINST files.
+This is a complete path, usually to a technology file with many standard
+cells defined in it.
+
+You might want these defined in each file; put at the *END* of your file
+something like:
+
+    // Local Variables:
+    // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
+    // End:
+
+Verilog-mode attempts to detect changes to this local variable, but they
+are only insured to be correct when the file is first visited. Thus if you
+have problems, use \\[find-alternate-file] RET to have these take effect.
+
+See also `verilog-library-flags', `verilog-library-directories'."
+  :group 'verilog-mode-auto
+  :type '(repeat directory))
+
+(defcustom verilog-library-extensions '(".v")
+  "*List of extensions to use when looking for files for /*AUTOINST*/.
+See also `verilog-library-flags', `verilog-library-directories'."
+  :type '(repeat string)
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-active-low-regexp nil
+  "*If set, treat signals matching this regexp as active low.
+This is used for AUTORESET and AUTOTIEOFF.  For proper behavior,
+you will probably also need `verilog-auto-reset-widths' set."
+  :group 'verilog-mode-auto
+  :type 'string)
+
+(defcustom verilog-auto-sense-include-inputs nil
+  "*If true, AUTOSENSE should include all inputs.
+If nil, only inputs that are NOT output signals in the same block are
+included."
+  :type 'boolean
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-auto-sense-defines-constant nil
+  "*If true, AUTOSENSE should assume all defines represent constants.
+When true, the defines will not be included in sensitivity lists.  To
+maintain compatibility with other sites, this should be set at the bottom
+of each verilog file that requires it, rather than being set globally."
+  :type 'boolean
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-auto-reset-widths t
+  "*If true, AUTORESET should determine the width of signals.
+This is then used to set the width of the zero (32'h0 for example).  This
+is required by some lint tools that aren't smart enough to ignore widths of
+the constant zero.  This may result in ugly code when parameters determine
+the MSB or LSB of a signal inside a AUTORESET."
+  :type 'boolean
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-assignment-delay ""
+  "*Text used for delays in delayed assignments.  Add a trailing space if set."
+  :type 'string
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-auto-inst-vector t
+  "*If true, when creating default ports with AUTOINST, use bus subscripts.
+If nil, skip the subscript when it matches the entire bus as declared in
+the module (AUTOWIRE signals always are subscripted, you must manually
+declare the wire to have the subscripts removed.)  Nil may speed up some
+simulators, but is less general and harder to read, so avoid."
+  :group 'verilog-mode-auto
+  :type 'boolean )
+
+(defcustom verilog-auto-inst-template-numbers nil
+  "*If true, when creating templated ports with AUTOINST, add a comment.
+The comment will add the line number of the template that was used for that
+port declaration.  Setting this aids in debugging, but nil is suggested for
+regular use to prevent large numbers of merge conflicts."
+  :group 'verilog-mode-auto
+  :type 'boolean )
+
+(defvar verilog-auto-inst-column 40
+  "Column number for first part of auto-inst.")
+
+(defcustom verilog-auto-input-ignore-regexp nil
+  "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
+See the \\[verilog-faq] for examples on using this."
+  :group 'verilog-mode-auto
+  :type 'string )
+
+(defcustom verilog-auto-inout-ignore-regexp nil
+  "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
+See the \\[verilog-faq] for examples on using this."
+  :group 'verilog-mode-auto
+  :type 'string )
+
+(defcustom verilog-auto-output-ignore-regexp nil
+  "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
+See the \\[verilog-faq] for examples on using this."
+  :group 'verilog-mode-auto
+  :type 'string )
+
+(defcustom verilog-auto-unused-ignore-regexp nil
+  "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
+See the \\[verilog-faq] for examples on using this."
+  :group 'verilog-mode-auto
+  :type 'string )
+
+(defcustom verilog-typedef-regexp nil
+  "*If non-nil, regular expression that matches Verilog-2001 typedef names.
+For example, \"_t$\" matches typedefs named with _t, as in the C language."
+  :group 'verilog-mode-auto
+  :type 'string )
+
+(defcustom verilog-mode-hook   'verilog-set-compile-command
+  "*Hook (List of functions) run after verilog mode is loaded."
+  :type 'hook
+  :group 'verilog-mode)
+
+(defcustom verilog-auto-hook nil
+  "*Hook run after `verilog-mode' updates AUTOs."
+  :type 'hook
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-before-auto-hook nil
+  "*Hook run before `verilog-mode' updates AUTOs."
+  :type 'hook
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-delete-auto-hook nil
+  "*Hook run after `verilog-mode' deletes AUTOs."
+  :type 'hook
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-before-delete-auto-hook nil
+  "*Hook run before `verilog-mode' deletes AUTOs."
+  :type 'hook
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-getopt-flags-hook nil
+  "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
+  :type 'hook
+  :group 'verilog-mode-auto)
+
+(defcustom verilog-before-getopt-flags-hook nil
+  "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
+  :type 'hook
+  :group 'verilog-mode-auto)
+
+(defvar verilog-imenu-generic-expression
+  '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
+    ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
+  "Imenu expression for Verilog-mode.  See `imenu-generic-expression'.")
+
+;;
+;; provide a verilog-header function.
+;; Customization variables:
+;;
+(defvar verilog-date-scientific-format nil
+  "*If non-nil, dates are written in scientific format (e.g.  1997/09/17).
+If nil, in European format (e.g.  17.09.1997).  The brain-dead American
+format (e.g.  09/17/1997) is not supported.")
+
+(defvar verilog-company nil
+  "*Default name of Company for verilog header.
+If set will become buffer local.")
+
+(defvar verilog-project nil
+  "*Default name of Project for verilog header.
+If set will become buffer local.")
+
+(defvar verilog-mode-map
+  (let ((map (make-sparse-keymap)))
+    (define-key map ";"        'electric-verilog-semi)
+    (define-key map [(control 59)]    'electric-verilog-semi-with-comment)
+    (define-key map ":"        'electric-verilog-colon)
+    ;;(define-key map "="        'electric-verilog-equal)
+    (define-key map "\`"       'electric-verilog-tick)
+    (define-key map "\t"       'electric-verilog-tab)
+    (define-key map "\r"       'electric-verilog-terminate-line)
+    ;; backspace/delete key bindings
+    (define-key map [backspace]    'backward-delete-char-untabify)
+    (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
+      (define-key map [delete]       'delete-char)
+      (define-key map [(meta delete)] 'kill-word))
+    (define-key map "\M-\C-b"  'electric-verilog-backward-sexp)
+    (define-key map "\M-\C-f"  'electric-verilog-forward-sexp)
+    (define-key map "\M-\r"    `electric-verilog-terminate-and-indent)
+    (define-key map "\M-\t"    'verilog-complete-word)
+    (define-key map "\M-?"     'verilog-show-completions)
+    (define-key map [(meta control h)] 'verilog-mark-defun)
+    (define-key map "\C-c\`"   'verilog-lint-off)
+    (define-key map "\C-c\*"   'verilog-delete-auto-star-implicit)
+    (define-key map "\C-c\C-r" 'verilog-label-be)
+    (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
+    (define-key map "\C-c="    'verilog-pretty-expr)
+    (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
+    (define-key map "\M-*"     'verilog-star-comment)
+    (define-key map "\C-c\C-c" 'verilog-comment-region)
+    (define-key map "\C-c\C-u" 'verilog-uncomment-region)
+    (define-key map "\M-\C-a"  'verilog-beg-of-defun)
+    (define-key map "\M-\C-e"  'verilog-end-of-defun)
+    (define-key map "\C-c\C-d" 'verilog-goto-defun)
+    (define-key map "\C-c\C-k" 'verilog-delete-auto)
+    (define-key map "\C-c\C-a" 'verilog-auto)
+    (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
+    (define-key map "\C-c\C-z" 'verilog-inject-auto)
+    (define-key map "\C-c\C-e" 'verilog-expand-vector)
+    (define-key map "\C-c\C-h" 'verilog-header)
+    map)
+  "Keymap used in Verilog mode.")
+
+;; menus
+(defvar verilog-xemacs-menu
+  '("Verilog"
+    ("Choose Compilation Action"
+     ["None"
+      (progn
+	(setq verilog-tool nil)
+	(verilog-set-compile-command))
+      :style radio
+      :selected (equal verilog-tool nil)]
+     ["Lint"
+      (progn
+	(setq verilog-tool 'verilog-linter)
+	(verilog-set-compile-command))
+      :style radio
+      :selected (equal verilog-tool `verilog-linter)]
+     ["Coverage"
+      (progn
+	(setq verilog-tool 'verilog-coverage)
+	(verilog-set-compile-command))
+      :style radio
+      :selected (equal verilog-tool `verilog-coverage)]
+     ["Simulator"
+      (progn
+	(setq verilog-tool 'verilog-simulator)
+	(verilog-set-compile-command))
+      :style radio
+      :selected (equal verilog-tool `verilog-simulator)]
+     ["Compiler"
+      (progn
+	(setq verilog-tool 'verilog-compiler)
+	(verilog-set-compile-command))
+      :style radio
+      :selected (equal verilog-tool `verilog-compiler)]
+     )
+    ("Move"
+     ["Beginning of function"		verilog-beg-of-defun t]
+     ["End of function"			verilog-end-of-defun t]
+     ["Mark function"			verilog-mark-defun t]
+     ["Goto function/module"		verilog-goto-defun t]
+     ["Move to beginning of block"	electric-verilog-backward-sexp t]
+     ["Move to end of block"		electric-verilog-forward-sexp t]
+     )
+    ("Comments"
+     ["Comment Region"			verilog-comment-region t]
+     ["UnComment Region"			verilog-uncomment-region t]
+     ["Multi-line comment insert"	verilog-star-comment t]
+     ["Lint error to comment"		verilog-lint-off t]
+     )
+    "----"
+    ["Compile"				compile t]
+    ["AUTO, Save, Compile"		verilog-auto-save-compile t]
+    ["Next Compile Error"		next-error t]
+    ["Ignore Lint Warning at point"	verilog-lint-off t]
+    "----"
+    ["Line up declarations around point"	verilog-pretty-declarations t]
+    ["Line up equations around point"		verilog-pretty-expr t]
+    ["Redo/insert comments on every end"	verilog-label-be t]
+    ["Expand [x:y] vector line"		verilog-expand-vector t]
+    ["Insert begin-end block"		verilog-insert-block t]
+    ["Complete word"			verilog-complete-word t]
+    "----"
+    ["Recompute AUTOs"			verilog-auto t]
+    ["Kill AUTOs"			verilog-delete-auto t]
+    ["Inject AUTOs"			verilog-inject-auto t]
+    ("AUTO Help..."
+     ["AUTO General"			(describe-function 'verilog-auto) t]
+     ["AUTO Library Flags"		(describe-variable 'verilog-library-flags) t]
+     ["AUTO Library Path"		(describe-variable 'verilog-library-directories) t]
+     ["AUTO Library Files"		(describe-variable 'verilog-library-files) t]
+     ["AUTO Library Extensions"		(describe-variable 'verilog-library-extensions) t]
+     ["AUTO `define Reading"		(describe-function 'verilog-read-defines) t]
+     ["AUTO `include Reading"		(describe-function 'verilog-read-includes) t]
+     ["AUTOARG"				(describe-function 'verilog-auto-arg) t]
+     ["AUTOASCIIENUM"			(describe-function 'verilog-auto-ascii-enum) t]
+     ["AUTOINOUTMODULE"			(describe-function 'verilog-auto-inout-module) t]
+     ["AUTOINOUT"			(describe-function 'verilog-auto-inout) t]
+     ["AUTOINPUT"			(describe-function 'verilog-auto-input) t]
+     ["AUTOINST"			(describe-function 'verilog-auto-inst) t]
+     ["AUTOINST (.*)"			(describe-function 'verilog-auto-star) t]
+     ["AUTOINSTPARAM"			(describe-function 'verilog-auto-inst-param) t]
+     ["AUTOOUTPUT"			(describe-function 'verilog-auto-output) t]
+     ["AUTOOUTPUTEVERY"			(describe-function 'verilog-auto-output-every) t]
+     ["AUTOREG"				(describe-function 'verilog-auto-reg) t]
+     ["AUTOREGINPUT"			(describe-function 'verilog-auto-reg-input) t]
+     ["AUTORESET"			(describe-function 'verilog-auto-reset) t]
+     ["AUTOSENSE"			(describe-function 'verilog-auto-sense) t]
+     ["AUTOTIEOFF"			(describe-function 'verilog-auto-tieoff) t]
+     ["AUTOUNUSED"			(describe-function 'verilog-auto-unused) t]
+     ["AUTOWIRE"			(describe-function 'verilog-auto-wire) t]
+     )
+    "----"
+    ["Submit bug report"		verilog-submit-bug-report t]
+    ["Version and FAQ"			verilog-faq t]
+    ["Customize Verilog Mode..."	verilog-customize t]
+    ["Customize Verilog Fonts & Colors"	verilog-font-customize t]
+    )
+  "Emacs menu for VERILOG mode."
+  )
+(defvar verilog-statement-menu
+  '("Statements"
+    ["Header"		verilog-sk-header  t]
+    ["Comment"		verilog-sk-comment t]
+    "----"
+    ["Module"		verilog-sk-module t]
+    ["Primitive"	verilog-sk-primitive t]
+    "----"
+    ["Input"		verilog-sk-input t]
+    ["Output"		verilog-sk-output t]
+    ["Inout"		verilog-sk-inout t]
+    ["Wire"		verilog-sk-wire t]
+    ["Reg"		verilog-sk-reg t]
+    ["Define thing under point as a register" verilog-sk-define-signal t]
+    "----"
+    ["Initial"		verilog-sk-initial t]
+    ["Always"		verilog-sk-always t]
+    ["Function"		verilog-sk-function t]
+    ["Task"		verilog-sk-task t]
+    ["Specify"		verilog-sk-specify t]
+    ["Generate"		verilog-sk-generate t]
+    "----"
+    ["Begin"		verilog-sk-begin t]
+    ["If"		verilog-sk-if t]
+    ["(if) else"	verilog-sk-else-if t]
+    ["For"		verilog-sk-for t]
+    ["While"		verilog-sk-while t]
+    ["Fork"		verilog-sk-fork t]
+    ["Repeat"		verilog-sk-repeat t]
+    ["Case"		verilog-sk-case t]
+    ["Casex"		verilog-sk-casex t]
+    ["Casez"		verilog-sk-casez t]
+    )
+  "Menu for statement templates in Verilog."
+  )
+
+(easy-menu-define verilog-menu verilog-mode-map "Menu for Verilog mode"
+		  verilog-xemacs-menu)
+(easy-menu-define verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
+		  verilog-statement-menu)
+
+(defvar verilog-mode-abbrev-table nil
+  "Abbrev table in use in Verilog-mode buffers.")
+
+(define-abbrev-table 'verilog-mode-abbrev-table ())
+
+;;
+;;  Macros
+;;
+
+(defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
+  "Replace occurrences of FROM-STRING with TO-STRING.
+FIXEDCASE and LITERAL as in `replace-match`.  STRING is what to replace.
+The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
+will break, as the o's continuously replace.  xa -> x works ok though."
+  ;; Hopefully soon to a emacs built-in
+  (let ((start 0))
+    (while (string-match from-string string start)
+      (setq string (replace-match to-string fixedcase literal string)
+	    start (min (length string) (match-end 0))))
+    string))
+
+(defsubst verilog-string-remove-spaces (string)
+  "Remove spaces surrounding STRING."
+  (save-match-data
+    (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
+    (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
+    string))
+
+(defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
+  ; checkdoc-params: (REGEXP BOUND NOERROR)
+  "Like `re-search-forward', but skips over match in comments or strings."
+  (store-match-data '(nil nil))
+  (while (and
+	  (re-search-forward REGEXP BOUND NOERROR)
+	  (and (verilog-skip-forward-comment-or-string)
+	       (progn
+		 (store-match-data '(nil nil))
+		 (if BOUND
+		     (< (point) BOUND)
+		   t)
+		 ))))
+  (match-end 0))
+
+(defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
+  ; checkdoc-params: (REGEXP BOUND NOERROR)
+  "Like `re-search-backward', but skips over match in comments or strings."
+  (store-match-data '(nil nil))
+  (while (and
+	  (re-search-backward REGEXP BOUND NOERROR)
+	  (and (verilog-skip-backward-comment-or-string)
+	       (progn
+		 (store-match-data '(nil nil))
+		 (if BOUND
+		     (> (point) BOUND)
+		   t)
+		 ))))
+  (match-end 0))
+
+(defsubst verilog-re-search-forward-quick (regexp bound noerror)
+  "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
+but trashes match data and is faster for REGEXP that doesn't match often.
+This may at some point use text properties to ignore comments,
+so there may be a large up front penalty for the first search."
+  (let (pt)
+    (while (and (not pt)
+		(re-search-forward regexp bound noerror))
+      (if (not (verilog-inside-comment-p))
+	  (setq pt (match-end 0))))
+    pt))
+
+(defsubst verilog-re-search-backward-quick (regexp bound noerror)
+  ; checkdoc-params: (REGEXP BOUND NOERROR)
+  "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
+but trashes match data and is faster for REGEXP that doesn't match often.
+This may at some point use text properties to ignore comments,
+so there may be a large up front penalty for the first search."
+  (let (pt)
+    (while (and (not pt)
+		(re-search-backward regexp bound noerror))
+      (if (not (verilog-inside-comment-p))
+	  (setq pt (match-end 0))))
+    pt))
+
+(defsubst verilog-get-beg-of-line (&optional arg)
+  (save-excursion
+    (beginning-of-line arg)
+    (point)))
+
+(defsubst verilog-get-end-of-line (&optional arg)
+  (save-excursion
+    (end-of-line arg)
+    (point)))
+
+(defsubst verilog-within-string ()
+  (save-excursion
+    (nth 3 (parse-partial-sexp (verilog-get-beg-of-line) (point)))))
+
+;; compilation program
+(defun verilog-set-compile-command ()
+  "Function to compute shell command to compile verilog.
+
+This reads `verilog-tool' and sets `compile-command'.  This specifies the
+program that executes when you type \\[compile] or
+\\[verilog-auto-save-compile].
+
+By default `verilog-tool' uses a Makefile if one exists in the current
+directory.  If not, it is set to the `verilog-linter', `verilog-coverage',
+`verilog-simulator', or `verilog-compiler' variables, as selected with the
+Verilog -> \"Choose Compilation Action\" menu.
+
+You should set `verilog-tool' or the other variables to the path and
+arguments for your Verilog simulator.  For example:
+    \"vcs -p123 -O\"
+or a string like:
+    \"(cd /tmp; surecov %s)\".
+
+In the former case, the path to the current buffer is concat'ed to the
+value of `verilog-tool'; in the later, the path to the current buffer is
+substituted for the %s.
+
+Where __FILE__ appears in the string, the buffer-file-name of the current
+buffer, without the directory portion, will be substituted."
+  (interactive)
+  (cond
+   ((or (file-exists-p "makefile")	;If there is a makefile, use it
+	(file-exists-p "Makefile"))
+    (make-local-variable 'compile-command)
+    (setq compile-command "make "))
+   (t
+    (make-local-variable 'compile-command)
+    (setq compile-command
+	  (if verilog-tool
+	      (if (string-match "%s" (eval verilog-tool))
+		  (format (eval verilog-tool) (or buffer-file-name ""))
+		(concat (eval verilog-tool) " " (or buffer-file-name "")))
+	    ""))))
+  (verilog-modify-compile-command))
+
+(defun verilog-modify-compile-command ()
+  "Replace meta-information in `compile-command'.
+Where __FILE__ appears in the string, the current buffer's file-name,
+without the directory portion, will be substituted."
+  (when (and
+	 (stringp compile-command)
+	 (string-match "\\b__FILE__\\b" compile-command))
+    (make-local-variable 'compile-command)
+    (setq compile-command
+	  (verilog-string-replace-matches
+	   "\\b__FILE__\\b" (file-name-nondirectory (buffer-file-name))
+	   t t compile-command))))
+
+(defun verilog-error-regexp-add ()
+  "Add the messages to the `compilation-error-regexp-alist'.
+Called by `compilation-mode-hook'.  This allows \\[next-error] to find the errors."
+  (if (not verilog-error-regexp-add-didit)
+      (progn
+	(setq verilog-error-regexp-add-didit t)
+	(setq-default compilation-error-regexp-alist
+		      (append verilog-error-regexp
+			      (default-value 'compilation-error-regexp-alist)))
+	;; Could be buffer local at this point; maybe also in let; change all three
+	(setq compilation-error-regexp-alist (default-value 'compilation-error-regexp-alist))
+	(set (make-local-variable 'compilation-error-regexp-alist)
+	     (default-value 'compilation-error-regexp-alist))
+	)))
+
+(add-hook 'compilation-mode-hook 'verilog-error-regexp-add)
+
+(defconst verilog-directive-re
+  ;; "`case" "`default" "`define" "`define" "`else" "`endfor" "`endif"
+  ;; "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
+  ;; "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
+  ;; "`time_scale" "`undef" "`while"
+  "\\<`\\(case\\|def\\(ault\\|ine\\(\\)?\\)\\|e\\(lse\\|nd\\(for\\|if\\|protect\\|switch\\|while\\)\\)\\|for\\(mat\\)?\\|i\\(f\\(def\\|ndef\\)?\\|nclude\\)\\|let\\|protect\\|switch\\|time\\(_scale\\|scale\\)\\|undef\\|while\\)\\>")
+
+(defconst verilog-directive-begin
+  "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
+
+(defconst verilog-directive-middle
+  "\\<`\\(else\\|default\\|case\\)\\>")
+
+(defconst verilog-directive-end
+  "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
+
+(defconst verilog-directive-re-1
+  (concat "[ \t]*"  verilog-directive-re))
+
+;;
+;; Regular expressions used to calculate indent, etc.
+;;
+(defconst verilog-symbol-re      "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
+(defconst verilog-case-re        "\\(\\<case[xz]?\\>\\|\\<randcase\\>\\)")
+;; Want to match
+;; aa :
+;; aa,bb :
+;; a[34:32] :
+;; a,
+;;   b :
+
+(defconst verilog-no-indent-begin-re
+  "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
+
+(defconst verilog-ends-re
+  ;; Parenthesis indicate type of keyword found
+  (concat
+   "\\(\\<else\\>\\)\\|"		; 1
+   "\\(\\<if\\>\\)\\|"			; 2
+   "\\(\\<end\\>\\)\\|"			; 3
+   "\\(\\<endcase\\>\\)\\|"		; 4
+   "\\(\\<endfunction\\>\\)\\|"		; 5
+   "\\(\\<endtask\\>\\)\\|"		; 6
+   "\\(\\<endspecify\\>\\)\\|"		; 7
+   "\\(\\<endtable\\>\\)\\|"		; 8
+   "\\(\\<endgenerate\\>\\)\\|"         ; 9
+   "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
+   "\\(\\<endclass\\>\\)\\|"            ; 11
+   "\\(\\<endgroup\\>\\)"               ; 12
+   ))
+
+(defconst verilog-auto-end-comment-lines-re
+  ;; Matches to names in this list cause auto-end-commentation
+  (concat "\\("
+	  verilog-directive-re "\\)\\|\\("
+	  (eval-when-compile
+	    (verilog-regexp-words
+	     `( "begin"
+		"else"
+		"end"
+		"endcase"
+		"endclass"
+		"endclocking"
+		"endgroup"
+		"endfunction"
+		"endmodule"
+		"endprogram"
+		"endprimitive"
+		"endinterface"
+		"endpackage"
+		"endsequence"
+		"endspecify"
+		"endtable"
+		"endtask"
+		"join"
+		"join_any"
+		"join_none"
+		"module"
+		"macromodule"
+		"primitive"
+		"interface"
+		"package")))
+	  "\\)"))
+
+;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
+;;; verilog-end-block-ordered-re matches exactly the same strings.
+(defconst verilog-end-block-ordered-re
+  ;; Parenthesis indicate type of keyword found
+  (concat "\\(\\<endcase\\>\\)\\|" ; 1
+	  "\\(\\<end\\>\\)\\|"     ; 2
+	  "\\(\\<end"              ; 3, but not used
+	  "\\("                    ; 4, but not used
+	  "\\(function\\)\\|"      ; 5
+	  "\\(task\\)\\|"          ; 6
+	  "\\(module\\)\\|"        ; 7
+	  "\\(primitive\\)\\|"     ; 8
+	  "\\(interface\\)\\|"     ; 9
+	  "\\(package\\)\\|"       ; 10
+	  "\\(class\\)\\|"         ; 11
+          "\\(group\\)\\|"         ; 12
+          "\\(program\\)\\|"	   ; 13
+          "\\(sequence\\)\\|"	   ; 14
+	  "\\(clocking\\)\\|"      ; 15
+	  "\\)\\>\\)"))
+(defconst verilog-end-block-re
+  (eval-when-compile
+    (verilog-regexp-words
+
+     `("end"  ;; closes begin
+       "endcase" ;; closes any of case, casex casez or randcase
+       "join" "join_any" "join_none" ;; closes fork
+       "endclass"
+       "endtable"
+       "endspecify"
+       "endfunction"
+       "endgenerate"
+       "endtask"
+       "endgroup"
+       "endproperty"
+       "endinterface"
+       "endpackage"
+       "endprogram"
+       "endsequence"
+       "endclocking"
+       )
+     )))
+
+
+(defconst verilog-endcomment-reason-re
+  ;; Parenthesis indicate type of keyword found
+  (concat
+   "\\(\\<fork\\>\\)\\|"
+   "\\(\\<begin\\>\\)\\|"
+   "\\(\\<if\\>\\)\\|"
+   "\\(\\<clocking\\>\\)\\|"
+   "\\(\\<else\\>\\)\\|"
+   "\\(\\<end\\>.*\\<else\\>\\)\\|"
+   "\\(\\<task\\>\\)\\|"
+   "\\(\\<function\\>\\)\\|"
+   "\\(\\<initial\\>\\)\\|"
+   "\\(\\<interface\\>\\)\\|"
+   "\\(\\<package\\>\\)\\|"
+   "\\(\\<final\\>\\)\\|"
+   "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
+   "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|"
+   "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|"
+   "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|"
+   "\\(@\\)\\|"
+   "\\(\\<while\\>\\)\\|"
+   "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
+   "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
+   "#"))
+
+(defconst verilog-named-block-re  "begin[ \t]*:")
+
+;; These words begin a block which can occur inside a module which should be indented,
+;; and closed with the respective word from the end-block list
+
+(defconst verilog-beg-block-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `("begin"
+       "case" "casex" "casez" "randcase"
+       "clocking"
+       "generate"
+       "fork"
+       "function"
+       "property"
+       "specify"
+       "table"
+       "task"
+       ))))
+;; These are the same words, in a specific order in the regular
+;; expression so that matching will work nicely for
+;; verilog-forward-sexp and verilog-calc-indent
+
+(defconst verilog-beg-block-re-ordered
+  ( concat "\\<"
+	   "\\(begin\\)"		;1
+	   "\\|\\(randcase\\|\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?\\)" ; 2
+;;	   "\\|\\(randcase\\|case[xz]?\\)" ; 2
+	   "\\|\\(fork\\)"		;3
+	   "\\|\\(class\\)"		;4
+	   "\\|\\(table\\)"		;5
+	   "\\|\\(specify\\)"		;6
+	   "\\|\\(function\\)"		;7
+	   "\\|\\(task\\)"		;8
+	   "\\|\\(generate\\)"		;9
+	   "\\|\\(covergroup\\)"	;10
+	   "\\|\\(property\\)"		;11
+	   "\\|\\(\\(rand\\)?sequence\\)"  ;12
+	   "\\|\\(clocking\\)"          ;13
+	   "\\>"))
+
+(defconst verilog-end-block-ordered-rry
+  [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
+    "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
+    "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
+    "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
+    "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
+    "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
+    "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
+    "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
+    "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
+    "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
+    "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
+    "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
+    "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
+    ] )
+
+(defconst verilog-nameable-item-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `("begin"
+       "fork"
+       "join" "join_any" "join_none"
+       "end"
+       "endcase"
+       "endconfig"
+       "endclass"
+       "endclocking"
+       "endfunction"
+       "endgenerate"
+       "endmodule"
+       "endprimative"
+       "endinterface"
+       "endpackage"
+       "endspecify"
+       "endtable"
+       "endtask" )
+     )))
+
+(defconst verilog-declaration-opener
+  (eval-when-compile
+    (verilog-regexp-words
+     `("module" "begin" "task" "function"))))
+
+(defconst verilog-declaration-prefix-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `(
+       ;; port direction
+       "inout" "input" "output" "ref"
+       ;; changeableness
+       "const" "static" "protected" "local"
+       ;; parameters
+       "localparam" "parameter" "var"
+       ;; type creation
+       "typedef"
+       ))))
+(defconst verilog-declaration-core-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `(
+       ;; integer_atom_type
+       "byte" "shortint" "int" "longint" "integer" "time"
+       ;; integer_vector_type
+       "bit" "logic" "reg"
+       ;; non_integer_type
+       "shortreal" "real" "realtime"
+       ;; net_type
+       "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
+       ;; misc
+       "string" "event" "chandle" "virtual" "enum" "genvar"
+       "struct" "union"
+       ;; builtin classes
+       "mailbox" "semaphore"
+       ))))
+(defconst verilog-declaration-re
+  (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
+(defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
+(defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
+(defconst verilog-optional-signed-range-re
+  (concat
+   "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
+(defconst verilog-macroexp-re "`\\sw+")
+
+(defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
+(defconst verilog-declaration-re-2-no-macro
+  (concat "\\s-*" verilog-declaration-re
+	  "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
+	  "\\)?"))
+(defconst verilog-declaration-re-2-macro
+  (concat "\\s-*" verilog-declaration-re
+	  "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
+	  "\\|\\(" verilog-macroexp-re "\\)"
+	  "\\)?"))
+(defconst verilog-declaration-re-1-macro
+  (concat "^" verilog-declaration-re-2-macro))
+
+(defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
+
+(defconst verilog-defun-re
+  (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
+(defconst verilog-end-defun-re
+  (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
+(defconst verilog-zero-indent-re
+  (concat verilog-defun-re "\\|" verilog-end-defun-re))
+
+(defconst verilog-behavioral-block-beg-re
+  (concat "\\(\\<initial\\>\\|\\<final\\>\\|\\<always\\>\\|\\<always_comb\\>\\|\\<always_ff\\>\\|"
+	  "\\<always_latch\\>\\|\\<function\\>\\|\\<task\\>\\)"))
+
+(defconst verilog-indent-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `(
+       "{"
+       "always" "always_latch" "always_ff" "always_comb"
+       "begin" "end"
+;       "unique" "priority"
+       "case" "casex" "casez" "randcase" "endcase"
+       "class" "endclass"
+       "clocking" "endclocking"
+       "config" "endconfig"
+       "covergroup" "endgroup"
+       "fork" "join" "join_any" "join_none"
+       "function" "endfunction"
+       "final"
+       "generate" "endgenerate"
+       "initial"
+       "interface" "endinterface"
+       "module" "macromodule" "endmodule"
+       "package" "endpackage"
+       "primitive" "endprimative"
+       "program" "endprogram"
+       "property" "endproperty"
+       "sequence" "randsequence" "endsequence"
+       "specify" "endspecify"
+       "table" "endtable"
+       "task" "endtask"
+       "`case"
+       "`default"
+       "`define" "`undef"
+       "`if" "`ifdef" "`ifndef" "`else" "`endif"
+       "`while" "`endwhile"
+       "`for" "`endfor"
+       "`format"
+       "`include"
+       "`let"
+       "`protect" "`endprotect"
+       "`switch" "`endswitch"
+       "`timescale"
+       "`time_scale"
+       ))))
+
+(defconst verilog-defun-level-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `(
+       "module" "macromodule" "primitive" "class" "program" "initial" "final" "always" "always_comb"
+       "always_ff" "always_latch" "endtask" "endfunction" "interface" "package"
+       "config"))))
+
+(defconst verilog-defun-level-not-generate-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `(
+       "module" "macromodule" "primitive" "class" "program" "interface" "package" "config"))))
+
+(defconst verilog-cpp-level-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `(
+       "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
+       ))))
+(defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
+(defconst verilog-extended-complete-re
+  (concat "\\(\\<extern\\s-+\\|\\<virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
+	  "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
+	  "\\|" verilog-extended-case-re ))
+(defconst verilog-basic-complete-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `(
+       "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
+       "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
+       "if" "for" "forever" "foreach" "else" "parameter" "do"
+       ))))
+(defconst verilog-complete-reg
+  (concat
+   verilog-extended-complete-re
+   "\\|"
+   verilog-basic-complete-re))
+
+(defconst verilog-end-statement-re
+  (concat "\\(" verilog-beg-block-re "\\)\\|\\("
+	  verilog-end-block-re "\\)"))
+
+(defconst verilog-endcase-re
+  (concat verilog-case-re "\\|"
+	  "\\(endcase\\)\\|"
+	  verilog-defun-re
+	  ))
+
+(defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
+  "String used to mark beginning of excluded text.")
+(defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
+  "String used to mark end of excluded text.")
+(defconst verilog-preprocessor-re
+  (eval-when-compile
+    (verilog-regexp-words
+     `(
+       "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
+       ))))
+
+(defconst verilog-keywords
+  '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
+     "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
+     "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
+     "`time_scale" "`undef" "`while"
+
+     "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
+     "assert" "assign" "assume" "automatic" "before" "begin" "bind"
+     "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
+     "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
+     "config" "const" "constraint" "context" "continue" "cover"
+     "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
+     "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
+     "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
+     "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
+     "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
+     "endtask" "enum" "event" "expect" "export" "extends" "extern"
+     "final" "first_match" "for" "force" "foreach" "forever" "fork"
+     "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
+     "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
+     "include" "initial" "inout" "input" "inside" "instance" "int"
+     "integer" "interface" "intersect" "join" "join_any" "join_none"
+     "large" "liblist" "library" "local" "localparam" "logic"
+     "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
+     "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
+     "notif0" "notif1" "null" "or" "output" "package" "packed"
+     "parameter" "pmos" "posedge" "primitive" "priority" "program"
+     "property" "protected" "pull0" "pull1" "pulldown" "pullup"
+     "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
+     "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
+     "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
+     "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
+     "showcancelled" "signed" "small" "solve" "specify" "specparam"
+     "static" "string" "strong0" "strong1" "struct" "super" "supply0"
+     "supply1" "table" "tagged" "task" "this" "throughout" "time"
+     "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
+     "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
+     "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
+     "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
+     "wire" "with" "within" "wor" "xnor" "xor"
+ )
+ "List of Verilog keywords.")
+
+
+(defconst verilog-emacs-features
+  ;; Documentation at the bottom
+  (let ((major (and (boundp 'emacs-major-version)
+		    emacs-major-version))
+	(minor (and (boundp 'emacs-minor-version)
+		    emacs-minor-version))
+	flavor comments flock-syntax)
+    ;; figure out version numbers if not already discovered
+    (and (or (not major) (not minor))
+	 (string-match "\\([0-9]+\\).\\([0-9]+\\)" emacs-version)
+	 (setq major (string-to-int (substring emacs-version
+					       (match-beginning 1)
+					       (match-end 1)))
+	       minor (string-to-int (substring emacs-version
+					       (match-beginning 2)
+					       (match-end 2)))))
+    (if (not (and major minor))
+	(error "Cannot figure out the major and minor version numbers"))
+    ;; calculate the major version
+    (cond
+     ((= major 4)  (setq major 'v18))	;Epoch 4
+     ((= major 18) (setq major 'v18))	;Emacs 18
+     ((= major 19) (setq major 'v19	;Emacs 19
+			 flavor (if (or (string-match "Lucid" emacs-version)
+					(string-match "XEmacs" emacs-version))
+				    'XEmacs 'FSF)))
+     ((> major 19) (setq major 'v20
+			 flavor (if (or (string-match "Lucid" emacs-version)
+					(string-match "XEmacs" emacs-version))
+				    'XEmacs 'FSF)))
+     ;; I don't know
+     (t (error "Cannot recognize major version number: %s" major)))
+    ;; XEmacs 19 uses 8-bit modify-syntax-entry flags, as do all
+    ;; patched Emacs 19, Emacs 18, Epoch 4's.  Only Emacs 19 uses a
+    ;; 1-bit flag.  Let's be as smart as we can about figuring this
+    ;; out.
+    (if (or (eq major 'v20) (eq major 'v19))
+	(let ((table (copy-syntax-table)))
+	  (modify-syntax-entry ?a ". 12345678" table)
+	  (cond
+	   ;; XEmacs pre 20 and Emacs pre 19.30 use vectors for syntax tables.
+	   ((vectorp table)
+	    (if (= (logand (lsh (aref table ?a) -16) 255) 255)
+		(setq comments '8-bit)
+	      (setq comments '1-bit)))
+	   ;; XEmacs 20 is known to be 8-bit
+	   ((eq flavor 'XEmacs) (setq comments '8-bit))
+	   ;; Emacs 19.30 and beyond are known to be 1-bit
+	   ((eq flavor 'FSF) (setq comments '1-bit))
+	   ;; Don't know what this is
+	   (t (error "Couldn't figure out syntax table format"))
+	   ))
+      ;; Emacs 18 has no support for dual comments
+      (setq comments 'no-dual-comments))
+    ;; determine whether to use old or new font lock syntax
+    ;; We can assume 8-bit syntax table emacsen support new syntax, otherwise
+    ;; look for version > 19.30
+    (setq flock-syntax
+        (if (or (equal comments '8-bit)
+                (equal major 'v20)
+                (and (equal major 'v19) (> minor 30)))
+            'flock-syntax-after-1930
+          'flock-syntax-before-1930))
+    ;; lets do some minimal sanity checking.
+    (if (or
+	 ;; Emacs before 19.6 had bugs
+	 (and (eq major 'v19) (eq flavor 'XEmacs) (< minor 6))
+	 ;; Emacs 19 before 19.21 has known bugs
+	 (and (eq major 'v19) (eq flavor 'FSF) (< minor 21))
+	 )
+	(with-output-to-temp-buffer "*verilog-mode warnings*"
+	  (print (format
+  "The version of Emacs that you are running, %s,
+has known bugs in its syntax parsing routines which will affect the
+performance of verilog-mode. You should strongly consider upgrading to the
+latest available version.  verilog-mode may continue to work, after a
+fashion, but strange indentation errors could be encountered."
+		     emacs-version))))
+    ;; Emacs 18, with no patch is not too good
+    (if (and (eq major 'v18) (eq comments 'no-dual-comments))
+	(with-output-to-temp-buffer "*verilog-mode warnings*"
+	  (print (format
+  "The version of Emacs 18 you are running, %s,
+has known deficiencies in its ability to handle the dual verilog
+\(and C++) comments, (e.g. the // and /* */ comments). This will
+not be much of a problem for you if you only use the /* */ comments,
+but you really should strongly consider upgrading to one of the latest
+Emacs 19's.  In Emacs 18, you may also experience performance degradations.
+Emacs 19 has some new built-in routines which will speed things up for you.
+Because of these inherent problems, verilog-mode is not supported
+on emacs-18."
+			    emacs-version))))
+    ;; Emacs 18 with the syntax patches are no longer supported
+    (if (and (eq major 'v18) (not (eq comments 'no-dual-comments)))
+	(with-output-to-temp-buffer "*verilog-mode warnings*"
+	  (print (format
+  "You are running a syntax patched Emacs 18 variant.  While this should
+work for you, you may want to consider upgrading to Emacs 19.
+The syntax patches are no longer supported either for verilog-mode."))))
+    (list major comments flock-syntax))
+  "A list of features extant in the Emacs you are using.
+There are many flavors of Emacs out there, each with different
+features supporting those needed by `verilog-mode'.  Here's the current
+supported list, along with the values for this variable:
+
+ Vanilla Emacs 18/Epoch 4:   (v18 no-dual-comments flock-syntax-before-1930)
+ Emacs 18/Epoch 4 (patch2):  (v18 8-bit flock-syntax-after-1930)
+ XEmacs (formerly Lucid) 19: (v19 8-bit flock-syntax-after-1930)
+ XEmacs 20:                  (v20 8-bit flock-syntax-after-1930)
+ Emacs 19.1-19.30:           (v19 8-bit flock-syntax-before-1930)
+ Emacs 19.31-19.xx:          (v19 8-bit flock-syntax-after-1930)
+ Emacs20        :            (v20 1-bit flock-syntax-after-1930).")
+
+(defconst verilog-comment-start-regexp "//\\|/\\*"
+  "Dual comment value for `comment-start-regexp'.")
+
+(defun verilog-populate-syntax-table (table)
+  "Populate the syntax TABLE."
+  (modify-syntax-entry ?\\ "\\" table)
+  (modify-syntax-entry ?+ "." table)
+  (modify-syntax-entry ?- "." table)
+  (modify-syntax-entry ?= "." table)
+  (modify-syntax-entry ?% "." table)
+  (modify-syntax-entry ?< "." table)
+  (modify-syntax-entry ?> "." table)
+  (modify-syntax-entry ?& "." table)
+  (modify-syntax-entry ?| "." table)
+  (modify-syntax-entry ?` "w" table)
+  (modify-syntax-entry ?_ "w" table)
+  (modify-syntax-entry ?\' "." table)
+)
+
+(defun verilog-setup-dual-comments (table)
+  "Set up TABLE to handle block and line style comments."
+  (cond
+   ((memq '8-bit verilog-emacs-features)
+    ;; XEmacs (formerly Lucid) has the best implementation
+    (modify-syntax-entry ?/  ". 1456" table)
+    (modify-syntax-entry ?*  ". 23"   table)
+    (modify-syntax-entry ?\n "> b"    table)
+    )
+   ((memq '1-bit verilog-emacs-features)
+    ;; Emacs 19 does things differently, but we can work with it
+    (modify-syntax-entry ?/  ". 124b" table)
+    (modify-syntax-entry ?*  ". 23"   table)
+    (modify-syntax-entry ?\n "> b"    table)
+    )
+   ))
+
+(defvar verilog-mode-syntax-table nil
+  "Syntax table used in `verilog-mode' buffers.")
+
+(defconst verilog-font-lock-keywords nil
+  "Default highlighting for Verilog mode.")
+
+(defconst verilog-font-lock-keywords-1 nil
+  "Subdued level highlighting for Verilog mode.")
+
+(defconst verilog-font-lock-keywords-2 nil
+  "Medium level highlighting for Verilog mode.
+See also `verilog-font-lock-extra-types'.")
+
+(defconst verilog-font-lock-keywords-3 nil
+  "Gaudy level highlighting for Verilog mode.
+See also `verilog-font-lock-extra-types'.")
+(defvar  verilog-font-lock-translate-off-face
+  'verilog-font-lock-translate-off-face
+  "Font to use for translated off regions.")
+(defface verilog-font-lock-translate-off-face
+  '((((class color)
+      (background light))
+     (:background "gray90" :italic t ))
+    (((class color)
+      (background dark))
+     (:background "gray10" :italic t ))
+    (((class grayscale) (background light))
+     (:foreground "DimGray" :italic t))
+    (((class grayscale) (background dark))
+     (:foreground "LightGray" :italic t))
+    (t (:italis t)))
+  "Font lock mode face used to background highlight translate-off regions."
+  :group 'font-lock-highlighting-faces)
+
+(defvar verilog-font-lock-p1800-face
+  'verilog-font-lock-p1800-face
+  "Font to use for p1800 keywords.")
+(defface verilog-font-lock-p1800-face
+  '((((class color)
+      (background light))
+     (:foreground "DarkOrange3" :bold t ))
+    (((class color)
+      (background dark))
+     (:foreground "orange1" :bold t ))
+    (t (:italic t)))
+  "Font lock mode face used to highlight P1800 keywords."
+  :group 'font-lock-highlighting-faces)
+
+(defvar verilog-font-lock-ams-face
+  'verilog-font-lock-ams-face
+  "Font to use for Analog/Mixed Signal keywords.")
+(defface verilog-font-lock-ams-face
+  '((((class color)
+      (background light))
+     (:foreground "Purple" :bold t ))
+    (((class color)
+      (background dark))
+     (:foreground "orange1" :bold t ))
+    (t (:italic t)))
+  "Font lock mode face used to highlight AMS keywords."
+  :group 'font-lock-highlighting-faces)
+
+(let* ((verilog-type-font-keywords
+	(eval-when-compile
+	  (verilog-regexp-opt
+	   '(
+	     "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
+	     "event" "genvar" "inout" "input" "integer" "localparam"
+	     "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
+	     "output" "parameter" "pmos" "pull0" "pull1" "pullup"
+	     "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
+	     "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
+	     "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
+	     "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
+	     "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
+	     ) nil  )))
+
+       (verilog-pragma-keywords
+	(eval-when-compile
+	  (verilog-regexp-opt
+	   '("surefire" "synopsys" "rtl_synthesis" "verilint" ) nil
+	    )))
+
+       (verilog-p1800-keywords
+	(eval-when-compile
+	  (verilog-regexp-opt
+	   '("alias" "assert" "assume" "automatic" "before" "bind"
+	     "bins" "binsof" "break" "byte" "cell" "chandle" "class"
+	     "clocking" "config" "const" "constraint" "context" "continue"
+	     "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
+	     "dist" "do" "edge" "endclass" "endclocking" "endconfig"
+	     "endgroup" "endprogram" "endproperty" "endsequence" "enum"
+	     "expect" "export" "extends" "extern" "first_match" "foreach"
+	     "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
+	     "illegal_bins" "import" "incdir" "include" "inside" "instance"
+	     "int" "intersect" "large" "liblist" "library" "local" "longint"
+	     "matches" "medium" "modport" "new" "noshowcancelled" "null"
+	     "packed" "program" "property" "protected" "pull0" "pull1"
+	     "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
+	     "randcase" "randsequence" "ref" "release" "return" "scalared"
+	     "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
+	     "specparam" "static" "string" "strong0" "strong1" "struct"
+	     "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
+	     "type" "union" "unsigned" "use" "var" "virtual" "void"
+	     "wait_order" "weak0" "weak1" "wildcard" "with" "within"
+	     ) nil )))
+
+       (verilog-ams-keywords
+	(eval-when-compile
+	  (verilog-regexp-opt
+	   '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
+	     "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
+	     "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
+	     "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
+	     "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
+	     "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
+	     "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
+	     "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
+	     "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
+	     "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
+	     "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
+
+       (verilog-font-keywords
+	(eval-when-compile
+	  (verilog-regexp-opt
+	   '(
+	     "assign" "begin" "case" "casex" "casez" "randcase" "deassign"
+	     "default" "disable" "else" "end" "endcase" "endfunction"
+	     "endgenerate" "endinterface" "endmodule" "endprimitive"
+	     "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
+	     "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
+	     "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
+	     "package" "endpackage" "always" "always_comb" "always_ff"
+	     "always_latch" "posedge" "primitive" "priority" "release"
+	     "repeat" "specify" "table" "task" "unique" "wait" "while"
+	     "class" "program" "endclass" "endprogram"
+	     ) nil  ))))
+
+  (setq verilog-font-lock-keywords
+	(list
+	 ;; Fontify all builtin keywords
+	 (concat "\\<\\(" verilog-font-keywords "\\|"
+		       ;; And user/system tasks and functions
+		       "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
+		       "\\)\\>")
+	 ;; Fontify all types
+	 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
+	       'font-lock-type-face)
+	 ;; Fontify IEEE-P1800 keywords appropriately
+	 (if verilog-highlight-p1800-keywords
+	     (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
+		   'verilog-font-lock-p1800-face)
+	   (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
+		 'font-lock-type-face))
+	 ;; Fontify Verilog-AMS keywords
+	 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
+	       'verilog-font-lock-ams-face)
+	 ))
+
+  (setq verilog-font-lock-keywords-1
+	(append verilog-font-lock-keywords
+		(list
+		 ;; Fontify module definitions
+		 (list
+		  "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
+		  '(1 font-lock-keyword-face)
+		  '(3 font-lock-function-name-face 'prepend))
+		 ;; Fontify function definitions
+		 (list
+		  (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
+		       '(1 font-lock-keyword-face)
+		       '(3 font-lock-reference-face prepend)
+		       )
+		 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
+		   (1 font-lock-keyword-face)
+		   (2 font-lock-reference-face append)
+		   )
+		 '("\\<function\\>\\s-+\\(\\sw+\\)"
+		   1 'font-lock-reference-face append)
+		 )))
+
+  (setq verilog-font-lock-keywords-2
+	(append verilog-font-lock-keywords-1
+		(list
+		 ;; Fontify pragmas
+		 (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
+		 ;; Fontify escaped names
+		 '("\\(\\\\\\S-*\\s-\\)"  0 font-lock-function-name-face)
+		 ;; Fontify macro definitions/ uses
+		 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
+						       'font-lock-preprocessor-face
+						     'font-lock-type-face))
+		 ;; Fontify delays/numbers
+		 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
+		   0 font-lock-type-face append)
+		 ;; Fontify instantiation names
+		 '("\\([A-Za-z][A-Za-z0-9_]+\\)\\s-*(" 1 font-lock-function-name-face)
+
+		 )))
+
+  (setq verilog-font-lock-keywords-3
+	(append verilog-font-lock-keywords-2
+		(when verilog-highlight-translate-off
+		  (list
+		   ;; Fontify things in translate off regions
+		   '(verilog-match-translate-off (0 'verilog-font-lock-translate-off-face prepend))
+		   )))
+  )
+  )
+
+
+
+(defun verilog-inside-comment-p ()
+  "Check if point inside a nested comment."
+  (save-excursion
+    (let ((st-point (point)) hitbeg)
+      (or (search-backward "//" (verilog-get-beg-of-line) t)
+	  (if (progn
+		;; This is for tricky case //*, we keep searching if /* is proceeded by // on same line
+		(while (and (setq hitbeg (search-backward "/*" nil t))
+			    (progn (forward-char 1) (search-backward "//" (verilog-get-beg-of-line) t))))
+		hitbeg)
+	      (not (search-forward "*/" st-point t)))))))
+
+(defun verilog-declaration-end ()
+  (search-forward ";"))
+
+(defun verilog-point-text (&optional pointnum)
+  "Return text describing where POINTNUM or current point is (for errors).
+Use filename, if current buffer being edited shorten to just buffer name."
+  (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
+		   (buffer-name))
+	      buffer-file-name
+	      (buffer-name))
+	  ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
+
+(defun electric-verilog-backward-sexp ()
+  "Move backward over a sexp."
+  (interactive)
+  ;; before that see if we are in a comment
+  (verilog-backward-sexp)
+)
+(defun electric-verilog-forward-sexp ()
+  "Move backward over a sexp."
+  (interactive)
+  ;; before that see if we are in a comment
+  (verilog-forward-sexp)
+)
+;;;used by hs-minor-mode
+(defun verilog-forward-sexp-function (arg)
+  (if (< arg 0)
+      (verilog-backward-sexp)
+    (verilog-forward-sexp)))
+
+
+(defun verilog-backward-sexp ()
+  (let ((reg)
+	(elsec 1)
+	(found nil)
+	(st (point))
+	)
+    (if (not (looking-at "\\<"))
+	(forward-word -1))
+    (cond
+     ((verilog-skip-backward-comment-or-string)
+      )
+     ((looking-at "\\<else\\>")
+      (setq reg (concat
+		 verilog-end-block-re
+		 "\\|\\(\\<else\\>\\)"
+		 "\\|\\(\\<if\\>\\)"
+		 ))
+      (while (and (not found)
+		  (verilog-re-search-backward reg nil 'move))
+	(cond
+	 ((match-end 1) ; matched verilog-end-block-re
+	; try to leap back to matching outward block by striding across
+	; indent level changing tokens then immediately
+	; previous line governs indentation.
+	  (verilog-leap-to-head))
+	 ((match-end 2) ; else, we're in deep
+	  (setq elsec (1+ elsec)))
+	 ((match-end 3) ; found it
+	  (setq elsec (1- elsec))
+	  (if (= 0 elsec)
+	      ;; Now previous line describes syntax
+	      (setq found 't)
+	    ))
+	 )
+	)
+      )
+     ((looking-at verilog-end-block-re)
+      (verilog-leap-to-head))
+     ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
+      (cond
+       ((match-end 1)
+	(verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
+       ((match-end 2)
+	(verilog-re-search-backward "\\<primitive\\>" nil 'move))
+       ((match-end 3)
+	(verilog-re-search-backward "\\<class\\>" nil 'move))
+       ((match-end 4)
+	(verilog-re-search-backward "\\<program\\>" nil 'move))
+       ((match-end 5)
+	(verilog-re-search-backward "\\<interface\\>" nil 'move))
+       ((match-end 6)
+	(verilog-re-search-backward "\\<package\\>" nil 'move))
+       (t
+	(goto-char st)
+	(backward-sexp 1))))
+     (t
+      (goto-char st)
+      (backward-sexp))
+     ) ;; cond
+    ))
+
+(defun verilog-forward-sexp ()
+  (let ((reg)
+	(md 2)
+	(st (point)))
+    (if (not (looking-at "\\<"))
+	(forward-word -1))
+    (cond
+     ((verilog-skip-forward-comment-or-string)
+      (verilog-forward-syntactic-ws)
+      )
+     ((looking-at verilog-beg-block-re-ordered);; begin|case|fork|class|table|specify|function|task|generate|covergroup|property|sequence|clocking
+      (cond
+       ((match-end 1) ; end
+	;; Search forward for matching begin
+	(setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
+       ((match-end 2) ; endcase
+	;; Search forward for matching case
+	(setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
+	)
+       ((match-end 3) ; join
+	;; Search forward for matching fork
+	(setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
+       ((match-end 4) ; endclass
+	;; Search forward for matching class
+	(setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
+       ((match-end 5) ; endtable
+	;; Search forward for matching table
+	(setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
+       ((match-end 6) ; endspecify
+	;; Search forward for matching specify
+	(setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
+       ((match-end 7) ; endfunction
+	;; Search forward for matching function
+	(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
+       ((match-end 8) ; endtask
+	;; Search forward for matching task
+	(setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
+       ((match-end 9) ; endgenerate
+	;; Search forward for matching generate
+	(setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
+       ((match-end 10) ; endgroup
+	;; Search forward for matching covergroup
+	(setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
+       ((match-end 11) ; endproperty
+	;; Search forward for matching property
+	(setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
+       ((match-end 12) ; endsequence
+	;; Search forward for matching sequence
+	(setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
+	(setq md 3) ; 3 to get to endsequence in the reg above
+	)
+       ((match-end 13) ; endclocking
+	;; Search forward for matching clocking
+	(setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" ))
+       )
+      (if (forward-word 1)
+	  (catch 'skip
+	    (let ((nest 1))
+	      (while (verilog-re-search-forward reg nil 'move)
+		(cond
+		 ((match-end md) ; the closer in reg, so we are climbing out
+		  (setq nest (1- nest))
+		  (if (= 0 nest) ; we are out!
+		      (throw 'skip 1)))
+		 ((match-end 1) ; the opener in reg, so we are deeper now
+		  (setq nest (1+ nest)))))
+	      )))
+      )
+     ((looking-at (concat
+		   "\\(\\<\\(macro\\)?module\\>\\)\\|"
+		   "\\(\\<primitive\\>\\)\\|"
+		   "\\(\\<class\\>\\)\\|"
+		   "\\(\\<program\\>\\)\\|"
+		   "\\(\\<interface\\>\\)\\|"
+		   "\\(\\<package\\>\\)"))
+      (cond
+       ((match-end 1)
+	(verilog-re-search-forward "\\<endmodule\\>" nil 'move))
+       ((match-end 2)
+	(verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
+       ((match-end 3)
+	(verilog-re-search-forward "\\<endclass\\>" nil 'move))
+       ((match-end 4)
+	(verilog-re-search-forward "\\<endprogram\\>" nil 'move))
+       ((match-end 5)
+	(verilog-re-search-forward "\\<endinterface\\>" nil 'move))
+       ((match-end 6)
+	(verilog-re-search-forward "\\<endpackage\\>" nil 'move))
+       (t
+	(goto-char st)
+	(if (= (following-char) ?\) )
+	    (forward-char 1)
+	  (forward-sexp 1)))))
+     (t
+      (goto-char st)
+      (if (= (following-char) ?\) )
+	  (forward-char 1)
+	(forward-sexp 1)))
+     ) ;; cond
+    ))
+
+(defun verilog-declaration-beg ()
+  (verilog-re-search-backward verilog-declaration-re (bobp) t))
+
+(require 'font-lock)
+(defvar verilog-need-fld 1)
+(defvar font-lock-defaults-alist nil)	;In case we are XEmacs
+
+(defun verilog-font-lock-init ()
+  "Initialize fontification."
+  ;; highlight keywords and standardized types, attributes, enumeration
+  ;; values, and subprograms
+  (setq verilog-font-lock-keywords-3
+	(append verilog-font-lock-keywords-2
+		(when verilog-highlight-translate-off
+		  (list
+		   ;; Fontify things in translate off regions
+		   '(verilog-match-translate-off (0 'verilog-font-lock-translate-off-face prepend))
+		   ))
+	)
+  )
+  (put 'verilog-mode 'font-lock-defaults
+       '((verilog-font-lock-keywords
+	  verilog-font-lock-keywords-1
+	  verilog-font-lock-keywords-2
+	  verilog-font-lock-keywords-3
+	  )
+	 nil ;; nil means highlight strings & comments as well as keywords
+	 nil ;; nil means keywords must match case
+	 nil ;; syntax table handled elsewhere
+	 verilog-beg-of-defun ;; function to move to beginning of reasonable region to highlight
+	 ))
+  (if verilog-need-fld
+      (let ((verilog-mode-defaults
+	     '((verilog-font-lock-keywords
+		verilog-font-lock-keywords-1
+		verilog-font-lock-keywords-2
+		verilog-font-lock-keywords-3
+		)
+	       nil ;; nil means highlight strings & comments as well as keywords
+	       nil ;; nil means keywords must match case
+	       nil ;; syntax table handled elsewhere
+	       verilog-beg-of-defun ;; function to move to beginning of reasonable region to highlight
+	       )))
+	(setq font-lock-defaults-alist
+	      (append
+	       font-lock-defaults-alist
+	       (list (cons 'verilog-mode  verilog-mode-defaults))))
+	(setq verilog-need-fld 0))))
+
+;; initialize fontification for Verilog Mode
+(verilog-font-lock-init)
+;; start up message
+(defconst verilog-startup-message-lines
+  '("Please use \\[verilog-submit-bug-report] to report bugs."
+    "Visit http://www.verilog.com to check for updates"
+    ))
+(defconst verilog-startup-message-displayed t)
+(defun verilog-display-startup-message ()
+  (if (not verilog-startup-message-displayed)
+      (if (sit-for 5)
+	  (let ((lines verilog-startup-message-lines))
+	    (message "verilog-mode version %s, released %s; type \\[describe-mode] for help"
+		     verilog-mode-version verilog-mode-release-date)
+	    (setq verilog-startup-message-displayed t)
+	    (while (and (sit-for 4) lines)
+	      (message (substitute-command-keys (car lines)))
+	      (setq lines (cdr lines)))))
+    (message "")))
+;;
+;;
+;;  Mode
+;;
+(defvar verilog-which-tool 1)
+;;;###autoload
+(defun verilog-mode ()
+  "Major mode for editing Verilog code.
+\\<verilog-mode-map>
+See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
+AUTOs can improve coding efficiency.
+
+Use \\[verilog-faq] for a pointer to frequently asked questions.
+
+NEWLINE, TAB indents for Verilog code.
+Delete converts tabs to spaces as it moves back.
+
+Supports highlighting.
+
+Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
+with no args, if that value is non-nil.
+
+Variables controlling indentation/edit style:
+
+ variable `verilog-indent-level'      (default 3)
+   Indentation of Verilog statements with respect to containing block.
+ `verilog-indent-level-module'        (default 3)
+   Absolute indentation of Module level Verilog statements.
+   Set to 0 to get initial and always statements lined up
+   on the left side of your screen.
+ `verilog-indent-level-declaration'   (default 3)
+   Indentation of declarations with respect to containing block.
+   Set to 0 to get them list right under containing block.
+ `verilog-indent-level-behavioral'    (default 3)
+   Indentation of first begin in a task or function block
+   Set to 0 to get such code to lined up underneath the task or function keyword
+ `verilog-indent-level-directive'     (default 1)
+   Indentation of `ifdef/`endif blocks
+ `verilog-cexp-indent'              (default 1)
+   Indentation of Verilog statements broken across lines i.e.:
+      if (a)
+        begin
+ `verilog-case-indent'              (default 2)
+   Indentation for case statements.
+ `verilog-auto-newline'             (default nil)
+   Non-nil means automatically newline after semicolons and the punctuation
+   mark after an end.
+ `verilog-auto-indent-on-newline'   (default t)
+   Non-nil means automatically indent line after newline
+ `verilog-tab-always-indent'        (default t)
+   Non-nil means TAB in Verilog mode should always reindent the current line,
+   regardless of where in the line point is when the TAB command is used.
+ `verilog-indent-begin-after-if'    (default t)
+   Non-nil means to indent begin statements following a preceding
+   if, else, while, for and repeat statements, if any.  otherwise,
+   the begin is lined up with the preceding token.  If t, you get:
+      if (a)
+         begin // amount of indent based on `verilog-cexp-indent'
+   otherwise you get:
+      if (a)
+      begin
+ `verilog-auto-endcomments'         (default t)
+   Non-nil means a comment /* ... */ is set after the ends which ends
+   cases, tasks, functions and modules.
+   The type and name of the object will be set between the braces.
+ `verilog-minimum-comment-distance' (default 10)
+   Minimum distance (in lines) between begin and end required before a comment
+   will be inserted.  Setting this variable to zero results in every
+   end acquiring a comment; the default avoids too many redundant
+   comments in tight quarters.
+ `verilog-auto-lineup'              (default `(all))
+   List of contexts where auto lineup of code should be done.
+
+Variables controlling other actions:
+
+ `verilog-linter'                   (default surelint)
+   Unix program to call to run the lint checker.  This is the default
+   command for \\[compile-command] and \\[verilog-auto-save-compile].
+
+See \\[customize] for the complete list of variables.
+
+AUTO expansion functions are, in part:
+
+    \\[verilog-auto]  Expand AUTO statements.
+    \\[verilog-delete-auto]  Remove the AUTOs.
+    \\[verilog-inject-auto]  Insert AUTOs for the first time.
+
+Some other functions are:
+
+    \\[verilog-complete-word]    Complete word with appropriate possibilities.
+    \\[verilog-mark-defun]  Mark function.
+    \\[verilog-beg-of-defun]  Move to beginning of current function.
+    \\[verilog-end-of-defun]  Move to end of current function.
+    \\[verilog-label-be]  Label matching begin ... end, fork ... join, etc statements.
+
+    \\[verilog-comment-region]  Put marked area in a comment.
+    \\[verilog-uncomment-region]  Uncomment an area commented with \\[verilog-comment-region].
+    \\[verilog-insert-block]  Insert begin ... end;.
+    \\[verilog-star-comment]    Insert /* ... */.
+
+    \\[verilog-sk-always]  Insert a always @(AS) begin .. end block.
+    \\[verilog-sk-begin]  Insert a begin .. end block.
+    \\[verilog-sk-case]  Insert a case block, prompting for details.
+    \\[verilog-sk-for]  Insert a for (...) begin .. end block, prompting for details.
+    \\[verilog-sk-generate]  Insert a generate .. endgenerate block.
+    \\[verilog-sk-header]  Insert a nice header block at the top of file.
+    \\[verilog-sk-initial]  Insert an initial begin .. end block.
+    \\[verilog-sk-fork]  Insert a fork begin .. end .. join block.
+    \\[verilog-sk-module]  Insert a module .. (/*AUTOARG*/);.. endmodule block.
+    \\[verilog-sk-primitive]  Insert a primitive .. (.. );.. endprimitive block.
+    \\[verilog-sk-repeat]  Insert a repeat (..) begin .. end block.
+    \\[verilog-sk-specify]  Insert a specify .. endspecify block.
+    \\[verilog-sk-task]  Insert a task .. begin .. end endtask block.
+    \\[verilog-sk-while]  Insert a while (...) begin .. end block, prompting for details.
+    \\[verilog-sk-casex]  Insert a casex (...) item: begin.. end endcase block, prompting for details.
+    \\[verilog-sk-casez]  Insert a casez (...) item: begin.. end endcase block, prompting for details.
+    \\[verilog-sk-if]  Insert an if (..) begin .. end block.
+    \\[verilog-sk-else-if]  Insert an else if (..) begin .. end block.
+    \\[verilog-sk-comment]  Insert a comment block.
+    \\[verilog-sk-assign]  Insert an assign .. = ..; statement.
+    \\[verilog-sk-function]  Insert a function .. begin .. end endfunction block.
+    \\[verilog-sk-input]  Insert an input declaration, prompting for details.
+    \\[verilog-sk-output]  Insert an output declaration, prompting for details.
+    \\[verilog-sk-state-machine]  Insert a state machine definition, prompting for details.
+    \\[verilog-sk-inout]  Insert an inout declaration, prompting for details.
+    \\[verilog-sk-wire]  Insert a wire declaration, prompting for details.
+    \\[verilog-sk-reg]  Insert a register declaration, prompting for details.
+    \\[verilog-sk-define-signal]  Define signal under point as a register at the top of the module.
+
+All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
+Key bindings specific to `verilog-mode-map' are:
+
+\\{verilog-mode-map}"
+  (interactive)
+  (kill-all-local-variables)
+  (use-local-map verilog-mode-map)
+  (setq major-mode 'verilog-mode)
+  (setq mode-name "Verilog")
+  (setq local-abbrev-table verilog-mode-abbrev-table)
+  (setq verilog-mode-syntax-table (make-syntax-table))
+  (verilog-populate-syntax-table verilog-mode-syntax-table)
+  (set (make-local-variable 'beginning-of-defun-function) 
+       'verilog-beg-of-defun)
+  (set (make-local-variable 'end-of-defun-function) 
+       'verilog-end-of-defun)
+  ;; add extra comment syntax
+  (verilog-setup-dual-comments verilog-mode-syntax-table)
+  (set-syntax-table verilog-mode-syntax-table)
+  (make-local-variable 'indent-line-function)
+  (setq indent-line-function 'verilog-indent-line-relative)
+  (setq comment-indent-function 'verilog-comment-indent)
+  (make-local-variable 'parse-sexp-ignore-comments)
+  (setq parse-sexp-ignore-comments nil)
+  (make-local-variable 'comment-start)
+  (make-local-variable 'comment-end)
+  (make-local-variable 'comment-multi-line)
+  (make-local-variable 'comment-start-skip)
+  (setq comment-start "// "
+	comment-end ""
+	comment-start-skip "/\\*+ *\\|// *"
+	comment-multi-line nil)
+  ;; Set up for compilation
+  (setq verilog-which-tool 1)
+  (setq verilog-tool 'verilog-linter)
+  (verilog-set-compile-command)
+  (when (boundp 'hack-local-variables-hook)  ;; Also modify any file-local-variables
+    (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
+
+  ;; Setting up menus
+  (when (featurep 'xemacs)
+    (when (and current-menubar
+	       (not (assoc "Verilog" current-menubar)))
+      ;; (set-buffer-menubar (copy-sequence current-menubar))
+      (add-submenu nil verilog-xemacs-menu)
+      (add-submenu nil verilog-stmt-menu)
+      ))
+  ;; Stuff for GNU emacs
+  (make-local-variable 'font-lock-defaults)
+  ;;------------------------------------------------------------
+  ;; now hook in 'verilog-colorize-include-files (eldo-mode.el&spice-mode.el)
+  ;; all buffer local:
+  (make-local-hook 'font-lock-mode-hook)
+  (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in emacs 20
+  (add-hook 'font-lock-mode-hook 'verilog-colorize-include-files-buffer t t)
+  (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-colorize-include-files-buffer t t) ; not in emacs 20
+  (make-local-hook 'after-change-functions)
+  (add-hook 'after-change-functions 'verilog-colorize-include-files t t)
+
+  ;; Tell imenu how to handle verilog.
+  (make-local-variable 'imenu-generic-expression)
+  (setq imenu-generic-expression verilog-imenu-generic-expression)
+  ;; hideshow support
+  (unless (assq 'verilog-mode hs-special-modes-alist)
+    (setq hs-special-modes-alist
+	  (cons '(verilog-mode-mode  "\\<begin\\>" "\\<end\\>" nil
+			     verilog-forward-sexp-function)
+		hs-special-modes-alist)))
+  ;; Display version splash information.
+  (verilog-display-startup-message)
+
+  ;; Stuff for autos
+  (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
+;;  (verilog-auto-reeval-locals t)   ; Save locals in case user changes them
+;;  (verilog-getopt-flags)
+  (run-hooks 'verilog-mode-hook))
+
+
+;;
+;;  Electric functions
+;;
+(defun electric-verilog-terminate-line (&optional arg)
+  "Terminate line and indent next line.
+With optional ARG, remove existing end of line comments."
+  (interactive)
+  ;; before that see if we are in a comment
+  (let ((state
+	 (save-excursion
+	   (parse-partial-sexp (point-min) (point)))))
+    (cond
+     ((nth 7 state)			; Inside // comment
+      (if (eolp)
+	  (progn
+	    (delete-horizontal-space)
+	    (newline))
+	(progn
+	  (newline)
+	  (insert-string "// ")
+	  (beginning-of-line)))
+      (verilog-indent-line))
+     ((nth 4 state)			; Inside any comment (hence /**/)
+      (newline)
+      (verilog-more-comment))
+     ((eolp)
+       ;; First, check if current line should be indented
+       (if (save-excursion
+             (delete-horizontal-space)
+	     (beginning-of-line)
+	     (skip-chars-forward " \t")
+	     (if (looking-at verilog-auto-end-comment-lines-re)
+		 (let ((indent-str (verilog-indent-line)))
+		   ;; Maybe we should set some endcomments
+		   (if verilog-auto-endcomments
+		       (verilog-set-auto-endcomments indent-str arg))
+		   (end-of-line)
+		   (delete-horizontal-space)
+		   (if arg
+		       ()
+		     (newline))
+		   nil)
+	       (progn
+		 (end-of-line)
+		 (delete-horizontal-space)
+		 't
+		 )
+	       )
+	     )
+	   ;; see if we should line up assignments
+	   (progn
+	     (if (or (memq 'all verilog-auto-lineup)
+		     (memq 'assignments verilog-auto-lineup))
+		 (verilog-pretty-expr)
+	       )
+	     (newline)
+	     )
+	 (forward-line 1)
+	 )
+       ;; Indent next line
+       (if verilog-auto-indent-on-newline
+	   (verilog-indent-line))
+       )
+     (t
+      (newline))
+     )))
+
+(defun electric-verilog-terminate-and-indent ()
+  "Insert a newline and indent for the next statement."
+  (interactive)
+  (electric-verilog-terminate-line 1))
+
+(defun electric-verilog-semi ()
+  "Insert `;' character and reindent the line."
+  (interactive)
+  (insert last-command-char)
+
+  (if (or (verilog-in-comment-or-string-p)
+	  (verilog-in-escaped-name-p))
+      ()
+    (save-excursion
+      (beginning-of-line)
+      (verilog-forward-ws&directives)
+      (verilog-indent-line)
+      )
+    (if (and verilog-auto-newline
+	     (not (verilog-parenthesis-depth)))
+	(electric-verilog-terminate-line))))
+
+(defun electric-verilog-semi-with-comment ()
+  "Insert `;' character, reindent the line and indent for comment."
+  (interactive)
+  (insert "\;")
+  (save-excursion
+    (beginning-of-line)
+    (verilog-indent-line))
+  (indent-for-comment))
+
+(defun electric-verilog-colon ()
+  "Insert `:' and do all indentations except line indent on this line."
+  (interactive)
+  (insert last-command-char)
+  ;; Do nothing if within string.
+  (if (or
+       (verilog-within-string)
+       (not (verilog-in-case-region-p)))
+      ()
+    (save-excursion
+      (let ((p (point))
+	    (lim (progn (verilog-beg-of-statement) (point))))
+	(goto-char p)
+	(verilog-backward-case-item lim)
+	(verilog-indent-line)))
+;;    (let ((verilog-tab-always-indent nil))
+;;      (verilog-indent-line))
+    ))
+
+;;(defun electric-verilog-equal ()
+;;  "Insert `=', and do indentation if within block."
+;;  (interactive)
+;;  (insert last-command-char)
+;; Could auto line up expressions, but not yet
+;;  (if (eq (car (verilog-calculate-indent)) 'block)
+;;      (let ((verilog-tab-always-indent nil))
+;;	(verilog-indent-command)))
+;;  )
+
+(defun electric-verilog-tick ()
+  "Insert back-tick, and indent to column 0 if this is a CPP directive."
+  (interactive)
+  (insert last-command-char)
+  (save-excursion
+    (if (progn
+	  (beginning-of-line)
+	  (looking-at verilog-directive-re-1))
+	(verilog-indent-line))))
+
+(defun electric-verilog-tab ()
+  "Function called when TAB is pressed in Verilog mode."
+  (interactive)
+  ;; If verilog-tab-always-indent, indent the beginning of the line.
+  (if (or verilog-tab-always-indent
+	  (save-excursion
+	    (skip-chars-backward " \t")
+	    (bolp)))
+      (let* ((oldpnt (point))
+	     (boi-point
+	      (save-excursion
+		(beginning-of-line)
+		(skip-chars-forward " \t")
+		(verilog-indent-line)
+		(back-to-indentation)
+		(point))))
+        (if (< (point) boi-point)
+            (back-to-indentation)
+	  (cond ((not verilog-tab-to-comment))
+		((not (eolp))
+		 (end-of-line))
+		(t
+		 (indent-for-comment)
+		 (when (and (eolp) (= oldpnt (point)))
+					; kill existing comment
+		   (beginning-of-line)
+		   (re-search-forward comment-start-skip oldpnt 'move)
+		   (goto-char (match-beginning 0))
+		   (skip-chars-backward " \t")
+		   (kill-region (point) oldpnt)
+		   ))))
+	)
+    (progn (insert "\t"))))
+
+
+
+;;
+;; Interactive functions
+;;
+
+(defun verilog-indent-buffer ()
+  "Indent-region the entire buffer as Verilog code.
+To call this from the command line, see \\[verilog-batch-indent]."
+  (interactive)
+  (verilog-mode)
+  (indent-region (point-min) (point-max) nil))
+
+(defun verilog-insert-block ()
+  "Insert Verilog begin ... end; block in the code with right indentation."
+  (interactive)
+  (verilog-indent-line)
+  (insert "begin")
+  (electric-verilog-terminate-line)
+  (save-excursion
+    (electric-verilog-terminate-line)
+    (insert "end")
+    (beginning-of-line)
+    (verilog-indent-line)))
+
+(defun verilog-star-comment ()
+  "Insert Verilog star comment at point."
+  (interactive)
+  (verilog-indent-line)
+  (insert "/*")
+  (save-excursion
+    (newline)
+    (insert " */"))
+  (newline)
+  (insert " * "))
+
+(defun verilog-insert-indices (MAX)
+  "Insert a set of indices at into the rectangle.
+The upper left corner is defined by the current point.  Indices always
+begin with 0 and extend to the MAX - 1.  If no prefix arg is given, the
+user is prompted for a value.  The indices are surrounded by square brackets
+\[].  For example, the following code with the point located after the first
+'a' gives:
+
+    a = b                           a[  0] = b
+    a = b                           a[  1] = b
+    a = b                           a[  2] = b
+    a = b                           a[  3] = b
+    a = b   ==> insert-indices ==>  a[  4] = b
+    a = b                           a[  5] = b
+    a = b                           a[  6] = b
+    a = b                           a[  7] = b
+    a = b                           a[  8] = b"
+
+  (interactive "NMAX?")
+  (save-excursion
+  (let ((n 0))
+    (while (< n MAX)
+      (save-excursion
+      (insert (format "[%3d]" n)))
+      (next-line 1)
+      (setq n (1+ n))))))
+
+
+(defun verilog-generate-numbers (MAX)
+  "Insert a set of generated numbers into a rectangle.
+The upper left corner is defined by point.  The numbers are padded to three
+digits, starting with 000 and extending to (MAX - 1).  If no prefix argument
+is supplied, then the user is prompted for the MAX number.  consider the
+following code fragment:
+
+    buf buf                           buf buf000
+    buf buf                           buf buf001
+    buf buf                           buf buf002
+    buf buf                           buf buf003
+    buf buf   ==> insert-indices ==>  buf buf004
+    buf buf                           buf buf005
+    buf buf                           buf buf006
+    buf buf                           buf buf007
+    buf buf                           buf buf008"
+
+  (interactive "NMAX?")
+  (save-excursion
+  (let ((n 0))
+    (while (< n MAX)
+      (save-excursion
+      (insert (format "%3.3d" n)))
+      (next-line 1)
+      (setq n (1+ n))))))
+
+(defun verilog-mark-defun ()
+  "Mark the current verilog function (or procedure).
+This puts the mark at the end, and point at the beginning."
+  (interactive)
+  (push-mark (point))
+  (verilog-end-of-defun)
+  (push-mark (point))
+  (verilog-beg-of-defun)
+  (zmacs-activate-region))
+
+(defun verilog-comment-region (start end)
+  ; checkdoc-params: (start end)
+  "Put the region into a Verilog comment.
+The comments that are in this area are \"deformed\":
+`*)' becomes `!(*' and `}' becomes `!{'.
+These deformed comments are returned to normal if you use
+\\[verilog-uncomment-region] to undo the commenting.
+
+The commented area starts with `verilog-exclude-str-start', and ends with
+`verilog-exclude-str-end'.  But if you change these variables,
+\\[verilog-uncomment-region] won't recognize the comments."
+  (interactive "r")
+  (save-excursion
+    ;; Insert start and endcomments
+    (goto-char end)
+    (if (and (save-excursion (skip-chars-forward " \t") (eolp))
+	     (not (save-excursion (skip-chars-backward " \t") (bolp))))
+	(forward-line 1)
+      (beginning-of-line))
+    (insert verilog-exclude-str-end)
+    (setq end (point))
+    (newline)
+    (goto-char start)
+    (beginning-of-line)
+    (insert verilog-exclude-str-start)
+    (newline)
+    ;; Replace end-comments within commented area
+    (goto-char end)
+    (save-excursion
+      (while (re-search-backward "\\*/" start t)
+	(replace-match "*-/" t t)))
+    (save-excursion
+      (let ((s+1 (1+ start)))
+	(while (re-search-backward "/\\*" s+1 t)
+	  (replace-match "/-*" t t))))
+    ))
+
+(defun verilog-uncomment-region ()
+  "Uncomment a commented area; change deformed comments back to normal.
+This command does nothing if the pointer is not in a commented
+area.  See also `verilog-comment-region'."
+  (interactive)
+  (save-excursion
+    (let ((start (point))
+	  (end (point)))
+      ;; Find the boundaries of the comment
+      (save-excursion
+	(setq start (progn (search-backward verilog-exclude-str-start nil t)
+			   (point)))
+	(setq end (progn (search-forward verilog-exclude-str-end nil t)
+			 (point))))
+      ;; Check if we're really inside a comment
+      (if (or (equal start (point)) (<= end (point)))
+	  (message "Not standing within commented area.")
+	(progn
+	  ;; Remove endcomment
+	  (goto-char end)
+	  (beginning-of-line)
+	  (let ((pos (point)))
+	    (end-of-line)
+	    (delete-region pos (1+ (point))))
+	  ;; Change comments back to normal
+	  (save-excursion
+	    (while (re-search-backward "\\*-/" start t)
+	      (replace-match "*/" t t)))
+	  (save-excursion
+	    (while (re-search-backward "/-\\*" start t)
+	      (replace-match "/*" t t)))
+	  ;; Remove start comment
+	  (goto-char start)
+	  (beginning-of-line)
+	  (let ((pos (point)))
+	    (end-of-line)
+	    (delete-region pos (1+ (point)))))))))
+
+(defun verilog-beg-of-defun ()
+  "Move backward to the beginning of the current function or procedure."
+  (interactive)
+  (verilog-re-search-backward verilog-defun-re nil 'move))
+
+(defun verilog-end-of-defun ()
+  "Move forward to the end of the current function or procedure."
+  (interactive)
+  (verilog-re-search-forward verilog-end-defun-re nil 'move))
+
+(defun verilog-get-beg-of-defun (&optional warn)
+  (save-excursion
+    (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
+	   (point))
+	  (t
+	   (error "%s: Can't find module beginning" (verilog-point-text))
+	   (point-max)))))
+(defun verilog-get-end-of-defun (&optional warn)
+  (save-excursion
+    (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
+	   (point))
+	  (t
+	   (error "%s: Can't find endmodule" (verilog-point-text))
+	   (point-max)))))
+
+(defun verilog-label-be (&optional arg)
+  "Label matching begin ... end, fork ... join and case ... endcase statements.
+With ARG, first kill any existing labels."
+  (interactive)
+  (let ((cnt 0)
+	(oldpos (point))
+	(b (progn
+	     (verilog-beg-of-defun)
+	     (point-marker)))
+	(e (progn
+	     (verilog-end-of-defun)
+	     (point-marker)))
+	)
+    (goto-char (marker-position b))
+    (if (> (- e b) 200)
+	(message  "Relabeling module..."))
+    (while (and
+	    (> (marker-position e) (point))
+	    (verilog-re-search-forward
+	     (concat
+	      "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
+	      "\\|\\(`endif\\)\\|\\(`else\\)")
+	     nil 'move))
+      (goto-char (match-beginning 0))
+      (let ((indent-str (verilog-indent-line)))
+	(verilog-set-auto-endcomments indent-str 't)
+	(end-of-line)
+	(delete-horizontal-space)
+	)
+      (setq cnt (1+ cnt))
+      (if (= 9 (% cnt 10))
+	  (message "%d..." cnt))
+      )
+    (goto-char oldpos)
+    (if (or
+	 (> (- e b) 200)
+	 (> cnt 20))
+	(message  "%d lines auto commented" cnt))
+    ))
+
+(defun verilog-beg-of-statement ()
+  "Move backward to beginning of statement."
+  (interactive)
+  ;; Move back token by token until we see the end
+  ;; of some ealier line.
+  (while
+      ;; If the current point does not begin a new
+      ;; statement, as in the character ahead of us is a ';', or SOF
+      ;; or the string after us unambiguosly starts a statement,
+      ;; or the token before us unambiguously ends a statement,
+      ;; then move back a token and test again.
+      (not (or
+	    (bolp)
+	    (= (preceding-char) ?\;)
+	    (not (or
+		  (looking-at "\\<")
+		  (forward-word -1)))
+	    (and
+	     (looking-at verilog-extended-complete-re)
+	     (not (save-excursion
+		    (verilog-backward-token)
+		    (looking-at verilog-extended-complete-re)))
+	     )
+	    (looking-at verilog-basic-complete-re)
+	    (save-excursion
+	      (verilog-backward-token)
+	      (or
+	       (looking-at verilog-end-block-re)
+	       (looking-at verilog-preprocessor-re)))
+	    ))
+    (verilog-backward-syntactic-ws)
+    (verilog-backward-token))
+  ;; Now point is where the previous line ended.
+  (verilog-forward-syntactic-ws))
+
+(defun verilog-beg-of-statement-1 ()
+  "Move backward to beginning of statement."
+  (interactive)
+  (let ((pt (point)))
+
+    (while (and (not (looking-at verilog-complete-reg))
+		(setq pt (point))
+		(verilog-backward-token)
+		(not (looking-at verilog-complete-reg))
+		(verilog-backward-syntactic-ws)
+		(setq pt (point))
+		(not (bolp))
+		(not (= (preceding-char) ?\;))))
+    (goto-char pt)
+    (verilog-forward-ws&directives)))
+
+(defun verilog-end-of-statement ()
+  "Move forward to end of current statement."
+  (interactive)
+  (let ((nest 0) pos)
+    (or (looking-at verilog-beg-block-re)
+	;; Skip to end of statement
+	(setq pos (catch 'found
+		    (while t
+		      (forward-sexp 1)
+		      (verilog-skip-forward-comment-or-string)
+		      (cond ((looking-at "[ \t]*;")
+			     (skip-chars-forward "^;")
+			     (forward-char 1)
+			     (throw 'found (point)))
+			    ((save-excursion
+			       (forward-sexp -1)
+			       (looking-at verilog-beg-block-re))
+			     (goto-char (match-beginning 0))
+			     (throw 'found nil))
+			    ((looking-at "[ \t]*)")
+			     (throw 'found (point)))
+			    ((eobp)
+			     (throw 'found (point))))))))
+    (if (not pos)
+	;; Skip a whole block
+	(catch 'found
+	  (while t
+	    (verilog-re-search-forward verilog-end-statement-re nil 'move)
+	    (setq nest (if (match-end 1)
+			   (1+ nest)
+			 (1- nest)))
+	    (cond ((eobp)
+		   (throw 'found (point)))
+		  ((= 0 nest)
+		   (throw 'found (verilog-end-of-statement))))))
+      pos)))
+
+(defun verilog-in-case-region-p ()
+  "Return TRUE if in a case region;
+more specifically, point @ in the line foo : @ begin"
+  (interactive)
+  (save-excursion
+    (if (and
+	 (progn (verilog-forward-syntactic-ws)
+		(looking-at "\\<begin\\>"))
+	 (progn (verilog-backward-syntactic-ws)
+		(= (preceding-char) ?\:)))
+	(catch 'found
+	  (let ((nest 1))
+	    (while t
+	      (verilog-re-search-backward
+	       (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
+		       "\\(\\<endcase\\>\\)\\>")
+	       nil 'move)
+	      (cond
+	       ((match-end 3)
+		(setq nest (1+ nest)))
+	       ((match-end 2)
+		(if (= nest 1)
+		(throw 'found 1))
+		(setq nest (1- nest)))
+	       (t
+		(throw 'found (= nest 0)))
+	       ))))
+      nil)))
+(defun verilog-in-struct-region-p ()
+  "Return TRUE if in a struct region;
+more specifically, in a list after a struct|union keyword"
+  (interactive)
+  (save-excursion
+    (let* ((state (parse-partial-sexp (point-min) (point)))
+	   (depth (nth 0 state)))
+      (if depth
+	  (progn (backward-up-list depth)
+		 (verilog-beg-of-statement)
+		 (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>")
+		 )
+	)
+      )
+    )
+  )
+
+(defun verilog-in-generate-region-p ()
+  "Return TRUE if in a generate region;
+more specifically, after a generate and before an endgenerate"
+  (interactive)
+  (let ((lim (save-excursion (verilog-beg-of-defun)  (point)))
+	(nest 1)
+	)
+    (save-excursion
+      (while (and
+	      (/= nest 0)
+	      (verilog-re-search-backward "\\<\\(generate\\)\\|\\(endgenerate\\)\\>" lim 'move)
+	      (cond
+	       ((match-end 1) ; generate
+		(setq nest (1- nest)))
+	       ((match-end 2) ; endgenerate
+		(setq nest (1+ nest)))
+	       ))
+	))
+    (= nest 0) )) ; return nest
+
+(defun verilog-in-fork-region-p ()
+  "Return true if between a fork and join."
+  (interactive)
+  (let ((lim (save-excursion (verilog-beg-of-defun)  (point)))
+	(nest 1)
+	)
+    (save-excursion
+      (while (and
+	      (/= nest 0)
+	      (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
+	      (cond
+	       ((match-end 1) ; fork
+		(setq nest (1- nest)))
+	       ((match-end 2) ; join
+		(setq nest (1+ nest)))
+	       ))
+	))
+    (= nest 0) )) ; return nest
+
+(defun verilog-backward-case-item (lim)
+  "Skip backward to nearest enclosing case item.
+Limit search to point LIM."
+  (interactive)
+  (let ((str 'nil)
+	(lim1
+	 (progn
+	   (save-excursion
+	     (verilog-re-search-backward verilog-endcomment-reason-re
+					 lim 'move)
+	     (point)))))
+    ;; Try to find the real :
+    (if (save-excursion (search-backward ":" lim1 t))
+	(let ((colon 0)
+	      b e )
+	  (while
+	      (and
+	       (< colon 1)
+	       (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
+					   lim1 'move))
+	    (cond
+	     ((match-end 1) ;; [
+	      (setq colon (1+ colon))
+	      (if (>= colon 0)
+		  (error "%s: unbalanced [" (verilog-point-text))))
+	     ((match-end 2) ;; ]
+	      (setq colon (1- colon)))
+
+	     ((match-end 3) ;; :
+	      (setq colon (1+ colon)))
+	     ))
+	  ;; Skip back to beginning of case item
+	  (skip-chars-backward "\t ")
+	  (verilog-skip-backward-comment-or-string)
+	  (setq e (point))
+	  (setq b
+		(progn
+		  (if
+		      (verilog-re-search-backward
+		       "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
+		      (progn
+			(cond
+			 ((match-end 1)
+			  (goto-char (match-end 1))
+			  (verilog-forward-ws&directives)
+			  (if (looking-at "(")
+			      (progn
+				(forward-sexp)
+				(verilog-forward-ws&directives)))
+			  (point))
+			 (t
+			  (goto-char (match-end 0))
+			  (verilog-forward-ws&directives)
+			  (point))
+			 ))
+		    (error "Malformed case item")
+		    )))
+	  (setq str (buffer-substring b e))
+	  (if
+	      (setq e
+		    (string-match
+		     "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
+	      (setq str (concat (substring str 0 e) "...")))
+	  str)
+      'nil)))
+
+
+;;
+;; Other functions
+;;
+
+(defun verilog-kill-existing-comment ()
+  "Kill auto comment on this line."
+  (save-excursion
+    (let* (
+	   (e (progn
+		(end-of-line)
+		(point)))
+	   (b (progn
+		(beginning-of-line)
+		(search-forward "//" e t))))
+      (if b
+	  (delete-region (- b 2) e)))))
+
+(defconst verilog-directive-nest-re
+  (concat "\\(`else\\>\\)\\|"
+	  "\\(`endif\\>\\)\\|"
+	  "\\(`if\\>\\)\\|"
+	  "\\(`ifdef\\>\\)\\|"
+	  "\\(`ifndef\\>\\)"))
+(defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
+  "Add ending comment with given INDENT-STR.
+With KILL-EXISTING-COMMENT, remove what was there before.
+Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
+Insert `// case expr ' if this line ends a case block.
+Insert `// ifdef FOO ' if this line ends code conditional on FOO.
+Insert `// NAME ' if this line ends a function, task, module, primitive or interface named NAME."
+  (save-excursion
+    (cond
+     (; Comment close preprocessor directives
+      (and
+       (looking-at "\\(`endif\\)\\|\\(`else\\)")
+       (or  kill-existing-comment
+	    (not (save-excursion
+		   (end-of-line)
+		   (search-backward "//" (verilog-get-beg-of-line) t)))))
+      (let ((nest 1) b e
+	    m
+	    (else (if (match-end 2) "!" " "))
+	    )
+	(end-of-line)
+	(if kill-existing-comment
+	    (verilog-kill-existing-comment))
+	(delete-horizontal-space)
+	(save-excursion
+	  (backward-sexp 1)
+	  (while (and (/= nest 0)
+		      (verilog-re-search-backward verilog-directive-nest-re nil 'move))
+	    (cond
+	     ((match-end 1) ; `else
+	      (if (= nest 1)
+		  (setq else "!")))
+	     ((match-end 2) ; `endif
+	      (setq nest (1+ nest)))
+	     ((match-end 3) ; `if
+	      (setq nest (1- nest)))
+	     ((match-end 4) ; `ifdef
+	      (setq nest (1- nest)))
+	     ((match-end 5) ; `ifndef
+	      (setq nest (1- nest)))
+	     ))
+	  (if (match-end 0)
+	      (setq
+	       m (buffer-substring
+		  (match-beginning 0)
+		  (match-end 0))
+	       b (progn
+		   (skip-chars-forward "^ \t")
+		   (verilog-forward-syntactic-ws)
+		   (point))
+	       e (progn
+		   (skip-chars-forward "a-zA-Z0-9_")
+		   (point)
+		   ))))
+	(if b
+	    (if (> (count-lines (point) b) verilog-minimum-comment-distance)
+		(insert (concat " // " else m " " (buffer-substring b e))))
+	  (progn
+	    (insert " // unmatched `else or `endif")
+	    (ding 't))
+	  )))
+
+     (; Comment close case/class/function/task/module and named block
+      (and (looking-at "\\<end")
+	   (or kill-existing-comment
+	       (not (save-excursion
+		      (end-of-line)
+		      (search-backward "//" (verilog-get-beg-of-line) t)))))
+      (let ((type (car indent-str)))
+	(unless (eq type 'declaration)
+	  (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
+	    (if (looking-at verilog-end-block-ordered-re)
+	      (cond
+	       (;- This is a case block; search back for the start of this case
+		(match-end 1) ;; of verilog-end-block-ordered-re
+
+		(let ((err 't)
+		      (str "UNMATCHED!!"))
+		  (save-excursion
+		    (verilog-leap-to-head)
+		    (cond
+		     ((looking-at "\\<randcase\\>")
+		      (setq str "randcase")
+		      (setq err nil)
+		      )
+		     ((match-end 0)
+		      (goto-char (match-end 1))
+		      (if nil
+			  (let (s f)
+			    (setq s (match-beginning 1))
+			    (setq f (progn (end-of-line)
+					   (point)))
+			    (setq str  (buffer-substring s f)))
+			(setq err nil))
+		      (setq str (concat (buffer-substring (match-beginning 1) (match-end 1))
+					" "
+					(verilog-get-expr))))))
+		  (end-of-line)
+		  (if kill-existing-comment
+		      (verilog-kill-existing-comment))
+		  (delete-horizontal-space)
+		  (insert (concat " // " str ))
+		  (if err (ding 't))
+		  ))
+
+	       (;- This is a begin..end block
+		(match-end 2) ;; of verilog-end-block-ordered-re
+		(let ((str " // UNMATCHED !!")
+		      (err 't)
+		      (here (point))
+		      there
+		      cntx
+		      )
+		  (save-excursion
+		    (verilog-leap-to-head)
+		    (setq there (point))
+		    (if (not (match-end 0))
+			(progn
+			  (goto-char here)
+			  (end-of-line)
+			  (if kill-existing-comment
+			      (verilog-kill-existing-comment))
+			  (delete-horizontal-space)
+			  (insert str)
+			  (ding 't)
+			  )
+		      (let ((lim
+			     (save-excursion (verilog-beg-of-defun) (point)))
+			    (here (point))
+			    )
+			(cond
+			 (;-- handle named block differently
+			  (looking-at verilog-named-block-re)
+			  (search-forward ":")
+			  (setq there (point))
+			  (setq str (verilog-get-expr))
+			  (setq err nil)
+			  (setq str (concat " // block: " str )))
+
+			 ((verilog-in-case-region-p) ;-- handle case item differently
+			  (goto-char here)
+			  (setq str (verilog-backward-case-item lim))
+			  (setq there (point))
+			  (setq err nil)
+			  (setq str (concat " // case: " str )))
+
+			 (;- try to find "reason" for this begin
+			  (cond
+			   (;
+			    (eq here (progn
+				       (verilog-backward-token)
+				       (verilog-beg-of-statement-1)
+				       (point)))
+			    (setq err nil)
+			    (setq str ""))
+			   ((looking-at verilog-endcomment-reason-re)
+			    (setq there (match-end 0))
+			    (setq cntx (concat
+					(buffer-substring (match-beginning 0) (match-end 0)) " "))
+			    (cond
+			     (;- begin
+			      (match-end 2)
+			      (setq err nil)
+			      (save-excursion
+				(if (and (verilog-continued-line)
+					 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
+				    (progn
+				      (goto-char (match-end 0))
+				      (setq there (point))
+				      (setq str
+					    (concat " // "
+						    (buffer-substring (match-beginning 0) (match-end 0)) " "
+						    (verilog-get-expr))))
+				  (setq str ""))))
+
+			     (;- else
+			      (match-end 4)
+			      (let ((nest 0)
+				    ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)")
+				    )
+				(catch 'skip
+				  (while (verilog-re-search-backward reg nil 'move)
+				    (cond
+				     ((match-end 1) ; begin
+				      (setq nest (1- nest)))
+				     ((match-end 2)                       ; end
+				      (setq nest (1+ nest)))
+				     ((match-end 3)
+				      (if (= 0 nest)
+					  (progn
+					    (goto-char (match-end 0))
+					    (setq there (point))
+					    (setq err nil)
+					    (setq str (verilog-get-expr))
+					    (setq str (concat " // else: !if" str ))
+					    (throw 'skip 1))
+					)))
+				    ))))
+
+			     (;- end else
+			      (match-end 5)
+			      (goto-char there)
+			      (let ((nest 0)
+				    ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)")
+				    )
+				(catch 'skip
+				  (while (verilog-re-search-backward reg nil 'move)
+				    (cond
+				     ((match-end 1) ; begin
+				      (setq nest (1- nest)))
+				     ((match-end 2)                       ; end
+				      (setq nest (1+ nest)))
+				     ((match-end 3)
+				      (if (= 0 nest)
+					  (progn
+					    (goto-char (match-end 0))
+					    (setq there (point))
+					    (setq err nil)
+					    (setq str (verilog-get-expr))
+					    (setq str (concat " // else: !if" str ))
+					    (throw 'skip 1))
+					)))
+				    ))))
+
+			     (;- task/function/initial et cetera
+			      t
+			      (match-end 0)
+			      (goto-char (match-end 0))
+			      (setq there (point))
+			      (setq err nil)
+			      (setq str (verilog-get-expr))
+			      (setq str (concat " // " cntx str )))
+
+			     (;-- otherwise...
+			      (setq str " // auto-endcomment confused "))
+			     ))
+
+			   ((and
+			     (verilog-in-case-region-p) ;-- handle case item differently
+			     (progn
+			       (setq there (point))
+			       (goto-char here)
+			       (setq str (verilog-backward-case-item lim))))
+			    (setq err nil)
+			    (setq str (concat " // case: " str )))
+
+			   ((verilog-in-fork-region-p)
+			    (setq err nil)
+			    (setq str " // fork branch" ))
+
+			   ((looking-at "\\<end\\>")
+			    ;; HERE
+			    (forward-word 1)
+			    (verilog-forward-syntactic-ws)
+			    (setq err nil)
+			    (setq str (verilog-get-expr))
+			    (setq str (concat " // " cntx str )))
+
+			   ))))
+		      (goto-char here)
+		      (end-of-line)
+		      (if kill-existing-comment
+			  (verilog-kill-existing-comment))
+		      (delete-horizontal-space)
+		      (if (or err
+			      (> (count-lines here there) verilog-minimum-comment-distance))
+			  (insert str))
+		      (if err (ding 't))
+		      ))))
+	       (;- this is endclass, which can be nested
+		(match-end 11) ;; of verilog-end-block-ordered-re
+		;;(goto-char there)
+		(let ((nest 0)
+		      ( reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
+		      string
+		      )
+		  (save-excursion
+		    (catch 'skip
+		      (while (verilog-re-search-backward reg nil 'move)
+			(cond
+			 ((match-end 3)	; endclass
+			  (ding 't)
+			  (setq string "unmatched endclass")
+			  (throw 'skip 1))
+
+			 ((match-end 2)	; endclass
+			  (setq nest (1+ nest)))
+
+			 ((match-end 1) ; class
+			  (setq nest (1- nest))
+			  (if (< nest 0)
+			      (progn
+				(goto-char (match-end 0))
+				(let (b e)
+				  (setq b (progn
+					    (skip-chars-forward "^ \t")
+					    (verilog-forward-ws&directives)
+					    (point))
+					e (progn
+					    (skip-chars-forward "a-zA-Z0-9_")
+					    (point)))
+				  (setq string (buffer-substring b e)))
+				(throw 'skip 1))))
+			 ))))
+		  (end-of-line)
+		  (insert (concat " // " string )))
+		)
+
+	       (;- this is end{function,generate,task,module,primitive,table,generate}
+		;- which can not be nested.
+		t
+		(let (string reg (width nil))
+		  (end-of-line)
+		  (if kill-existing-comment
+		      (save-match-data
+		       (verilog-kill-existing-comment)))
+		  (delete-horizontal-space)
+		  (backward-sexp)
+		  (cond
+		   ((match-end 5) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
+		    (setq width "\\(\\s-*\\(\\[[^]]*\\]\\)\\|\\(real\\(time\\)?\\)\\|\\(integer\\)\\|\\(time\\)\\)?")
+		    )
+		   ((match-end 6) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
+		   ((match-end 7) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
+		   ((match-end 8) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
+		   ((match-end 9) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
+		   ((match-end 10) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
+		   ((match-end 11) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
+		   ((match-end 12) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
+		   ((match-end 13) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
+		   ((match-end 14) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
+		   ((match-end 15) ;; of verilog-end-block-ordered-re
+		    (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
+
+		   (t (error "Problem in verilog-set-auto-endcomments"))
+		   )
+		  (let (b e)
+		    (save-excursion
+		      (verilog-re-search-backward reg nil 'move)
+		      (cond
+		       ((match-end 1)
+			(setq b (progn
+				  (skip-chars-forward "^ \t")
+				  (verilog-forward-ws&directives)
+				  (if (and width (looking-at width))
+				      (progn
+					(goto-char (match-end 0))
+					(verilog-forward-ws&directives)
+					))
+				  (point))
+			      e (progn
+				  (skip-chars-forward "a-zA-Z0-9_")
+				  (point)))
+			(setq string (buffer-substring b e)))
+		       (t
+			(ding 't)
+			(setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
+		  (end-of-line)
+		  (insert (concat " // " string )))
+		))))))))))
+
+(defun verilog-get-expr()
+  "Grab expression at point, e.g, case ( a | b & (c ^d))"
+  (let* ((b (progn
+	      (verilog-forward-syntactic-ws)
+	      (skip-chars-forward " \t")
+	      (point)))
+	 (e (let ((par 1))
+	      (cond
+	       ((looking-at "@")
+		(forward-char 1)
+		(verilog-forward-syntactic-ws)
+		(if (looking-at "(")
+		    (progn
+		      (forward-char 1)
+		      (while (and (/= par 0)
+				  (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
+			(cond
+			 ((match-end 1)
+			  (setq par (1+ par)))
+			 ((match-end 2)
+			  (setq par (1- par)))))))
+		(point))
+	       ((looking-at "(")
+		(forward-char 1)
+		(while (and (/= par 0)
+			    (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
+		  (cond
+		   ((match-end 1)
+		    (setq par (1+ par)))
+		   ((match-end 2)
+		    (setq par (1- par)))))
+		(point))
+	       ((looking-at "\\[")
+		(forward-char 1)
+		(while (and (/= par 0)
+			    (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
+		  (cond
+		   ((match-end 1)
+		    (setq par (1+ par)))
+		   ((match-end 2)
+		    (setq par (1- par)))))
+		(verilog-forward-syntactic-ws)
+		(skip-chars-forward "^ \t\n\f")
+		(point))
+	       ((looking-at "/[/\\*]")
+		b)
+	       ('t
+		(skip-chars-forward "^: \t\n\f")
+		(point)
+		))))
+	 (str (buffer-substring b e)))
+    (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
+	(setq str (concat (substring str 0 e) "...")))
+    str))
+
+(defun verilog-expand-vector ()
+  "Take a signal vector on the current line and expand it to multiple lines.
+Useful for creating tri's and other expanded fields."
+  (interactive)
+  (verilog-expand-vector-internal "[" "]"))
+
+(defun verilog-expand-vector-internal (bra ket)
+  "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
+  (save-excursion
+    (forward-line 0)
+    (let ((signal-string (buffer-substring (point)
+					   (progn
+					     (end-of-line) (point)))))
+      (if (string-match (concat "\\(.*\\)"
+				(regexp-quote bra)
+				"\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
+				(regexp-quote ket)
+				"\\(.*\\)$") signal-string)
+	  (let* ((sig-head (match-string 1 signal-string))
+		 (vec-start (string-to-int (match-string 2 signal-string)))
+		 (vec-end (if (= (match-beginning 3) (match-end 3))
+			      vec-start
+			    (string-to-int (substring signal-string (1+ (match-beginning 3)) (match-end 3)))))
+		 (vec-range (if (= (match-beginning 4) (match-end 4))
+				1
+			      (string-to-int (substring signal-string (+ 2 (match-beginning 4)) (match-end 4)))))
+		 (sig-tail (match-string 5 signal-string))
+		 vec)
+	    ;; Decode vectors
+	    (setq vec nil)
+	    (if (< vec-range 0)
+		(let ((tmp vec-start))
+		  (setq vec-start vec-end
+			vec-end tmp
+			vec-range (- vec-range))))
+	    (if (< vec-end vec-start)
+		(while (<= vec-end vec-start)
+		  (setq vec (append vec (list vec-start)))
+		  (setq vec-start (- vec-start vec-range)))
+	      (while (<= vec-start vec-end)
+		(setq vec (append vec (list vec-start)))
+		(setq vec-start (+ vec-start vec-range))))
+	    ;;
+	    ;; Delete current line
+	    (delete-region (point) (progn (forward-line 0) (point)))
+	    ;;
+	    ;; Expand vector
+	    (while vec
+	      (insert (concat sig-head bra (int-to-string (car vec)) ket sig-tail "\n"))
+	      (setq vec (cdr vec)))
+	    (delete-char -1)
+	    ;;
+	    )))))
+
+(defun verilog-strip-comments ()
+  "Strip all comments from the verilog code."
+  (interactive)
+  (goto-char (point-min))
+  (while (re-search-forward "//" nil t)
+    (if (verilog-within-string)
+	(re-search-forward "\"" nil t)
+      (if (verilog-in-star-comment-p)
+	  (re-search-forward "\*/" nil t)
+	(let ((bpt (- (point) 2)))
+	  (end-of-line)
+	  (delete-region bpt (point))))))
+    ;;
+  (goto-char (point-min))
+  (while (re-search-forward "/\\*" nil t)
+    (if (verilog-within-string)
+	(re-search-forward "\"" nil t)
+      (let ((bpt (- (point) 2)))
+	(re-search-forward "\\*/")
+	(delete-region bpt (point))))))
+
+(defun verilog-one-line ()
+  "Convert structural verilog instances to occupy one line."
+  (interactive)
+  (goto-char (point-min))
+  (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
+	(replace-match "\\1 " nil nil)))
+
+(defun verilog-linter-name ()
+  "Return name of linter, either surelint or verilint."
+  (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
+						       compile-command))
+	(lint-word1    (verilog-string-replace-matches "\\s .*$" "" nil nil
+						       verilog-linter)))
+    (cond ((equal compile-word1 "surelint") `surelint)
+	  ((equal compile-word1 "verilint") `verilint)
+	  ((equal lint-word1 "surelint")    `surelint)
+	  ((equal lint-word1 "verilint")    `verilint)
+	  (t `surelint))))  ;; back compatibility
+
+(defun verilog-lint-off ()
+  "Convert a Verilog linter warning line into a disable statement.
+For example:
+	pci_bfm_null.v, line  46: Unused input: pci_rst_
+becomes a comment for the appropriate tool.
+
+The first word of the `compile-command' or `verilog-linter'
+variables are used to determine which product is being used.
+
+See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
+  (interactive)
+  (let ((linter (verilog-linter-name)))
+    (cond ((equal linter `surelint)
+	   (verilog-surelint-off))
+	  ((equal linter `verilint)
+	   (verilog-verilint-off))
+	  (t (error "Linter name not set")))))
+
+(defun verilog-surelint-off ()
+  "Convert a SureLint warning line into a disable statement.
+Run from Verilog source window; assumes there is a *compile* buffer
+with point set appropriately.
+
+For example:
+	WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
+becomes:
+	// surefire lint_line_off UDDONX"
+  (interactive)
+  (save-excursion
+    (switch-to-buffer compilation-last-buffer)
+    (beginning-of-line)
+    (when
+	(looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
+      (let* ((code (match-string 2))
+	     (file (match-string 3))
+	     (line (match-string 4))
+	     (buffer (get-file-buffer file))
+	     dir filename)
+	(unless buffer
+	  (progn
+	    (setq buffer
+		  (and (file-exists-p file)
+		       (find-file-noselect file)))
+	    (or buffer
+		(let* ((pop-up-windows t))
+		  (let ((name (expand-file-name
+			       (read-file-name
+				(format "Find this error in: (default %s) "
+					file)
+				dir file t))))
+		    (if (file-directory-p name)
+			(setq name (expand-file-name filename name)))
+		    (setq buffer
+			  (and (file-exists-p name)
+			       (find-file-noselect name))))))))
+	(switch-to-buffer buffer)
+	(goto-line (string-to-number line))
+	(end-of-line)
+	(catch 'already
+	  (cond
+	   ((verilog-in-slash-comment-p)
+	    (re-search-backward "//")
+	    (cond
+	     ((looking-at "// surefire lint_off_line ")
+	      (goto-char (match-end 0))
+	      (let ((lim (save-excursion (end-of-line) (point))))
+		(if (re-search-forward code lim 'move)
+		    (throw 'already t)
+		  (insert-string (concat " " code)))))
+	     (t
+	      )))
+	   ((verilog-in-star-comment-p)
+	    (re-search-backward "/\*")
+	    (insert-string (format " // surefire lint_off_line %6s" code ))
+	    )
+	   (t
+	    (insert-string (format " // surefire lint_off_line %6s" code ))
+	    )))))))
+
+(defun verilog-verilint-off ()
+  "Convert a Verilint warning line into a disable statement.
+
+For example:
+	(W240)  pci_bfm_null.v, line  46: Unused input: pci_rst_
+becomes:
+	//Verilint 240 off // WARNING: Unused input"
+  (interactive)
+  (save-excursion
+    (beginning-of-line)
+    (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
+      (replace-match (format
+		      ;; %3s makes numbers 1-999 line up nicely
+		      "\\1//Verilint %3s off // WARNING: \\3"
+		      (match-string 2)))
+      (beginning-of-line)
+      (verilog-indent-line))))
+
+(defun verilog-auto-save-compile ()
+  "Update automatics with \\[verilog-auto], save the buffer, and compile."
+  (interactive)
+  (verilog-auto)	; Always do it for safety
+  (save-buffer)
+  (compile compile-command))
+
+
+
+;;
+;; Batch
+;;
+
+(defmacro verilog-batch-error-wrapper (&rest body)
+  "Execute BODY and add error prefix to any errors found.
+This lets programs calling batch mode to easily extract error messages."
+  `(condition-case err
+       (progn ,@body)
+     (error
+      (error "%%Error: %s%s" (error-message-string err)
+	     (if (featurep 'xemacs) "\n" "")))))  ;; xemacs forgets to add a newline
+
+(defun verilog-batch-execute-func (funref)
+  "Internal processing of a batch command, running FUNREF on all command arguments."
+  (verilog-batch-error-wrapper
+   ;; General globals needed
+   (setq make-backup-files nil)
+   (setq-default make-backup-files nil)
+   (setq enable-local-variables t)
+   (setq enable-local-eval t)
+   ;; Make sure any sub-files we read get proper mode
+   (setq default-major-mode `verilog-mode)
+   ;; Ditto files already read in
+   (mapcar '(lambda (buf)
+	      (when (buffer-file-name buf)
+		(save-excursion
+		  (set-buffer buf)
+		  (verilog-mode))))
+	   (buffer-list))
+   ;; Process the files
+   (mapcar '(lambda (buf)
+	      (when (buffer-file-name buf)
+		(save-excursion
+		  (if (not (file-exists-p (buffer-file-name buf)))
+		      (error (concat "File not found: " (buffer-file-name buf))))
+		  (message (concat "Processing " (buffer-file-name buf)))
+		  (set-buffer buf)
+		  (funcall funref)
+		  (save-buffer))))
+	   (buffer-list))))
+
+(defun verilog-batch-auto ()
+  "For use with --batch, perform automatic expansions as a stand-alone tool.
+This sets up the appropriate Verilog-Mode environment, updates automatics
+with \\[verilog-auto] on all command-line files, and saves the buffers.
+For proper results, multiple filenames need to be passed on the command
+line in bottom-up order."
+  (unless noninteractive
+    (error "Use verilog-batch-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
+  (verilog-batch-execute-func `verilog-auto))
+
+(defun verilog-batch-delete-auto ()
+  "For use with --batch, perform automatic deletion as a stand-alone tool.
+This sets up the appropriate Verilog-Mode environment, deletes automatics
+with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
+  (unless noninteractive
+    (error "Use verilog-batch-delete-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
+  (verilog-batch-execute-func `verilog-delete-auto))
+
+(defun verilog-batch-inject-auto ()
+  "For use with --batch, perform automatic injection as a stand-alone tool.
+This sets up the appropriate Verilog-Mode environment, injects new automatics
+with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
+For proper results, multiple filenames need to be passed on the command
+line in bottom-up order."
+  (unless noninteractive
+    (error "Use verilog-batch-inject-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
+  (verilog-batch-execute-func `verilog-inject-auto))
+
+(defun verilog-batch-indent ()
+  "For use with --batch, reindent an a entire file as a stand-alone tool.
+This sets up the appropriate Verilog-Mode environment, calls
+\\[verilog-indent-buffer] on all command-line files, and saves the buffers."
+  (unless noninteractive
+    (error "Use verilog-batch-indent only with --batch"))  ;; Otherwise we'd mess up buffer modes
+  (verilog-batch-execute-func `verilog-indent-buffer))
+
+
+;;
+;; Indentation
+;;
+(defconst verilog-indent-alist
+  '((block       . (+ ind verilog-indent-level))
+    (case        . (+ ind verilog-case-indent))
+    (cparenexp   . (+ ind verilog-indent-level))
+    (cexp        . (+ ind verilog-cexp-indent))
+    (defun       . verilog-indent-level-module)
+    (declaration . verilog-indent-level-declaration)
+    (directive   . (verilog-calculate-indent-directive))
+    (tf          . verilog-indent-level)
+    (behavioral  . (+ verilog-indent-level-behavioral verilog-indent-level-module))
+    (statement   . ind)
+    (cpp         . 0)
+    (comment     . (verilog-comment-indent))
+    (unknown     . 3)
+    (string      . 0)))
+
+(defun verilog-continued-line-1 (lim)
+  "Return true if this is a continued line.
+Set point to where line starts.  Limit search to point LIM."
+  (let ((continued 't))
+    (if (eq 0 (forward-line -1))
+	(progn
+	  (end-of-line)
+	  (verilog-backward-ws&directives lim)
+	  (if (bobp)
+	      (setq continued nil)
+	    (setq continued (verilog-backward-token))))
+      (setq continued nil))
+    continued))
+
+(defun verilog-calculate-indent ()
+  "Calculate the indent of the current Verilog line.
+Examine previous lines.  Once a line is found that is definitive as to the
+type of the current line, return that lines' indent level and its
+type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
+  (save-excursion
+    (let* ((starting_position (point))
+	   (par 0)
+	   (begin (looking-at "[ \t]*begin\\>"))
+	   (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
+	   (type (catch 'nesting
+		   ;; Keep working backwards until we can figure out
+		   ;; what type of statement this is.
+		   ;; Basically we need to figure out
+		   ;; 1) if this is a continuation of the previous line;
+		   ;; 2) are we in a block scope (begin..end)
+
+		   ;; if we are in a comment, done.
+		   (if (verilog-in-star-comment-p)
+		       (throw 'nesting 'comment))
+
+		   ;; if we have a directive, done.
+		   (if (save-excursion (beginning-of-line) (looking-at verilog-directive-re-1))
+		       (throw 'nesting 'directive))
+
+		   ;; unless we are in the newfangled coverpoint or constraint blocks
+		   ;; if we are in a parenthesized list, and the user likes to indent these, return.
+		   (if (and
+			verilog-indent-lists
+			(not (verilog-in-coverage))
+			(verilog-in-paren))
+		       (progn (setq par 1)
+			      (throw 'nesting 'block))
+		     )
+
+		   ;; See if we are continuing a previous line
+		   (while t
+		     ;; trap out if we crawl off the top of the buffer
+		     (if (bobp) (throw 'nesting 'cpp))
+
+		     (if (verilog-continued-line-1 lim)
+			 (let ((sp (point)))
+			   (if (and
+				(not (looking-at verilog-complete-reg))
+				(verilog-continued-line-1 lim))
+			       (progn (goto-char sp)
+				      (throw 'nesting 'cexp))
+
+			     (goto-char sp))
+
+			   (if (and begin
+				    (not verilog-indent-begin-after-if)
+				    (looking-at verilog-no-indent-begin-re))
+			       (progn
+				 (beginning-of-line)
+				 (skip-chars-forward " \t")
+				 (throw 'nesting 'statement))
+			     (progn
+			       (throw 'nesting 'cexp))))
+		       ;; not a continued line
+		       (goto-char starting_position))
+
+		     (if (looking-at "\\<else\\>")
+			 ;; search back for governing if, striding across begin..end pairs
+			 ;; appropriately
+			 (let ((elsec 1))
+			   (while (verilog-re-search-backward verilog-ends-re nil 'move)
+			     (cond
+			      ((match-end 1) ; else, we're in deep
+			       (setq elsec (1+ elsec)))
+			      ((match-end 2) ; if
+			       (setq elsec (1- elsec))
+			       (if (= 0 elsec)
+				   (if verilog-align-ifelse
+				       (throw 'nesting 'statement)
+				     (progn ;; back up to first word on this line
+				       (beginning-of-line)
+				       (verilog-forward-syntactic-ws)
+				       (throw 'nesting 'statement)))))
+			      (t ; endblock
+				; try to leap back to matching outward block by striding across
+				; indent level changing tokens then immediately
+				; previous line governs indentation.
+			       (let (( reg) (nest 1))
+;;	 verilog-ends =>  else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
+				 (cond
+				  ((match-end 3) ; end
+				   ;; Search back for matching begin
+				   (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
+				  ((match-end 4) ; endcase
+				   ;; Search back for matching case
+				   (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
+				  ((match-end 5) ; endfunction
+				   ;; Search back for matching function
+				   (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
+				  ((match-end 6) ; endtask
+				   ;; Search back for matching task
+				   (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
+				  ((match-end 7) ; endspecify
+				   ;; Search back for matching specify
+				   (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
+				  ((match-end 8) ; endtable
+				   ;; Search back for matching table
+				   (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
+				  ((match-end 9) ; endgenerate
+				   ;; Search back for matching generate
+				   (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
+				  ((match-end 10) ; joins
+				   ;; Search back for matching fork
+				   (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
+				  ((match-end 11) ; class
+				   ;; Search back for matching class
+				   (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
+				  ((match-end 12) ; covergroup
+				   ;; Search back for matching covergroup
+				   (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
+				  )
+				 (catch 'skip
+				   (while (verilog-re-search-backward reg nil 'move)
+				     (cond
+				      ((match-end 1) ; begin
+				       (setq nest (1- nest))
+				       (if (= 0 nest)
+					   (throw 'skip 1)))
+				      ((match-end 2) ; end
+				       (setq nest (1+ nest)))))
+				   )
+				 ))
+			      ))))
+		     (throw 'nesting (verilog-calc-1))
+		     )
+		   );; catch nesting
+		 );; type
+	   )
+      ;; Return type of block and indent level.
+      (if (not type)
+	  (setq type 'cpp))
+      (if (> par 0)			; Unclosed Parenthesis
+	  (list 'cparenexp par)
+	(cond
+	  ((eq type 'case)
+	   (list type (verilog-case-indent-level)))
+	  ((eq type 'statement)
+	   (list type (current-column)))
+	  ((eq type 'defun)
+	   (list type 0))
+	  (t
+	   (list type (verilog-current-indent-level)))))
+      )))
+(defun verilog-wai ()
+  "Show matching nesting block for debugging."
+  (interactive)
+  (save-excursion
+    (let ((nesting (verilog-calc-1)))
+      (message "You are at nesting %s" nesting))))
+
+(defun verilog-calc-1 ()
+  (catch 'nesting
+    (while (verilog-re-search-backward (concat "\\({\\|}\\|" verilog-indent-re "\\)") nil 'move)
+      (cond
+       ((equal (char-after) ?\{)
+	(if (verilog-at-constraint-p)
+	    (throw 'nesting 'block)
+	  ))
+       ((equal (char-after) ?\})
+
+	(let ((there (verilog-at-close-constraint-p)))
+	  (if there (goto-char there))))
+
+       ((looking-at verilog-beg-block-re-ordered)
+	(cond
+	 ((match-end 2)  ; *sigh* could be "unique case" or "priority casex"
+	  (let ((here (point)))
+	    (verilog-beg-of-statement)
+	    (if (looking-at verilog-extended-case-re)
+		(throw 'nesting 'case)
+	      (goto-char here)))
+	  (throw 'nesting 'case))
+
+	 ;; need to consider typedef struct here...
+	 ((looking-at "\\<class\\|struct\\|function\\|task\\|property\\>")
+					; *sigh* These words have an optional prefix:
+					; extern {virtual|protected}? function a();
+					; assert property (p_1);
+	                                ; typedef class foo;
+					; and we don't want to confuse this with
+					; function a();
+	                                ; property
+					; ...
+					; endfunction
+	  (let ((here (point)))
+	    (save-excursion
+	      (verilog-beg-of-statement)
+	      (if (= (point) here)
+		  (throw 'nesting 'block))
+	      )))
+	 (t              (throw 'nesting 'block))))
+
+       ((looking-at verilog-end-block-re)
+	(verilog-leap-to-head)
+	(if (verilog-in-case-region-p)
+	    (progn
+	      (verilog-leap-to-case-head)
+	      (if (looking-at verilog-case-re)
+		  (throw 'nesting 'case)))))
+
+       ((looking-at (if (verilog-in-generate-region-p)
+			verilog-defun-level-not-generate-re
+		      verilog-defun-level-re))
+	(throw 'nesting 'defun))
+
+       ((looking-at verilog-cpp-level-re)
+	(throw 'nesting 'cpp))
+
+       ((bobp)
+	(throw 'nesting 'cpp))
+       ))
+    (throw 'nesting 'cpp)
+    )
+  )
+
+(defun verilog-calculate-indent-directive ()
+  "Return indentation level for directive.
+For speed, the searcher looks at the last directive, not the indent
+of the appropriate enclosing block."
+  (let ((base -1)	;; Indent of the line that determines our indentation
+	(ind 0)	        ;; Relative offset caused by other directives (like `endif on same line as `else)
+	)
+    ;; Start at current location, scan back for another directive
+
+    (save-excursion
+      (beginning-of-line)
+      (while (and (< base 0)
+		  (verilog-re-search-backward verilog-directive-re nil t))
+	(cond ((save-excursion (skip-chars-backward " \t") (bolp))
+	       (setq base (current-indentation))
+	       ))
+	(cond ((and (looking-at verilog-directive-end) (< base 0))  ;; Only matters when not at BOL
+	       (setq ind (- ind verilog-indent-level-directive)))
+	      ((and (looking-at verilog-directive-middle) (>= base 0))  ;; Only matters when at BOL
+	       (setq ind (+ ind verilog-indent-level-directive)))
+	      ((looking-at verilog-directive-begin)
+	       (setq ind (+ ind verilog-indent-level-directive)))))
+      ;; Adjust indent to starting indent of critical line
+      (setq ind (max 0 (+ ind base))))
+
+    (save-excursion
+      (beginning-of-line)
+      (skip-chars-forward " \t")
+      (cond ((or (looking-at verilog-directive-middle)
+		 (looking-at verilog-directive-end))
+	     (setq ind (max 0 (- ind verilog-indent-level-directive))))))
+   ind))
+
+(defun verilog-leap-to-case-head ()
+  (let ((nest 1))
+    (while (/= 0 nest)
+      (verilog-re-search-backward "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" nil 'move)
+      (cond
+       ((match-end 1)
+	(setq nest (1- nest)))
+       ((match-end 2)
+	(setq nest (1+ nest)))
+       ((bobp)
+	(ding 't)
+	(setq nest 0))))))
+
+(defun verilog-leap-to-head ()
+  "Move point to the head of this block; jump from end to matching begin,
+from endcase to matching case, and so on."
+  (let ((reg nil)
+	snest
+	(nest 1))
+    (cond
+     ((looking-at "\\<end\\>")
+      ;; 1: Search back for matching begin
+      (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
+			"\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
+     ((looking-at "\\<endcase\\>")
+      ;; 2: Search back for matching case
+      (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)" ))
+     ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
+      ;; 3: Search back for matching fork
+      (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
+     ((looking-at "\\<endclass\\>")
+      ;; 4: Search back for matching class
+      (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
+     ((looking-at "\\<endtable\\>")
+      ;; 5: Search back for matching table
+      (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
+     ((looking-at "\\<endspecify\\>")
+      ;; 6: Search back for matching specify
+      (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
+     ((looking-at "\\<endfunction\\>")
+      ;; 7: Search back for matching function
+      (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
+     ((looking-at "\\<endgenerate\\>")
+      ;; 8: Search back for matching generate
+      (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
+     ((looking-at "\\<endtask\\>")
+      ;; 9: Search back for matching task
+      (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
+     ((looking-at "\\<endgroup\\>")
+      ;; 10: Search back for matching covergroup
+      (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
+     ((looking-at "\\<endproperty\\>")
+      ;; 11: Search back for matching property
+      (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
+     ((looking-at "\\<endinterface\\>")
+      ;; 12: Search back for matching interface
+      (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
+     ((looking-at "\\<endsequence\\>")
+      ;; 12: Search back for matching sequence
+      (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
+     ((looking-at "\\<endclocking\\>")
+      ;; 12: Search back for matching clocking
+      (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" ))
+     )
+    (if reg
+	(catch 'skip
+	  (let (sreg)
+	    (while (verilog-re-search-backward reg nil 'move)
+	      (cond
+	       ((match-end 1) ; begin
+		(setq nest (1- nest))
+		(if (= 0 nest)
+		    ;; Now previous line describes syntax
+		    (throw 'skip 1))
+		(if (and snest
+			 (= snest nest))
+		    (setq reg sreg)))
+	       ((match-end 2) ; end
+		(setq nest (1+ nest)))
+	       ((match-end 3)
+		;; endcase, jump to case
+		(setq snest nest)
+		(setq nest (1+ nest))
+		(setq sreg reg)
+		(setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
+	       ((match-end 4)
+		;; join, jump to fork
+		(setq snest nest)
+		(setq nest (1+ nest))
+		(setq sreg reg)
+		(setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
+	       )))))))
+
+(defun verilog-continued-line ()
+  "Return true if this is a continued line.
+Set point to where line starts"
+  (let ((continued 't))
+    (if (eq 0 (forward-line -1))
+	(progn
+	  (end-of-line)
+	  (verilog-backward-ws&directives)
+	  (if (bobp)
+	      (setq continued nil)
+	    (while (and continued
+			(save-excursion
+			  (skip-chars-backward " \t")
+			  (not (bolp))))
+	    (setq continued (verilog-backward-token))
+	    ) ;; while
+	    ))
+      (setq continued nil))
+    continued))
+
+(defun verilog-backward-token ()
+  "Step backward token, returning true if we are now at an end of line token."
+  (interactive)
+  (verilog-backward-syntactic-ws)
+  (cond
+   ((bolp)
+    nil)
+   (;-- Anything ending in a ; is complete
+    (= (preceding-char) ?\;)
+    nil)
+   (; If a "}" is prefixed by a ";", then this is a complete statement
+    ; i.e.: constraint foo { a = b; }
+    (= (preceding-char) ?\})
+    (progn
+      (backward-char)
+      (verilog-at-close-constraint-p))
+    )
+   (;-- constraint foo { a = b }
+    ;   is a complete statement. *sigh*
+    (= (preceding-char) ?\{)
+    (progn
+      (backward-char)
+      (not (verilog-at-constraint-p)))
+    )
+   (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
+    ;   also could be simply '@(foo)'
+    ;   or foo u1 #(a=8)
+    ;            (b, ... which ISN'T complete
+    ;;;; Do we need this???
+    (= (preceding-char) ?\))
+    (progn
+      (backward-char)
+      (backward-up-list 1)
+      (verilog-backward-syntactic-ws)
+      (let ((back (point)))
+	(forward-word -1)
+	(cond
+	 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
+	  (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
+	 (t
+	  (goto-char back)
+	  (cond
+	   ((= (preceding-char) ?\@)
+	    (backward-char)
+	    (save-excursion
+	      (verilog-backward-token)
+	      (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
+	   ((= (preceding-char) ?\#)
+	    (backward-char)
+	    )
+	   (t t))
+	  )))))
+
+   (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
+    t
+    (forward-word -1)
+    (cond
+     ((looking-at "\\<else\\>")
+      t)
+     ((looking-at verilog-indent-re)
+      nil)
+     (t
+      (let
+	  ((back (point)))
+	(verilog-backward-syntactic-ws)
+	(cond
+	 ((= (preceding-char) ?\:)
+	  (backward-char)
+	  (verilog-backward-syntactic-ws)
+	  (backward-sexp)
+	  (if (looking-at verilog-nameable-item-re )
+	      nil
+	    t)
+	  )
+	 ((= (preceding-char) ?\#)
+	  (backward-char)
+	  t)
+	 ((= (preceding-char) ?\`)
+	  (backward-char)
+	  t)
+
+	 (t
+	  (goto-char back)
+	  t)
+	 )))))))
+
+(defun verilog-backward-syntactic-ws (&optional bound)
+  "Backward skip over syntactic whitespace for Emacs 19.
+Optional BOUND limits search."
+  (save-restriction
+    (let* ((bound (or bound (point-min))) (here bound) )
+      (if (< bound (point))
+	  (progn
+	    (narrow-to-region bound (point))
+	    (while (/= here (point))
+	      (setq here (point))
+	      (verilog-skip-backward-comments)
+	      )))
+      ))
+  t)
+
+(defun verilog-forward-syntactic-ws (&optional bound)
+  "Forward skip over syntactic whitespace for Emacs 19.
+Optional BOUND limits search."
+  (save-restriction
+    (let* ((bound (or bound (point-max)))
+	   (here bound)
+	   )
+      (if (> bound (point))
+	  (progn
+	    (narrow-to-region (point) bound)
+	    (while (/= here (point))
+	      (setq here (point))
+	      (forward-comment (buffer-size))
+	      )))
+      )))
+
+(defun verilog-backward-ws&directives (&optional bound)
+  "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
+Optional BOUND limits search."
+  (save-restriction
+    (let* ((bound (or bound (point-min)))
+	   (here bound)
+	   (p nil) )
+      (if (< bound (point))
+	  (progn
+	    (let ((state
+		   (save-excursion
+		     (parse-partial-sexp (point-min) (point)))))
+	      (cond
+	       ((nth 7 state) ;; in // comment
+		(verilog-re-search-backward "//" nil 'move)
+                (skip-chars-backward "/"))
+	       ((nth 4 state) ;; in /* */ comment
+		(verilog-re-search-backward "/\*" nil 'move))))
+	    (narrow-to-region bound (point))
+	    (while (/= here (point))
+	      (setq here (point))
+	      (verilog-skip-backward-comments)
+	      (setq p
+		    (save-excursion
+		      (beginning-of-line)
+		      (cond
+		       ((verilog-within-translate-off)
+			(verilog-back-to-start-translate-off (point-min)))
+		       ((looking-at verilog-directive-re-1)
+			(point))
+		       (t
+			nil))))
+	      (if p (goto-char p))
+	      )))
+      )))
+
+(defun verilog-forward-ws&directives (&optional bound)
+  "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
+Optional BOUND limits search."
+  (save-restriction
+    (let* ((bound (or bound (point-max)))
+	   (here bound)
+	   jump
+	   )
+      (if (> bound (point))
+	  (progn
+	    (let ((state
+		   (save-excursion
+		     (parse-partial-sexp (point-min) (point)))))
+	      (cond
+	       ((nth 7 state) ;; in // comment
+		(verilog-re-search-forward "//" nil 'move))
+	       ((nth 4 state) ;; in /* */ comment
+		(verilog-re-search-forward "/\*" nil 'move))))
+	    (narrow-to-region (point) bound)
+	    (while (/= here (point))
+	      (setq here (point)
+		    jump nil)
+	      (forward-comment (buffer-size))
+	      (save-excursion
+		(beginning-of-line)
+		(if (looking-at verilog-directive-re-1)
+		    (setq jump t)))
+	      (if jump
+		  (beginning-of-line 2))
+	      )))
+      )))
+
+(defun verilog-in-comment-p ()
+ "Return true if in a star or // comment."
+ (let ((state
+	(save-excursion
+	  (parse-partial-sexp (point-min) (point)))))
+   (or (nth 4 state) (nth 7 state))))
+
+(defun verilog-in-star-comment-p ()
+ "Return true if in a star comment."
+ (let ((state
+	(save-excursion
+	  (parse-partial-sexp (point-min) (point)))))
+   (and
+    (nth 4 state)			; t if in a comment of style a // or b /**/
+	(not
+	 (nth 7 state)			; t if in a comment of style b /**/
+	 ))))
+
+(defun verilog-in-slash-comment-p ()
+ "Return true if in a slash comment."
+ (let ((state
+	(save-excursion
+	  (parse-partial-sexp (point-min) (point)))))
+   (nth 7 state)))
+
+(defun verilog-in-comment-or-string-p ()
+ "Return true if in a string or comment."
+ (let ((state
+	(save-excursion
+	  (parse-partial-sexp (point-min) (point)))))
+   (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
+
+(defun verilog-in-escaped-name-p ()
+ "Return true if in an escaped name."
+ (save-excursion
+   (backward-char)
+   (skip-chars-backward "^ \t\n\f")
+   (if (equal (char-after (point) ) ?\\ )
+       t
+     nil)))
+
+(defun verilog-in-paren ()
+ "Return true if in a parenthetical expression."
+ (let ((state
+	(save-excursion
+	  (parse-partial-sexp (point-min) (point)))))
+   (> (nth 0 state) 0 )))
+
+(defun verilog-in-coverage ()
+ "Return true if in a constraint or coverpoint expression."
+ (interactive)
+ (save-excursion
+   (if (verilog-in-paren)
+       (progn
+	 (backward-up-list 1)
+	 (verilog-at-constraint-p)
+	 )
+     nil)))
+(defun verilog-at-close-constraint-p ()
+  "If at the } that closes a constraint or covergroup, return true."
+  (if (and
+       (equal (char-after) ?\})
+       (verilog-in-paren))
+
+      (save-excursion
+	(verilog-backward-ws&directives)
+	(if (equal (char-before) ?\;)
+	    (point)
+	  nil))))
+
+(defun verilog-at-constraint-p ()
+  "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
+  (if (save-excursion
+	(and
+	 (equal (char-after) ?\{)
+	 (forward-list)
+	 (progn (backward-char 1)
+		(verilog-backward-ws&directives)
+		(equal (char-before) ?\;))
+	 ))
+      ;; maybe
+      (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
+    ;; not
+    nil
+    )
+  )
+
+(defun verilog-parenthesis-depth ()
+ "Return non zero if in parenthetical-expression."
+ (save-excursion
+   (nth 1 (parse-partial-sexp (point-min) (point)))))
+
+
+(defun verilog-skip-forward-comment-or-string ()
+ "Return true if in a string or comment."
+ (let ((state
+	(save-excursion
+	  (parse-partial-sexp (point-min) (point)))))
+   (cond
+    ((nth 3 state)			;Inside string
+     (goto-char (nth 3 state))
+     t)
+    ((nth 7 state)			;Inside // comment
+     (forward-line 1)
+     t)
+    ((nth 4 state)			;Inside any comment (hence /**/)
+     (search-forward "*/"))
+    (t
+     nil))))
+
+(defun verilog-skip-backward-comment-or-string ()
+ "Return true if in a string or comment."
+ (let ((state
+	(save-excursion
+	  (parse-partial-sexp (point-min) (point)))))
+   (cond
+    ((nth 3 state)			;Inside string
+     (search-backward "\"")
+     t)
+    ((nth 7 state)			;Inside // comment
+     (search-backward "//")
+     (skip-chars-backward "/")
+     t)
+    ((nth 4 state)			;Inside /* */ comment
+     (search-backward "/*")
+     t)
+    (t
+     nil))))
+
+(defun verilog-skip-backward-comments ()
+ "Return true if a comment was skipped."
+ (let ((more t))
+   (while more
+     (setq more
+	   (let ((state
+		  (save-excursion
+		    (parse-partial-sexp (point-min) (point)))))
+	     (cond
+	      ((nth 7 state)			;Inside // comment
+	       (search-backward "//")
+	       (skip-chars-backward "/")
+	       (skip-chars-backward " \t\n\f")
+	       t)
+	      ((nth 4 state)			;Inside /* */ comment
+	       (search-backward "/*")
+	       (skip-chars-backward " \t\n\f")
+	       t)
+	      ((and (not (bobp))
+		    (= (char-before) ?\/)
+		    (= (char-before (1- (point))) ?\*)
+		    )
+	       (goto-char (- (point) 2))
+	       t)
+	      (t
+	       (skip-chars-backward " \t\n\f")
+	       nil)))))))
+
+(defun verilog-skip-forward-comment-p ()
+  "If in comment, move to end and return true."
+  (let (state)
+    (progn
+      (setq state
+	    (save-excursion
+	      (parse-partial-sexp (point-min) (point))))
+      (cond
+       ((nth 3 state)
+	t)
+       ((nth 7 state)			;Inside // comment
+	(end-of-line)
+	(forward-char 1)
+	t)
+       ((nth 4 state)			;Inside any comment
+	t)
+       (t
+	nil)))))
+
+(defun verilog-indent-line-relative ()
+  "Cheap version of indent line.
+Only look at a few lines to determine indent level."
+  (interactive)
+  (let ((indent-str)
+	(sp (point)))
+    (if (looking-at "^[ \t]*$")
+	(cond  ;- A blank line; No need to be too smart.
+	 ((bobp)
+	  (setq indent-str (list 'cpp 0)))
+	 ((verilog-continued-line)
+	  (let ((sp1 (point)))
+	    (if (verilog-continued-line)
+		(progn (goto-char sp)
+		       (setq indent-str (list 'statement (verilog-current-indent-level))))
+	      (goto-char sp1)
+	      (setq indent-str (list 'block (verilog-current-indent-level)))))
+	  (goto-char sp))
+	 ((goto-char sp)
+	  (setq indent-str (verilog-calculate-indent))))
+      (progn (skip-chars-forward " \t")
+	     (setq indent-str (verilog-calculate-indent))))
+    (verilog-do-indent indent-str)))
+
+(defun verilog-indent-line ()
+  "Indent for special part of code."
+  (verilog-do-indent (verilog-calculate-indent)))
+
+(defun verilog-do-indent (indent-str)
+  (let ((type (car indent-str))
+	(ind (car (cdr indent-str))))
+    (cond
+     (; handle continued exp
+      (eq type 'cexp)
+      (let ((here (point)))
+	(verilog-backward-syntactic-ws)
+	(cond
+	 ((or
+	   (= (preceding-char) ?\,)
+	   (= (preceding-char) ?\])
+	   (save-excursion
+	     (verilog-beg-of-statement-1)
+	     (looking-at verilog-declaration-re)))
+	  (let* ( fst
+		  (val
+		   (save-excursion
+		     (backward-char 1)
+		     (verilog-beg-of-statement-1)
+		     (setq fst (point))
+		     (if (looking-at verilog-declaration-re)
+			 (progn ;; we have multiple words
+			   (goto-char (match-end 0))
+			   (skip-chars-forward " \t")
+			   (cond
+			    ((and verilog-indent-declaration-macros
+				  (= (following-char) ?\`))
+			     (progn
+			       (forward-char 1)
+			       (forward-word 1)
+			       (skip-chars-forward " \t")))
+			    ((= (following-char) ?\[)
+			     (progn
+			       (forward-char 1)
+			       (backward-up-list -1)
+			       (skip-chars-forward " \t")))
+			    )
+			   (current-column))
+		       (progn
+			 (goto-char fst)
+			 (+ (current-column) verilog-cexp-indent))
+		       ))))
+	    (goto-char here)
+	    (indent-line-to val))
+	  )
+	 ((= (preceding-char) ?\) )
+	  (goto-char here)
+	  (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
+	    (indent-line-to val)))
+	 (t
+	  (goto-char here)
+	  (let ((val))
+	    (verilog-beg-of-statement-1)
+	    (if (and (< (point) here)
+		     (verilog-re-search-forward "=[ \\t]*" here 'move))
+		(setq val (current-column))
+	      (setq val (eval (cdr (assoc type verilog-indent-alist)))))
+	    (goto-char here)
+	    (indent-line-to val)))
+	 )))
+
+     (; handle inside parenthetical expressions
+      (eq type 'cparenexp)
+      (let ((val (save-excursion
+		   (backward-up-list 1)
+		   (forward-char 1)
+		   (skip-chars-forward " \t")
+		   (current-column))))
+	(indent-line-to val)
+	(if (and (not (verilog-in-struct-region-p))
+		 (looking-at verilog-declaration-re))
+	    (verilog-indent-declaration ind))
+	))
+
+     (;-- Handle the ends
+      (or
+       (looking-at verilog-end-block-re )
+       (verilog-at-close-constraint-p))
+      (let ((val (if (eq type 'statement)
+		     (- ind verilog-indent-level)
+		   ind)))
+	(indent-line-to val)))
+
+     (;-- Case -- maybe line 'em up
+      (and (eq type 'case) (not (looking-at "^[ \t]*$")))
+      (progn
+	(cond
+	 ((looking-at "\\<endcase\\>")
+	  (indent-line-to ind))
+	 (t
+	  (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
+	    (indent-line-to val))))))
+
+     (;-- defun
+      (and (eq type 'defun)
+	   (looking-at verilog-zero-indent-re))
+      (indent-line-to 0))
+
+     (;-- declaration
+      (and (or
+	    (eq type 'defun)
+	    (eq type 'block))
+	   (looking-at verilog-declaration-re))
+      (verilog-indent-declaration ind))
+
+     (;-- Everything else
+      t
+      (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
+	(indent-line-to val)))
+     )
+    (if (looking-at "[ \t]+$")
+	(skip-chars-forward " \t"))
+    indent-str				; Return indent data
+    ))
+
+(defun verilog-current-indent-level ()
+  "Return the indent-level the current statement has."
+  (save-excursion
+    (let (par-pos)
+      (beginning-of-line)
+      (setq par-pos (verilog-parenthesis-depth))
+      (while par-pos
+	(goto-char par-pos)
+	(beginning-of-line)
+	(setq par-pos (verilog-parenthesis-depth)))
+      (skip-chars-forward " \t")
+      (current-column))))
+
+(defun verilog-case-indent-level ()
+  "Return the indent-level the current statement has.
+Do not count named blocks or case-statements."
+  (save-excursion
+    (skip-chars-forward " \t")
+    (cond
+     ((looking-at verilog-named-block-re)
+      (current-column))
+     ((and (not (looking-at verilog-case-re))
+	   (looking-at "^[^:;]+[ \t]*:"))
+      (verilog-re-search-forward ":" nil t)
+      (skip-chars-forward " \t")
+      (current-column))
+     (t
+      (current-column)))))
+
+(defun verilog-indent-comment ()
+  "Indent current line as comment."
+  (let* ((stcol
+	  (cond
+	   ((verilog-in-star-comment-p)
+	    (save-excursion
+	      (re-search-backward "/\\*" nil t)
+	      (1+(current-column))))
+	   (comment-column
+	     comment-column )
+	   (t
+	    (save-excursion
+	      (re-search-backward "//" nil t)
+	      (current-column)))
+	   )))
+    (indent-line-to stcol)
+    stcol))
+
+(defun verilog-more-comment ()
+  "Make more comment lines like the previous."
+  (let* ((star 0)
+	 (stcol
+	  (cond
+	   ((verilog-in-star-comment-p)
+	    (save-excursion
+	      (setq star 1)
+	      (re-search-backward "/\\*" nil t)
+	      (1+(current-column))))
+	   (comment-column
+	    comment-column )
+	   (t
+	    (save-excursion
+	      (re-search-backward "//" nil t)
+	      (current-column)))
+	   )))
+    (progn
+      (indent-to stcol)
+      (if (and star
+	       (save-excursion
+		 (forward-line -1)
+		 (skip-chars-forward " \t")
+		 (looking-at "\*")))
+	  (insert "* ")))))
+
+(defun verilog-comment-indent (&optional arg)
+  "Return the column number the line should be indented to.
+ARG is ignored, for `comment-indent-function' compatibility."
+  (cond
+   ((verilog-in-star-comment-p)
+    (save-excursion
+      (re-search-backward "/\\*" nil t)
+      (1+(current-column))))
+   ( comment-column
+     comment-column )
+   (t
+    (save-excursion
+      (re-search-backward "//" nil t)
+      (current-column)))))
+
+;;
+
+(defun verilog-pretty-declarations ()
+  "Line up declarations around point."
+  (interactive)
+  (save-excursion
+    (if (progn
+	  (verilog-beg-of-statement-1)
+	  (looking-at verilog-declaration-re))
+	(let* ((m1 (make-marker))
+	       (e) (r)
+	       (here (point))
+	       ;; Start of declaration range
+	       (start
+		(progn
+		  (verilog-beg-of-statement-1)
+		  (while (looking-at verilog-declaration-re)
+		    (beginning-of-line)
+		    (setq e (point))
+		    (verilog-backward-syntactic-ws)
+		    (backward-char)
+		    (verilog-beg-of-statement-1)) ;Ack, need to grok `define
+		  e))
+	       ;; End of declaration range
+	       (end
+		(progn
+		  (goto-char here)
+		  (verilog-end-of-statement)
+		  (setq e (point))	;Might be on last line
+		  (verilog-forward-syntactic-ws)
+		  (while (looking-at verilog-declaration-re)
+		    (beginning-of-line)
+		    (verilog-end-of-statement)
+		    (setq e (point))
+		    (verilog-forward-syntactic-ws))
+		  e))
+	       (edpos (set-marker (make-marker) end))
+	       (ind)
+	       (base-ind
+		(progn
+		  (goto-char start)
+		  (verilog-do-indent (verilog-calculate-indent))
+		  (verilog-forward-ws&directives)
+		  (current-column)))
+	       )
+	  (goto-char end)
+	  (goto-char start)
+	  (if (> (- end start) 100)
+	      (message "Lining up declarations..(please stand by)"))
+	  ;; Get the beginning of line indent first
+	  (while (progn (setq e (marker-position edpos))
+			(< (point) e))
+	    (cond
+	     ( (save-excursion (skip-chars-backward " \t")
+			       (bolp))
+	       (verilog-forward-ws&directives)
+	       (indent-line-to base-ind)
+	       (verilog-forward-ws&directives)
+	       (verilog-re-search-forward "[ \t\n\f]" e 'move)
+	       )
+	     (t
+	      (just-one-space)
+	      (verilog-re-search-forward "[ \t\n\f]" e 'move)
+	      )
+	     )
+	    )
+	    ;;(forward-line))
+	  ;; Now find biggest prefix
+	  (setq ind (verilog-get-lineup-indent start edpos))
+	  ;; Now indent each line.
+	  (goto-char start)
+	  (while (progn (setq e (marker-position edpos))
+			(setq r (- e (point)))
+			(> r 0))
+	    (setq e (point))
+	    (message "%d" r)
+	    (cond
+	     ((or (and verilog-indent-declaration-macros
+		       (looking-at verilog-declaration-re-1-macro))
+		  (looking-at verilog-declaration-re-1-no-macro))
+	      (let ((p (match-end 0)))
+		(set-marker m1 p)
+		(if (verilog-re-search-forward "[[#`]" p 'move)
+		    (progn
+		      (forward-char -1)
+		      (just-one-space)
+		      (goto-char (marker-position m1))
+		      (just-one-space)
+		      (indent-to ind))
+		  (progn
+		    (just-one-space)
+		    (indent-to ind))
+		  )))
+	     ((verilog-continued-line-1 start)
+	      (goto-char e)
+	      (indent-line-to ind))
+	     (t		; Must be comment or white space
+	      (goto-char e)
+	      (verilog-forward-ws&directives)
+	      (forward-line -1))
+	     )
+	    (forward-line 1))
+	  (message "")))))
+
+(defun verilog-pretty-expr (&optional myre)
+  "Line up expressions around point."
+  (interactive "sRegular Expression: ((<|:)?=) ")
+  (save-excursion
+    (if (or (eq myre nil)
+	    (string-equal myre ""))
+	(setq myre "\\(<\\|:\\)?="))
+;    (setq myre (concat "\\(^[^;" myre "]*\\)\\([" myre "]\\)"))
+    (setq myre (concat "\\(^[^;#:?=]*\\)\\([" myre "]\\)"))
+    (beginning-of-line)
+    (if (and (not (looking-at (concat "^\\s-*" verilog-complete-reg)))
+	     (looking-at myre))
+	(let* ((here (point))
+	       (e) (r)
+	       (start
+		(progn
+		  (beginning-of-line)
+		  (setq e (point))
+		  (verilog-backward-syntactic-ws)
+		  (beginning-of-line)
+		  (while (and (not (looking-at (concat "^\\s-*" verilog-complete-reg)))
+			      (looking-at myre)
+			      (not (bobp))
+			      )
+		    (setq e (point))
+		    (verilog-backward-syntactic-ws)
+		    (beginning-of-line)
+		    ) ;Ack, need to grok `define
+		  e))
+	       (end
+		(progn
+		  (goto-char here)
+		  (end-of-line)
+		  (setq e (point))	;Might be on last line
+		  (verilog-forward-syntactic-ws)
+		  (beginning-of-line)
+		  (while (and (not(looking-at (concat "^\\s-*" verilog-complete-reg)))
+			      (looking-at myre))
+		    (end-of-line)
+		    (setq e (point))
+		    (verilog-forward-syntactic-ws)
+		    (beginning-of-line)
+		    )
+		  e))
+	       (edpos (set-marker (make-marker) end))
+	       (ind)
+	       )
+	  (goto-char start)
+	  (verilog-do-indent (verilog-calculate-indent))
+	  (if (> (- end start) 100)
+	      (message "Lining up expressions..(please stand by)"))
+
+	  ;; Set indent to minimum throughout region
+	  (while (< (point) (marker-position edpos))
+	    (beginning-of-line)
+	    (verilog-just-one-space myre)
+	    (end-of-line)
+	    (verilog-forward-syntactic-ws)
+	    )
+
+	  ;; Now find biggest prefix
+	  (setq ind (verilog-get-lineup-indent-2 myre start edpos))
+
+	  ;; Now indent each line.
+	  (goto-char start)
+	  (while (progn (setq e (marker-position edpos))
+			(setq r (- e (point)))
+			(> r 0))
+	    (setq e (point))
+	    (message "%d" r)
+	    (cond
+	     ((looking-at myre)
+	      (goto-char (match-end 1))
+	      (if (eq (char-after) ?=)
+		  (indent-to (1+ ind))	; line up the = of the <= with surrounding =
+		(indent-to ind)
+		)
+	      )
+	     ((verilog-continued-line-1 start)
+	      (goto-char e)
+	      (indent-line-to ind))
+	     (t		; Must be comment or white space
+	      (goto-char e)
+	      (verilog-forward-ws&directives)
+	      (forward-line -1))
+	     )
+	    (forward-line 1))
+	  (message "")
+	  ))))
+
+(defun verilog-just-one-space (myre)
+  "Remove extra spaces around regular expression MYRE."
+  (interactive)
+  (if (and (not(looking-at verilog-complete-reg))
+	   (looking-at myre))
+      (let ((p1 (match-end 1))
+	    (p2 (match-end 2)))
+	(progn
+	  (goto-char p2)
+	  (if (looking-at "\\s-") (just-one-space) )
+	  (goto-char p1)
+	  (forward-char -1)
+	  (if (looking-at "\\s-") (just-one-space))
+	  )
+	))
+  (message ""))
+
+(defun verilog-indent-declaration (baseind)
+  "Indent current lines as declaration.
+Line up the variable names based on previous declaration's indentation.
+BASEIND is the base indent to offset everything."
+  (interactive)
+  (let ((pos (point-marker))
+	(lim (save-excursion
+	       ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
+	       (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
+	       (point)))
+	(ind)
+	(val)
+	(m1 (make-marker))
+	)
+    (setq val (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
+    (indent-line-to val)
+
+    ;; Use previous declaration (in this module) as template.
+    (if (or (memq 'all verilog-auto-lineup)
+	    (memq 'declaration verilog-auto-lineup))
+	(if (verilog-re-search-backward
+	     (or (and verilog-indent-declaration-macros
+		      verilog-declaration-re-1-macro)
+		 verilog-declaration-re-1-no-macro) lim t)
+	    (progn
+	      (goto-char (match-end 0))
+	      (skip-chars-forward " \t")
+	      (setq ind (current-column))
+	      (goto-char pos)
+	      (setq val (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
+	      (indent-line-to val)
+	      (if (and verilog-indent-declaration-macros
+		       (looking-at verilog-declaration-re-2-macro))
+		  (let ((p (match-end 0)))
+		    (set-marker m1 p)
+		    (if (verilog-re-search-forward "[[#`]" p 'move)
+			(progn
+			  (forward-char -1)
+			  (just-one-space)
+			  (goto-char (marker-position m1))
+			  (just-one-space)
+			  (indent-to ind)
+			  )
+		      (if (/= (current-column) ind)
+			  (progn
+			    (just-one-space)
+			    (indent-to ind))
+			)))
+		(if (looking-at verilog-declaration-re-2-no-macro)
+		    (let ((p (match-end 0)))
+		      (set-marker m1 p)
+		      (if (verilog-re-search-forward "[[`#]" p 'move)
+			  (progn
+			    (forward-char -1)
+			    (just-one-space)
+			    (goto-char (marker-position m1))
+			    (just-one-space)
+			    (indent-to ind))
+			(if (/= (current-column) ind)
+			    (progn
+			      (just-one-space)
+			      (indent-to ind))
+			  )))
+		  )))
+	  )
+      )
+    (goto-char pos)
+    )
+  )
+
+(defun verilog-get-lineup-indent (b edpos)
+  "Return the indent level that will line up several lines within the region.
+Region is defined by B and EDPOS."
+  (save-excursion
+    (let ((ind 0) e)
+      (goto-char b)
+      ;; Get rightmost position
+      (while (progn (setq e (marker-position edpos))
+		    (< (point) e))
+	(if (verilog-re-search-forward
+	     (or (and verilog-indent-declaration-macros
+		      verilog-declaration-re-1-macro)
+		 verilog-declaration-re-1-no-macro) e 'move)
+	    (progn
+	      (goto-char (match-end 0))
+	      (verilog-backward-syntactic-ws)
+	      (if (> (current-column) ind)
+		  (setq ind (current-column)))
+	      (goto-char (match-end 0)))))
+      (if (> ind 0)
+	  (1+ ind)
+	;; No lineup-string found
+	(goto-char b)
+	(end-of-line)
+	(skip-chars-backward " \t")
+	(1+ (current-column))))))
+
+(defun verilog-get-lineup-indent-2 (myre b edpos)
+  "Return the indent level that will line up several lines within the region."
+  (save-excursion
+    (let ((ind 0) e)
+      (goto-char b)
+      ;; Get rightmost position
+      (while (progn (setq e (marker-position edpos))
+		    (< (point) e))
+	(if (verilog-re-search-forward myre e 'move)
+	    (progn
+	      (goto-char (match-end 0))
+	      (verilog-backward-syntactic-ws)
+	      (if (> (current-column) ind)
+		  (setq ind (current-column)))
+	      (goto-char (match-end 0)))))
+      (if (> ind 0)
+	  (1+ ind)
+	;; No lineup-string found
+	(goto-char b)
+	(end-of-line)
+	(skip-chars-backward " \t")
+	(1+ (current-column))))))
+
+(defun verilog-comment-depth (type val)
+  "A useful mode debugging aide.  TYPE and VAL are comments for insertion."
+  (save-excursion
+    (let
+	((b (prog2
+		(beginning-of-line)
+		(point-marker)
+	      (end-of-line)))
+	 (e (point-marker)))
+      (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
+	  (progn
+	    (replace-match " /* -#  ## */")
+	    (end-of-line))
+	(progn
+	  (end-of-line)
+	  (insert " /* ##  ## */"))))
+    (backward-char 6)
+    (insert
+     (format "%s %d" type val))))
+
+;; 
+;;
+;; Completion
+;;
+(defvar verilog-str nil)
+(defvar verilog-all nil)
+(defvar verilog-pred nil)
+(defvar verilog-buffer-to-use nil)
+(defvar verilog-flag nil)
+(defvar verilog-toggle-completions nil
+  "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
+Repeated use of \\[verilog-complete-word] will show you all of them.
+Normally, when there is more than one possible completion,
+it displays a list of all possible completions.")
+
+
+(defvar verilog-type-keywords
+  '(
+    "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
+    "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
+    "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pullup"
+    "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
+    "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
+    "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
+    )
+  "*Keywords for types used when completing a word in a declaration or parmlist.
+\(eg.  integer, real, reg...)")
+
+(defvar verilog-cpp-keywords
+  '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
+    "endif")
+  "*Keywords to complete when at first word of a line in declarative scope.
+\(eg.  initial, always, begin, assign.)
+The procedures and variables defined within the Verilog program
+will be completed runtime and should not be added to this list.")
+
+(defvar verilog-defun-keywords
+  (append
+   '(
+     "always" "always_comb" "always_ff" "always_latch" "assign"
+     "begin" "end" "generate" "endgenerate" "module" "endmodule"
+     "specify" "endspecify" "function" "endfunction" "initial" "final"
+     "task" "endtask" "primitive" "endprimitive"
+     )
+   verilog-type-keywords)
+  "*Keywords to complete when at first word of a line in declarative scope.
+\(eg.  initial, always, begin, assign.)
+The procedures and variables defined within the Verilog program
+will be completed runtime and should not be added to this list.")
+
+(defvar verilog-block-keywords
+  '(
+    "begin" "break" "case" "continue" "else" "end" "endfunction"
+    "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
+    "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
+    "while")
+  "*Keywords to complete when at first word of a line in behavioral scope.
+\(eg.  begin, if, then, else, for, fork.)
+The procedures and variables defined within the Verilog program
+will be completed runtime and should not be added to this list.")
+
+(defvar verilog-tf-keywords
+  '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
+  "*Keywords to complete when at first word of a line in a task or function.
+\(eg.  begin, if, then, else, for, fork.)
+The procedures and variables defined within the Verilog program
+will be completed runtime and should not be added to this list.")
+
+(defvar verilog-case-keywords
+  '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
+  "*Keywords to complete when at first word of a line in case scope.
+\(eg.  begin, if, then, else, for, fork.)
+The procedures and variables defined within the Verilog program
+will be completed runtime and should not be added to this list.")
+
+(defvar verilog-separator-keywords
+  '("else" "then" "begin")
+  "*Keywords to complete when NOT standing at the first word of a statement.
+\(eg.  else, then.)
+Variables and function names defined within the
+Verilog program are completed runtime and should not be added to this list.")
+
+(defun verilog-string-diff (str1 str2)
+  "Return index of first letter where STR1 and STR2 differs."
+  (catch 'done
+    (let ((diff 0))
+      (while t
+	(if (or (> (1+ diff) (length str1))
+		(> (1+ diff) (length str2)))
+	    (throw 'done diff))
+	(or (equal (aref str1 diff) (aref str2 diff))
+	    (throw 'done diff))
+	(setq diff (1+ diff))))))
+
+;; Calculate all possible completions for functions if argument is `function',
+;; completions for procedures if argument is `procedure' or both functions and
+;; procedures otherwise.
+
+(defun verilog-func-completion (type)
+  "Build regular expression for module/task/function names.
+TYPE is 'module, 'tf for task or function, or t if unknown."
+  (if (string= verilog-str "")
+      (setq verilog-str "[a-zA-Z_]"))
+  (let ((verilog-str (concat (cond
+			     ((eq type 'module) "\\<\\(module\\)\\s +")
+			     ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
+			     (t "\\<\\(task\\|function\\|module\\)\\s +"))
+			    "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
+	match)
+
+    (if (not (looking-at verilog-defun-re))
+	(verilog-re-search-backward verilog-defun-re nil t))
+    (forward-char 1)
+
+    ;; Search through all reachable functions
+    (goto-char (point-min))
+    (while (verilog-re-search-forward verilog-str (point-max) t)
+      (progn (setq match (buffer-substring (match-beginning 2)
+					   (match-end 2)))
+	     (if (or (null verilog-pred)
+		     (funcall verilog-pred match))
+		 (setq verilog-all (cons match verilog-all)))))
+    (if (match-beginning 0)
+	(goto-char (match-beginning 0)))))
+
+(defun verilog-get-completion-decl (end)
+  "Macro for searching through current declaration (var, type or const)
+for matches of `str' and adding the occurrence tp `all' through point END."
+  (let ((re (or (and verilog-indent-declaration-macros
+		     verilog-declaration-re-2-macro)
+		verilog-declaration-re-2-no-macro))
+	decl-end match)
+    ;; Traverse lines
+    (while (and (< (point) end)
+		(verilog-re-search-forward re end t))
+      ;; Traverse current line
+      (setq decl-end (save-excursion (verilog-declaration-end)))
+      (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
+		  (not (match-end 1)))
+	(setq match (buffer-substring (match-beginning 0) (match-end 0)))
+	(if (string-match (concat "\\<" verilog-str) match)
+	    (if (or (null verilog-pred)
+		    (funcall verilog-pred match))
+		(setq verilog-all (cons match verilog-all)))))
+      (forward-line 1)
+      )
+    )
+  verilog-all
+  )
+
+(defun verilog-type-completion ()
+  "Calculate all possible completions for types."
+  (let ((start (point))
+	goon)
+    ;; Search for all reachable type declarations
+    (while (or (verilog-beg-of-defun)
+	       (setq goon (not goon)))
+      (save-excursion
+	(if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
+						 (point))
+			    (forward-char 1)))
+		 (verilog-re-search-forward
+		  "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
+		  start t)
+		 (not (match-end 1)))
+	    ;; Check current type declaration
+	    (verilog-get-completion-decl start))))))
+
+(defun verilog-var-completion ()
+  "Calculate all possible completions for variables (or constants)."
+  (let ((start (point)))
+    ;; Search for all reachable var declarations
+    (verilog-beg-of-defun)
+    (save-excursion
+      ;; Check var declarations
+      (verilog-get-completion-decl start))))
+
+(defun verilog-keyword-completion (keyword-list)
+  "Give list of all possible completions of keywords in KEYWORD-LIST."
+  (mapcar '(lambda (s)
+	     (if (string-match (concat "\\<" verilog-str) s)
+		 (if (or (null verilog-pred)
+			 (funcall verilog-pred s))
+		     (setq verilog-all (cons s verilog-all)))))
+	  keyword-list))
+
+
+(defun verilog-completion (verilog-str verilog-pred verilog-flag)
+  "Function passed to `completing-read', `try-completion' or `all-completions'.
+Called to get completion on VERILOG-STR.  If VERILOG-PRED is non-nil, it
+must be a function to be called for every match to check if this should
+really be a match.  If VERILOG-FLAG is t, the function returns a list of all
+possible completions.  If VERILOG-FLAG is nil it returns a string, the
+longest possible completion, or t if STR is an exact match.  If VERILOG-FLAG
+is 'lambda, the function returns t if STR is an exact match, nil
+otherwise."
+  (save-excursion
+    (let ((verilog-all nil))
+      ;; Set buffer to use for searching labels. This should be set
+      ;; within functions which use verilog-completions
+      (set-buffer verilog-buffer-to-use)
+
+      ;; Determine what should be completed
+      (let ((state (car (verilog-calculate-indent))))
+	(cond ((eq state 'defun)
+	       (save-excursion (verilog-var-completion))
+	       (verilog-func-completion 'module)
+	       (verilog-keyword-completion verilog-defun-keywords))
+
+	      ((eq state 'behavioral)
+	       (save-excursion (verilog-var-completion))
+	       (verilog-func-completion 'module)
+	       (verilog-keyword-completion verilog-defun-keywords))
+
+	      ((eq state 'block)
+	       (save-excursion (verilog-var-completion))
+	       (verilog-func-completion 'tf)
+	       (verilog-keyword-completion verilog-block-keywords))
+
+	      ((eq state 'case)
+	       (save-excursion (verilog-var-completion))
+	       (verilog-func-completion 'tf)
+	       (verilog-keyword-completion verilog-case-keywords))
+
+	      ((eq state 'tf)
+	       (save-excursion (verilog-var-completion))
+	       (verilog-func-completion 'tf)
+	       (verilog-keyword-completion verilog-tf-keywords))
+
+	      ((eq state 'cpp)
+	       (save-excursion (verilog-var-completion))
+	       (verilog-keyword-completion verilog-cpp-keywords))
+
+	      ((eq state 'cparenexp)
+	       (save-excursion (verilog-var-completion)))
+
+	      (t;--Anywhere else
+	       (save-excursion (verilog-var-completion))
+	       (verilog-func-completion 'both)
+	       (verilog-keyword-completion verilog-separator-keywords))))
+
+      ;; Now we have built a list of all matches. Give response to caller
+      (verilog-completion-response))))
+
+(defun verilog-completion-response ()
+  (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
+	 ;; This was not called by all-completions
+	 (if (null verilog-all)
+	     ;; Return nil if there was no matching label
+	     nil
+	   ;; Get longest string common in the labels
+	   (let* ((elm (cdr verilog-all))
+		  (match (car verilog-all))
+		  (min (length match))
+		  tmp)
+	     (if (string= match verilog-str)
+		 ;; Return t if first match was an exact match
+		 (setq match t)
+	       (while (not (null elm))
+		 ;; Find longest common string
+		 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
+		     (progn
+		       (setq min tmp)
+		       (setq match (substring match 0 min))))
+		 ;; Terminate with match=t if this is an exact match
+		 (if (string= (car elm) verilog-str)
+		     (progn
+		       (setq match t)
+		       (setq elm nil))
+		   (setq elm (cdr elm)))))
+	     ;; If this is a test just for exact match, return nil ot t
+	     (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
+		 nil
+	       match))))
+	;; If flag is t, this was called by all-completions. Return
+	;; list of all possible completions
+	(verilog-flag
+	 verilog-all)))
+
+(defvar verilog-last-word-numb 0)
+(defvar verilog-last-word-shown nil)
+(defvar verilog-last-completions nil)
+
+(defun verilog-complete-word ()
+  "Complete word at current point.
+\(See also `verilog-toggle-completions', `verilog-type-keywords',
+and `verilog-separator-keywords'.)"
+  (interactive)
+  (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
+	 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
+	 (verilog-str (buffer-substring b e))
+	 ;; The following variable is used in verilog-completion
+	 (verilog-buffer-to-use (current-buffer))
+	 (allcomp (if (and verilog-toggle-completions
+			   (string= verilog-last-word-shown verilog-str))
+		      verilog-last-completions
+		    (all-completions verilog-str 'verilog-completion)))
+	 (match (if verilog-toggle-completions
+		    "" (try-completion
+			verilog-str (mapcar '(lambda (elm)
+					      (cons elm 0)) allcomp)))))
+    ;; Delete old string
+    (delete-region b e)
+
+    ;; Toggle-completions inserts whole labels
+    (if verilog-toggle-completions
+	(progn
+	  ;; Update entry number in list
+	  (setq verilog-last-completions allcomp
+		verilog-last-word-numb
+		(if (>= verilog-last-word-numb (1- (length allcomp)))
+		    0
+		  (1+ verilog-last-word-numb)))
+	  (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
+	  ;; Display next match or same string if no match was found
+	  (if (not (null allcomp))
+	      (insert "" verilog-last-word-shown)
+	    (insert "" verilog-str)
+	    (message "(No match)")))
+      ;; The other form of completion does not necessarily do that.
+
+      ;; Insert match if found, or the original string if no match
+      (if (or (null match) (equal match 't))
+	  (progn (insert "" verilog-str)
+		 (message "(No match)"))
+	(insert "" match))
+      ;; Give message about current status of completion
+      (cond ((equal match 't)
+	     (if (not (null (cdr allcomp)))
+		 (message "(Complete but not unique)")
+	       (message "(Sole completion)")))
+	    ;; Display buffer if the current completion didn't help
+	    ;; on completing the label.
+	    ((and (not (null (cdr allcomp))) (= (length verilog-str)
+						(length match)))
+	     (with-output-to-temp-buffer "*Completions*"
+	       (display-completion-list allcomp))
+	     ;; Wait for a key press. Then delete *Completion*  window
+	     (momentary-string-display "" (point))
+	     (delete-window (get-buffer-window (get-buffer "*Completions*")))
+	     )))))
+
+(defun verilog-show-completions ()
+  "Show all possible completions at current point."
+  (interactive)
+  (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
+	 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
+	 (verilog-str (buffer-substring b e))
+	 ;; The following variable is used in verilog-completion
+	 (verilog-buffer-to-use (current-buffer))
+	 (allcomp (if (and verilog-toggle-completions
+			   (string= verilog-last-word-shown verilog-str))
+		      verilog-last-completions
+		    (all-completions verilog-str 'verilog-completion))))
+    ;; Show possible completions in a temporary buffer.
+    (with-output-to-temp-buffer "*Completions*"
+      (display-completion-list allcomp))
+    ;; Wait for a key press. Then delete *Completion*  window
+    (momentary-string-display "" (point))
+    (delete-window (get-buffer-window (get-buffer "*Completions*")))))
+
+
+(defun verilog-get-default-symbol ()
+  "Return symbol around current point as a string."
+  (save-excursion
+    (buffer-substring (progn
+			(skip-chars-backward " \t")
+			(skip-chars-backward "a-zA-Z0-9_")
+			(point))
+		      (progn
+			(skip-chars-forward "a-zA-Z0-9_")
+			(point)))))
+
+(defun verilog-build-defun-re (str &optional arg)
+  "Return function/task/module starting with STR as regular expression.
+With optional second ARG non-nil, STR is the complete name of the instruction."
+  (if arg
+      (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
+    (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
+
+(defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
+  "Function passed to `completing-read', `try-completion' or `all-completions'.
+Returns a completion on any function name based on VERILOG-STR prefix.  If
+VERILOG-PRED is non-nil, it must be a function to be called for every match
+to check if this should really be a match.  If VERILOG-FLAG is t, the
+function returns a list of all possible completions.  If it is nil it
+returns a string, the longest possible completion, or t if VERILOG-STR is
+an exact match.  If VERILOG-FLAG is 'lambda, the function returns t if
+VERILOG-STR is an exact match, nil otherwise."
+  (save-excursion
+    (let ((verilog-all nil)
+	  match)
+
+      ;; Set buffer to use for searching labels. This should be set
+      ;; within functions which use verilog-completions
+      (set-buffer verilog-buffer-to-use)
+
+      (let ((verilog-str verilog-str))
+	;; Build regular expression for functions
+	(if (string= verilog-str "")
+	    (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
+	  (setq verilog-str (verilog-build-defun-re verilog-str)))
+	(goto-char (point-min))
+
+	;; Build a list of all possible completions
+	(while (verilog-re-search-forward verilog-str nil t)
+	  (setq match (buffer-substring (match-beginning 2) (match-end 2)))
+	  (if (or (null verilog-pred)
+		  (funcall verilog-pred match))
+	      (setq verilog-all (cons match verilog-all)))))
+
+      ;; Now we have built a list of all matches. Give response to caller
+      (verilog-completion-response))))
+
+(defun verilog-goto-defun ()
+  "Move to specified Verilog module/task/function.
+The default is a name found in the buffer around point.
+If search fails, other files are checked based on
+`verilog-library-flags'."
+  (interactive)
+  (let* ((default (verilog-get-default-symbol))
+	 ;; The following variable is used in verilog-comp-function
+	 (verilog-buffer-to-use (current-buffer))
+	 (label (if (not (string= default ""))
+		    ;; Do completion with default
+		    (completing-read (concat "Label: (default " default ") ")
+				     'verilog-comp-defun nil nil "")
+		  ;; There is no default value. Complete without it
+		  (completing-read "Label: "
+				   'verilog-comp-defun nil nil "")))
+	 pt)
+    ;; If there was no response on prompt, use default value
+    (if (string= label "")
+	(setq label default))
+    ;; Goto right place in buffer if label is not an empty string
+    (or (string= label "")
+	(progn
+	  (save-excursion
+	    (goto-char (point-min))
+	    (setq pt (re-search-forward (verilog-build-defun-re label t) nil t)))
+	  (when pt
+	    (goto-char pt)
+	    (beginning-of-line))
+	  pt)
+	(verilog-goto-defun-file label)
+	)))
+
+;; Eliminate compile warning
+(eval-when-compile
+  (if (not (boundp 'occur-pos-list))
+      (defvar occur-pos-list nil "Backward compatibility occur positions.")))
+
+(defun verilog-showscopes ()
+  "List all scopes in this module."
+  (interactive)
+  (let ((buffer (current-buffer))
+	(linenum 1)
+	(nlines 0)
+	(first 1)
+	(prevpos (point-min))
+        (final-context-start (make-marker))
+	(regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)")
+	)
+    (with-output-to-temp-buffer "*Occur*"
+      (save-excursion
+	(message (format "Searching for %s ..." regexp))
+	;; Find next match, but give up if prev match was at end of buffer.
+	(while (and (not (= prevpos (point-max)))
+		    (verilog-re-search-forward regexp nil t))
+	  (goto-char (match-beginning 0))
+	  (beginning-of-line)
+	  (save-match-data
+            (setq linenum (+ linenum (count-lines prevpos (point)))))
+	  (setq prevpos (point))
+	  (goto-char (match-end 0))
+	  (let* ((start (save-excursion
+			  (goto-char (match-beginning 0))
+			  (forward-line (if (< nlines 0) nlines (- nlines)))
+			  (point)))
+		 (end (save-excursion
+			(goto-char (match-end 0))
+			(if (> nlines 0)
+			    (forward-line (1+ nlines))
+			    (forward-line 1))
+			(point)))
+		 (tag (format "%3d" linenum))
+		 (empty (make-string (length tag) ?\ ))
+		 tem)
+	    (save-excursion
+	      (setq tem (make-marker))
+	      (set-marker tem (point))
+	      (set-buffer standard-output)
+	      (setq occur-pos-list (cons tem occur-pos-list))
+	      (or first (zerop nlines)
+		  (insert "--------\n"))
+	      (setq first nil)
+	      (insert-buffer-substring buffer start end)
+	      (backward-char (- end start))
+	      (setq tem (if (< nlines 0) (- nlines) nlines))
+	      (while (> tem 0)
+		(insert empty ?:)
+		(forward-line 1)
+		(setq tem (1- tem)))
+	      (let ((this-linenum linenum))
+		(set-marker final-context-start
+			    (+ (point) (- (match-end 0) (match-beginning 0))))
+		(while (< (point) final-context-start)
+		  (if (null tag)
+		      (setq tag (format "%3d" this-linenum)))
+		  (insert tag ?:)))))))
+      (set-buffer-modified-p nil))))
+
+
+;; Highlight helper functions
+(defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
+(defun verilog-within-translate-off ()
+  "Return point if within translate-off region, else nil."
+  (and (save-excursion
+	 (re-search-backward
+	  (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
+	  nil t))
+       (equal "off" (match-string 2))
+       (point)))
+
+(defun verilog-start-translate-off (limit)
+  "Return point before translate-off directive if before LIMIT, else nil."
+  (when (re-search-forward
+	  (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
+	  limit t)
+    (match-beginning 0)))
+
+(defun verilog-back-to-start-translate-off (limit)
+  "Return point before translate-off directive if before LIMIT, else nil."
+  (when (re-search-backward
+	  (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
+	  limit t)
+    (match-beginning 0)))
+
+(defun verilog-end-translate-off (limit)
+  "Return point after translate-on directive if before LIMIT, else nil."
+
+  (re-search-forward (concat
+		      "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
+
+(defun verilog-match-translate-off (limit)
+  "Match a translate-off block, setting `match-data' and returning t, else nil.
+Bound search by LIMIT."
+  (when (< (point) limit)
+    (let ((start (or (verilog-within-translate-off)
+		     (verilog-start-translate-off limit)))
+	  (case-fold-search t))
+      (when start
+	(let ((end (or (verilog-end-translate-off limit) limit)))
+	  (set-match-data (list start end))
+	  (goto-char end))))))
+
+(defun verilog-font-lock-match-item (limit)
+  "Match, and move over, any declaration item after point.
+Bound search by LIMIT.  Adapted from
+`font-lock-match-c-style-declaration-item-and-skip-to-next'."
+  (condition-case nil
+      (save-restriction
+	(narrow-to-region (point-min) limit)
+	;; match item
+	(when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
+	  (save-match-data
+	    (goto-char (match-end 1))
+	    ;; move to next item
+	    (if (looking-at "\\(\\s-*,\\)")
+		(goto-char (match-end 1))
+	      (end-of-line) t))))
+    (error nil)))
+
+
+;; Added by Subbu Meiyappan for Header
+
+(defun verilog-header ()
+  "Insert a standard Verilog file header."
+  (interactive)
+  (let ((start (point)))
+  (insert "\
+//-----------------------------------------------------------------------------
+// Title         : <title>
+// Project       : <project>
+//-----------------------------------------------------------------------------
+// File          : <filename>
+// Author        : <author>
+// Created       : <credate>
+// Last modified : <moddate>
+//-----------------------------------------------------------------------------
+// Description :
+// <description>
+//-----------------------------------------------------------------------------
+// Copyright (c) <copydate> by <company> This model is the confidential and
+// proprietary property of <company> and the possession or use of this
+// file requires a written license from <company>.
+//------------------------------------------------------------------------------
+// Modification history :
+// <modhist>
+//-----------------------------------------------------------------------------
+
+")
+    (goto-char start)
+    (search-forward "<filename>")
+    (replace-match (buffer-name) t t)
+    (search-forward "<author>") (replace-match "" t t)
+    (insert (user-full-name))
+    (insert "  <" (user-login-name) "@" (system-name) ">")
+    (search-forward "<credate>") (replace-match "" t t)
+    (verilog-insert-date)
+    (search-forward "<moddate>") (replace-match "" t t)
+    (verilog-insert-date)
+    (search-forward "<copydate>") (replace-match "" t t)
+    (verilog-insert-year)
+    (search-forward "<modhist>") (replace-match "" t t)
+    (verilog-insert-date)
+    (insert " : created")
+    (goto-char start)
+    (let (string)
+      (setq string (read-string "title: "))
+      (search-forward "<title>")
+      (replace-match string t t)
+      (setq string (read-string "project: " verilog-project))
+      (make-variable-buffer-local 'verilog-project)
+      (setq verilog-project string)
+      (search-forward "<project>")
+      (replace-match string t t)
+      (setq string (read-string "Company: " verilog-company))
+      (make-variable-buffer-local 'verilog-company)
+      (setq verilog-company string)
+      (search-forward "<company>")
+      (replace-match string t t)
+      (search-forward "<company>")
+      (replace-match string t t)
+      (search-forward "<company>")
+      (replace-match string t t)
+      (search-backward "<description>")
+      (replace-match "" t t)
+      )))
+
+;; verilog-header Uses the verilog-insert-date function
+
+(defun verilog-insert-date ()
+  "Insert date from the system."
+  (interactive)
+  (let ((timpos))
+    (setq timpos (point))
+    (if verilog-date-scientific-format
+	(shell-command  "date \"+@%Y/%m/%d\"" t)
+      (shell-command  "date \"+@%d.%m.%Y\"" t))
+    (search-forward "@")
+    (delete-region timpos (point))
+    (end-of-line))
+    (delete-char 1))
+
+(defun verilog-insert-year ()
+  "Insert year from the system."
+  (interactive)
+  (let ((timpos))
+    (setq timpos (point))
+    (shell-command  "date \"+@%Y\"" t)
+    (search-forward "@")
+    (delete-region timpos (point))
+    (end-of-line))
+  (delete-char 1))
+
+
+;;
+;; Signal list parsing
+;;
+
+;; Elements of a signal list
+(defsubst verilog-sig-name (sig)
+  (car sig))
+(defsubst verilog-sig-bits (sig)
+  (nth 1 sig))
+(defsubst verilog-sig-comment (sig)
+  (nth 2 sig))
+(defsubst verilog-sig-memory (sig)
+  (nth 3 sig))
+(defsubst verilog-sig-enum (sig)
+  (nth 4 sig))
+(defsubst verilog-sig-signed (sig)
+  (nth 5 sig))
+(defsubst verilog-sig-type (sig)
+  (nth 6 sig))
+(defsubst verilog-sig-multidim (sig)
+  (nth 7 sig))
+(defsubst verilog-sig-multidim-string (sig)
+  (if (verilog-sig-multidim sig)
+      (let ((str "") (args (verilog-sig-multidim sig)))
+	(while args
+	  (setq str (concat str (car args)))
+	  (setq args (cdr args)))
+	str)))
+(defsubst verilog-sig-width (sig)
+  (verilog-make-width-expression (verilog-sig-bits sig)))
+
+(defsubst verilog-alw-get-inputs (sigs)
+  (nth 2 sigs))
+(defsubst verilog-alw-get-outputs (sigs)
+  (nth 0 sigs))
+(defsubst verilog-alw-get-uses-delayed (sigs)
+  (nth 3 sigs))
+
+(defun verilog-signals-not-in (in-list not-list)
+  "Return list of signals in IN-LIST that aren't also in NOT-LIST,
+and also remove any duplicates in IN-LIST.
+Signals must be in standard (base vector) form."
+  (let (out-list)
+    (while in-list
+      (if (not (or (assoc (car (car in-list)) not-list)
+		   (assoc (car (car in-list)) out-list)))
+	  (setq out-list (cons (car in-list) out-list)))
+      (setq in-list (cdr in-list)))
+    (nreverse out-list)))
+;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
+
+(defun verilog-signals-in (in-list other-list)
+  "Return list of signals in IN-LIST that are also in OTHER-LIST.
+Signals must be in standard (base vector) form."
+  (let (out-list)
+    (while in-list
+      (if (assoc (car (car in-list)) other-list)
+	  (setq out-list (cons (car in-list) out-list)))
+      (setq in-list (cdr in-list)))
+    (nreverse out-list)))
+;;(verilog-signals-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
+
+(defun verilog-signals-memory (in-list)
+  "Return list of signals in IN-LIST that are memoried (multidimensional)."
+  (let (out-list)
+    (while in-list
+      (if (nth 3 (car in-list))
+	  (setq out-list (cons (car in-list) out-list)))
+      (setq in-list (cdr in-list)))
+    out-list))
+;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
+
+(defun verilog-signals-sort-compare (a b)
+  "Compare signal A and B for sorting."
+  (string< (car a) (car b)))
+
+(defun verilog-signals-not-params (in-list)
+  "Return list of signals in IN-LIST that aren't parameters or numeric constants."
+  (let (out-list)
+    (while in-list
+      (unless (boundp (intern (concat "vh-" (car (car in-list)))))
+	(setq out-list (cons (car in-list) out-list)))
+      (setq in-list (cdr in-list)))
+    (nreverse out-list)))
+
+(defun verilog-signals-combine-bus (in-list)
+  "Return a list of signals in IN-LIST, with busses combined.
+Duplicate signals are also removed.  For example A[2] and A[1] become A[2:1]."
+  (let (combo buswarn
+	out-list
+	sig highbit lowbit		; Temp information about current signal
+	sv-name sv-highbit sv-lowbit	; Details about signal we are forming
+	sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
+	bus)
+    ;; Shove signals so duplicated signals will be adjacent
+    (setq in-list (sort in-list `verilog-signals-sort-compare))
+    (while in-list
+      (setq sig (car in-list))
+      ;; No current signal; form from existing details
+      (unless sv-name
+	(setq sv-name    (verilog-sig-name sig)
+	      sv-highbit nil
+	      sv-busstring nil
+	      sv-comment (verilog-sig-comment sig)
+	      sv-memory  (verilog-sig-memory sig)
+	      sv-enum    (verilog-sig-enum sig)
+	      sv-signed  (verilog-sig-signed sig)
+	      sv-type    (verilog-sig-type sig)
+	      sv-multidim (verilog-sig-multidim sig)
+	      combo ""
+	      buswarn ""
+	      ))
+      ;; Extract bus details
+      (setq bus (verilog-sig-bits sig))
+      (cond ((and bus
+		  (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
+			   (setq highbit (string-to-int (match-string 1 bus))
+				 lowbit  (string-to-int (match-string 2 bus))))
+		      (and (string-match "\\[\\([0-9]+\\)\\]" bus)
+			   (setq highbit (string-to-int (match-string 1 bus))
+				 lowbit  highbit))))
+	     ;; Combine bits in bus
+	     (if sv-highbit
+		 (setq sv-highbit (max highbit sv-highbit)
+		       sv-lowbit  (min lowbit  sv-lowbit))
+	       (setq sv-highbit highbit
+		     sv-lowbit  lowbit)))
+	    (bus
+	     ;; String, probably something like `preproc:0
+	     (setq sv-busstring bus)))
+      ;; Peek ahead to next signal
+      (setq in-list (cdr in-list))
+      (setq sig (car in-list))
+      (cond ((and sig (equal sv-name (verilog-sig-name sig)))
+	     ;; Combine with this signal
+	     (when (and sv-busstring (not (equal sv-busstring (verilog-sig-bits sig))))
+	       (when nil  ;; Debugging
+		 (message (concat "Warning, can't merge into single bus "
+				  sv-name bus
+				  ", the AUTOs may be wrong")))
+	       (setq buswarn ", Couldn't Merge"))
+	     (if (verilog-sig-comment sig) (setq combo ", ..."))
+	     (setq sv-memory (or sv-memory (verilog-sig-memory sig))
+		   sv-enum   (or sv-enum   (verilog-sig-enum sig))
+		   sv-signed (or sv-signed (verilog-sig-signed sig))
+                   sv-type   (or sv-type   (verilog-sig-type sig))
+                   sv-multidim (or sv-multidim (verilog-sig-multidim sig))))
+	    ;; Doesn't match next signal, add to queue, zero in prep for next
+	    ;; Note sig may also be nil for the last signal in the list
+	    (t
+	     (setq out-list
+		   (cons (list sv-name
+			       (or sv-busstring
+				   (if sv-highbit
+				       (concat "[" (int-to-string sv-highbit) ":" (int-to-string sv-lowbit) "]")))
+			       (concat sv-comment combo buswarn)
+			       sv-memory sv-enum sv-signed sv-type sv-multidim)
+			 out-list)
+		   sv-name nil)))
+      )
+    ;;
+    out-list))
+
+(defun verilog-sig-tieoff (sig &optional no-width)
+  "Return tieoff expression for given SIGNAL, with appropriate width.
+Ignore width if optional NO-WIDTH is set."
+  (let* ((width (if no-width nil (verilog-sig-width sig))))
+    (concat
+     (if (and verilog-active-low-regexp
+	      (string-match verilog-active-low-regexp (verilog-sig-name sig)))
+	 "~" "")
+     (cond ((not width)
+	    "0")
+	   ((string-match "^[0-9]+$" width)
+	    (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
+	   (t
+	    (concat "{" width "{1'b0}}"))))))
+
+;;
+;; Port/Wire/Etc Reading
+;;
+
+(defun verilog-read-inst-backward-name ()
+  "Internal.  Move point back to beginning of inst-name."
+    (verilog-backward-open-paren)
+    (let (done)
+      (while (not done)
+	(verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil)  ; ] isn't word boundary
+	(cond ((looking-at ")")
+	       (verilog-backward-open-paren))
+	      (t (setq done t)))))
+    (while (looking-at "\\]")
+      (verilog-backward-open-bracket)
+      (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
+    (skip-chars-backward "a-zA-Z0-9`_$"))
+
+(defun verilog-read-inst-module ()
+  "Return module_name when point is inside instantiation."
+  (save-excursion
+    (verilog-read-inst-backward-name)
+    ;; Skip over instantiation name
+    (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil)  ; ) isn't word boundary
+    ;; Check for parameterized instantiations
+    (when (looking-at ")")
+      (verilog-backward-open-paren)
+      (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
+    (skip-chars-backward "a-zA-Z0-9'_$")
+    (looking-at "[a-zA-Z0-9`_\$]+")
+    ;; Important: don't use match string, this must work with emacs 19 font-lock on
+    (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
+
+(defun verilog-read-inst-name ()
+  "Return instance_name when point is inside instantiation."
+  (save-excursion
+    (verilog-read-inst-backward-name)
+    (looking-at "[a-zA-Z0-9`_\$]+")
+    ;; Important: don't use match string, this must work with emacs 19 font-lock on
+    (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
+
+(defun verilog-read-module-name ()
+  "Return module name when after its ( or ;."
+  (save-excursion
+    (re-search-backward "[(;]")
+    (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
+    (skip-chars-backward "a-zA-Z0-9`_$")
+    (looking-at "[a-zA-Z0-9`_\$]+")
+    ;; Important: don't use match string, this must work with emacs 19 font-lock on
+    (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
+
+(defun verilog-read-auto-params (num-param &optional max-param)
+  "Return parameter list inside auto.
+Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
+  (let ((olist))
+    (save-excursion
+      ;; /*AUTOPUNT("parameter", "parameter")*/
+      (search-backward "(")
+      (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
+	(setq olist (cons (match-string 1) olist))
+	(goto-char (match-end 0))))
+    (or (eq nil num-param)
+	(<= num-param (length olist))
+	(error "%s: Expected %d parameters" (verilog-point-text) num-param))
+    (if (eq max-param nil) (setq max-param num-param))
+    (or (eq nil max-param)
+	(>= max-param (length olist))
+	(error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
+    (nreverse olist)))
+
+(defun verilog-read-decls ()
+  "Compute signal declaration information for the current module at point.
+Return a array of [outputs inouts inputs wire reg assign const]."
+  (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
+	(functask 0) (paren 0) (sig-paren 0)
+	sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const sigs-gparam
+	vec expect-signal keywd newsig rvalue enum io signed typedefed multidim)
+    (save-excursion
+      (verilog-beg-of-defun)
+      (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
+      (while (< (point) end-mod-point)
+	;;(if dbg (setq dbg (cons (format "Pt %s  Vec %s   Kwd'%s'\n" (point) vec keywd) dbg)))
+	(cond
+	 ((looking-at "//")
+	  (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
+	      (setq enum (match-string 1)))
+	  (search-forward "\n"))
+	 ((looking-at "/\\*")
+	  (forward-char 2)
+	  (if (looking-at "[^*]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
+	      (setq enum (match-string 1)))
+	  (or (search-forward "*/")
+	      (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
+	 ((looking-at "(\\*")
+	  (forward-char 2)
+	  (or (looking-at "\\s-*)")   ; It's a "always @ (*)"
+	      (search-forward "*)")
+	      (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
+	 ((eq ?\" (following-char))
+	  (or (re-search-forward "[^\\]\"" nil t)	;; don't forward-char first, since we look for a non backslash first
+	      (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
+	 ((eq ?\; (following-char))
+	  (setq vec nil  io nil  expect-signal nil  newsig nil  paren 0  rvalue nil)
+	  (forward-char 1))
+	 ((eq ?= (following-char))
+	  (setq rvalue t  newsig nil)
+	  (forward-char 1))
+	 ((and (or rvalue sig-paren)
+	       (cond ((and (eq ?, (following-char))
+			   (eq paren sig-paren))
+		      (setq rvalue nil)
+		      (forward-char 1)
+		      t)
+		     ;; ,'s can occur inside {} & funcs
+		     ((looking-at "[{(]")
+		      (setq paren (1+ paren))
+		      (forward-char 1)
+		      t)
+		     ((looking-at "[})]")
+		      (setq paren (1- paren))
+		      (forward-char 1)
+		      (when (< paren sig-paren)
+			(setq expect-signal nil))   ; ) that ends variables inside v2k arg list
+		      t)
+		     )))
+	 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
+	  (goto-char (match-end 0))
+	  (cond (newsig	; Memory, not just width.  Patch last signal added's memory (nth 3)
+		 (setcar (cdr (cdr (cdr newsig))) (match-string 1)))
+		(vec ;; Multidimensional
+		 (setq multidim (cons vec multidim))
+		 (setq vec (verilog-string-replace-matches
+			    "\\s-+" "" nil nil (match-string 1))))
+		(t ;; Bit width
+		 (setq vec (verilog-string-replace-matches
+			    "\\s-+" "" nil nil (match-string 1))))))
+	 ;; Normal or escaped identifier -- note we remember the \ if escaped
+	 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
+	  (goto-char (match-end 0))
+	  (setq keywd (match-string 1))
+	  (when (string-match "^\\\\" keywd)
+	    (setq keywd (concat keywd " ")))  ;; Escaped ID needs space at end
+	  (cond ((equal keywd "input")
+		 (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  sig-paren paren
+		       expect-signal 'sigs-in  io t))
+		((equal keywd "output")
+		 (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  sig-paren paren
+		       expect-signal 'sigs-out  io t))
+		((equal keywd "inout")
+		 (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  sig-paren paren
+		       expect-signal 'sigs-inout  io t))
+		((or (equal keywd "wire")
+		     (equal keywd "tri")
+		     (equal keywd "tri0")
+		     (equal keywd "tri1"))
+		 (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
+				  expect-signal 'sigs-wire)))
+		((or (equal keywd "reg")
+		     (equal keywd "trireg"))
+		 (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
+				  expect-signal 'sigs-reg)))
+		((equal keywd "assign")
+		 (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
+		       expect-signal 'sigs-assign))
+		((or (equal keywd "supply0")
+		     (equal keywd "supply1")
+		     (equal keywd "supply")
+		     (equal keywd "localparam"))
+		 (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
+				  expect-signal 'sigs-const)))
+		((or (equal keywd "parameter"))
+		 (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
+				  expect-signal 'sigs-gparam)))
+		((equal keywd "signed")
+		 (setq signed "signed"))
+		((or (equal keywd "function")
+		     (equal keywd "task"))
+		 (setq functask (1+ functask)))
+		((or (equal keywd "endfunction")
+		     (equal keywd "endtask"))
+		 (setq functask (1- functask)))
+		((or (equal keywd "`ifdef")
+		     (equal keywd "`ifndef"))
+		 (setq rvalue t))
+		((verilog-typedef-name-p keywd)
+		 (setq typedefed keywd))
+		((and expect-signal
+		      (eq functask 0)
+		      (not rvalue)
+		      (eq paren sig-paren)
+		      (not (member keywd verilog-keywords)))
+		 ;; Add new signal to expect-signal's variable
+		 (setq newsig (list keywd vec nil nil enum signed typedefed multidim))
+		 (set expect-signal (cons newsig
+					  (symbol-value expect-signal))))))
+	 (t
+	  (forward-char 1)))
+	(skip-syntax-forward " "))
+      ;; Return arguments
+      (vector (nreverse sigs-out)
+	      (nreverse sigs-inout)
+	      (nreverse sigs-in)
+	      (nreverse sigs-wire)
+	      (nreverse sigs-reg)
+	      (nreverse sigs-assign)
+	      (nreverse sigs-const)
+	      (nreverse sigs-gparam)
+	      ))))
+
+(defvar sigs-in nil) ; Prevent compile warning
+(defvar sigs-inout nil) ; Prevent compile warning
+(defvar sigs-out nil) ; Prevent compile warning
+
+(defun verilog-read-sub-decls-sig (submodi comment port sig vec multidim)
+  "For verilog-read-sub-decls-line, add a signal."
+  (let (portdata)
+    (when sig
+      (setq port (verilog-symbol-detick-denumber port))
+      (setq sig  (verilog-symbol-detick-denumber sig))
+      (if sig (setq sig  (verilog-string-replace-matches "^[---+~!|&]+" "" nil nil sig)))
+      (if vec (setq vec  (verilog-symbol-detick-denumber vec)))
+      (if multidim (setq multidim  (mapcar `verilog-symbol-detick-denumber multidim)))
+      (unless (or (not sig)
+		  (equal sig ""))  ;; Ignore .foo(1'b1) assignments
+	(cond ((setq portdata (assoc port (verilog-modi-get-inouts submodi)))
+	       (setq sigs-inout (cons (list sig vec (concat "To/From " comment) nil nil
+					    (verilog-sig-signed portdata)
+					    (verilog-sig-type portdata)
+					    multidim)
+				      sigs-inout)))
+	      ((setq portdata (assoc port (verilog-modi-get-outputs submodi)))
+	       (setq sigs-out   (cons (list sig vec (concat "From " comment) nil nil
+					    (verilog-sig-signed portdata)
+					    (verilog-sig-type portdata)
+					    multidim)
+				      sigs-out)))
+	      ((setq portdata (assoc port (verilog-modi-get-inputs submodi)))
+	       (setq sigs-in    (cons (list sig vec (concat "To " comment) nil nil
+					    (verilog-sig-signed portdata)
+					    (verilog-sig-type portdata)
+					    multidim)
+				      sigs-in)))
+	      ;; (t  -- warning pin isn't defined.)   ; Leave for lint tool
+	      )))))
+
+(defun verilog-read-sub-decls-line (submodi comment)
+  "For read-sub-decls, read lines of port defs until none match anymore.
+Return the list of signals found, using submodi to look up each port."
+  (let (done port sig vec multidim)
+    (save-excursion
+      (forward-line 1)
+      (while (not done)
+	;; Get port name
+	(cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
+	       (setq port (match-string 1))
+	       (goto-char (match-end 0)))
+	      ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
+	       (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
+	       (goto-char (match-end 0)))
+	      ((looking-at "\\s-*\\.[^(]*(")
+	       (setq port nil) ;; skip this line
+	       (goto-char (match-end 0)))
+	      (t
+	       (setq port nil  done t))) ;; Unknown, ignore rest of line
+	;; Get signal name
+	(when port
+	  (setq multidim nil)
+	  (cond ((looking-at "\\(\\\\[^ \t\n\f]*\\)\\s-*)")
+		 (setq sig (concat (match-string 1) " ") ;; escaped id's need trailing space
+		       vec nil))
+		; We intentionally ignore (non-escaped) signals with .s in them
+		; this prevents AUTOWIRE etc from noticing hierarchical sigs.
+		((looking-at "\\([^[({).]*\\)\\s-*)")
+		 (setq sig (verilog-string-remove-spaces (match-string 1))
+		       vec nil))
+		((looking-at "\\([^[({).]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
+		 (setq sig (verilog-string-remove-spaces (match-string 1))
+		       vec (match-string 2)))
+		((looking-at "\\([^[({).]*\\)\\s-*/\\*\\(\\[[^*]+\\]\\)\\*/\\s-*)")
+		 (setq sig (verilog-string-remove-spaces (match-string 1))
+		       vec nil)
+		 (let ((parse (match-string 2)))
+		   (while (string-match "^\\(\\[[^]]+\\]\\)\\(.*\\)$" parse)
+		     (when vec (setq multidim (cons vec multidim)))
+		     (setq vec (match-string 1 parse))
+		     (setq parse (match-string 2 parse)))))
+		((looking-at "{\\(.*\\)}.*\\s-*)")
+		 (let ((mlst (split-string (match-string 1) ","))
+		       mstr)
+		   (while (setq mstr (pop mlst))
+		     ;;(unless noninteractive (message "sig: %s " mstr))
+		     (cond
+		      ((string-match "\\(['`a-zA-Z0-9_$]+\\)\\s-*$" mstr)
+		       (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
+			     vec nil)
+		       ;;(unless noninteractive (message "concat sig1: %s %s" mstr (match-string 1 mstr)))
+		       )
+		      ((string-match "\\([^[({).]+\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*" mstr)
+		       (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
+			     vec (match-string 2 mstr))
+		       ;;(unless noninteractive (message "concat sig2: '%s' '%s' '%s'" mstr (match-string 1 mstr) (match-string 2 mstr)))
+		       )
+		      (t
+		       (setq sig nil)))
+		     ;; Process signals
+		     (verilog-read-sub-decls-sig submodi comment port sig vec multidim))))
+		(t
+		 (setq sig nil)))
+	  ;; Process signals
+	  (verilog-read-sub-decls-sig submodi comment port sig vec multidim))
+	;;
+	(forward-line 1)))))
+
+(defun verilog-read-sub-decls ()
+  "Internally parse signals going to modules under this module.
+Return a array of [ outputs inouts inputs ] signals for modules that are
+instantiated in this module.  For example if declare A A (.B(SIG)) and SIG
+is a output, then SIG will be included in the list.
+
+This only works on instantiations created with /*AUTOINST*/ converted by
+\\[verilog-auto-inst].  Otherwise, it would have to read in the whole
+component library to determine connectivity of the design.
+
+One work around for this problem is to manually create // Inputs and //
+Outputs comments above subcell signals, for example:
+
+	module1 instance1x (
+	    // Outputs
+	    .out (out),
+	    // Inputs
+	    .in  (in));"
+  (save-excursion
+    (let ((end-mod-point (verilog-get-end-of-defun t))
+	  st-point end-inst-point
+	  ;; below 3 modified by verilog-read-sub-decls-line
+	  sigs-out sigs-inout sigs-in)
+      (verilog-beg-of-defun)
+      (while (re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
+	(save-excursion
+	  (goto-char (match-beginning 0))
+	  (unless (verilog-inside-comment-p)
+	    ;; Attempt to snarf a comment
+	    (let* ((submod (verilog-read-inst-module))
+		   (inst (verilog-read-inst-name))
+		   (comment (concat inst " of " submod ".v")) submodi)
+	      (when (setq submodi (verilog-modi-lookup submod t))
+		;; This could have used a list created by verilog-auto-inst
+		;; However I want it to be runnable even on user's manually added signals
+		(verilog-backward-open-paren)
+		(setq end-inst-point (save-excursion (forward-sexp 1) (point))
+		      st-point (point))
+		(while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
+		  (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-out
+		(goto-char st-point)
+		(while (re-search-forward "\\s *// Inouts" end-inst-point t)
+		  (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-inout
+		(goto-char st-point)
+		(while (re-search-forward "\\s *// Inputs" end-inst-point t)
+		  (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-in
+		)))))
+      ;; Combine duplicate bits
+      ;;(setq rr (vector sigs-out sigs-inout sigs-in))
+      (vector (verilog-signals-combine-bus (nreverse sigs-out))
+	      (verilog-signals-combine-bus (nreverse sigs-inout))
+	      (verilog-signals-combine-bus (nreverse sigs-in))))))
+
+(defun verilog-read-inst-pins ()
+  "Return a array of [ pins ] for the current instantiation at point.
+For example if declare A A (.B(SIG)) then B will be included in the list."
+  (save-excursion
+    (let ((end-mod-point (point))	;; presume at /*AUTOINST*/ point
+	  pins pin)
+      (verilog-backward-open-paren)
+      (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
+	(setq pin (match-string 1))
+	(unless (verilog-inside-comment-p)
+	  (setq pins (cons (list pin) pins))
+	  (when (looking-at "(")
+	    (forward-sexp 1))))
+      (vector pins))))
+
+(defun verilog-read-arg-pins ()
+  "Return a array of [ pins ] for the current argument declaration at point."
+  (save-excursion
+    (let ((end-mod-point (point))	;; presume at /*AUTOARG*/ point
+	  pins pin)
+      (verilog-backward-open-paren)
+      (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
+	(setq pin (match-string 1))
+	(unless (verilog-inside-comment-p)
+	  (setq pins (cons (list pin) pins))))
+      (vector pins))))
+
+(defun verilog-read-auto-constants (beg end-mod-point)
+  "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
+  ;; Insert new
+  (save-excursion
+    (let (sig-list tpl-end-pt)
+      (goto-char beg)
+      (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
+	(if (not (looking-at "\\s *("))
+	    (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
+	(search-forward "(" end-mod-point)
+	(setq tpl-end-pt (save-excursion
+			   (backward-char 1)
+			   (forward-sexp 1)   ;; Moves to paren that closes argdecl's
+			   (backward-char 1)
+			   (point)))
+	(while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
+	  (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
+      sig-list)))
+
+(defun verilog-read-auto-lisp (start end)
+  "Look for and evaluate a AUTO_LISP between START and END."
+  (save-excursion
+    (goto-char start)
+    (while (re-search-forward "\\<AUTO_LISP(" end t)
+      (backward-char)
+      (let* ((beg-pt (prog1 (point)
+		       (forward-sexp 1)))	;; Closing paren
+	     (end-pt (point)))
+	(eval-region beg-pt end-pt nil)))))
+
+(eval-when-compile
+  ;; These are passed in a let, not global
+  (if (not (boundp 'sigs-in))
+      (defvar sigs-in nil) (defvar sigs-out nil)
+      (defvar got-sig nil) (defvar got-rvalue nil) (defvar uses-delayed nil)))
+
+(defun verilog-read-always-signals-recurse
+  (exit-keywd rvalue ignore-next)
+  "Recursive routine for parentheses/bracket matching.
+EXIT-KEYWD is expression to stop at, nil if top level.
+RVALUE is true if at right hand side of equal.
+IGNORE-NEXT is true to ignore next token, fake from inside case statement."
+  (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
+	 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-rvalue end-else-check)
+    ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue ignore-next))))
+    (while (not (or (eobp) gotend))
+      (cond
+       ((looking-at "//")
+	(search-forward "\n"))
+       ((looking-at "/\\*")
+	(or (search-forward "*/")
+	    (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
+       ((looking-at "(\\*")
+	(or (looking-at "(\\*\\s-*)")   ; It's a "always @ (*)"
+	    (search-forward "*)")
+	    (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
+       (t (setq keywd (buffer-substring-no-properties
+		       (point)
+		       (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
+					 (forward-char 1))
+				       (point)))
+		sig-last-tolk sig-tolk
+		sig-tolk nil)
+	  ;;(if dbg (setq dbg (concat dbg (format "\tPt=%S %S\trv=%S in=%S ee=%S\n" (point) keywd rvalue ignore-next end-else-check))))
+	  (cond
+	   ((equal keywd "\"")
+	    (or (re-search-forward "[^\\]\"" nil t)
+		(error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
+	   ;; else at top level loop, keep parsing
+	   ((and end-else-check (equal keywd "else"))
+	    ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
+	    ;; no forward movement, want to see else in lower loop
+	    (setq end-else-check nil))
+	   ;; End at top level loop
+	   ((and end-else-check (looking-at "[^ \t\n\f]"))
+	    ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
+	    (setq gotend t))
+	   ;; Final statement?
+	   ((and exit-keywd (equal keywd exit-keywd))
+	    (setq gotend t)
+	    (forward-char (length keywd)))
+	   ;; Standard tokens...
+	   ((equal keywd ";")
+	    (setq ignore-next nil  rvalue semi-rvalue)
+	    ;; Final statement at top level loop?
+	    (when (not exit-keywd)
+	      ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
+	      (setq end-else-check t))
+	    (forward-char 1))
+	   ((equal keywd "'")
+	    (if (looking-at "'s?[hdxbo][0-9a-fA-F_xz? \t]*")
+		(goto-char (match-end 0))
+	      (forward-char 1)))
+	   ((equal keywd ":")	;; Case statement, begin/end label, x?y:z
+	    (cond ((equal "endcase" exit-keywd)  ;; case x: y=z; statement next
+		   (setq ignore-next nil rvalue nil))
+		  ((equal "?" exit-keywd)  ;; x?y:z rvalue
+		   ) ;; NOP
+		  (got-sig	;; label: statement
+		   (setq ignore-next nil rvalue semi-rvalue got-sig nil))
+		  ((not rvalue)	;; begin label
+		   (setq ignore-next t rvalue nil)))
+	    (forward-char 1))
+	   ((equal keywd "=")
+	    (if (eq (char-before) ?< )
+		(setq uses-delayed 1))
+	    (setq ignore-next nil rvalue t)
+	    (forward-char 1))
+	   ((equal keywd "?")
+	    (forward-char 1)
+	    (verilog-read-always-signals-recurse ":" rvalue nil))
+	   ((equal keywd "[")
+	    (forward-char 1)
+	    (verilog-read-always-signals-recurse "]" t nil))
+	   ((equal keywd "(")
+	    (forward-char 1)
+	    (cond (sig-last-tolk	;; Function call; zap last signal
+		   (setq got-sig nil)))
+	    (cond ((equal last-keywd "for")
+		   (verilog-read-always-signals-recurse ";" nil nil)
+		   (verilog-read-always-signals-recurse ";" t nil)
+		   (verilog-read-always-signals-recurse ")" nil nil))
+		  (t (verilog-read-always-signals-recurse ")" t nil))))
+	   ((equal keywd "begin")
+	    (skip-syntax-forward "w_")
+	    (verilog-read-always-signals-recurse "end" nil nil)
+	    ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
+	    (setq ignore-next nil  rvalue semi-rvalue)
+	    (if (not exit-keywd) (setq end-else-check t)))
+	   ((or (equal keywd "case")
+		(equal keywd "casex")
+		(equal keywd "casez"))
+	    (skip-syntax-forward "w_")
+	    (verilog-read-always-signals-recurse "endcase" t nil)
+	    (setq ignore-next nil  rvalue semi-rvalue)
+	    (if (not exit-keywd) (setq gotend t)))	;; top level begin/end
+	   ((string-match "^[$`a-zA-Z_]" keywd)	;; not exactly word constituent
+	    (cond ((or (equal keywd "`ifdef")
+		       (equal keywd "`ifndef"))
+		   (setq ignore-next t))
+		  ((or ignore-next
+		       (member keywd verilog-keywords)
+		       (string-match "^\\$" keywd))	;; PLI task
+		   (setq ignore-next nil))
+		  (t
+		   (setq keywd (verilog-symbol-detick-denumber keywd))
+		   (when got-sig
+		     (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
+		       (setq sigs-out (cons got-sig sigs-out)))
+		     ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
+		     )
+		   (setq got-rvalue rvalue
+			 got-sig (if (or (not keywd)
+					 (assoc keywd (if got-rvalue sigs-in sigs-out)))
+				     nil (list keywd nil nil))
+			 sig-tolk t)))
+	    (skip-chars-forward "a-zA-Z0-9$_.%`"))
+	   (t
+	    (forward-char 1)))
+	  ;; End of non-comment token
+	  (setq last-keywd keywd)
+	  ))
+      (skip-syntax-forward " "))
+    ;; Append the final pending signal
+    (when got-sig
+      (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
+	(setq sigs-out (cons got-sig sigs-out)))
+      ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
+      (setq got-sig nil))
+    ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
+    ))
+
+(defun verilog-read-always-signals ()
+  "Parse always block at point and return list of (outputs inout inputs)."
+  ;; Insert new
+  (save-excursion
+    (let* (;;(dbg "")
+	   sigs-in sigs-out
+	   uses-delayed)	;; Found signal/rvalue; push if not function
+      (search-forward ")")
+      (verilog-read-always-signals-recurse nil nil nil)
+      ;;(if dbg (save-excursion (set-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg "")))
+      ;; Return what was found
+      (list sigs-out nil sigs-in uses-delayed))))
+
+(defun verilog-read-instants ()
+  "Parse module at point and return list of ( ( file instance ) ... )."
+  (verilog-beg-of-defun)
+  (let* ((end-mod-point (verilog-get-end-of-defun t))
+	 (state nil)
+	 (instants-list nil))
+    (save-excursion
+      (while (< (point) end-mod-point)
+	;; Stay at level 0, no comments
+	(while (progn
+		 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
+		 (or (> (car state) 0)	; in parens
+		     (nth 5 state)		; comment
+		     ))
+	  (forward-line 1))
+	(beginning-of-line)
+	(if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
+	    ;;(if (looking-at "^\\(.+\\)$")
+	    (let ((module (match-string 1))
+		  (instant (match-string 2)))
+	      (if (not (member module verilog-keywords))
+		  (setq instants-list (cons (list module instant) instants-list)))))
+	(forward-line 1)
+	))
+    instants-list))
+
+
+(defun verilog-read-auto-template (module)
+  "Look for a auto_template for the instantiation of the given MODULE.
+If found returns the signal name connections.  Return REGEXP and
+list of ( (signal_name connection_name)... )"
+  (save-excursion
+    ;; Find beginning
+    (let ((tpl-regexp "\\([0-9]+\\)")
+	  (lineno 0)
+	  (templateno 0)
+	  tpl-sig-list tpl-wild-list tpl-end-pt rep)
+      (cond ((or
+	       (re-search-backward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
+	       (progn
+		 (goto-char (point-min))
+		 (re-search-forward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
+	     (goto-char (match-end 0))
+	     ;; Parse "REGEXP"
+	     ;; We reserve @"..." for future lisp expressions that evaluate once-per-AUTOINST
+	     (when (looking-at "\\s-*\"\\([^\"]*)\\)\"")
+	       (setq tpl-regexp (match-string 1))
+	       (goto-char (match-end 0)))
+	     (search-forward "(")
+	     ;; Parse lines in the template
+	     (when verilog-auto-inst-template-numbers
+	       (save-excursion
+		 (goto-char (point-min))
+		 (while (search-forward "AUTO_TEMPLATE" nil t)
+		   (setq templateno (1+ templateno)))))
+	     (setq tpl-end-pt (save-excursion
+				(backward-char 1)
+				(forward-sexp 1)   ;; Moves to paren that closes argdecl's
+				(backward-char 1)
+				(point)))
+	     ;;
+	     (while (< (point) tpl-end-pt)
+	       (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
+		      (setq tpl-sig-list (cons (list
+						(match-string-no-properties 1)
+						(match-string-no-properties 2)
+						templateno lineno)
+					       tpl-sig-list))
+		      (goto-char (match-end 0)))
+		     ;; Regexp form??
+		     ((looking-at
+		       ;; Regexp bug in xemacs disallows ][ inside [], and wants + last
+		       "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
+		      (setq rep (match-string-no-properties 3))
+		      (goto-char (match-end 0))
+		      (setq tpl-wild-list
+			    (cons (list
+				   (concat "^"
+					   (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
+									   (match-string 1))
+					   "$")
+				   rep
+				   templateno lineno)
+				  tpl-wild-list)))
+		     ((looking-at "[ \t\f]+")
+		      (goto-char (match-end 0)))
+		     ((looking-at "\n")
+		      (setq lineno (1+ lineno))
+		      (goto-char (match-end 0)))
+		     ((looking-at "//")
+		      (search-forward "\n"))
+		     ((looking-at "/\\*")
+		      (forward-char 2)
+		      (or (search-forward "*/")
+			  (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
+		     (t
+		      (error "%s: AUTO_TEMPLATE parsing error: %s"
+			     (verilog-point-text)
+			     (progn (looking-at ".*$") (match-string 0))))
+		     ))
+	     ;; Return
+	     (vector tpl-regexp
+		     (list tpl-sig-list tpl-wild-list)))
+	    ;; If no template found
+	    (t (vector tpl-regexp nil))))))
+;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
+
+(defun verilog-set-define (defname defvalue &optional buffer enumname)
+  "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
+Optionally associate it with the specified enumeration ENUMNAME."
+  (save-excursion
+    (set-buffer (or buffer (current-buffer)))
+    (let ((mac (intern (concat "vh-" defname))))
+      ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
+      ;; Need to define to a constant if no value given
+      (set (make-variable-buffer-local mac)
+	   (if (equal defvalue "") "1" defvalue)))
+    (if enumname
+	(let ((enumvar (intern (concat "venum-" enumname))))
+	  ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
+	  (make-variable-buffer-local enumvar)
+	  (add-to-list enumvar defname)))
+    ))
+
+(defun verilog-read-defines (&optional filename recurse subcall)
+  "Read `defines and parameters for the current file, or optional FILENAME.
+If the filename is provided, `verilog-library-flags' will be used to
+resolve it.  If optional RECURSE is non-nil, recurse through `includes.
+
+Parameters must be simple assignments to constants, or have their own
+\"parameter\" label rather than a list of parameters.  Thus:
+
+    parameter X = 5, Y = 10;	// Ok
+    parameter X = {1'b1, 2'h2};	// Ok
+    parameter X = {1'b1, 2'h2}, Y = 10;	// Bad, make into 2 parameter lines
+
+Defines must be simple text substitutions, one on a line, starting
+at the beginning of the line.  Any ifdefs or multiline comments around the
+define are ignored.
+
+Defines are stored inside Emacs variables using the name vh-{definename}.
+
+This function is useful for setting vh-* variables.  The file variables
+feature can be used to set defines that `verilog-mode' can see; put at the
+*END* of your file something like:
+
+    // Local Variables:
+    // vh-macro:\"macro_definition\"
+    // End:
+
+If macros are defined earlier in the same file and you want their values,
+you can read them automatically (provided `enable-local-eval' is on):
+
+    // Local Variables:
+    // eval:(verilog-read-defines)
+    // eval:(verilog-read-defines \"group_standard_includes.v\")
+    // End:
+
+Note these are only read when the file is first visited, you must use
+\\[find-alternate-file] RET  to have these take effect after editing them!
+
+If you want to disable the \"Process `eval' or hook local variables\"
+warning message, you need to add to your .emacs file:
+
+    (setq enable-local-eval t)"
+  (let ((origbuf (current-buffer)))
+    (save-excursion
+      (unless subcall (verilog-getopt-flags))
+      (when filename
+	(let ((fns (verilog-library-filenames filename (buffer-file-name))))
+	  (if fns
+	      (set-buffer (find-file-noselect (car fns)))
+	    (error (concat (verilog-point-text)
+			   ": Can't find verilog-read-defines file: " filename)))))
+      (when recurse
+	(goto-char (point-min))
+	(while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
+	  (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string-no-properties 1))))
+	    (unless (verilog-inside-comment-p)
+	      (verilog-read-defines inc recurse t)))))
+      ;; Read `defines
+      ;; note we don't use verilog-re... it's faster this way, and that
+      ;; function has problems when comments are at the end of the define
+      (goto-char (point-min))
+      (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
+	(let ((defname (match-string-no-properties 1))
+	      (defvalue (match-string-no-properties 2)))
+	  (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
+	  (verilog-set-define defname defvalue origbuf)))
+      ;; Hack: Read parameters
+      (goto-char (point-min))
+      (while (re-search-forward
+	      "^\\s-*\\(parameter\\|localparam\\)\\(\\(\\s-*\\[[^]]*\\]\\|\\)\\s-+\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\|\\)\\s-*" nil t)
+	(let ((var (match-string-no-properties 4))
+	      (val (match-string-no-properties 5))
+	      enumname)
+	  ;; The primary way of getting defines is verilog-read-decls
+	  ;; However, that isn't called yet for included files, so we'll add another scheme
+	  (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
+	      (setq enumname (match-string-no-properties 1)))
+	  (if var
+	    (verilog-set-define var val origbuf enumname))
+	  (forward-comment 999)
+	  (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
+	    (verilog-set-define (match-string-no-properties 1) (match-string-no-properties 2) origbuf enumname)
+	    (goto-char (match-end 0))
+	    (forward-comment 999))))
+      )))
+
+(defun verilog-read-includes ()
+  "Read `includes for the current file.
+This will find all of the `includes which are at the beginning of lines,
+ignoring any ifdefs or multiline comments around them.
+`verilog-read-defines' is then performed on the current and each included
+file.
+
+It is often useful put at the *END* of your file something like:
+
+    // Local Variables:
+    // eval:(verilog-read-defines)
+    // eval:(verilog-read-includes)
+    // End:
+
+Note includes are only read when the file is first visited, you must use
+\\[find-alternate-file] RET  to have these take effect after editing them!
+
+It is good to get in the habit of including all needed files in each .v
+file that needs it, rather than waiting for compile time.  This will aid
+this process, Verilint, and readability.  To prevent defining the same
+variable over and over when many modules are compiled together, put a test
+around the inside each include file:
+
+foo.v (a include):
+	`ifdef _FOO_V	// include if not already included
+	`else
+	`define _FOO_V
+	... contents of file
+	`endif // _FOO_V"
+;;slow:  (verilog-read-defines nil t))
+  (save-excursion
+    (verilog-getopt-flags)
+    (goto-char (point-min))
+    (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
+      (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
+	(verilog-read-defines inc nil t)))))
+
+(defun verilog-read-signals (&optional start end)
+  "Return a simple list of all possible signals in the file.
+Bounded by optional region from START to END.  Overly aggressive but fast.
+Some macros and such are also found and included.  For dinotrace.el"
+  (let (sigs-all keywd)
+    (progn;save-excursion
+      (goto-char (or start (point-min)))
+      (setq end (or end (point-max)))
+      (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
+	(forward-char -1)
+	(cond
+	 ((looking-at "//")
+	  (search-forward "\n"))
+	 ((looking-at "/\\*")
+	  (search-forward "*/"))
+	 ((looking-at "(\\*")
+	  (or (looking-at "(\\*\\s-*)")   ; It's a "always @ (*)"
+	      (search-forward "*)")))
+	 ((eq ?\" (following-char))
+	  (re-search-forward "[^\\]\""))	;; don't forward-char first, since we look for a non backslash first
+	 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
+	  (goto-char (match-end 0))
+	  (setq keywd (match-string-no-properties 1))
+	  (or (member keywd verilog-keywords)
+	      (member keywd sigs-all)
+	      (setq sigs-all (cons keywd sigs-all))))
+	 (t (forward-char 1)))
+	)
+      ;; Return list
+      sigs-all)))
+
+;;
+;; Argument file parsing
+;;
+
+(defun verilog-getopt (arglist)
+  "Parse -f, -v etc arguments in ARGLIST list or string."
+  (unless (listp arglist) (setq arglist (list arglist)))
+  (let ((space-args '())
+	arg next-param)
+    ;; Split on spaces, so users can pass whole command lines
+    (while arglist
+      (setq arg (car arglist)
+	    arglist (cdr arglist))
+      (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
+	(setq space-args (append space-args
+				 (list (match-string-no-properties 1 arg))))
+	(setq arg (match-string 2 arg))))
+    ;; Parse arguments
+    (while space-args
+      (setq arg (car space-args)
+	    space-args (cdr space-args))
+      (cond
+       ;; Need another arg
+       ((equal arg "-f")
+	(setq next-param arg))
+       ((equal arg "-v")
+	(setq next-param arg))
+       ((equal arg "-y")
+	(setq next-param arg))
+       ;; +libext+(ext1)+(ext2)...
+       ((string-match "^\\+libext\\+\\(.*\\)" arg)
+	(setq arg (match-string 1 arg))
+	(while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
+	  (verilog-add-list-unique `verilog-library-extensions
+				   (match-string 1 arg))
+	  (setq arg (match-string 2 arg))))
+       ;;
+       ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg)	;; -Ddefine=val
+	    (string-match "^-D\\([^+=]*\\)\\(\\)" arg)	;; -Ddefine
+	    (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg)	;; +define+val
+	    (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg))		;; +define+define
+	(verilog-set-define (match-string 1 arg) (match-string 2 arg)))
+       ;;
+       ((or (string-match "^\\+incdir\\+\\(.*\\)" arg)	;; +incdir+dir
+	    (string-match "^-I\\(.*\\)" arg))	;; -Idir
+	(verilog-add-list-unique `verilog-library-directories
+				 (match-string 1 arg)))
+       ;; Ignore
+       ((equal "+librescan" arg))
+       ((string-match "^-U\\(.*\\)" arg))	;; -Udefine
+       ;; Second parameters
+       ((equal next-param "-f")
+	(setq next-param nil)
+	(verilog-getopt-file arg))
+       ((equal next-param "-v")
+	(setq next-param nil)
+	(verilog-add-list-unique `verilog-library-files arg))
+       ((equal next-param "-y")
+	(setq next-param nil)
+	(verilog-add-list-unique `verilog-library-directories arg))
+       ;; Filename
+       ((string-match "^[^-+]" arg)
+	(verilog-add-list-unique `verilog-library-files arg))
+       ;; Default - ignore; no warning
+       )
+      )
+    )
+  )
+;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
+
+(defun verilog-getopt-file (filename)
+  "Read verilog options from the specified FILENAME."
+  (save-excursion
+    (let ((fns (verilog-library-filenames filename (buffer-file-name)))
+	  (orig-buffer (current-buffer))
+	  line)
+      (if fns
+	  (set-buffer (find-file-noselect (car fns)))
+	(error (concat (verilog-point-text)
+		       "Can't find verilog-getopt-file -f file: " filename)))
+      (goto-char (point-min))
+      (while (not (eobp))
+	(setq line (buffer-substring (point)
+				     (save-excursion (end-of-line) (point))))
+	(forward-line 1)
+	(when (string-match "//" line)
+	  (setq line (substring line 0 (match-beginning 0))))
+	(save-excursion
+	  (set-buffer orig-buffer)  ; Variables are buffer-local, so need right context.
+	  (verilog-getopt line))))))
+
+(defun verilog-getopt-flags ()
+  "Convert `verilog-library-flags' into standard library variables."
+  ;; If the flags are local, then all the outputs should be local also
+  (when (local-variable-p `verilog-library-flags (current-buffer))
+    (make-variable-buffer-local 'verilog-library-extensions)
+    (make-variable-buffer-local 'verilog-library-directories)
+    (make-variable-buffer-local 'verilog-library-files)
+    (make-variable-buffer-local 'verilog-library-flags))
+  ;; Allow user to customize
+  (run-hooks 'verilog-before-getopt-flags-hook)
+  ;; Process arguments
+  (verilog-getopt verilog-library-flags)
+  ;; Allow user to customize
+  (run-hooks 'verilog-getopt-flags-hook))
+
+(defun verilog-add-list-unique (varref object)
+  "Append to VARREF list the given OBJECT,
+unless it is already a member of the variable's list"
+  (unless (member object (symbol-value varref))
+    (set varref (append (symbol-value varref) (list object))))
+  varref)
+;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
+
+
+;;
+;; Module name lookup
+;;
+
+(defun verilog-module-inside-filename-p (module filename)
+  "Return point if MODULE is specified inside FILENAME, else nil.
+Allows version control to check out the file if need be."
+  (and (or (file-exists-p filename)
+	   (and
+	    (condition-case nil
+		(fboundp 'vc-backend)
+	      (error nil))
+	    (vc-backend filename)))
+       (let (pt)
+	 (save-excursion
+	   (set-buffer (find-file-noselect filename))
+	   (goto-char (point-min))
+	   (while (and
+		   ;; It may be tempting to look for verilog-defun-re, don't, it slows things down a lot!
+		   (verilog-re-search-forward-quick "\\<module\\>" nil t)
+		   (verilog-re-search-forward-quick "[(;]" nil t))
+	     (if (equal module (verilog-read-module-name))
+		 (setq pt (point))))
+	   pt))))
+
+(defun verilog-is-number (symbol)
+  "Return true if SYMBOL is number-like."
+  (or (string-match "^[0-9 \t:]+$" symbol)
+      (string-match "^[---]*[0-9]+$" symbol)
+      (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)
+      ))
+
+(defun verilog-symbol-detick (symbol wing-it)
+  "Return a expanded SYMBOL name without any defines.
+If the variable vh-{symbol} is defined, return that value.
+If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
+  (while (and symbol (string-match "^`" symbol))
+    (setq symbol (substring symbol 1))
+    (setq symbol
+	  (if (boundp (intern (concat "vh-" symbol)))
+	      ;; Emacs has a bug where boundp on a buffer-local
+	      ;; variable in only one buffer returns t in another.
+	      ;; This can confuse, so check for nil.
+	      (let ((val (eval (intern (concat "vh-" symbol)))))
+		(if (eq val nil)
+		    (if wing-it symbol nil)
+		  val))
+	    (if wing-it symbol nil))))
+  symbol)
+;;(verilog-symbol-detick "`mod" nil)
+
+(defun verilog-symbol-detick-denumber (symbol)
+  "Return SYMBOL with defines converted and any numbers dropped to nil."
+  (when (string-match "^`" symbol)
+    ;; This only will work if the define is a simple signal, not
+    ;; something like a[b].  Sorry, it should be substituted into the parser
+    (setq symbol
+	  (verilog-string-replace-matches
+	   "\[[^0-9: \t]+\]" "" nil nil
+	   (or (verilog-symbol-detick symbol nil)
+	       (if verilog-auto-sense-defines-constant
+		   "0"
+		 symbol)))))
+  (if (verilog-is-number symbol)
+      nil
+    symbol))
+
+(defun verilog-symbol-detick-text (text)
+  "Return TEXT with any without any known defines.
+If the variable vh-{symbol} is defined, substitute that value."
+  (let ((ok t) symbol val)
+    (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
+      (setq symbol (match-string 1 text))
+      (message symbol)
+      (cond ((and
+	      (boundp (intern (concat "vh-" symbol)))
+	      ;; Emacs has a bug where boundp on a buffer-local
+	      ;; variable in only one buffer returns t in another.
+	      ;; This can confuse, so check for nil.
+	      (setq val (eval (intern (concat "vh-" symbol)))))
+	     (setq text (replace-match val nil nil text)))
+	    (t (setq ok nil)))))
+  text)
+;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
+
+(defun verilog-expand-dirnames (&optional dirnames)
+  "Return a list of existing directories given a list of wildcarded DIRNAMES.
+Or, just the existing dirnames themselves if there are no wildcards."
+  (interactive)
+  (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
+  (setq dirnames (reverse dirnames))	; not nreverse
+  (let ((dirlist nil)
+	pattern dirfile dirfiles dirname root filename rest)
+    (while dirnames
+      (setq dirname (substitute-in-file-name (car dirnames))
+	    dirnames (cdr dirnames))
+      (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)"  ;; root
+				   "\\([^/\\]*[*?][^/\\]*\\)"	  ;; filename with *?
+				   "\\(.*\\)")			  ;; rest
+			   dirname)
+	     (setq root (match-string 1 dirname)
+		   filename (match-string 2 dirname)
+		   rest (match-string 3 dirname)
+		   pattern filename)
+	     ;; now replace those * and ? with .+ and .
+	     ;; use ^ and /> to get only whole file names
+	     ;;verilog-string-replace-matches
+	     (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
+		   pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
+
+		   ;; Unfortunately allows abc/*/rtl to match abc/rtl
+		   ;; because abc/.. shows up in dirfiles.  Solutions welcome.
+		   dirfiles (if (file-directory-p root)	; Ignore version control external
+				(directory-files root t pattern nil)))
+	     (while dirfiles
+	       (setq dirfile (expand-file-name (concat (car dirfiles) rest))
+		     dirfiles (cdr dirfiles))
+	       (if (file-directory-p dirfile)
+		   (setq dirlist (cons dirfile dirlist))))
+	     )
+	    ;; Defaults
+	    (t
+	     (if (file-directory-p dirname)
+		 (setq dirlist (cons dirname dirlist))))
+	    ))
+    dirlist))
+;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
+
+(defun verilog-library-filenames (filename current &optional check-ext)
+  "Return a search path to find the given FILENAME name.
+Uses the CURRENT filename, `verilog-library-directories' and
+`verilog-library-extensions' variables to build the path.
+With optional CHECK-EXT also check `verilog-library-extensions'."
+  (let ((ckdir (verilog-expand-dirnames verilog-library-directories))
+	fn outlist)
+    (while ckdir
+      (let ((ckext (if check-ext verilog-library-extensions `(""))))
+	(while ckext
+	  (setq fn (expand-file-name
+		    (concat filename (car ckext))
+		    (expand-file-name (car ckdir) (file-name-directory current))))
+	  (if (file-exists-p fn)
+	      (setq outlist (cons fn outlist)))
+	  (setq ckext (cdr ckext))))
+      (setq ckdir (cdr ckdir)))
+    (nreverse outlist)))
+
+(defun verilog-module-filenames (module current)
+  "Return a search path to find the given MODULE name.
+Uses the CURRENT filename, `verilog-library-extensions',
+`verilog-library-directories' and `verilog-library-files'
+variables to build the path."
+  ;; Return search locations for it
+  (append (list current)		; first, current buffer
+	  (verilog-library-filenames module current t)
+	  verilog-library-files))	; finally, any libraries
+
+;;
+;; Module Information
+;;
+;; Many of these functions work on "modi" a module information structure
+;; A modi is:  [module-name-string file-name begin-point]
+
+(defvar verilog-cache-enabled t
+  "If true, enable caching of signals, etc.  Set to nil for debugging to make things SLOW!")
+
+(defvar verilog-modi-cache-list nil
+  "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
+For speeding up verilog-modi-get-* commands.
+Buffer-local.")
+
+(defvar verilog-modi-cache-preserve-tick nil
+  "Modification tick after which the cache is still considered valid.
+Use verilog-preserve-cache's to set")
+(defvar verilog-modi-cache-preserve-buffer nil
+  "Modification tick after which the cache is still considered valid.
+Use verilog-preserve-cache's to set")
+
+(defun verilog-modi-current ()
+  "Return the modi structure for the module currently at point."
+  (let* (name pt)
+    ;; read current module's name
+    (save-excursion
+      (verilog-re-search-backward-quick verilog-defun-re nil nil)
+      (verilog-re-search-forward-quick "(" nil nil)
+      (setq name (verilog-read-module-name))
+      (setq pt (point)))
+    ;; return
+    (vector name (or (buffer-file-name) (current-buffer)) pt)))
+
+(defvar verilog-modi-lookup-last-mod nil "Cache of last module looked up.")
+(defvar verilog-modi-lookup-last-modi nil "Cache of last modi returned.")
+(defvar verilog-modi-lookup-last-current nil "Cache of last `current-buffer' looked up.")
+(defvar verilog-modi-lookup-last-tick nil "Cache of last `buffer-modified-tick' looked up.")
+
+(defun verilog-modi-lookup (module allow-cache &optional ignore-error)
+  "Find the file and point at which MODULE is defined.
+If ALLOW-CACHE is set, check and remember cache of previous lookups.
+Return modi if successful, else print message unless IGNORE-ERROR is true."
+  (let* ((current (or (buffer-file-name) (current-buffer))))
+    (cond ((and verilog-modi-lookup-last-modi
+		verilog-cache-enabled
+		allow-cache
+		(equal verilog-modi-lookup-last-mod module)
+		(equal verilog-modi-lookup-last-current current)
+		(equal verilog-modi-lookup-last-tick (buffer-modified-tick)))
+	   ;; ok as is
+	   )
+	  (t (let* ((realmod (verilog-symbol-detick module t))
+		    (orig-filenames (verilog-module-filenames realmod current))
+		    (filenames orig-filenames)
+		    pt)
+	       (while (and filenames (not pt))
+		 (if (not (setq pt (verilog-module-inside-filename-p realmod (car filenames))))
+		     (setq filenames (cdr filenames))))
+	       (cond (pt (setq verilog-modi-lookup-last-modi
+			       (vector realmod (car filenames) pt)))
+		     (t (setq verilog-modi-lookup-last-modi nil)
+			(or ignore-error
+			    (error (concat (verilog-point-text)
+					   ": Can't locate " module " module definition"
+					   (if (not (equal module realmod))
+					       (concat " (Expanded macro to " realmod ")")
+					     "")
+					   "\n    Check the verilog-library-directories variable."
+					   "\n    I looked in (if not listed, doesn't exist):\n\t"
+					   (mapconcat 'concat orig-filenames "\n\t")))))
+		     )
+	       (setq verilog-modi-lookup-last-mod module
+		     verilog-modi-lookup-last-current current
+		     verilog-modi-lookup-last-tick (buffer-modified-tick)))))
+    verilog-modi-lookup-last-modi
+    ))
+
+(defsubst verilog-modi-name (modi)
+  (aref modi 0))
+(defsubst verilog-modi-file-or-buffer (modi)
+  (aref modi 1))
+(defsubst verilog-modi-point (modi)
+  (aref modi 2))
+
+(defun verilog-modi-filename (modi)
+  "Filename of MODI, or name of buffer if its never been saved."
+  (if (bufferp (verilog-modi-file-or-buffer modi))
+      (or (buffer-file-name (verilog-modi-file-or-buffer modi))
+	  (buffer-name (verilog-modi-file-or-buffer modi)))
+    (verilog-modi-file-or-buffer modi)))
+
+(defun verilog-modi-goto (modi)
+  "Move point/buffer to specified MODI."
+  (or modi (error "Passed unfound modi to goto, check earlier"))
+  (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
+		  (verilog-modi-file-or-buffer modi)
+		(find-file-noselect (verilog-modi-file-or-buffer modi))))
+  (or (equal major-mode `verilog-mode)	;; Put into verilog mode to get syntax
+      (verilog-mode))
+  (goto-char (verilog-modi-point modi)))
+
+(defun verilog-goto-defun-file (module)
+  "Move point to the file at which a given MODULE is defined."
+  (interactive "sGoto File for Module: ")
+  (let* ((modi (verilog-modi-lookup module nil)))
+    (when modi
+      (verilog-modi-goto modi)
+      (switch-to-buffer (current-buffer)))))
+
+(defun verilog-modi-cache-results (modi function)
+  "Run on MODI the given FUNCTION.  Locate the module in a file.
+Cache the output of function so next call may have faster access."
+  (let (func-returns fass)
+    (save-excursion
+      (verilog-modi-goto modi)
+      (if (and (setq fass (assoc (list (verilog-modi-name modi) function)
+				 verilog-modi-cache-list))
+	       ;; Destroy caching when incorrect; Modified or file changed
+	       (not (and verilog-cache-enabled
+			 (or (equal (buffer-modified-tick) (nth 1 fass))
+			     (and verilog-modi-cache-preserve-tick
+				  (<= verilog-modi-cache-preserve-tick  (nth 1 fass))
+				  (equal  verilog-modi-cache-preserve-buffer (current-buffer))))
+			 (equal (visited-file-modtime) (nth 2 fass)))))
+	  (setq verilog-modi-cache-list nil
+		fass nil))
+      (cond (fass
+	     ;; Found
+	     (setq func-returns (nth 3 fass)))
+	    (t
+	     ;; Read from file
+	     ;; Clear then restore any hilighting to make emacs19 happy
+	     (let ((fontlocked (when (and (boundp 'font-lock-mode)
+					  font-lock-mode)
+				 (font-lock-mode nil)
+				 t)))
+	       (setq func-returns (funcall function))
+	       (when fontlocked (font-lock-mode t)))
+	     ;; Cache for next time
+	     (make-variable-buffer-local 'verilog-modi-cache-list)
+	     (setq verilog-modi-cache-list
+		   (cons (list (list (verilog-modi-name modi) function)
+			       (buffer-modified-tick)
+			       (visited-file-modtime)
+			       func-returns)
+			 verilog-modi-cache-list)))
+	    ))
+      ;;
+      func-returns))
+
+(defun verilog-modi-cache-add (modi function element sig-list)
+  "Add function return results to the module cache.
+Update MODI's cache for given FUNCTION so that the return ELEMENT of that
+function now contains the additional SIG-LIST parameters."
+  (let (fass)
+    (save-excursion
+      (verilog-modi-goto modi)
+      (if (setq fass (assoc (list (verilog-modi-name modi) function)
+			    verilog-modi-cache-list))
+	  (let ((func-returns (nth 3 fass)))
+	    (aset func-returns element
+		  (append sig-list (aref func-returns element))))))))
+
+(defmacro verilog-preserve-cache (&rest body)
+  "Execute the BODY forms, allowing cache preservation within BODY.
+This means that changes to the buffer will not result in the cache being
+flushed.  If the changes affect the modsig state, they must call the
+modsig-cache-add-* function, else the results of later calls may be
+incorrect.  Without this, changes are assumed to be adding/removing signals
+and invalidating the cache."
+  `(let ((verilog-modi-cache-preserve-tick (buffer-modified-tick))
+	 (verilog-modi-cache-preserve-buffer (current-buffer)))
+     (progn ,@body)))
+
+(defsubst verilog-modi-get-decls (modi)
+  (verilog-modi-cache-results modi 'verilog-read-decls))
+
+(defsubst verilog-modi-get-sub-decls (modi)
+  (verilog-modi-cache-results modi 'verilog-read-sub-decls))
+
+;; Signal reading for given module
+;; Note these all take modi's - as returned from the verilog-modi-current function
+(defsubst verilog-modi-get-outputs (modi)
+  (aref (verilog-modi-get-decls modi) 0))
+(defsubst verilog-modi-get-inouts (modi)
+  (aref (verilog-modi-get-decls modi) 1))
+(defsubst verilog-modi-get-inputs (modi)
+  (aref (verilog-modi-get-decls modi) 2))
+(defsubst verilog-modi-get-wires (modi)
+  (aref (verilog-modi-get-decls modi) 3))
+(defsubst verilog-modi-get-regs (modi)
+  (aref (verilog-modi-get-decls modi) 4))
+(defsubst verilog-modi-get-assigns (modi)
+  (aref (verilog-modi-get-decls modi) 5))
+(defsubst verilog-modi-get-consts (modi)
+  (aref (verilog-modi-get-decls modi) 6))
+(defsubst verilog-modi-get-gparams (modi)
+  (aref (verilog-modi-get-decls modi) 7))
+(defsubst verilog-modi-get-sub-outputs (modi)
+  (aref (verilog-modi-get-sub-decls modi) 0))
+(defsubst verilog-modi-get-sub-inouts (modi)
+  (aref (verilog-modi-get-sub-decls modi) 1))
+(defsubst verilog-modi-get-sub-inputs (modi)
+  (aref (verilog-modi-get-sub-decls modi) 2))
+
+
+(defun verilog-signals-matching-enum (in-list enum)
+  "Return all signals in IN-LIST matching the given ENUM."
+  (let (out-list)
+    (while in-list
+      (if (equal (verilog-sig-enum (car in-list)) enum)
+	  (setq out-list (cons (car in-list) out-list)))
+      (setq in-list (cdr in-list)))
+    ;; New scheme
+    (let* ((enumvar (intern (concat "venum-" enum)))
+	   (enumlist (and (boundp enumvar) (eval enumvar))))
+      (while enumlist
+	(add-to-list 'out-list (list (car enumlist)))
+	(setq enumlist (cdr enumlist))))
+    (nreverse out-list)))
+
+(defun verilog-signals-not-matching-regexp (in-list regexp)
+  "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
+  (if (not regexp)
+      in-list
+    (let (out-list)
+      (while in-list
+	(if (not (string-match regexp (verilog-sig-name (car in-list))))
+	    (setq out-list (cons (car in-list) out-list)))
+	(setq in-list (cdr in-list)))
+      (nreverse out-list))))
+
+;; Combined
+(defun verilog-modi-get-signals (modi)
+  (append
+   (verilog-modi-get-outputs modi)
+   (verilog-modi-get-inouts modi)
+   (verilog-modi-get-inputs modi)
+   (verilog-modi-get-wires modi)
+   (verilog-modi-get-regs modi)
+   (verilog-modi-get-assigns modi)
+   (verilog-modi-get-consts modi)
+   (verilog-modi-get-gparams modi)))
+
+(defun verilog-modi-get-ports (modi)
+  (append
+   (verilog-modi-get-outputs modi)
+   (verilog-modi-get-inouts modi)
+   (verilog-modi-get-inputs modi)))
+
+(defsubst verilog-modi-cache-add-outputs (modi sig-list)
+  (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
+(defsubst verilog-modi-cache-add-inouts (modi sig-list)
+  (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
+(defsubst verilog-modi-cache-add-inputs (modi sig-list)
+  (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
+(defsubst verilog-modi-cache-add-wires (modi sig-list)
+  (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
+(defsubst verilog-modi-cache-add-regs (modi sig-list)
+  (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
+
+(defun verilog-signals-from-signame (signame-list)
+  "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
+  (mapcar (function (lambda (name) (list name nil nil)))
+	  signame-list))
+
+;;
+;; Auto creation utilities
+;;
+
+(defun verilog-auto-search-do (search-for func)
+  "Search for the given auto text SEARCH-FOR, and perform FUNC where it occurs."
+  (goto-char (point-min))
+  (while (search-forward search-for nil t)
+    (if (not (save-excursion
+	       (goto-char (match-beginning 0))
+	       (verilog-inside-comment-p)))
+	(funcall func))))
+
+(defun verilog-auto-re-search-do (search-for func)
+  "Search for the given auto text SEARCH-FOR, and perform FUNC where it occurs."
+  (goto-char (point-min))
+  (while (re-search-forward search-for nil t)
+    (if (not (save-excursion
+	       (goto-char (match-beginning 0))
+	       (verilog-inside-comment-p)))
+	(funcall func))))
+
+(defun verilog-insert-one-definition (sig type indent-pt)
+  "Print out a definition for SIGNAL of the given TYPE,
+with appropriate INDENT-PT indentation."
+  (indent-to indent-pt)
+  (insert type)
+  (when (verilog-sig-signed sig)
+    (insert " " (verilog-sig-signed sig)))
+  (when (verilog-sig-multidim sig)
+    (insert " " (verilog-sig-multidim-string sig)))
+  (when (verilog-sig-bits sig)
+    (insert " " (verilog-sig-bits sig)))
+  (indent-to (max 24 (+ indent-pt 16)))
+  (unless (= (char-syntax (preceding-char)) ?\  )
+    (insert " "))  ; Need space between "]name" if indent-to did nothing
+  (insert (verilog-sig-name sig)))
+
+(defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
+  "Print out a definition for a list of SIGS of the given DIRECTION,
+with appropriate INDENT-PT indentation.  If V2K, use Verilog 2001 I/O
+format.  Sort unless DONT-SORT.  DIRECTION is normally wire/reg/output."
+  (or dont-sort
+      (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
+  (while sigs
+    (let ((sig (car sigs)))
+      (verilog-insert-one-definition
+       sig
+       ;; Want "type x" or "output type x", not "wire type x"
+       (cond ((verilog-sig-type sig)
+	      (concat
+	       (if (not (equal direction "wire"))
+		   (concat direction " "))
+	       (verilog-sig-type sig)))
+	     (t direction))
+       indent-pt)
+      (insert (if v2k "," ";"))
+      (if (or (not (verilog-sig-comment sig))
+	      (equal "" (verilog-sig-comment sig)))
+	  (insert "\n")
+	(indent-to (max 48 (+ indent-pt 40)))
+	(insert (concat "// " (verilog-sig-comment sig) "\n")))
+      (setq sigs (cdr sigs)))))
+
+(eval-when-compile
+  (if (not (boundp 'indent-pt))
+      (defvar indent-pt nil "Local used by insert-indent")))
+
+(defun verilog-insert-indent (&rest stuff)
+  "Indent to position stored in local `indent-pt' variable, then insert STUFF.
+Presumes that any newlines end a list element."
+  (let ((need-indent t))
+    (while stuff
+      (if need-indent (indent-to indent-pt))
+      (setq need-indent nil)
+      (insert (car stuff))
+      (setq need-indent (string-match "\n$" (car stuff))
+	    stuff (cdr stuff)))))
+;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
+
+(defun verilog-repair-open-comma ()
+  "If backwards-from-point is other than a open parenthesis insert comma."
+  (save-excursion
+    (verilog-backward-syntactic-ws)
+    (when (save-excursion
+	    (backward-char 1)
+	    (and (not (looking-at "[(,]"))
+		 (progn
+		   (verilog-re-search-backward "[(`]" nil t)
+		   (looking-at "("))))
+    (insert ","))))
+
+(defun verilog-repair-close-comma ()
+  "If point is at a comma followed by a close parenthesis, fix it.
+This repairs those mis-inserted by a AUTOARG."
+  ;; It would be much nicer if Verilog allowed extra commas like Perl does!
+  (save-excursion
+    (verilog-forward-close-paren)
+    (backward-char 1)
+    (verilog-backward-syntactic-ws)
+    (backward-char 1)
+    (when (looking-at ",")
+      (delete-char 1))))
+
+(defun verilog-get-list (start end)
+  "Return the elements of a comma separated list between START and END."
+  (interactive)
+  (let ((my-list (list))
+	my-string)
+    (save-excursion
+      (while (< (point) end)
+	(when (re-search-forward "\\([^,{]+\\)" end t)
+	  (setq my-string (verilog-string-remove-spaces (match-string 1)))
+	  (setq my-list (nconc my-list (list my-string) ))
+	  (goto-char (match-end 0))))
+      my-list)))
+
+(defun verilog-make-width-expression (range-exp)
+  "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
+  ;; strip off the []
+  (cond ((not range-exp)
+	 "1")
+	(t
+	 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
+	     (setq range-exp (match-string 1 range-exp)))
+	 (cond ((not range-exp)
+		"1")
+	       ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$" range-exp)
+		(int-to-string (1+ (abs (- (string-to-int (match-string 1 range-exp))
+					   (string-to-int (match-string 2 range-exp)))))))
+	       ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
+		(concat "(1+(" (match-string 1 range-exp)
+			")"
+			(if (equal "0" (match-string 2 range-exp))  ;; Don't bother with -(0)
+			    ""
+			  (concat "-(" (match-string 2 range-exp) ")"))
+			")"))
+	       (t nil)))))
+;;(verilog-make-width-expression "`A:`B")
+
+(defun verilog-typedef-name-p (variable-name)
+  "Return true if the VARIABLE-NAME is a type definition."
+  (when verilog-typedef-regexp
+    (string-match verilog-typedef-regexp variable-name)))
+
+;;
+;; Auto deletion
+;;
+
+(defun verilog-delete-autos-lined ()
+  "Delete autos that occupy multiple lines, between begin and end comments."
+  (let ((pt (point)))
+    (forward-line 1)
+    (when (and
+	   (looking-at "\\s-*// Beginning")
+	   (search-forward "// End of automatic" nil t))
+      ;; End exists
+      (end-of-line)
+      (delete-region pt (point))
+      (forward-line 1))
+  ))
+
+(defun verilog-forward-close-paren ()
+  "Find the close parenthesis that match the current point,
+ignore other close parenthesis with matching open parens"
+  (let ((parens 1))
+    (while (> parens 0)
+      (unless (verilog-re-search-forward-quick "[()]" nil t)
+	(error "%s: Mismatching ()" (verilog-point-text)))
+      (cond ((= (preceding-char) ?\( )
+	     (setq parens (1+ parens)))
+	    ((= (preceding-char) ?\) )
+	     (setq parens (1- parens)))))))
+
+(defun verilog-backward-open-paren ()
+  "Find the open parenthesis that match the current point,
+ignore other open parenthesis with matching close parens"
+  (let ((parens 1))
+    (while (> parens 0)
+      (unless (verilog-re-search-backward-quick "[()]" nil t)
+	(error "%s: Mismatching ()" (verilog-point-text)))
+      (cond ((= (following-char) ?\) )
+	     (setq parens (1+ parens)))
+	    ((= (following-char) ?\( )
+	     (setq parens (1- parens)))))))
+
+(defun verilog-backward-open-bracket ()
+  "Find the open bracket that match the current point,
+ignore other open bracket with matching close bracket"
+  (let ((parens 1))
+    (while (> parens 0)
+      (unless (verilog-re-search-backward-quick "[][]" nil t)
+	(error "%s: Mismatching []" (verilog-point-text)))
+      (cond ((= (following-char) ?\] )
+	     (setq parens (1+ parens)))
+	    ((= (following-char) ?\[ )
+	     (setq parens (1- parens)))))))
+
+(defun verilog-delete-to-paren ()
+  "Delete the automatic inst/sense/arg created by autos.
+Deletion stops at the matching end parenthesis."
+  (delete-region (point)
+		 (save-excursion
+		   (verilog-backward-open-paren)
+		   (forward-sexp 1)   ;; Moves to paren that closes argdecl's
+		   (backward-char 1)
+		   (point))))
+
+(defun verilog-auto-star-safe ()
+  "Return if a .* AUTOINST is safe to delete or expand.
+It was created by the AUTOS themselves, or by the user."
+  (and verilog-auto-star-expand
+       (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\)\\)")))
+
+(defun verilog-delete-auto-star-all ()
+  "Delete a .* AUTOINST, if it is safe."
+  (when (verilog-auto-star-safe)
+    (verilog-delete-to-paren)))
+
+(defun verilog-delete-auto-star-implicit ()
+  "Delete all .* implicit connections created by `verilog-auto-star'.
+This function will be called automatically at save unless
+`verilog-auto-star-save' is set, any non-templated expanded pins will be
+removed."
+  (interactive)
+  (let (paren-pt indent have-close-paren)
+    (save-excursion
+      (goto-char (point-min))
+      ;; We need to match these even outside of comments.
+      ;; For reasonable performance, we don't check if inside comments, sorry.
+      (while (re-search-forward "// Implicit \\.\\*" nil t)
+	(setq paren-pt (point))
+	(beginning-of-line)
+	(setq have-close-paren
+	      (save-excursion
+		(when (search-forward ");" paren-pt t)
+		  (setq indent (current-indentation))
+		  t)))
+	(delete-region (point) (+ 1 paren-pt))  ; Nuke line incl CR
+	(when have-close-paren
+	  ;; Delete extra commentary
+	  (save-excursion
+	    (while (progn
+		     (forward-line -1)
+		     (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\)\n"))
+	      (delete-region (match-beginning 0) (match-end 0))))
+	  ;; If it is simple, we can put the ); on the same line as the last text
+	  (let ((rtn-pt (point)))
+	    (save-excursion
+	      (while (progn (backward-char 1)
+			    (looking-at "[ \t\n\f]")))
+	      (when (looking-at ",")
+		(delete-region (+ 1 (point)) rtn-pt))))
+	  (when (bolp)
+	    (indent-to indent))
+	  (insert ");\n")
+	  ;; Still need to kill final comma - always is one as we put one after the .*
+	  (re-search-backward ",")
+	  (delete-char 1))))))
+
+(defun verilog-delete-auto ()
+  "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
+Use \\[verilog-auto] to re-insert the updated AUTOs.
+
+The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
+called before and after this function, respectively."
+  (interactive)
+  (save-excursion
+    (if (buffer-file-name)
+	(find-file-noselect (buffer-file-name)))	;; To check we have latest version
+    ;; Allow user to customize
+    (run-hooks 'verilog-before-delete-auto-hook)
+
+    ;; Remove those that have multi-line insertions
+    (verilog-auto-re-search-do "/\\*AUTO\\(OUTPUTEVERY\\|CONCATCOMMENT\\|WIRE\\|REG\\|DEFINEVALUE\\|REGINPUT\\|INPUT\\|OUTPUT\\|INOUT\\|RESET\\|TIEOFF\\|UNUSED\\)\\*/"
+			       'verilog-delete-autos-lined)
+    ;; Remove those that have multi-line insertions with parameters
+    (verilog-auto-re-search-do "/\\*AUTO\\(INOUTMODULE\\|ASCIIENUM\\)([^)]*)\\*/"
+			       'verilog-delete-autos-lined)
+    ;; Remove those that are in parenthesis
+    (verilog-auto-re-search-do "/\\*\\(AS\\|AUTO\\(ARG\\|CONCATWIDTH\\|INST\\|INSTPARAM\\|SENSE\\)\\)\\*/"
+			       'verilog-delete-to-paren)
+    ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
+    (verilog-auto-re-search-do "\\.\\*"
+			       'verilog-delete-auto-star-all)
+    ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
+    (goto-char (point-min))
+    (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
+      (replace-match ""))
+
+    ;; Final customize
+    (run-hooks 'verilog-delete-auto-hook)))
+
+;;
+;; Auto inject
+;;
+
+(defun verilog-inject-auto ()
+  "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
+
+Any always @ blocks with sensitivity lists that match computed lists will
+be replaced with /*AS*/ comments.
+
+Any cells will get /*AUTOINST*/ added to the end of the pin list.  Pins with
+have identical names will be deleted.
+
+Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
+support adding new ports.  You may wish to delete older ports yourself.
+
+For example:
+
+	module ex_inject (i, o);
+	  input i;
+	  input j;
+	  output o;
+	  always @ (i or j)
+	     o = i | j;
+	  cell cell (.foobar(baz),
+		     .j(j));
+	endmodule
+
+Typing \\[verilog-inject-auto] will make this into:
+
+	module ex_inject (i, o/*AUTOARG*/
+	  // Inputs
+	  j);
+	  input i;
+	  output o;
+	  always @ (/*AS*/i or j)
+	     o = i | j;
+	  cell cell (.foobar(baz),
+		     /*AUTOINST*/
+		     // Outputs
+		     .j(j));
+	endmodule"
+  (interactive)
+  (verilog-auto t))
+
+(defun verilog-inject-arg ()
+  "Inject AUTOARG into new code.  See `verilog-inject-auto'."
+  ;; Presume one module per file.
+  (save-excursion
+    (goto-char (point-min))
+    (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
+      (let ((endmodp (save-excursion
+		       (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
+		       (point))))
+	;; See if there's already a comment .. inside a comment so not verilog-re-search
+	(when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
+	  (verilog-re-search-forward-quick ";" nil t)
+	  (backward-char 1)
+	  (verilog-backward-syntactic-ws)
+	  (backward-char 1) ; Moves to paren that closes argdecl's
+	  (when (looking-at ")")
+	    (insert "/*AUTOARG*/")))))))
+
+(defun verilog-inject-sense ()
+  "Inject AUTOSENSE into new code.  See `verilog-inject-auto'."
+  (save-excursion
+    (goto-char (point-min))
+    (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
+      (let ((start-pt (point))
+	    (modi (verilog-modi-current))
+	    pre-sigs
+	    got-sigs)
+	(backward-char 1)
+	(forward-sexp 1)
+	(backward-char 1) ;; End )
+	(when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
+	  (setq pre-sigs (verilog-signals-from-signame
+			  (verilog-read-signals start-pt (point)))
+		got-sigs (verilog-auto-sense-sigs modi nil))
+	  (when (not (or (verilog-signals-not-in pre-sigs got-sigs)  ; Both are equal?
+			 (verilog-signals-not-in got-sigs pre-sigs)))
+	    (delete-region start-pt (point))
+	    (insert "/*AS*/")))))))
+
+(defun verilog-inject-inst ()
+  "Inject AUTOINST into new code.  See `verilog-inject-auto'."
+  (save-excursion
+    (goto-char (point-min))
+    ;; It's hard to distinguish modules; we'll instead search for pins.
+    (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
+      (verilog-backward-open-paren) ;; Inst start
+      (cond
+       ((= (preceding-char) ?\#)  ;; #(...) parameter section, not pin.  Skip.
+	(forward-char 1)
+	(verilog-forward-close-paren)) ;; Parameters done
+       (t
+	(forward-char 1)
+	(let ((indent-pt (+ (current-column)))
+	      (end-pt (save-excursion (verilog-forward-close-paren) (point))))
+	  (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
+		 (goto-char end-pt)) ;; Already there, continue search with next instance
+		(t
+		 ;; Delete identical interconnect
+		 (let ((case-fold-search nil))  ;; So we don't convert upper-to-lower, etc
+		   (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
+		     (delete-region (match-beginning 0) (match-end 0))
+		     (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
+		     (while (or (looking-at "[ \t\n\f,]+")
+				(looking-at "//[^\n]*"))
+		       (delete-region (match-beginning 0) (match-end 0))
+		       (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
+		 (verilog-forward-close-paren)
+		 (backward-char 1)
+		 ;; Not verilog-re-search, as we don't want to strip comments
+		 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
+		   (delete-region (match-beginning 0) (match-end 0)))
+		 (insert "\n")
+		 (indent-to indent-pt)
+		 (insert "/*AUTOINST*/")))))))))
+
+;;
+;; Auto save
+;;
+
+(defun verilog-auto-save-check ()
+  "On saving see if we need auto update."
+  (cond ((not verilog-auto-save-policy)) ; disabled
+	((not (save-excursion
+		(save-match-data
+		  (let ((case-fold-search nil))
+		    (goto-char (point-min))
+		    (re-search-forward "AUTO" nil t))))))
+	((eq verilog-auto-save-policy 'force)
+	 (verilog-auto))
+	((not (buffer-modified-p)))
+	((eq verilog-auto-update-tick (buffer-modified-tick))) ; up-to-date
+	((eq verilog-auto-save-policy 'detect)
+	 (verilog-auto))
+	(t
+	 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
+	   (verilog-auto))
+	 ;; Don't ask again if didn't update
+	 (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))
+	 ))
+  (when (not verilog-auto-star-save)
+    (verilog-delete-auto-star-implicit))
+  nil)	;; Always return nil -- we don't write the file ourselves
+
+(defun verilog-auto-read-locals ()
+  "Return file local variable segment at bottom of file."
+  (save-excursion
+    (goto-char (point-max))
+    (if (re-search-backward "Local Variables:" nil t)
+	(buffer-substring-no-properties (point) (point-max))
+      "")))
+
+(defun verilog-auto-reeval-locals (&optional force)
+  "Read file local variable segment at bottom of file if it has changed.
+If FORCE, always reread it."
+  (make-variable-buffer-local 'verilog-auto-last-file-locals)
+  (let ((curlocal (verilog-auto-read-locals)))
+    (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
+      (setq verilog-auto-last-file-locals curlocal)
+      ;; Note this may cause this function to be recursively invoked.
+      ;; The above when statement will prevent it from recursing forever.
+      (hack-local-variables)
+      t)))
+
+;;
+;; Auto creation
+;;
+
+(defun verilog-auto-arg-ports (sigs message indent-pt)
+  "Print a list of ports for a AUTOINST.
+Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
+  (when sigs
+    (insert "\n")
+    (indent-to indent-pt)
+    (insert message)
+    (insert "\n")
+    (let ((space ""))
+      (indent-to indent-pt)
+      (while sigs
+	(cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
+	       (insert "\n")
+	       (indent-to indent-pt))
+	      (t (insert space)))
+	(insert (verilog-sig-name (car sigs)) ",")
+	(setq sigs (cdr sigs)
+	      space " ")))))
+
+(defun verilog-auto-arg ()
+  "Expand AUTOARG statements.
+Replace the argument declarations at the beginning of the
+module with ones automatically derived from input and output
+statements.  This can be dangerous if the module is instantiated
+using position-based connections, so use only name-based when
+instantiating the resulting module.  Long lines are split based
+on the `fill-column', see \\[set-fill-column].
+
+Limitations:
+  Concatenation and outputting partial busses is not supported.
+
+  Typedefs must match `verilog-typedef-regexp', which is disabled by default.
+
+For example:
+
+	module ex_arg (/*AUTOARG*/);
+	  input i;
+	  output o;
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_arg (/*AUTOARG*/
+	  // Outputs
+	  o,
+	  // Inputs
+	  i
+	);
+	  input i;
+	  output o;
+	endmodule
+
+Any ports declared between the ( and /*AUTOARG*/ are presumed to be
+predeclared and are not redeclared by AUTOARG.  AUTOARG will make a
+conservative guess on adding a comma for the first signal, if you have any
+ifdefs or complicated expressions before the AUTOARG you will need to
+choose the comma yourself.
+
+Avoid declaring ports manually, as it makes code harder to maintain."
+  (save-excursion
+    (let ((modi (verilog-modi-current))
+	  (skip-pins (aref (verilog-read-arg-pins) 0)))
+      (verilog-repair-open-comma)
+      (verilog-auto-arg-ports (verilog-signals-not-in
+			       (verilog-modi-get-outputs modi)
+			       skip-pins)
+			      "// Outputs"
+			      verilog-indent-level-declaration)
+      (verilog-auto-arg-ports (verilog-signals-not-in
+			       (verilog-modi-get-inouts modi)
+			       skip-pins)
+			      "// Inouts"
+			      verilog-indent-level-declaration)
+      (verilog-auto-arg-ports (verilog-signals-not-in
+			       (verilog-modi-get-inputs modi)
+			       skip-pins)
+			      "// Inputs"
+			      verilog-indent-level-declaration)
+      (verilog-repair-close-comma)
+      (unless (eq (char-before) ?/ )
+	(insert "\n"))
+      (indent-to verilog-indent-level-declaration)
+      )))
+
+(defun verilog-auto-inst-port-map (port-st)
+  nil)
+
+(defvar vector-skip-list nil) ; Prevent compile warning
+(defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
+(defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
+(defvar vl-name  nil "See `verilog-auto-inst'.") ; Prevent compile warning
+(defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
+(defvar vl-dir   nil "See `verilog-auto-inst'.") ; Prevent compile warning
+
+(defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star)
+  "Print out a instantiation connection for this PORT-ST.
+Insert to INDENT-PT, use template TPL-LIST.
+@ are instantiation numbers, replaced with TPL-NUM.
+@\"(expression @)\" are evaluated, with @ as a variable."
+  (let* ((port (verilog-sig-name port-st))
+	 (tpl-ass (or (assoc port (car tpl-list))
+		      (verilog-auto-inst-port-map port-st)))
+	 ;; vl-* are documented for user use
+	 (vl-name (verilog-sig-name port-st))
+	 (vl-width (verilog-sig-width port-st))
+	 (vl-bits (if (or verilog-auto-inst-vector
+			  (not (assoc port vector-skip-list))
+			  (not (equal (verilog-sig-bits port-st)
+				      (verilog-sig-bits (assoc port vector-skip-list)))))
+		      (or (verilog-sig-bits port-st) "")
+		    ""))
+	 ;; Default if not found
+	 (tpl-net (if (verilog-sig-multidim port-st)
+		      (concat port "/*" (verilog-sig-multidim-string port-st)
+			      vl-bits "*/")
+		    (concat port vl-bits)))
+	 (case-fold-search nil))
+    ;; Find template
+    (cond (tpl-ass	    ; Template of exact port name
+	   (setq tpl-net (nth 1 tpl-ass)))
+	  ((nth 1 tpl-list) ; Wildcards in template, search them
+	   (let ((wildcards (nth 1 tpl-list)))
+	     (while wildcards
+	       (when (string-match (nth 0 (car wildcards)) port)
+		 (setq tpl-ass (car wildcards)  ; so allow @ parsing
+		       tpl-net (replace-match (nth 1 (car wildcards))
+					      t nil port)))
+	       (setq wildcards (cdr wildcards))))))
+    ;; Parse Templated variable
+    (when tpl-ass
+      ;; Evaluate @"(lispcode)"
+      (when (string-match "@\".*[^\\]\"" tpl-net)
+	(while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
+	  (setq tpl-net
+		(concat
+		 (substring tpl-net 0 (match-beginning 0))
+		 (save-match-data
+		   (let* ((expr (match-string 1 tpl-net))
+			  (value
+			   (progn
+			     (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
+			     (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
+			     (prin1 (eval (car (read-from-string expr)))
+				    (lambda (ch) ())))))
+		     (if (numberp value) (setq value (number-to-string value)))
+		     value
+		     ))
+		 (substring tpl-net (match-end 0))))))
+      ;; Replace @ and [] magic variables in final output
+      (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
+      (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net))
+      )
+    (indent-to indent-pt)
+    (insert "." port)
+    (indent-to verilog-auto-inst-column)
+    (insert "(" tpl-net "),")
+    (cond (tpl-ass
+	   (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
+			 verilog-auto-inst-column))
+	   (insert " // Templated")
+	   (when verilog-auto-inst-template-numbers
+	     (insert " T" (int-to-string (nth 2 tpl-ass))
+		     " L" (int-to-string (nth 3 tpl-ass)))))
+	  (for-star
+	   (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
+			 verilog-auto-inst-column))
+	   (insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
+    (insert "\n")))
+;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
+;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
+;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
+
+(defun verilog-auto-inst-first ()
+  "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
+  ;; Do we need a trailing comma?
+  ;; There maybe a ifdef or something similar before us.  What a mess.  Thus
+  ;; to avoid trouble we only insert on preceeding ) or *.
+  ;; Insert first port on new line
+  (insert "\n")  ;; Must insert before search, so point will move forward if insert comma
+  (save-excursion
+    (verilog-re-search-backward "[^ \t\n\f]" nil nil)
+    (when (looking-at ")\\|\\*")  ;; Generally don't insert, unless we are fairly sure
+      (forward-char 1)
+      (insert ","))))
+
+(defun verilog-auto-star ()
+  "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
+
+If `verilog-auto-star-expand' is set, .* pins are treated if they were
+AUTOINST statements, otherwise they are ignored.  For safety, Verilog-Mode
+will also ignore any .* that are not last in your pin list (this prevents
+it from deleting pins following the .* when it expands the AUTOINST.)
+
+On writing your file, unless `verilog-auto-star-save' is set, any
+non-templated expanded pins will be removed.  You may do this at any time
+with \\[verilog-delete-auto-star-implicit].
+
+If you are converting a module to use .* for the first time, you may wish
+to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
+
+See `verilog-auto-inst' for examples, templates, and more information."
+  (when (verilog-auto-star-safe)
+    (verilog-auto-inst)))
+
+(defun verilog-auto-inst ()
+  "Expand AUTOINST statements, as part of \\[verilog-auto].
+Replace the pin connections to an instantiation with ones
+automatically derived from the module header of the instantiated netlist.
+
+If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
+and delete them before saving unless `verilog-auto-star-save' is set.
+See `verilog-auto-star' for more information.
+
+Limitations:
+  Module names must be resolvable to filenames by adding a
+  `verilog-library-extensions', and being found in the same directory, or
+  by changing the variable `verilog-library-flags' or
+  `verilog-library-directories'.  Macros `modname are translated through the
+  vh-{name} Emacs variable, if that is not found, it just ignores the `.
+
+  In templates you must have one signal per line, ending in a ), or ));,
+  and have proper () nesting, including a final ); to end the template.
+
+  Typedefs must match `verilog-typedef-regexp', which is disabled by default.
+
+  SystemVerilog multidimmensional input/output has only experimental support.
+
+For example, first take the submodule inst.v:
+
+	module inst (o,i)
+	   output [31:0] o;
+	   input i;
+	   wire [31:0] o = {32{i}};
+	endmodule
+
+This is then used in a upper level module:
+
+	module ex_inst (o,i)
+	   output o;
+	   input i;
+	   inst inst (/*AUTOINST*/);
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_inst (o,i)
+	   output o;
+	   input i;
+	   inst inst (/*AUTOINST*/
+		      // Outputs
+		      .ov			(ov[31:0]),
+		      // Inputs
+		      .i			(i));
+	endmodule
+
+Where the list of inputs and outputs came from the inst module.
+
+Exceptions:
+
+  Unless you are instantiating a module multiple times, or the module is
+  something trivial like a adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
+  It just makes for unmaintainable code.  To sanitize signal names, try
+  vrename from http://www.veripool.com
+
+  When you need to violate this suggestion there are two ways to list
+  exceptions, placing them before the AUTOINST, or using templates.
+
+  Any ports defined before the /*AUTOINST*/ are not included in the list of
+  automatics.  This is similar to making a template as described below, but
+  is restricted to simple connections just like you normally make.  Also note
+  that any signals before the AUTOINST will only be picked up by AUTOWIRE if
+  you have the appropriate // Input or // Output comment, and exactly the
+  same line formatting as AUTOINST itself uses.
+
+	inst inst (// Inputs
+		   .i		(my_i_dont_mess_with_it),
+		   /*AUTOINST*/
+		   // Outputs
+		   .ov		(ov[31:0]));
+
+
+Templates:
+
+  For multiple instantiations based upon a single template, create a
+  commented out template:
+
+	/* instantiating_module_name AUTO_TEMPLATE (
+		.sig3	(sigz[]),
+		);
+	*/
+
+  Templates go ABOVE the instantiation(s).  When a instantiation is
+  expanded `verilog-mode' simply searches up for the closest template.
+  Thus you can have multiple templates for the same module, just alternate
+  between the template for a instantiation and the instantiation itself.
+
+  The module name must be the same as the name of the module in the
+  instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
+  words and capitalized.  Only signals that must be different for each
+  instantiation need to be listed.
+
+  Inside a template, a [] in a connection name (with nothing else inside
+  the brackets) will be replaced by the same bus subscript as it is being
+  connected to, or the [] will be removed if it is a single bit signal.
+  Generally it is a good idea to do this for all connections in a template,
+  as then they will work for any width signal, and with AUTOWIRE.  See
+  PTL_BUS becoming PTL_BUSNEW below.
+
+  If you have a complicated template, set `verilog-auto-inst-template-numbers'
+  to see which regexps are matching.  Don't leave that mode set after
+  debugging is completed though, it will result in lots of extra differences
+  and merge conflicts.
+
+  For example:
+
+	/* psm_mas AUTO_TEMPLATE (
+		.ptl_bus	(ptl_busnew[]),
+		);
+	*/
+	psm_mas ms2m (/*AUTOINST*/);
+
+  Typing \\[verilog-auto] will make this into:
+
+	psm_mas ms2m (/*AUTOINST*/
+	    // Outputs
+	    .NotInTemplate	(NotInTemplate),
+	    .ptl_bus		(ptl_busnew[3:0]),  // Templated
+	    ....
+
+@ Templates:
+
+  It is common to instantiate a cell multiple times, so templates make it
+  trivial to substitute part of the cell name into the connection name.
+
+	/* cell_type AUTO_TEMPLATE <optional \"REGEXP\"> (
+		.sig1	(sigx[@]),
+		.sig2	(sigy[@\"(% (+ 1 @) 4)\"]),
+		);
+	*/
+
+  If no regular expression is provided immediately after the AUTO_TEMPLATE
+  keyword, then the @ character in any connection names will be replaced
+  with the instantiation number; the first digits found in the cell's
+  instantiation name.
+
+  If a regular expression is provided, the @ character will be replaced
+  with the first \(\) grouping that matches against the cell name.  Using a
+  regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
+  regexp is provided.  If you use multiple layers of parenthesis,
+  \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
+  characters after test and before _, whereas
+  \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
+  match.
+
+  For example:
+
+	/* psm_mas AUTO_TEMPLATE (
+		.ptl_mapvalidx		(ptl_mapvalid[@]),
+		.ptl_mapvalidp1x	(ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
+		);
+	*/
+	psm_mas ms2m (/*AUTOINST*/);
+
+  Typing \\[verilog-auto] will make this into:
+
+	psm_mas ms2m (/*AUTOINST*/
+	    // Outputs
+	    .ptl_mapvalidx		(ptl_mapvalid[2]),
+	    .ptl_mapvalidp1x		(ptl_mapvalid[3]));
+
+  Note the @ character was replaced with the 2 from \"ms2m\".
+
+  Alternatively, using a regular expression for @:
+
+	/* psm_mas AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
+		.ptl_mapvalidx		(@_ptl_mapvalid),
+		.ptl_mapvalidp1x	(ptl_mapvalid_@),
+		);
+	*/
+	psm_mas ms2_FOO (/*AUTOINST*/);
+	psm_mas ms2_BAR (/*AUTOINST*/);
+
+  Typing \\[verilog-auto] will make this into:
+
+	psm_mas ms2_FOO (/*AUTOINST*/
+	    // Outputs
+	    .ptl_mapvalidx		(FOO_ptl_mapvalid),
+	    .ptl_mapvalidp1x		(ptl_mapvalid_FOO));
+	psm_mas ms2_BAR (/*AUTOINST*/
+	    // Outputs
+	    .ptl_mapvalidx		(BAR_ptl_mapvalid),
+	    .ptl_mapvalidp1x		(ptl_mapvalid_BAR));
+
+
+Regexp Templates:
+
+  A template entry of the form
+
+	    .pci_req\\([0-9]+\\)_l	(pci_req_jtag_[\\1]),
+
+  will apply a Emacs style regular expression search for any port beginning
+  in pci_req followed by numbers and ending in _l and connecting that to
+  the pci_req_jtag_[] net, with the bus subscript coming from what matches
+  inside the first set of \\( \\).  Thus pci_req2_l becomes pci_req_jtag_[2].
+
+  Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
+  does the same thing. (Note a @ in the connection/replacement text is
+  completely different -- still use \\1 there!)  Thus this is the same as
+  the above template:
+
+	    .pci_req@_l		(pci_req_jtag_[\\1]),
+
+  Here's another example to remove the _l, useful when naming conventions
+  specify _ alone to mean active low.  Note the use of [] to keep the bus
+  subscript:
+
+	    .\\(.*\\)_l		(\\1_[]),
+
+Lisp Templates:
+
+  First any regular expression template is expanded.
+
+  If the syntax @\"( ... )\" is found in a connection, the expression in
+  quotes will be evaluated as a Lisp expression, with @ replaced by the
+  instantiation number.  The MAPVALIDP1X example above would put @+1 modulo
+  4 into the brackets.  Quote all double-quotes inside the expression with
+  a leading backslash (\\\").  There are special variables defined that are
+  useful in these Lisp functions:
+
+	vl-name        Name portion of the input/output port
+	vl-bits        Bus bits portion of the input/output port ('[2:0]')
+	vl-width       Width of the input/output port ('3' for [2:0])
+                       May be a (...) expression if bits isn't a constant.
+	vl-dir         Direction of the pin input/output/inout.
+	vl-cell-type   Module name/type of the cell ('psm_mas')
+	vl-cell-name   Instance name of the cell ('ms2m')
+
+  Normal Lisp variables may be used in expressions.  See
+  `verilog-read-defines' which can set vh-{definename} variables for use
+  here.  Also, any comments of the form:
+
+	/*AUTO_LISP(setq foo 1)*/
+
+  will evaluate any Lisp expression inside the parenthesis between the
+  beginning of the buffer and the point of the AUTOINST.  This allows
+  functions to be defined or variables to be changed between instantiations.
+
+  Note that when using lisp expressions errors may occur when @ is not a
+  number, you may need to use the standard Emacs Lisp functions
+  `number-to-string' and `string-to-number'.
+
+  After the evaluation is completed, @ substitution and [] substitution
+  occur."
+  (save-excursion
+    ;; Find beginning
+    (let* ((pt (point))
+	   (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
+	   (indent-pt (save-excursion (verilog-backward-open-paren)
+				      (1+ (current-column))))
+	   (verilog-auto-inst-column (max verilog-auto-inst-column
+					  (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
+	   (modi (verilog-modi-current))
+	   (vector-skip-list (unless verilog-auto-inst-vector
+			       (verilog-modi-get-signals modi)))
+	   submod submodi inst skip-pins tpl-list tpl-num did-first)
+      ;; Find module name that is instantiated
+      (setq submod  (verilog-read-inst-module)
+	    inst (verilog-read-inst-name)
+	    vl-cell-type submod
+	    vl-cell-name inst
+	    skip-pins (aref (verilog-read-inst-pins) 0))
+
+      ;; Parse any AUTO_LISP() before here
+      (verilog-read-auto-lisp (point-min) pt)
+
+      ;; Lookup position, etc of submodule
+      ;; Note this may raise an error
+      (when (setq submodi (verilog-modi-lookup submod t))
+	;; If there's a number in the instantiation, it may be a argument to the
+	;; automatic variable instantiation program.
+	(let* ((tpl-info (verilog-read-auto-template submod))
+	       (tpl-regexp (aref tpl-info 0)))
+	  (setq tpl-num (if (string-match tpl-regexp inst)
+			    (match-string 1 inst)
+			  "")
+		tpl-list (aref tpl-info 1)))
+	;; Find submodule's signals and dump
+	(let ((sig-list (verilog-signals-not-in
+			 (verilog-modi-get-outputs submodi)
+			 skip-pins))
+	      (vl-dir "output"))
+	  (when sig-list
+	    (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
+	    (indent-to indent-pt)
+	    (insert "// Outputs\n")	;; Note these are searched for in verilog-read-sub-decls
+	    (mapcar (function (lambda (port)
+				(verilog-auto-inst-port port indent-pt tpl-list tpl-num for-star)))
+		    sig-list)))
+	(let ((sig-list (verilog-signals-not-in
+			 (verilog-modi-get-inouts submodi)
+			 skip-pins))
+	      (vl-dir "inout"))
+	  (when sig-list
+	    (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
+	    (indent-to indent-pt)
+	    (insert "// Inouts\n")
+	    (mapcar (function (lambda (port)
+				(verilog-auto-inst-port port indent-pt tpl-list tpl-num for-star)))
+		    sig-list)))
+	(let ((sig-list (verilog-signals-not-in
+			 (verilog-modi-get-inputs submodi)
+			 skip-pins))
+	      (vl-dir "input"))
+	  (when sig-list
+	    (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
+	    (indent-to indent-pt)
+	    (insert "// Inputs\n")
+	    (mapcar (function (lambda (port)
+				(verilog-auto-inst-port port indent-pt tpl-list tpl-num for-star)))
+		    sig-list)))
+	;; Kill extra semi
+	(save-excursion
+	  (cond (did-first
+		 (re-search-backward "," pt t)
+		 (delete-char 1)
+		 (insert ");")
+		 (search-forward "\n")	;; Added by inst-port
+		 (delete-backward-char 1)
+		 (if (search-forward ")" nil t) ;; From user, moved up a line
+		     (delete-backward-char 1))
+		 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
+		     (delete-backward-char 1))
+		 )))
+	))))
+
+(defun verilog-auto-inst-param ()
+  "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
+Replace the parameter connections to an instantiation with ones
+automatically derived from the module header of the instantiated netlist.
+
+See \\[verilog-auto-inst] for limitations, and templates to customize the
+output.
+
+For example, first take the submodule inst.v:
+
+	module inst (o,i)
+	   parameter PAR;
+	endmodule
+
+This is then used in a upper level module:
+
+	module ex_inst (o,i)
+	   parameter PAR;
+	   inst #(/*AUTOINSTPARAM*/)
+		inst (/*AUTOINST*/);
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_inst (o,i)
+	   output o;
+	   input i;
+	   inst (/*AUTOINSTPARAM*/
+		 // Parameters
+		 .PAR			(PAR));
+		inst (/*AUTOINST*/);
+	endmodule
+
+Where the list of parameter connections come from the inst module.
+
+Templates:
+
+  You can customize the parameter connections using AUTO_TEMPLATEs,
+  just as you would with \\[verilog-auto-inst]."
+  (save-excursion
+    ;; Find beginning
+    (let* ((pt (point))
+	   (indent-pt (save-excursion (verilog-backward-open-paren)
+				      (1+ (current-column))))
+	   (verilog-auto-inst-column (max verilog-auto-inst-column
+					  (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
+	   (modi (verilog-modi-current))
+	   (vector-skip-list (unless verilog-auto-inst-vector
+			       (verilog-modi-get-signals modi)))
+	   submod submodi inst skip-pins tpl-list tpl-num did-first)
+      ;; Find module name that is instantiated
+      (setq submod (save-excursion
+		     ;; Get to the point where AUTOINST normally is to read the module
+		     (verilog-re-search-forward-quick "[(;]" nil nil)
+		     (verilog-read-inst-module))
+	    inst   (save-excursion
+		     ;; Get to the point where AUTOINST normally is to read the module
+		     (verilog-re-search-forward-quick "[(;]" nil nil)
+		     (verilog-read-inst-name))
+	    vl-cell-type submod
+	    vl-cell-name inst
+	    skip-pins (aref (verilog-read-inst-pins) 0))
+
+      ;; Parse any AUTO_LISP() before here
+      (verilog-read-auto-lisp (point-min) pt)
+
+      ;; Lookup position, etc of submodule
+      ;; Note this may raise an error
+      (when (setq submodi (verilog-modi-lookup submod t))
+	;; If there's a number in the instantiation, it may be a argument to the
+	;; automatic variable instantiation program.
+	(let* ((tpl-info (verilog-read-auto-template submod))
+	       (tpl-regexp (aref tpl-info 0)))
+	  (setq tpl-num (if (string-match tpl-regexp inst)
+			    (match-string 1 inst)
+			  "")
+		tpl-list (aref tpl-info 1)))
+	;; Find submodule's signals and dump
+	(let ((sig-list (verilog-signals-not-in
+			 (verilog-modi-get-gparams submodi)
+			 skip-pins))
+	      (vl-dir "parameter"))
+	  (when sig-list
+	    (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
+	    (indent-to indent-pt)
+	    (insert "// Parameters\n")	;; Note these are searched for in verilog-read-sub-decls
+	    (mapcar (function (lambda (port)
+				(verilog-auto-inst-port port indent-pt tpl-list tpl-num nil)))
+		    sig-list)))
+	;; Kill extra semi
+	(save-excursion
+	  (cond (did-first
+		 (re-search-backward "," pt t)
+		 (delete-char 1)
+		 (insert ")")
+		 (search-forward "\n")	;; Added by inst-port
+		 (delete-backward-char 1)
+		 (if (search-forward ")" nil t) ;; From user, moved up a line
+		     (delete-backward-char 1))
+		 )))
+	))))
+
+(defun verilog-auto-reg ()
+  "Expand AUTOREG statements, as part of \\[verilog-auto].
+Make reg statements for any output that isn't already declared,
+and isn't a wire output from a block.
+
+Limitations:
+  This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
+
+  This does NOT work on memories, declare those yourself.
+
+An example:
+
+	module ex_reg (o,i)
+	   output o;
+	   input i;
+	   /*AUTOREG*/
+	   always o = i;
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_reg (o,i)
+	   output o;
+	   input i;
+	   /*AUTOREG*/
+	   // Beginning of automatic regs (for this module's undeclared outputs)
+	   reg			o;
+	   // End of automatics
+	   always o = i;
+	endmodule"
+  (save-excursion
+    ;; Point must be at insertion point.
+    (let* ((indent-pt (current-indentation))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-not-in
+		      (verilog-modi-get-outputs modi)
+		      (append (verilog-modi-get-wires modi)
+			      (verilog-modi-get-regs modi)
+			      (verilog-modi-get-assigns modi)
+			      (verilog-modi-get-consts modi)
+			      (verilog-modi-get-gparams modi)
+			      (verilog-modi-get-sub-outputs modi)
+			      (verilog-modi-get-sub-inouts modi)
+			      ))))
+      (forward-line 1)
+      (when sig-list
+	(verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
+	(verilog-insert-definition sig-list "reg" indent-pt nil)
+	(verilog-modi-cache-add-regs modi sig-list)
+	(verilog-insert-indent "// End of automatics\n"))
+      )))
+
+(defun verilog-auto-reg-input ()
+  "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
+Make reg statements instantiation inputs that aren't already declared.
+This is useful for making a top level shell for testing the module that is
+to be instantiated.
+
+Limitations:
+  This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
+
+  This does NOT work on memories, declare those yourself.
+
+An example (see `verilog-auto-inst' for what else is going on here):
+
+	module ex_reg_input (o,i)
+	   output o;
+	   input i;
+	   /*AUTOREGINPUT*/
+           inst inst (/*AUTOINST*/);
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_reg_input (o,i)
+	   output o;
+	   input i;
+	   /*AUTOREGINPUT*/
+	   // Beginning of automatic reg inputs (for undeclared ...
+	   reg [31:0]		iv;		// From inst of inst.v
+	   // End of automatics
+	   inst inst (/*AUTOINST*/
+		      // Outputs
+		      .o			(o[31:0]),
+		      // Inputs
+		      .iv			(iv));
+	endmodule"
+  (save-excursion
+    ;; Point must be at insertion point.
+    (let* ((indent-pt (current-indentation))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-combine-bus
+		      (verilog-signals-not-in
+		       (append (verilog-modi-get-sub-inputs modi)
+			       (verilog-modi-get-sub-inouts modi))
+		       (verilog-modi-get-signals modi)
+		       ))))
+      (forward-line 1)
+      (when sig-list
+	(verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
+	(verilog-insert-definition sig-list "reg" indent-pt nil)
+	(verilog-modi-cache-add-regs modi sig-list)
+	(verilog-insert-indent "// End of automatics\n"))
+      )))
+
+(defun verilog-auto-wire ()
+  "Expand AUTOWIRE statements, as part of \\[verilog-auto].
+Make wire statements for instantiations outputs that aren't
+already declared.
+
+Limitations:
+  This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
+  and all busses must have widths, such as those from AUTOINST, or using []
+  in AUTO_TEMPLATEs.
+
+  This does NOT work on memories or SystemVerilog .name connections,
+  declare those yourself.
+
+  Verilog-mode will add \"Couldn't Merge\" comments to signals it cannot
+  determine how to bus together. This occurs when you have ports with
+  non-numeric or non-sequential bus subscripts. If Verilog-Mode
+  mis-guessed, you'll have to declare them yourself.
+
+An example (see `verilog-auto-inst' for what else is going on here):
+
+	module ex_wire (o,i)
+	   output o;
+	   input i;
+	   /*AUTOWIRE*/
+           inst inst (/*AUTOINST*/);
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_wire (o,i)
+	   output o;
+	   input i;
+	   /*AUTOWIRE*/
+	   // Beginning of automatic wires
+	   wire [31:0]		ov;	// From inst of inst.v
+	   // End of automatics
+	   inst inst (/*AUTOINST*/
+		      // Outputs
+		      .ov	(ov[31:0]),
+		      // Inputs
+		      .i	(i));
+	   wire o = | ov;
+	endmodule"
+  (save-excursion
+    ;; Point must be at insertion point.
+    (let* ((indent-pt (current-indentation))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-combine-bus
+		      (verilog-signals-not-in
+		       (append (verilog-modi-get-sub-outputs modi)
+			       (verilog-modi-get-sub-inouts modi))
+		       (verilog-modi-get-signals modi)
+		       ))))
+      (forward-line 1)
+      (when sig-list
+	(verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
+	(verilog-insert-definition sig-list "wire" indent-pt nil)
+	(verilog-modi-cache-add-wires modi sig-list)
+	(verilog-insert-indent "// End of automatics\n")
+	(when nil	;; Too slow on huge modules, plus makes everyone's module change
+	  (beginning-of-line)
+	  (setq pnt (point))
+	  (verilog-pretty-declarations)
+	  (goto-char pnt)
+	  (verilog-pretty-expr "//")))
+      )))
+
+(defun verilog-auto-output ()
+  "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
+Make output statements for any output signal from an /*AUTOINST*/ that
+isn't a input to another AUTOINST.  This is useful for modules which
+only instantiate other modules.
+
+Limitations:
+  This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
+
+  If placed inside the parenthesis of a module declaration, it creates
+  Verilog 2001 style, else uses Verilog 1995 style.
+
+  If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
+  instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
+
+  Typedefs must match `verilog-typedef-regexp', which is disabled by default.
+
+  Signals matching `verilog-auto-output-ignore-regexp' are not included.
+
+An example (see `verilog-auto-inst' for what else is going on here):
+
+	module ex_output (ov,i)
+	   input i;
+	   /*AUTOOUTPUT*/
+	   inst inst (/*AUTOINST*/);
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_output (ov,i)
+	   input i;
+	   /*AUTOOUTPUT*/
+	   // Beginning of automatic outputs (from unused autoinst outputs)
+	   output [31:0]	ov;			// From inst of inst.v
+	   // End of automatics
+	   inst inst (/*AUTOINST*/
+		      // Outputs
+		      .ov			(ov[31:0]),
+		      // Inputs
+		      .i			(i));
+	endmodule"
+  (save-excursion
+    ;; Point must be at insertion point.
+    (let* ((indent-pt (current-indentation))
+	   (v2k  (verilog-in-paren))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-not-in
+		      (verilog-modi-get-sub-outputs modi)
+		      (append (verilog-modi-get-outputs modi)
+			      (verilog-modi-get-inouts modi)
+			      (verilog-modi-get-sub-inputs modi)
+			      (verilog-modi-get-sub-inouts modi)
+			      ))))
+      (setq sig-list (verilog-signals-not-matching-regexp
+		      sig-list verilog-auto-output-ignore-regexp))
+      (forward-line 1)
+      (when v2k (verilog-repair-open-comma))
+      (when sig-list
+	(verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
+	(verilog-insert-definition sig-list "output" indent-pt v2k)
+	(verilog-modi-cache-add-outputs modi sig-list)
+	(verilog-insert-indent "// End of automatics\n"))
+      (when v2k (verilog-repair-close-comma))
+      )))
+
+(defun verilog-auto-output-every ()
+  "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
+Make output statements for any signals that aren't primary inputs or
+outputs already.  This makes every signal in the design a output.  This is
+useful to get Synopsys to preserve every signal in the design, since it
+won't optimize away the outputs.
+
+An example:
+
+	module ex_output_every (o,i,tempa,tempb)
+	   output o;
+	   input i;
+	   /*AUTOOUTPUTEVERY*/
+	   wire tempa = i;
+	   wire tempb = tempa;
+	   wire o = tempb;
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_output_every (o,i,tempa,tempb)
+	   output o;
+	   input i;
+	   /*AUTOOUTPUTEVERY*/
+	   // Beginning of automatic outputs (every signal)
+	   output		tempb;
+	   output		tempa;
+	   // End of automatics
+	   wire tempa = i;
+	   wire tempb = tempa;
+	   wire o = tempb;
+	endmodule"
+  (save-excursion
+    ;;Point must be at insertion point
+    (let* ((indent-pt (current-indentation))
+	   (v2k  (verilog-in-paren))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-combine-bus
+		      (verilog-signals-not-in
+		       (verilog-modi-get-signals modi)
+		       (verilog-modi-get-ports modi)
+		       ))))
+      (forward-line 1)
+      (when v2k (verilog-repair-open-comma))
+      (when sig-list
+	(verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
+	(verilog-insert-definition sig-list "output" indent-pt v2k)
+	(verilog-modi-cache-add-outputs modi sig-list)
+	(verilog-insert-indent "// End of automatics\n"))
+      (when v2k (verilog-repair-close-comma))
+      )))
+
+(defun verilog-auto-input ()
+  "Expand AUTOINPUT statements, as part of \\[verilog-auto].
+Make input statements for any input signal into an /*AUTOINST*/ that
+isn't declared elsewhere inside the module.  This is useful for modules which
+only instantiate other modules.
+
+Limitations:
+  This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
+
+  If placed inside the parenthesis of a module declaration, it creates
+  Verilog 2001 style, else uses Verilog 1995 style.
+
+  If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
+  instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
+
+  Typedefs must match `verilog-typedef-regexp', which is disabled by default.
+
+  Signals matching `verilog-auto-input-ignore-regexp' are not included.
+
+An example (see `verilog-auto-inst' for what else is going on here):
+
+	module ex_input (ov,i)
+	   output [31:0] ov;
+	   /*AUTOINPUT*/
+	   inst inst (/*AUTOINST*/);
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_input (ov,i)
+	   output [31:0] ov;
+	   /*AUTOINPUT*/
+	   // Beginning of automatic inputs (from unused autoinst inputs)
+	   input		i;			// From inst of inst.v
+	   // End of automatics
+	   inst inst (/*AUTOINST*/
+		      // Outputs
+		      .ov			(ov[31:0]),
+		      // Inputs
+		      .i			(i));
+	endmodule"
+  (save-excursion
+    (let* ((indent-pt (current-indentation))
+	   (v2k  (verilog-in-paren))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-not-in
+		      (verilog-modi-get-sub-inputs modi)
+		      (append (verilog-modi-get-inputs modi)
+			      (verilog-modi-get-inouts modi)
+			      (verilog-modi-get-wires modi)
+			      (verilog-modi-get-regs modi)
+			      (verilog-modi-get-consts modi)
+			      (verilog-modi-get-gparams modi)
+			      (verilog-modi-get-sub-outputs modi)
+			      (verilog-modi-get-sub-inouts modi)
+			      ))))
+      (setq sig-list (verilog-signals-not-matching-regexp
+		      sig-list verilog-auto-input-ignore-regexp))
+      (forward-line 1)
+      (when v2k (verilog-repair-open-comma))
+      (when sig-list
+	(verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
+	(verilog-insert-definition sig-list "input" indent-pt v2k)
+	(verilog-modi-cache-add-inputs modi sig-list)
+	(verilog-insert-indent "// End of automatics\n"))
+      (when v2k (verilog-repair-close-comma))
+      )))
+
+(defun verilog-auto-inout ()
+  "Expand AUTOINOUT statements, as part of \\[verilog-auto].
+Make inout statements for any inout signal in an /*AUTOINST*/ that
+isn't declared elsewhere inside the module.
+
+Limitations:
+  This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
+
+  If placed inside the parenthesis of a module declaration, it creates
+  Verilog 2001 style, else uses Verilog 1995 style.
+
+  If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
+  instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
+
+  Typedefs must match `verilog-typedef-regexp', which is disabled by default.
+
+  Signals matching `verilog-auto-inout-ignore-regexp' are not included.
+
+An example (see `verilog-auto-inst' for what else is going on here):
+
+	module ex_inout (ov,i)
+	   input i;
+	   /*AUTOINOUT*/
+	   inst inst (/*AUTOINST*/);
+	endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_inout (ov,i)
+	   input i;
+	   /*AUTOINOUT*/
+	   // Beginning of automatic inouts (from unused autoinst inouts)
+	   inout [31:0]	ov;			// From inst of inst.v
+	   // End of automatics
+	   inst inst (/*AUTOINST*/
+		      // Inouts
+		      .ov			(ov[31:0]),
+		      // Inputs
+		      .i			(i));
+	endmodule"
+  (save-excursion
+    ;; Point must be at insertion point.
+    (let* ((indent-pt (current-indentation))
+	   (v2k  (verilog-in-paren))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-not-in
+		      (verilog-modi-get-sub-inouts modi)
+		      (append (verilog-modi-get-outputs modi)
+			      (verilog-modi-get-inouts modi)
+			      (verilog-modi-get-inputs modi)
+			      (verilog-modi-get-sub-inputs modi)
+			      (verilog-modi-get-sub-outputs modi)
+			      ))))
+      (setq sig-list (verilog-signals-not-matching-regexp
+		      sig-list verilog-auto-inout-ignore-regexp))
+      (forward-line 1)
+      (when v2k (verilog-repair-open-comma))
+      (when sig-list
+	(verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
+	(verilog-insert-definition sig-list "inout" indent-pt v2k)
+	(verilog-modi-cache-add-inouts modi sig-list)
+	(verilog-insert-indent "// End of automatics\n"))
+      (when v2k (verilog-repair-close-comma))
+      )))
+
+(defun verilog-auto-inout-module ()
+  "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
+Take input/output/inout statements from the specified module and insert
+into the current module.  This is useful for making null templates and
+shell modules which need to have identical I/O with another module.  Any
+I/O which are already defined in this module will not be redefined.
+
+Limitations:
+  If placed inside the parenthesis of a module declaration, it creates
+  Verilog 2001 style, else uses Verilog 1995 style.
+
+  Concatenation and outputting partial busses is not supported.
+
+  Module names must be resolvable to filenames.  See `verilog-auto-inst'.
+
+  Signals are not inserted in the same order as in the original module,
+  though they will appear to be in the same order to a AUTOINST
+  instantiating either module.
+
+An example:
+
+	module ex_shell (/*AUTOARG*/)
+	   /*AUTOINOUTMODULE(\"ex_main\")*/
+	endmodule
+
+	module ex_main (i,o,io)
+          input i;
+          output o;
+          inout io;
+        endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+	module ex_shell (/*AUTOARG*/i,o,io)
+	   /*AUTOINOUTMODULE(\"ex_main\")*/
+           // Beginning of automatic in/out/inouts (from specific module)
+           input i;
+           output o;
+           inout io;
+	   // End of automatics
+	endmodule"
+  (save-excursion
+    (let* ((submod (car (verilog-read-auto-params 1))) submodi)
+      ;; Lookup position, etc of co-module
+      ;; Note this may raise an error
+      (when (setq submodi (verilog-modi-lookup submod t))
+	(let* ((indent-pt (current-indentation))
+	       (v2k  (verilog-in-paren))
+	       (modi (verilog-modi-current))
+	       (sig-list-i  (verilog-signals-not-in
+			     (verilog-modi-get-inputs submodi)
+			     (append (verilog-modi-get-inputs modi))))
+	       (sig-list-o  (verilog-signals-not-in
+			     (verilog-modi-get-outputs submodi)
+			     (append (verilog-modi-get-outputs modi))))
+	       (sig-list-io (verilog-signals-not-in
+			     (verilog-modi-get-inouts submodi)
+			     (append (verilog-modi-get-inouts modi)))))
+	  (forward-line 1)
+	  (when v2k (verilog-repair-open-comma))
+	  (when (or sig-list-i sig-list-o sig-list-io)
+	    (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
+	    ;; Don't sort them so a upper AUTOINST will match the main module
+	    (verilog-insert-definition sig-list-o  "output" indent-pt v2k t)
+	    (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
+	    (verilog-insert-definition sig-list-i  "input" indent-pt v2k t)
+	    (verilog-modi-cache-add-inputs modi sig-list-i)
+	    (verilog-modi-cache-add-outputs modi sig-list-o)
+	    (verilog-modi-cache-add-inouts modi sig-list-io)
+	    (verilog-insert-indent "// End of automatics\n"))
+	  (when v2k (verilog-repair-close-comma))
+	  )))))
+
+(defun verilog-auto-sense-sigs (modi presense-sigs)
+  "Return list of signals for current AUTOSENSE block."
+  (let* ((sigss (verilog-read-always-signals))
+	 (sig-list (verilog-signals-not-params
+		    (verilog-signals-not-in (verilog-alw-get-inputs sigss)
+					    (append (and (not verilog-auto-sense-include-inputs)
+							 (verilog-alw-get-outputs sigss))
+						    (verilog-modi-get-consts modi)
+						    (verilog-modi-get-gparams modi)
+						    presense-sigs)))))
+    sig-list))
+
+(defun verilog-auto-sense ()
+  "Expand AUTOSENSE statements, as part of \\[verilog-auto].
+Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
+with one automatically derived from all inputs declared in the always
+statement.  Signals that are generated within the same always block are NOT
+placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
+Long lines are split based on the `fill-column', see \\[set-fill-column].
+
+Limitations:
+  Verilog does not allow memories (multidimensional arrays) in sensitivity
+  lists.  AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
+
+Constant signals:
+  AUTOSENSE cannot always determine if a `define is a constant or a signal
+  (it could be in a include file for example).  If a `define or other signal
+  is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
+  declaration anywhere in the module (parenthesis are required):
+
+	/* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
+
+  Better yet, use a parameter, which will be understood to be constant
+  automatically.
+
+OOps!
+  If AUTOSENSE makes a mistake, please report it.  (First try putting
+  a begin/end after your always!) As a workaround, if a signal that
+  shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
+  If a signal should be in the sensitivity list wasn't, placing it before
+  the /*AUTOSENSE*/ comment will prevent it from being deleted when the
+  autos are updated (or added if it occurs there already).
+
+An example:
+
+	   always @ (/*AUTOSENSE*/) begin
+	      /* AUTO_CONSTANT (`constant) */
+	      outin = ina | inb | `constant;
+	      out = outin;
+	   end
+
+Typing \\[verilog-auto] will make this into:
+
+	   always @ (/*AUTOSENSE*/ina or inb) begin
+	      /* AUTO_CONSTANT (`constant) */
+	      outin = ina | inb | `constant;
+	      out = outin;
+	   end"
+  (save-excursion
+    ;; Find beginning
+    (let* ((start-pt (save-excursion
+		       (verilog-re-search-backward "(" nil t)
+		       (point)))
+	   (indent-pt (save-excursion
+			(or (and (goto-char start-pt) (1+ (current-column)))
+			    (current-indentation))))
+	   (modi (verilog-modi-current))
+	   (sig-memories (verilog-signals-memory
+			  (append
+			   (verilog-modi-get-regs modi)
+			   (verilog-modi-get-wires modi))))
+	   sig-list not-first presense-sigs)
+      ;; Read signals in always, eliminate outputs from sense list
+      (setq presense-sigs (verilog-signals-from-signame
+			   (save-excursion
+			     (verilog-read-signals start-pt (point)))))
+      (setq sig-list (verilog-auto-sense-sigs modi presense-sigs))
+      (when sig-memories
+	(let ((tlen (length sig-list)))
+	  (setq sig-list (verilog-signals-not-in sig-list sig-memories))
+	  (if (not (eq tlen (length sig-list))) (insert " /*memory or*/ "))))
+      (if (and presense-sigs  ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
+	       (save-excursion (goto-char (point))
+			       (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
+			       (verilog-re-search-backward "\\s-" start-pt t)
+			       (while (looking-at "\\s-`endif")
+				 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
+				 (verilog-re-search-backward "\\s-" start-pt t))
+			       (not (looking-at "\\s-or\\b"))))
+	  (setq not-first t))
+      (setq sig-list (sort sig-list `verilog-signals-sort-compare))
+      (while sig-list
+	(cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
+	       (insert "\n")
+	       (indent-to indent-pt)
+	       (if not-first (insert "or ")))
+	      (not-first (insert " or ")))
+	(insert (verilog-sig-name (car sig-list)))
+	(setq sig-list (cdr sig-list)
+	      not-first t))
+      )))
+
+(defun verilog-auto-reset ()
+  "Expand AUTORESET statements, as part of \\[verilog-auto].
+Replace the /*AUTORESET*/ comment with code to initialize all
+registers set elsewhere in the always block.
+
+Limitations:
+  AUTORESET will not clear memories.
+
+  AUTORESET uses <= if there are any <= in the block, else it uses =.
+
+/*AUTORESET*/ presumes that any signals mentioned between the previous
+begin/case/if statement and the AUTORESET comment are being reset manually
+and should not be automatically reset.  This includes omitting any signals
+used on the right hand side of assignments.
+
+By default, AUTORESET will include the width of the signal in the autos,
+this is a recent change.  To control this behavior, see
+`verilog-auto-reset-widths'.
+
+AUTORESET ties signals to deasserted, which is presumed to be zero.
+Signals that match `verilog-active-low-regexp' will be deasserted by tieing
+them to a one.
+
+An example:
+
+    always @(posedge clk or negedge reset_l) begin
+        if (!reset_l) begin
+            c <= 1;
+            /*AUTORESET*/
+        end
+        else begin
+            a <= in_a;
+            b <= in_b;
+            c <= in_c;
+        end
+    end
+
+Typing \\[verilog-auto] will make this into:
+
+    always @(posedge core_clk or negedge reset_l) begin
+        if (!reset_l) begin
+            c <= 1;
+            /*AUTORESET*/
+            // Beginning of autoreset for uninitialized flops
+            a <= 0;
+            b <= 0;
+            // End of automatics
+        end
+        else begin
+            a <= in_a;
+            b <= in_b;
+            c <= in_c;
+        end
+    end"
+
+  (interactive)
+  (save-excursion
+    ;; Find beginning
+    (let* ((indent-pt (current-indentation))
+	   (modi (verilog-modi-current))
+	   (all-list (verilog-modi-get-signals modi))
+	   sigss sig-list prereset-sigs assignment-str)
+      ;; Read signals in always, eliminate outputs from reset list
+      (setq prereset-sigs (verilog-signals-from-signame
+			   (save-excursion
+			     (verilog-read-signals
+			      (save-excursion
+				(verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
+				(point))
+			      (point)))))
+      (save-excursion
+	(verilog-re-search-backward "@" nil t)
+        (setq sigss (verilog-read-always-signals)))
+      (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
+			       (concat " <= " verilog-assignment-delay)
+			     " = "))
+      (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
+					     prereset-sigs))
+      (setq sig-list (sort sig-list `verilog-signals-sort-compare))
+      (when sig-list
+	(insert "\n");
+	(indent-to indent-pt)
+	(insert "// Beginning of autoreset for uninitialized flops\n");
+	(indent-to indent-pt)
+	(while sig-list
+	  (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
+			 (car sig-list))))
+	    (insert (verilog-sig-name sig)
+		    assignment-str
+		    (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
+		    ";\n")
+	    (indent-to indent-pt)
+	    (setq sig-list (cdr sig-list))))
+	(insert "// End of automatics"))
+      )))
+
+(defun verilog-auto-tieoff ()
+  "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
+Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
+signals to deasserted.
+
+/*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
+input/output list as another module, but no internals.  Specifically, it
+finds all outputs in the module, and if that input is not otherwise declared
+as a register or wire, creates a tieoff.
+
+AUTORESET ties signals to deasserted, which is presumed to be zero.
+Signals that match `verilog-active-low-regexp' will be deasserted by tieing
+them to a one.
+
+An example of making a stub for another module:
+
+    module FooStub (/*AUTOINST*/);
+	/*AUTOINOUTMODULE(\"Foo\")*/
+        /*AUTOTIEOFF*/
+        // verilator lint_off UNUSED
+        wire _unused_ok = &{1'b0,
+                            /*AUTOUNUSED*/
+                            1'b0};
+        // verilator lint_on  UNUSED
+    endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+    module FooStub (/*AUTOINST*/...);
+	/*AUTOINOUTMODULE(\"Foo\")*/
+        // Beginning of autotieoff
+        output [2:0] foo;
+        // End of automatics
+
+        /*AUTOTIEOFF*/
+        // Beginning of autotieoff
+        wire [2:0] foo = 3'b0;
+        // End of automatics
+        ...
+    endmodule"
+  (interactive)
+  (save-excursion
+    ;; Find beginning
+    (let* ((indent-pt (current-indentation))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-not-in
+		      (verilog-modi-get-outputs modi)
+		      (append (verilog-modi-get-wires modi)
+			      (verilog-modi-get-regs modi)
+			      (verilog-modi-get-assigns modi)
+			      (verilog-modi-get-consts modi)
+			      (verilog-modi-get-gparams modi)
+			      (verilog-modi-get-sub-outputs modi)
+			      (verilog-modi-get-sub-inouts modi)
+			      ))))
+      (when sig-list
+	(forward-line 1)
+	(verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
+	(setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
+	(verilog-modi-cache-add-wires modi sig-list)  ; Before we trash list
+	(while sig-list
+	  (let ((sig (car sig-list)))
+	    (verilog-insert-one-definition sig "wire" indent-pt)
+	    (indent-to (max 48 (+ indent-pt 40)))
+	    (insert "= " (verilog-sig-tieoff sig)
+		    ";\n")
+	    (setq sig-list (cdr sig-list))))
+	(verilog-insert-indent "// End of automatics\n")
+	))))
+
+(defun verilog-auto-unused ()
+  "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
+Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
+input and inout signals.
+
+/*AUTOUNUSED*/ is used to make stub modules; modules that have the same
+input/output list as another module, but no internals.  Specifically, it
+finds all inputs and inouts in the module, and if that input is not otherwise
+used, adds it to a comma separated list.
+
+The comma separated list is intended to be used to create a _unused_ok
+signal.  Using the exact name \"_unused_ok\" for name of the temporary
+signal is recommended as it will insure maximum forward compatibility, it
+also makes lint warnings easy to understand; ignore any unused warnings
+with \"unused\" in the signal name.
+
+To reduce simulation time, the _unused_ok signal should be forced to a
+constant to prevent wiggling.  The easiest thing to do is use a
+reduction-and with 1'b0 as shown.
+
+This way all unused signals are in one place, making it convenient to add
+your tool's specific pragmas around the assignment to disable any unused
+warnings.
+
+You can add signals you do not want included in AUTOUNUSED with
+`verilog-auto-unused-ignore-regexp'.
+
+An example of making a stub for another module:
+
+    module FooStub (/*AUTOINST*/);
+	/*AUTOINOUTMODULE(\"Foo\")*/
+        /*AUTOTIEOFF*/
+        // verilator lint_off UNUSED
+        wire _unused_ok = &{1'b0,
+                            /*AUTOUNUSED*/
+                            1'b0};
+        // verilator lint_on  UNUSED
+    endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+        ...
+        // verilator lint_off UNUSED
+        wire _unused_ok = &{1'b0,
+                            /*AUTOUNUSED*/
+			    // Beginning of automatics
+			    unused_input_a,
+			    unused_input_b,
+			    unused_input_c,
+			    // End of automatics
+                            1'b0};
+        // verilator lint_on  UNUSED
+    endmodule"
+  (interactive)
+  (save-excursion
+    ;; Find beginning
+    (let* ((indent-pt (progn (search-backward "/*") (current-column)))
+	   (modi (verilog-modi-current))
+	   (sig-list (verilog-signals-not-in
+		      (append (verilog-modi-get-inputs modi)
+			      (verilog-modi-get-inouts modi))
+		      (append (verilog-modi-get-sub-inputs modi)
+			      (verilog-modi-get-sub-inouts modi)
+			      ))))
+      (setq sig-list (verilog-signals-not-matching-regexp
+		      sig-list verilog-auto-unused-ignore-regexp))
+      (when sig-list
+	(forward-line 1)
+	(verilog-insert-indent "// Beginning of automatic unused inputs\n")
+	(setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
+	(while sig-list
+	  (let ((sig (car sig-list)))
+	    (indent-to indent-pt)
+	    (insert (verilog-sig-name sig) ",\n")
+	    (setq sig-list (cdr sig-list))))
+	(verilog-insert-indent "// End of automatics\n")
+	))))
+
+(defun verilog-enum-ascii (signm elim-regexp)
+  "Convert a enum name SIGNM to a ascii string for insertion.
+Remove user provided prefix ELIM-REGEXP."
+  (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
+  (let ((case-fold-search t))
+    ;; All upper becomes all lower for readability
+    (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
+
+(defun verilog-auto-ascii-enum ()
+  "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
+Create a register to contain the ASCII decode of a enumerated signal type.
+This will allow trace viewers to show the ASCII name of states.
+
+First, parameters are built into a enumeration using the synopsys enum
+comment.  The comment must be between the keyword and the symbol.
+\(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
+
+Next, registers which that enum applies to are also tagged with the same
+enum.  Synopsys also suggests labeling state vectors, but `verilog-mode'
+doesn't care.
+
+Finally, a AUTOASCIIENUM command is used.
+
+  The first parameter is the name of the signal to be decoded.
+
+  The second parameter is the name to store the ASCII code into.  For the
+  signal foo, I suggest the name _foo__ascii, where the leading _ indicates
+  a signal that is just for simulation, and the magic characters _ascii
+  tell viewers like Dinotrace to display in ASCII format.
+
+  The final optional parameter is a string which will be removed from the
+  state names.
+
+An example:
+
+	//== State enumeration
+	parameter [2:0] // synopsys enum state_info
+			   SM_IDLE =  3'b000,
+			   SM_SEND =  3'b001,
+			   SM_WAIT1 = 3'b010;
+	//== State variables
+	reg [2:0]	/* synopsys enum state_info */
+			state_r;		/* synopsys state_vector state_r */
+	reg [2:0]	/* synopsys enum state_info */
+			state_e1;
+
+	//== ASCII state decoding
+
+	/*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
+
+Typing \\[verilog-auto] will make this into:
+
+	... same front matter ...
+
+	/*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
+	// Beginning of automatic ASCII enum decoding
+	reg [39:0]		state_ascii_r;		// Decode of state_r
+	always @(state_r) begin
+	   case ({state_r})
+		SM_IDLE:  state_ascii_r = \"idle \";
+		SM_SEND:  state_ascii_r = \"send \";
+		SM_WAIT1: state_ascii_r = \"wait1\";
+		default:  state_ascii_r = \"%Erro\";
+	   endcase
+	end
+	// End of automatics"
+  (save-excursion
+    (let* ((params (verilog-read-auto-params 2 3))
+	   (undecode-name (nth 0 params))
+	   (ascii-name (nth 1 params))
+	   (elim-regexp (nth 2 params))
+	   ;;
+	   (indent-pt (current-indentation))
+	   (modi (verilog-modi-current))
+	   ;;
+	   (sig-list-consts (append (verilog-modi-get-consts modi)
+				    (verilog-modi-get-gparams modi)))
+	   (sig-list-all  (append (verilog-modi-get-regs modi)
+				  (verilog-modi-get-outputs modi)
+				  (verilog-modi-get-inouts modi)
+				  (verilog-modi-get-inputs modi)
+				  (verilog-modi-get-wires modi)))
+	   ;;
+	   (undecode-sig (or (assoc undecode-name sig-list-all)
+			     (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
+	   (undecode-enum (or (verilog-sig-enum undecode-sig)
+			      (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
+	   ;;
+	   (enum-sigs (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
+			  (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum)))
+	   ;;
+	   (enum-chars 0)
+	   (ascii-chars 0))
+      ;;
+      ;; Find number of ascii chars needed
+      (let ((tmp-sigs enum-sigs))
+	(while tmp-sigs
+	  (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
+		ascii-chars (max ascii-chars (length (verilog-enum-ascii
+						      (verilog-sig-name (car tmp-sigs))
+						      elim-regexp)))
+		tmp-sigs (cdr tmp-sigs))))
+      ;;
+      (forward-line 1)
+      (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
+      (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
+					 (concat "Decode of " undecode-name) nil nil))))
+	(verilog-insert-definition decode-sig-list "reg" indent-pt nil)
+	(verilog-modi-cache-add-regs modi decode-sig-list))
+      ;;
+      (verilog-insert-indent "always @(" undecode-name ") begin\n")
+      (setq indent-pt (+ indent-pt verilog-indent-level))
+      (indent-to indent-pt)
+      (insert "case ({" undecode-name "})\n")
+      (setq indent-pt (+ indent-pt verilog-case-indent))
+      ;;
+      (let ((tmp-sigs enum-sigs)
+	    (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n" (1+ (max 8 enum-chars))
+			    ascii-name ascii-chars))
+	    (errname (substring "%Error" 0 (min 6 ascii-chars))))
+	(while tmp-sigs
+	  (verilog-insert-indent
+	   (format chrfmt (concat (verilog-sig-name (car tmp-sigs)) ":")
+		   (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
+				       elim-regexp)))
+	  (setq tmp-sigs (cdr tmp-sigs)))
+	(verilog-insert-indent (format chrfmt "default:" errname)))
+      ;;
+      (setq indent-pt (- indent-pt verilog-case-indent))
+      (verilog-insert-indent "endcase\n")
+      (setq indent-pt (- indent-pt verilog-indent-level))
+      (verilog-insert-indent "end\n"
+			     "// End of automatics\n")
+      )))
+
+(defun verilog-auto-templated-rel ()
+  "Replace Templated relative line numbers with absolute line numbers.
+Internal use only.  This hacks around the line numbers in AUTOINST Templates
+being different from the final output's line numbering."
+  (let ((templateno 0) (template-line (list 0)))
+    ;; Find line number each template is on
+    (goto-char (point-min))
+    (while (search-forward "AUTO_TEMPLATE" nil t)
+      (setq templateno (1+ templateno))
+      (setq template-line (cons (count-lines (point-min) (point)) template-line)))
+    (setq template-line (nreverse template-line))
+    ;; Replace T# L# with absolute line number
+    (goto-char (point-min))
+    (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
+      (replace-match (concat " Templated "
+			     (int-to-string (+ (nth (string-to-int (match-string 1))
+						    template-line)
+					       (string-to-int (match-string 2)))))
+		     t t))))
+
+
+;;
+;; Auto top level
+;;
+
+(defun verilog-auto (&optional inject)  ; Use verilog-inject-auto instead of passing a arg
+  "Expand AUTO statements.
+Look for any /*AUTO...*/ commands in the code, as used in
+instantiations or argument headers.  Update the list of signals
+following the /*AUTO...*/ command.
+
+Use \\[verilog-delete-auto] to remove the AUTOs.
+
+Use \\[verilog-inject-auto] to insert AUTOs for the first time.
+
+Use \\[verilog-faq] for a pointer to frequently asked questions.
+
+The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
+called before and after this function, respectively.
+
+For example:
+	module (/*AUTOARG*/)
+	/*AUTOINPUT*/
+	/*AUTOOUTPUT*/
+	/*AUTOWIRE*/
+	/*AUTOREG*/
+	somesub sub #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
+
+You can also update the AUTOs from the shell using:
+	emacs --batch  <filenames.v>  -f verilog-batch-auto
+Or fix indentation with:
+	emacs --batch  <filenames.v>  -f verilog-batch-indent
+Likewise, you can delete or inject AUTOs with:
+	emacs --batch  <filenames.v>  -f verilog-batch-delete-auto
+	emacs --batch  <filenames.v>  -f verilog-batch-inject-auto
+
+Using \\[describe-function], see also:
+    `verilog-auto-arg'          for AUTOARG module instantiations
+    `verilog-auto-ascii-enum'   for AUTOASCIIENUM enumeration decoding
+    `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
+    `verilog-auto-inout'        for AUTOINOUT making hierarchy inouts
+    `verilog-auto-input'        for AUTOINPUT making hierarchy inputs
+    `verilog-auto-inst'         for AUTOINST instantiation pins
+    `verilog-auto-star'         for AUTOINST .* SystemVerilog pins
+    `verilog-auto-inst-param'   for AUTOINSTPARAM instantiation params
+    `verilog-auto-output'       for AUTOOUTPUT making hierarchy outputs
+    `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
+    `verilog-auto-reg'          for AUTOREG registers
+    `verilog-auto-reg-input'    for AUTOREGINPUT instantiation registers
+    `verilog-auto-reset'        for AUTORESET flop resets
+    `verilog-auto-sense'        for AUTOSENSE always sensitivity lists
+    `verilog-auto-tieoff'       for AUTOTIEOFF output tieoffs
+    `verilog-auto-unused'       for AUTOUNUSED unused inputs/inouts
+    `verilog-auto-wire'         for AUTOWIRE instantiation wires
+
+    `verilog-read-defines'      for reading `define values
+    `verilog-read-includes'     for reading `includes
+
+If you have bugs with these autos, try contacting the AUTOAUTHOR
+Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
+  (interactive)
+  (unless noninteractive (message "Updating AUTOs..."))
+  (if (featurep 'dinotrace)
+      (dinotrace-unannotate-all))
+  (let ((oldbuf (if (not (buffer-modified-p))
+		    (buffer-string)))
+	;; Before version 20, match-string with font-lock returns a
+	;; vector that is not equal to the string.  IE if on "input"
+	;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
+	(fontlocked (when (and (boundp 'font-lock-mode)
+			       font-lock-mode)
+		      (font-lock-mode nil)
+		      t)))
+    (unwind-protect
+	(save-excursion
+	  ;; If we're not in verilog-mode, change syntax table so parsing works right
+	  (unless (eq major-mode `verilog-mode) (verilog-mode))
+	  ;; Allow user to customize
+	  (run-hooks 'verilog-before-auto-hook)
+	  ;; Try to save the user from needing to revert-file to reread file local-variables
+	  (verilog-auto-reeval-locals)
+	  (verilog-read-auto-lisp (point-min) (point-max))
+	  (verilog-getopt-flags)
+	  ;; These two may seem obvious to do always, but on large includes it can be way too slow
+	  (when verilog-auto-read-includes
+	    (verilog-read-includes)
+	    (verilog-read-defines nil nil t))
+	  ;; This particular ordering is important
+	  ;; INST: Lower modules correct, no internal dependencies, FIRST
+	  (verilog-preserve-cache
+	   ;; Clear existing autos else we'll be screwed by existing ones
+	   (verilog-delete-auto)
+	   ;; Injection if appropriate
+	   (when inject
+	     (verilog-inject-inst)
+	     (verilog-inject-sense)
+	     (verilog-inject-arg))
+	   ;;
+	   (verilog-auto-search-do "/*AUTOINSTPARAM*/" 'verilog-auto-inst-param)
+	   (verilog-auto-search-do "/*AUTOINST*/" 'verilog-auto-inst)
+	   (verilog-auto-search-do ".*" 'verilog-auto-star)
+	   ;; Doesn't matter when done, but combine it with a common changer
+	   (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
+	   (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
+	   ;; Must be done before autoin/out as creates a reg
+	   (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
+	   ;;
+	   ;; first in/outs from other files
+	   (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
+	   ;; next in/outs which need previous sucked inputs first
+	   (verilog-auto-search-do "/*AUTOOUTPUT*/" 'verilog-auto-output)
+	   (verilog-auto-search-do "/*AUTOINPUT*/" 'verilog-auto-input)
+	   (verilog-auto-search-do "/*AUTOINOUT*/" 'verilog-auto-inout)
+	   ;; Then tie off those in/outs
+	   (verilog-auto-search-do "/*AUTOTIEOFF*/" 'verilog-auto-tieoff)
+	   ;; Wires/regs must be after inputs/outputs
+	   (verilog-auto-search-do "/*AUTOWIRE*/" 'verilog-auto-wire)
+	   (verilog-auto-search-do "/*AUTOREG*/" 'verilog-auto-reg)
+	   (verilog-auto-search-do "/*AUTOREGINPUT*/" 'verilog-auto-reg-input)
+	   ;; outputevery needs AUTOOUTPUTs done first
+	   (verilog-auto-search-do "/*AUTOOUTPUTEVERY*/" 'verilog-auto-output-every)
+	   ;; After we've created all new variables
+	   (verilog-auto-search-do "/*AUTOUNUSED*/" 'verilog-auto-unused)
+	   ;; Must be after all inputs outputs are generated
+	   (verilog-auto-search-do "/*AUTOARG*/" 'verilog-auto-arg)
+	   ;; Fix line numbers (comments only)
+	   (verilog-auto-templated-rel)
+	   )
+	  ;;
+	  (run-hooks 'verilog-auto-hook)
+	  ;;
+	  (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))
+	  ;;
+	  ;; If end result is same as when started, clear modified flag
+	  (cond ((and oldbuf (equal oldbuf (buffer-string)))
+		 (set-buffer-modified-p nil)
+		 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
+		(t (unless noninteractive (message "Updating AUTOs...done")))))
+      ;; Unwind forms
+      (progn
+	;; Restore font-lock
+	(when fontlocked (font-lock-mode t)))
+      )))
+
+
+;;
+;; Skeleton based code insertion
+;;
+(defvar verilog-template-map 
+  (let ((map (make-sparse-keymap)))
+    (define-key map "a" 'verilog-sk-always)
+    (define-key map "b" 'verilog-sk-begin)
+    (define-key map "c" 'verilog-sk-case)
+    (define-key map "f" 'verilog-sk-for)
+    (define-key map "g" 'verilog-sk-generate)
+    (define-key map "h" 'verilog-sk-header)
+    (define-key map "i" 'verilog-sk-initial)
+    (define-key map "j" 'verilog-sk-fork)
+    (define-key map "m" 'verilog-sk-module)
+    (define-key map "p" 'verilog-sk-primitive)
+    (define-key map "r" 'verilog-sk-repeat)
+    (define-key map "s" 'verilog-sk-specify)
+    (define-key map "t" 'verilog-sk-task)
+    (define-key map "w" 'verilog-sk-while)
+    (define-key map "x" 'verilog-sk-casex)
+    (define-key map "z" 'verilog-sk-casez)
+    (define-key map "?" 'verilog-sk-if)
+    (define-key map ":" 'verilog-sk-else-if)
+    (define-key map "/" 'verilog-sk-comment)
+    (define-key map "A" 'verilog-sk-assign)
+    (define-key map "F" 'verilog-sk-function)
+    (define-key map "I" 'verilog-sk-input)
+    (define-key map "O" 'verilog-sk-output)
+    (define-key map "S" 'verilog-sk-state-machine)
+    (define-key map "=" 'verilog-sk-inout)
+    (define-key map "W" 'verilog-sk-wire)
+    (define-key map "R" 'verilog-sk-reg)
+    (define-key map "D" 'verilog-sk-define-signal)
+    map)
+  "Keymap used in Verilog mode for smart template operations.")
+
+
+;;
+;; Place the templates into Verilog Mode.  They may be inserted under any key.
+;; C-c C-t will be the default.  If you use templates a lot, you
+;; may want to consider moving the binding to another key in your .emacs
+;; file.
+;;
+;(define-key verilog-mode-map "\C-ct" verilog-template-map)
+(define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
+
+;;; ---- statement skeletons ------------------------------------------
+
+(define-skeleton verilog-sk-prompt-condition
+  "Prompt for the loop condition."
+  "[condition]: " str )
+
+(define-skeleton verilog-sk-prompt-init
+  "Prompt for the loop init statement."
+  "[initial statement]: " str )
+
+(define-skeleton verilog-sk-prompt-inc
+  "Prompt for the loop increment statement."
+  "[increment statement]: " str )
+
+(define-skeleton verilog-sk-prompt-name
+  "Prompt for the name of something."
+  "[name]: " str)
+
+(define-skeleton verilog-sk-prompt-clock
+  "Prompt for the name of something."
+  "name and edge of clock(s): " str)
+
+(defvar verilog-sk-reset nil)
+(defun verilog-sk-prompt-reset ()
+  "Prompt for the name of a state machine reset."
+  (setq verilog-sk-reset (read-input "name of reset: " "rst")))
+
+
+(define-skeleton verilog-sk-prompt-state-selector
+  "Prompt for the name of a state machine selector."
+  "name of selector (eg {a,b,c,d}): " str )
+
+(define-skeleton verilog-sk-prompt-output
+  "Prompt for the name of something."
+  "output: " str)
+
+(define-skeleton verilog-sk-prompt-msb
+  "Prompt for least significant bit specification."
+  "msb:" str & ?: & (verilog-sk-prompt-lsb) | -1 )
+
+(define-skeleton verilog-sk-prompt-lsb
+  "Prompt for least significant bit specification."
+  "lsb:" str )
+
+(defvar verilog-sk-p nil)
+(define-skeleton verilog-sk-prompt-width
+  "Prompt for a width specification."
+  ()
+  (progn
+    (setq verilog-sk-p (point))
+    (verilog-sk-prompt-msb)
+    (if (> (point) verilog-sk-p) "] " " ")))
+
+(defun verilog-sk-header ()
+  "Insert a descriptive header at the top of the file."
+  (interactive "*")
+  (save-excursion
+    (goto-char (point-min))
+    (verilog-sk-header-tmpl)))
+
+(define-skeleton verilog-sk-header-tmpl
+  "Insert a comment block containing the module title, author, etc."
+  "[Description]: "
+  "//                              -*- Mode: Verilog -*-"
+  "\n// Filename        : " (buffer-name)
+  "\n// Description     : " str
+  "\n// Author          : " (user-full-name)
+  "\n// Created On      : " (current-time-string)
+  "\n// Last Modified By: ."
+  "\n// Last Modified On: ."
+  "\n// Update Count    : 0"
+  "\n// Status          : Unknown, Use with caution!"
+  "\n")
+
+(define-skeleton verilog-sk-module
+  "Insert a module definition."
+  ()
+  > "module " (verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
+  > _ \n
+  > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-primitive
+  "Insert a task definition."
+  ()
+  > "primitive " (verilog-sk-prompt-name) " ( " (verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
+  > _ \n
+  > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-task
+  "Insert a task definition."
+  ()
+  > "task " (verilog-sk-prompt-name) & ?; \n
+  > _ \n
+  > "begin" \n
+  > \n
+  > (- verilog-indent-level-behavioral) "end" \n
+  > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-function
+  "Insert a function definition."
+  ()
+  > "function [" (verilog-sk-prompt-width) | -1 (verilog-sk-prompt-name) ?; \n
+  > _ \n
+  > "begin" \n
+  > \n
+  > (- verilog-indent-level-behavioral) "end" \n
+  > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-always
+  "Insert always block.  Uses the minibuffer to prompt
+for sensitivity list."
+  ()
+  > "always @ ( /*AUTOSENSE*/ ) begin\n"
+  > _ \n
+  > (- verilog-indent-level-behavioral) "end" \n >
+  )
+
+(define-skeleton verilog-sk-initial
+  "Insert an initial block."
+  ()
+  > "initial begin\n"
+  > _ \n
+  > (- verilog-indent-level-behavioral) "end" \n > )
+
+(define-skeleton verilog-sk-specify
+  "Insert specify block.  "
+  ()
+  > "specify\n"
+  > _ \n
+  > (- verilog-indent-level-behavioral) "endspecify" \n > )
+
+(define-skeleton verilog-sk-generate
+  "Insert generate block.  "
+  ()
+  > "generate\n"
+  > _ \n
+  > (- verilog-indent-level-behavioral) "endgenerate" \n > )
+
+(define-skeleton verilog-sk-begin
+  "Insert begin end block.  Uses the minibuffer to prompt for name"
+  ()
+  > "begin" (verilog-sk-prompt-name) \n
+  > _ \n
+  > (- verilog-indent-level-behavioral) "end"
+)
+
+(define-skeleton verilog-sk-fork
+  "Insert an fork join block."
+  ()
+  > "fork\n"
+  > "begin" \n
+  > _ \n
+  > (- verilog-indent-level-behavioral) "end" \n
+  > "begin" \n
+  > \n
+  > (- verilog-indent-level-behavioral) "end" \n
+  > (- verilog-indent-level-behavioral) "join" \n
+  > )
+
+
+(define-skeleton verilog-sk-case
+  "Build skeleton case statement, prompting for the selector expression,
+and the case items."
+  "[selector expression]: "
+  > "case (" str ") " \n
+  > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
+  resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-casex
+  "Build skeleton casex statement, prompting for the selector expression,
+and the case items."
+  "[selector expression]: "
+  > "casex (" str ") " \n
+  > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
+  resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-casez
+  "Build skeleton casez statement, prompting for the selector expression,
+and the case items."
+  "[selector expression]: "
+  > "casez (" str ") " \n
+  > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
+  resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-if
+  "Insert a skeleton if statement."
+  > "if (" (verilog-sk-prompt-condition) & ")" " begin" \n
+  > _ \n
+  > (- verilog-indent-level-behavioral) "end " \n )
+
+(define-skeleton verilog-sk-else-if
+  "Insert a skeleton else if statement."
+  > (verilog-indent-line) "else if ("
+  (progn (setq verilog-sk-p (point)) nil) (verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
+  > _ \n
+  > "end" (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-datadef
+  "Common routine to get data definition"
+  ()
+  (verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
+
+(define-skeleton verilog-sk-input
+  "Insert an input definition."
+  ()
+  > "input  [" (verilog-sk-datadef))
+
+(define-skeleton verilog-sk-output
+  "Insert an output definition."
+  ()
+  > "output [" (verilog-sk-datadef))
+
+(define-skeleton verilog-sk-inout
+  "Insert an inout definition."
+  ()
+  > "inout  [" (verilog-sk-datadef))
+
+(defvar verilog-sk-signal nil)
+(define-skeleton verilog-sk-def-reg
+  "Insert a reg definition."
+  ()
+  > "reg    [" (verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
+
+(defun verilog-sk-define-signal ()
+  "Insert a definition of signal under point at top of module."
+  (interactive "*")
+  (let* (
+	 (sig-re "[a-zA-Z0-9_]*")
+	 (v1 (buffer-substring
+	       (save-excursion
+		 (skip-chars-backward sig-re)
+		 (point))
+	       (save-excursion
+		 (skip-chars-forward sig-re)
+		 (point))))
+	 )
+    (if (not (member v1 verilog-keywords))
+	(save-excursion
+	  (setq verilog-sk-signal v1)
+	  (verilog-beg-of-defun)
+	  (verilog-end-of-statement)
+	  (verilog-forward-syntactic-ws)
+	  (verilog-sk-def-reg)
+	  (message "signal at point is %s" v1))
+      (message "object at point (%s) is a keyword" v1))
+    )
+  )
+
+
+(define-skeleton verilog-sk-wire
+  "Insert a wire definition."
+  ()
+  > "wire   [" (verilog-sk-datadef))
+
+(define-skeleton verilog-sk-reg
+  "Insert a reg definition."
+  ()
+  > "reg   [" (verilog-sk-datadef))
+
+(define-skeleton verilog-sk-assign
+  "Insert a skeleton assign statement."
+  ()
+  > "assign " (verilog-sk-prompt-name) " = " _ ";" \n)
+
+(define-skeleton verilog-sk-while
+  "Insert a skeleton while loop statement."
+  ()
+  > "while ("  (verilog-sk-prompt-condition)  ") begin" \n
+  > _ \n
+  > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-repeat
+  "Insert a skeleton repeat loop statement."
+  ()
+  > "repeat ("  (verilog-sk-prompt-condition)  ") begin" \n
+  > _ \n
+  > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-for
+  "Insert a skeleton while loop statement."
+  ()
+  > "for ("
+  (verilog-sk-prompt-init) "; "
+  (verilog-sk-prompt-condition) "; "
+  (verilog-sk-prompt-inc)
+  ") begin" \n
+  > _ \n
+  > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
+
+(define-skeleton verilog-sk-comment
+  "Inserts three comment lines, making a display comment."
+  ()
+  > "/*\n"
+  > "* " _ \n
+  > "*/")
+
+(define-skeleton verilog-sk-state-machine
+  "Insert a state machine definition."
+  "Name of state variable: "
+  '(setq input "state")
+  > "// State registers for " str | -23 \n
+  '(setq verilog-sk-state str)
+  > "reg [" (verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
+  '(setq input nil)
+  > \n
+  > "// State FF for " verilog-sk-state \n
+  > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
+  > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
+  > verilog-sk-state " = next_" verilog-sk-state ?; \n
+  > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
+  > \n
+  > "// Next State Logic for " verilog-sk-state \n
+  > "always @ ( /*AUTOSENSE*/ ) begin\n"
+  > "case (" (verilog-sk-prompt-state-selector) ") " \n
+  > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
+  resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
+  > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
+
+;; Eliminate compile warning
+(eval-when-compile
+  (if (not (boundp 'mode-popup-menu))
+      (defvar mode-popup-menu nil "Compatibility with XEmacs.")))
+
+;; ---- add menu 'Statements' in Verilog mode (MH)
+(defun verilog-add-statement-menu ()
+  "Add the menu 'Statements' to the menu bar in Verilog mode."
+  (if (featurep 'xemacs)
+      (progn
+	(easy-menu-add verilog-stmt-menu)
+	(easy-menu-add verilog-menu)
+	(setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))))
+
+(add-hook 'verilog-mode-hook 'verilog-add-statement-menu)
+
+
+
+;;
+;; Include file loading with mouse/return event
+;;
+;; idea & first impl.: M. Rouat (eldo-mode.el)
+;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
+
+(if (featurep 'xemacs)
+    (require 'overlay)
+  (require 'lucid)) ;; what else can we do ??
+
+(defconst verilog-include-file-regexp
+  "^`include\\s-+\"\\([^\n\"]*\\)\""
+  "Regexp that matches the include file.")
+
+(defvar verilog-mode-mouse-map 
+  (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
+    (set-keymap-parent map verilog-mode-map)
+    ;; mouse button bindings
+    (define-key map "\r"            'verilog-load-file-at-point)
+    (if (featurep 'xemacs)
+	(define-key map 'button2    'verilog-load-file-at-mouse);ffap-at-mouse ?
+      (define-key map [mouse-2]     'verilog-load-file-at-mouse))
+    (if (featurep 'xemacs)
+	(define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
+      (define-key map [S-mouse-2]   'mouse-yank-at-click))
+    map)
+  "Map containing mouse bindings for `verilog-mode'.")
+
+
+(defun verilog-colorize-include-files (beg end old-len)
+  "This function colorizes included files when the mouse passes over them.
+Clicking on the middle-mouse button loads them in a buffer (as in dired)."
+  (save-excursion
+    (save-match-data
+      (let (end-point)
+	(goto-char end)
+	(setq end-point (verilog-get-end-of-line))
+	(goto-char beg)
+	(beginning-of-line)  ; scan entire line !
+	;; delete overlays existing on this line
+	(let ((overlays (overlays-in (point) end-point)))
+	  (while overlays
+	    (if (and
+		 (overlay-get (car overlays) 'detachable)
+		 (overlay-get (car overlays) 'verilog-include-file))
+		(delete-overlay (car overlays)))
+	    (setq overlays (cdr overlays)))) ; let
+	;; make new ones, could reuse deleted one ?
+	(while (search-forward-regexp verilog-include-file-regexp end-point t)
+	  (let (ov)
+	    (goto-char (match-beginning 1))
+	    (setq ov (make-overlay (match-beginning 1) (match-end 1)))
+	    (overlay-put ov 'start-closed 't)
+	    (overlay-put ov 'end-closed 't)
+	    (overlay-put ov 'evaporate 't)
+	    (overlay-put ov 'verilog-include-file 't)
+	    (overlay-put ov 'mouse-face 'highlight)
+	    (overlay-put ov 'local-map verilog-mode-mouse-map)))))))
+
+
+(defun verilog-colorize-include-files-buffer ()
+  "Colorize a include file."
+  (interactive)
+  ;; delete overlays
+  (let ((overlays (overlays-in (point-min) (point-max))))
+    (while overlays
+      (if (and
+	   (overlay-get (car overlays) 'detachable)
+	   (overlay-get (car overlays) 'verilog-include-file))
+	  (delete-overlay (car overlays)))
+      (setq overlays (cdr overlays)))) ; let
+  ;; remake overlays
+  (verilog-colorize-include-files (point-min) (point-max) nil))
+
+;; ffap-at-mouse isn't useful for verilog mode. It uses library paths.
+;; so define this function to do more or less the same as ffap-at-mouse
+;; but first resolve filename...
+(defun verilog-load-file-at-mouse (event)
+  "Load file under button 2 click's EVENT.
+Files are checked based on `verilog-library-directories'."
+  (interactive "@e")
+  (save-excursion ;; implement a verilog specific ffap-at-mouse
+    (mouse-set-point event)
+    (beginning-of-line)
+    (if (looking-at verilog-include-file-regexp)
+	(if (and (car (verilog-library-filenames
+		       (match-string 1) (buffer-file-name)))
+		 (file-readable-p (car (verilog-library-filenames
+					(match-string 1) (buffer-file-name)))))
+	    (find-file (car (verilog-library-filenames
+			     (match-string 1) (buffer-file-name))))
+	  (progn
+	    (message
+	     "File '%s' isn't readable, use shift-mouse2 to paste in this field"
+	     (match-string 1))))
+      )))
+
+;; ffap isn't useable for verilog mode. It uses library paths.
+;; so define this function to do more or less the same as ffap
+;; but first resolve filename...
+(defun verilog-load-file-at-point ()
+  "Load file under point.
+Files are checked based on `verilog-library-directories'."
+  (interactive)
+  (save-excursion ;; implement a verilog specific ffap
+    (beginning-of-line)
+    (if (looking-at verilog-include-file-regexp)
+	(if (and
+	     (car (verilog-library-filenames
+		   (match-string 1) (buffer-file-name)))
+	     (file-readable-p (car (verilog-library-filenames
+				    (match-string 1) (buffer-file-name)))))
+	    (find-file (car (verilog-library-filenames
+			     (match-string 1) (buffer-file-name))))))
+      ))
+
+
+;;
+;; Bug reporting
+;;
+
+(defun verilog-faq ()
+  "Tell the user their current version, and where to get the FAQ etc."
+  (interactive)
+  (with-output-to-temp-buffer "*verilog-mode help*"
+    (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
+    (princ "\n")
+    (princ "For new releases, see http://www.verilog.com\n")
+    (princ "\n")
+    (princ "For frequently asked questions, see http://www.veripool.com/verilog-mode-faq.html\n")
+    (princ "\n")
+    (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
+    (princ "\n")))
+
+(defun verilog-submit-bug-report ()
+  "Submit via mail a bug report on verilog-mode.el."
+  (interactive)
+  (let ((reporter-prompt-for-summary-p t))
+    (reporter-submit-bug-report
+     "mac@verilog.com"
+     (concat "verilog-mode v" verilog-mode-version)
+     '(
+       verilog-align-ifelse
+       verilog-auto-endcomments
+       verilog-auto-hook
+       verilog-auto-indent-on-newline
+       verilog-auto-inst-vector
+       verilog-auto-inst-template-numbers
+       verilog-auto-lineup
+       verilog-auto-newline
+       verilog-auto-save-policy
+       verilog-auto-sense-defines-constant
+       verilog-auto-sense-include-inputs
+       verilog-before-auto-hook
+       verilog-case-indent
+       verilog-cexp-indent
+       verilog-compiler
+       verilog-coverage
+       verilog-highlight-translate-off
+       verilog-indent-begin-after-if
+       verilog-indent-declaration-macros
+       verilog-indent-level
+       verilog-indent-level-behavioral
+       verilog-indent-level-declaration
+       verilog-indent-level-directive
+       verilog-indent-level-module
+       verilog-indent-lists
+       verilog-library-flags
+       verilog-library-directories
+       verilog-library-extensions
+       verilog-library-files
+       verilog-linter
+       verilog-minimum-comment-distance
+       verilog-mode-hook
+       verilog-simulator
+       verilog-tab-always-indent
+       verilog-tab-to-comment
+       )
+     nil nil
+     (concat "Hi Mac,
+
+I want to report a bug.  I've read the `Bugs' section of `Info' on
+Emacs, so I know how to make a clear and unambiguous report.  To get
+to that Info section, I typed
+
+M-x info RET m " invocation-name " RET m bugs RET
+
+Before I go further, I want to say that Verilog mode has changed my life.
+I save so much time, my files are colored nicely, my co workers respect
+my coding ability... until now.  I'd really appreciate anything you
+could do to help me out with this minor deficiency in the product.
+
+If you have bugs with the AUTO functions, please CC the AUTOAUTHOR Wilson
+Snyder (wsnyder@wsnyder.org) and/or see http://www.veripool.com.
+You may also want to look at the Verilog-Mode FAQ, see
+http://www.veripool.com/verilog-mode-faq.html.
+
+To reproduce the bug, start a fresh Emacs via " invocation-name "
+-no-init-file -no-site-file'.  In a new buffer, in verilog mode, type
+the code included below.
+
+Given those lines, I expected [[Fill in here]] to happen;
+but instead, [[Fill in here]] happens!.
+
+== The code: =="))))
+
+(provide 'verilog-mode)
+
+;; Local Variables:
+;; checkdoc-permit-comma-termination-flag:t
+;; checkdoc-force-docstrings-flag:nil
+;; End:
+
+;; arch-tag: 87923725-57b3-41b5-9494-be21118c6a6f
+;;; verilog-mode.el ends here
--- a/lisp/progmodes/vhdl-mode.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/progmodes/vhdl-mode.el	Sun Dec 16 05:08:49 2007 +0000
@@ -9095,8 +9095,9 @@
 	 (progn (delete-region (point) (progn (end-of-line) (point)))
 		(vhdl-template-insert-date))
        (unless noerror
-	 (error (concat "ERROR:  Modification date prefix string \""
-			vhdl-modify-date-prefix-string "\" not found")))))))
+	 (error "ERROR:  Modification date prefix string \"%s\" not found"
+			vhdl-modify-date-prefix-string))))))
+
 
 (defun vhdl-template-modify-noerror ()
   "Call `vhdl-template-modify' with NOERROR non-nil."
@@ -10432,7 +10433,7 @@
   "Query a decision from the user."
   (let ((start (point)))
     (when string (vhdl-insert-keyword (concat string " ")))
-    (message prompt)
+    (message "%s" (or prompt ""))
     (let ((char (read-char)))
       (delete-region start (point))
       (if (and optional (eq char ?\r))
--- a/lisp/replace.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/replace.el	Sun Dec 16 05:08:49 2007 +0000
@@ -552,8 +552,8 @@
 When called from Lisp (and usually interactively as well, see below)
 applies to all lines starting after point.
 
-If REGEXP contains upper case characters (excluding those preceded by `\\'),
-the matching is case-sensitive.
+If REGEXP contains upper case characters (excluding those preceded by `\\')
+and `search-upper-case' is non-nil, the matching is case-sensitive.
 
 Second and third arg RSTART and REND specify the region to operate on.
 This command operates on (the accessible part of) all lines whose
@@ -597,8 +597,10 @@
   (save-excursion
     (or (bolp) (forward-line 1))
     (let ((start (point))
-	  (case-fold-search  (and case-fold-search
-				  (isearch-no-upper-case-p regexp t))))
+	  (case-fold-search
+	   (if (and case-fold-search search-upper-case)
+	       (isearch-no-upper-case-p regexp t)
+	     case-fold-search)))
       (while (< (point) rend)
 	;; Start is first char not preserved by previous match.
 	(if (not (re-search-forward regexp rend 'move))
@@ -626,8 +628,8 @@
 The line point is in is deleted if and only if it contains a
 match for regexp starting after point.
 
-If REGEXP contains upper case characters (excluding those preceded by `\\'),
-the matching is case-sensitive.
+If REGEXP contains upper case characters (excluding those preceded by `\\')
+and `search-upper-case' is non-nil, the matching is case-sensitive.
 
 Second and third arg RSTART and REND specify the region to operate on.
 Lines partially contained in this region are deleted if and only if
@@ -657,8 +659,10 @@
       (setq rstart (point)
 	    rend (point-max-marker)))
     (goto-char rstart))
-  (let ((case-fold-search (and case-fold-search
-			       (isearch-no-upper-case-p regexp t))))
+  (let ((case-fold-search
+	 (if (and case-fold-search search-upper-case)
+	     (isearch-no-upper-case-p regexp t)
+	   case-fold-search)))
     (save-excursion
       (while (and (< (point) rend)
 		  (re-search-forward regexp rend t))
@@ -676,8 +680,8 @@
 the number, do not print it; if INTERACTIVE is t, the function behaves
 in all respects has if it had been called interactively.
 
-If REGEXP contains upper case characters (excluding those preceded by `\\'),
-the matching is case-sensitive.
+If REGEXP contains upper case characters (excluding those preceded by `\\')
+and `search-upper-case' is non-nil, the matching is case-sensitive.
 
 Second and third arg RSTART and REND specify the region to operate on.
 
@@ -704,8 +708,10 @@
       (goto-char rstart))
     (let ((count 0)
 	  opoint
-	  (case-fold-search (and case-fold-search
-				 (isearch-no-upper-case-p regexp t))))
+	  (case-fold-search
+	   (if (and case-fold-search search-upper-case)
+	       (isearch-no-upper-case-p regexp t)
+	     case-fold-search)))
       (while (and (< (point) rend)
 		  (progn (setq opoint (point))
 			 (re-search-forward regexp rend t)))
@@ -1030,8 +1036,8 @@
 It serves as a menu to find any of the occurrences in this buffer.
 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
 
-If REGEXP contains upper case characters (excluding those preceded by `\\'),
-the matching is case-sensitive."
+If REGEXP contains upper case characters (excluding those preceded by `\\')
+and `search-upper-case' is non-nil, the matching is case-sensitive."
   (interactive (occur-read-primary-args))
   (occur-1 regexp nlines (list (current-buffer))))
 
@@ -1119,8 +1125,9 @@
 	(let ((count (occur-engine
 		      regexp active-bufs occur-buf
 		      (or nlines list-matching-lines-default-context-lines)
-		      (and case-fold-search
-			   (isearch-no-upper-case-p regexp t))
+		      (if (and case-fold-search search-upper-case)
+			  (isearch-no-upper-case-p regexp t)
+			case-fold-search)
 		      list-matching-lines-buffer-name-face
 		      nil list-matching-lines-face
 		      (not (eq occur-excluded-properties t)))))
@@ -1459,8 +1466,9 @@
   (and query-flag minibuffer-auto-raise
        (raise-frame (window-frame (minibuffer-window))))
   (let* ((case-fold-search
-          (and case-fold-search
-               (isearch-no-upper-case-p from-string regexp-flag)))
+	  (if (and case-fold-search search-upper-case)
+	      (isearch-no-upper-case-p from-string regexp-flag)
+	    case-fold-search))
          (nocasify (not (and case-replace case-fold-search)))
          (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
          (search-function (if regexp-flag 're-search-forward 'search-forward))
--- a/lisp/server.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/server.el	Sun Dec 16 05:08:49 2007 +0000
@@ -242,8 +242,7 @@
   "Delete PROC, including its buffers, terminals and frames.
 If NOFRAME is non-nil, let the frames live.  (To be used from
 `delete-frame-functions'.)"
-  (server-log (concat "server-delete-client" (if noframe " noframe"))
-	      proc)
+  (server-log (concat "server-delete-client" (if noframe " noframe")) proc)
   ;; Force a new lookup of client (prevents infinite recursion).
   (when (memq proc server-clients)
     (let ((buffers (process-get proc 'buffers)))
@@ -339,7 +338,7 @@
                      display
                      ;; Make it display (and remember) some dummy buffer, so
                      ;; we can detect later if the frame is in use or not.
-                     `((server-dummmy-buffer . ,buffer)
+                     `((server-dummy-buffer . ,buffer)
                        ;; This frame may be deleted later (see
                        ;; server-unselect-display) so we want it to be as
                        ;; unobtrusive as possible.
@@ -833,7 +832,8 @@
 		 ;; -display DISPLAY:
 		 ;; Open X frames on the given display instead of the default.
 		 ((and (equal "-display" arg) command-line-args-left)
-		  (setq display (pop command-line-args-left)))
+		  (setq display (pop command-line-args-left))
+                  (if (zerop (length display)) (setq display nil)))
 
 		 ;; -window-system:  Open a new X frame.
 		 ((equal "-window-system" arg)
--- a/lisp/startup.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/startup.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1538,7 +1538,7 @@
 	  (apply #'fancy-splash-insert text)
 	  (insert "\n"))
 	(unless (current-message)
-	  (message fancy-splash-help-echo))
+	  (message "%s" (or fancy-splash-help-echo "")))
 	(set-buffer-modified-p nil)
 	(goto-char (point-min))
 	(force-mode-line-update))
--- a/lisp/term/mac-win.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/term/mac-win.el	Sun Dec 16 05:08:49 2007 +0000
@@ -2228,7 +2228,7 @@
     (if (not buffer-read-only)
 	(insert text)
       (kill-new text)
-      (message
+      (message "%s"
        (substitute-command-keys
 	"The text from the Services menu can be accessed with \\[yank]")))))
 
--- a/lisp/textmodes/artist.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/textmodes/artist.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1151,14 +1151,14 @@
   (interactive)
   (let ((next-op (cdr (cdr (assoc artist-curr-go artist-prev-next-op-alist)))))
     (artist-select-operation next-op)
-    (message next-op)))
+    (message "%s" next-op)))
 
 (defun artist-select-prev-op-in-list ()
   "Cyclically select previous drawing mode operation."
   (interactive)
   (let ((prev-op (car (cdr (assoc artist-curr-go artist-prev-next-op-alist)))))
     (artist-select-operation prev-op)
-    (message prev-op)))
+    (message "%s" prev-op)))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
--- a/lisp/textmodes/org-publish.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/textmodes/org-publish.el	Sun Dec 16 05:08:49 2007 +0000
@@ -481,7 +481,7 @@
 	 (plist (org-publish-get-plist-from-filename filename))
 	 (publishing-function (or (plist-get plist :publishing-function) 'org-publish-org-to-html)))
     (if (not project-name)
-	(error (format "File %s is not part of any known project." filename)))
+	(error "File %s is not part of any known project." filename))
     (when (org-publish-needed-p filename)
       (if (listp publishing-function)
 	  ;; allow chain of publishing functions
@@ -575,7 +575,7 @@
     (let* ((project-name (org-publish-get-project-from-filename (buffer-file-name)))
 	   (org-publish-use-timestamps-flag (if force nil t)))
       (if (not project-name)
-	  (error (format "File %s is not part of any known project." (buffer-file-name))))
+	  (error "File %s is not part of any known project." (buffer-file-name)))
       (org-publish project-name))))
 
 
--- a/lisp/textmodes/org.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/textmodes/org.el	Sun Dec 16 05:08:49 2007 +0000
@@ -6076,7 +6076,7 @@
 If optional TREE is given, use this text instead of the kill ring."
   (interactive "P")
   (unless (org-kill-is-subtree-p tree)
-    (error
+    (error "%s"
      (substitute-command-keys
       "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
   (let* ((txt (or tree (and kill-ring (current-kill 0))))
@@ -7487,7 +7487,7 @@
 	(org-hide-archived-subtrees beg end)
 	(goto-char beg)
 	(if (looking-at (concat ".*:" org-archive-tag ":"))
-	    (message (substitute-command-keys
+	    (message "%s" (substitute-command-keys
 		      "Subtree is archived and stays closed.  Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
 
 (defun org-force-cycle-archived ()
@@ -9366,7 +9366,8 @@
 	  (goto-line l1)))
     (if (not (= epos (point-at-eol))) (org-table-align))
     (goto-line l)
-    (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
+    (and (interactive-p)
+	 (message "%s" (or (cdr (assoc new org-recalc-marks)) "")))))
 
 (defun org-table-maybe-recalculate-line ()
   "Recompute the current line if marked for it, and if we haven't just done it."
@@ -12347,7 +12348,7 @@
   (move-marker (car org-mark-ring)
 	       (or pos (point))
 	       (or buffer (current-buffer)))
-  (message
+  (message "%s"
    (substitute-command-keys
     "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
 
@@ -12429,7 +12430,7 @@
         (if (match-string 2 name) ; If there isn't a node, choose "Top"
             (Info-find-node (match-string 1 name) (match-string 2 name))
           (Info-find-node (match-string 1 name) "Top")))
-    (message (concat "Could not open: " name))))
+    (message "Could not open: %s" name)))
 
 (defun org-follow-gnus-link (&optional group article)
   "Follow a Gnus link to GROUP and ARTICLE."
@@ -12553,7 +12554,7 @@
   (save-excursion
     (mh-index-previous-folder)
     (re-search-forward "^\\(+.*\\)$" nil t)
-    (message (match-string 1))))
+    (message "%s" (match-string 1))))
 
 (defun org-mhe-get-message-folder ()
   "Return the name of the current message folder.  Be careful if you
@@ -13759,7 +13760,7 @@
 	  (org-timestamp-change n (cdr (assoc what whata))))
 	(setq msg (concat msg type org-last-changed-timestamp " ")))
       (setq org-log-post-message msg)
-      (message msg))))
+      (message "%s" msg))))
 
 (defun org-show-todo-tree (arg)
   "Make a compact tree which shows all headlines marked with TODO.
@@ -13978,7 +13979,7 @@
   (with-current-buffer (marker-buffer org-log-note-return-to)
     (goto-char org-log-note-return-to))
   (move-marker org-log-note-return-to nil)
-  (and org-log-post-message (message org-log-post-message)))
+  (and org-log-post-message (message "%s" org-log-post-message)))
 
 ;; FIXME: what else would be useful?
 ;; - priority
@@ -15216,10 +15217,10 @@
    (let* ((prop (completing-read
 		 "Property: " (org-entry-properties nil 'standard))))
      (list prop)))
-  (message (concat "Property " property
-		   (if (org-entry-delete nil property)
-		       " deleted"
-		     " was not present in the entry"))))
+  (message "Property %s %s" property
+	   (if (org-entry-delete nil property)
+	       "deleted"
+	     "was not present in the entry")))
 
 (defun org-delete-property-globally (property)
   "Remove PROPERTY globally, from all entries."
@@ -16863,7 +16864,7 @@
 	d (floor (+ (/ diff ds) 0.5))
 	h 0 m 0))
      (if (not to-buffer)
-	 (message (org-make-tdiff-string y d h m))
+	 (message "%s" (org-make-tdiff-string y d h m))
        (when (org-at-table-p)
 	 (goto-char match-end)
 	 (setq align t)
@@ -18806,7 +18807,7 @@
 			(org-install-agenda-files-menu)
 			(message "New agenda file list installed"))
 		      nil 'local)
-	(message (substitute-command-keys
+	(message "%s" (substitute-command-keys
 		  "Edit list and finish with \\[save-buffer]")))
     (customize-variable 'org-agenda-files)))
 
--- a/lisp/textmodes/reftex-index.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/textmodes/reftex-index.el	Sun Dec 16 05:08:49 2007 +0000
@@ -367,7 +367,7 @@
             (goto-char (or pos (point-min)))
             (or (looking-at re)
                 (reftex-nearest-match re (length literal))))
-           (t (message reftex-no-follow-message) nil))))
+           (t (message "%s" reftex-no-follow-message) nil))))
     (when match
       (goto-char (match-beginning 0))
       (recenter '(4))
--- a/lisp/textmodes/reftex-toc.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/textmodes/reftex-toc.el	Sun Dec 16 05:08:49 2007 +0000
@@ -626,7 +626,7 @@
             (message "%d section%s %smoted" 
                      nsec (if (= 1 nsec) "" "s") pro-or-de)
             nil))
-    (if msg (progn (ding) (message msg)))))
+    (if msg (progn (ding) (message "%s" msg)))))
 
 
 (defun reftex-toc-restore-region (point-line &optional mark-line)
@@ -833,7 +833,7 @@
                     (switch-to-buffer-other-window 
                      (reftex-get-file-buffer-force file nil))
                     (goto-char (if (eq where 'bof) (point-min) (point-max))))
-                (message reftex-no-follow-message) nil))))
+                (message "%s" reftex-no-follow-message) nil))))
 
      ((stringp (car toc))
       ;; a label
@@ -900,7 +900,7 @@
                        (reftex-make-regexp-allow-for-ctrl-m literal) len)
                       (reftex-nearest-match
                        (reftex-make-desperate-section-regexp literal) len)))))
-           (t (message reftex-no-follow-message) nil))))
+           (t (message "%s" reftex-no-follow-message) nil))))
     (when match
       (goto-char (match-beginning 0))
       (if (not (= (point) (point-max))) (recenter 1))
--- a/lisp/textmodes/reftex.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/textmodes/reftex.el	Sun Dec 16 05:08:49 2007 +0000
@@ -1978,7 +1978,7 @@
   (let ((char ?\?))
     (save-window-excursion
       (catch 'exit
-        (message (concat prompt "   (?=Help)"))
+        (message "%s   (?=Help)" prompt)
         (when (or (sit-for (or delay-time 0))
                   (= ?\? (setq char (read-char-exclusive))))
           (reftex-kill-buffer "*RefTeX Select*")
@@ -1994,17 +1994,17 @@
                  (pos-visible-in-window-p (point-max)))
             nil
           (setq prompt (concat prompt (if scroll "   (SPC/DEL=Scroll)" ""))))
-        (message prompt)
+        (message "%s" prompt)
         (and (equal char ?\?) (setq char (read-char-exclusive)))
         (while t
           (cond ((equal char ?\C-g) (keyboard-quit))
                 ((equal char ?\?))
                 ((and scroll (equal char ?\ ))
                  (condition-case nil (scroll-up) (error nil))
-                 (message prompt))
+                 (message "%s" prompt))
                 ((and scroll (equal char ?\C-? ))
                  (condition-case nil (scroll-down) (error nil))
-                 (message prompt))
+                 (message "%s" prompt))
                 (t (message "") 
                    (throw 'exit char)))
           (setq char (read-char-exclusive)))))))
--- a/lisp/textmodes/texinfmt.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/textmodes/texinfmt.el	Sun Dec 16 05:08:49 2007 +0000
@@ -2061,9 +2061,8 @@
             (apply '+ texinfo-multitable-width-list))))
       (if (> desired-columns fill-column)
           (error
-           (format
-            "Multi-column table width, %d chars, is greater than page width, %d chars."
-            desired-columns fill-column))))
+           "Multi-column table width, %d chars, is greater than page width, %d chars."
+            desired-columns fill-column)))
     texinfo-multitable-width-list))
 
 ;; @item  A1  @tab  A2  @tab  A3
--- a/lisp/url/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/url/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,12 @@
+2007-12-11  Glenn Morris  <rgm@gnu.org>
+
+	* url.el (url-configuration-directory): Make it a defcustom.
+
+	* url-util.el (url-make-private-file): New function.
+	* url-cookie.el (url-cookie-write-file):
+	* url-history.el (url-history-save-history):
+	Use url-make-private-file and with-temp-buffer.
+
 2007-12-06  Glenn Morris  <rgm@gnu.org>
 
 	* url-file.el, url-mailto.el: Remove directory part from filenames
--- a/lisp/url/url-cookie.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/url/url-cookie.el	Sun Dec 16 05:08:49 2007 +0000
@@ -119,19 +119,17 @@
     (set var new)))
 
 (defun url-cookie-write-file (&optional fname)
-  (setq fname (or fname url-cookie-file))
-  (unless (file-directory-p (file-name-directory fname))
-    (ignore-errors (make-directory (file-name-directory fname))))
-  (cond
-   ((not url-cookies-changed-since-last-save) nil)
-   ((not (file-writable-p fname))
-    (message "Cookies file %s (see variable `url-cookie-file') is unwritable." fname))
-   (t
+  (when url-cookies-changed-since-last-save
+    (or fname (setq fname (expand-file-name url-cookie-file)))
+    (if (condition-case nil
+            (progn
+              (url-make-private-file fname)
+              nil)
+          (error t))
+        (message "Error accessing cookie file `%s'" fname)
     (url-cookie-clean-up)
     (url-cookie-clean-up t)
-    (with-current-buffer (get-buffer-create " *cookies*")
-      (erase-buffer)
-      (fundamental-mode)
+    (with-temp-buffer
       (insert ";; Emacs-W3 HTTP cookies file\n"
 	      ";; Automatically generated file!!! DO NOT EDIT!!!\n\n"
 	      "(setq url-cookie-storage\n '")
@@ -144,9 +142,8 @@
               ";; no-byte-compile: t\n"
               ";; End:\n")
       (set (make-local-variable 'version-control) 'never)
-      (write-file fname)
-      (setq url-cookies-changed-since-last-save nil)
-      (kill-buffer (current-buffer))))))
+      (write-file fname))
+    (setq url-cookies-changed-since-last-save nil))))
 
 (defun url-cookie-store (name value &optional expires domain localpart secure)
   "Store a netscape-style cookie."
--- a/lisp/url/url-history.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/url/url-history.el	Sun Dec 16 05:08:49 2007 +0000
@@ -112,29 +112,28 @@
   (puthash (if (vectorp url) (url-recreate-url url) url) time
            url-history-hash-table))
 
+(autoload 'url-make-private-file "url-util")
+
 (defun url-history-save-history (&optional fname)
   "Write the global history file into `url-history-file'.
 The type of data written is determined by what is in the file to begin
 with.  If the type of storage cannot be determined, then prompt the
 user for what type to save as."
   (interactive)
-  (or fname (setq fname (expand-file-name url-history-file)))
-  (unless (file-directory-p (file-name-directory fname))
-    (condition-case nil
-        (make-directory (file-name-directory fname))
-      (error nil)))
-  (cond
-   ((not url-history-changed-since-last-save) nil)
-   ((not (file-writable-p fname))
-    (message "%s is unwritable." fname))
-   (t
-    (let ((make-backup-files nil)
-	  (version-control nil)
-	  (require-final-newline t))
-      (with-current-buffer (get-buffer-create " *url-tmp*")
-	(erase-buffer)
-	(let ((count 0))
-	  (maphash (lambda (key value)
+  (when url-history-changed-since-last-save
+    (or fname (setq fname (expand-file-name url-history-file)))
+    (if (condition-case nil
+            (progn
+              (url-make-private-file fname)
+              nil)
+          (error t))
+        (message "Error accessing history file `%s'" fname)
+      (let ((make-backup-files nil)
+            (version-control nil)
+            (require-final-newline t)
+            (count 0))
+        (with-temp-buffer
+          (maphash (lambda (key value)
                      (while (string-match "[\r\n]+" key)
                        (setq key (concat (substring key 0 (match-beginning 0))
                                          (substring key (match-end 0) nil))))
@@ -153,9 +152,8 @@
 	  ;;          (/ count 4)))
 	  ;; (goto-char (point-max))
 	  (insert "\n")
-	  (write-file fname))
-	(kill-buffer (current-buffer))))))
-  (setq url-history-changed-since-last-save nil))
+	  (write-file fname)))
+      (setq url-history-changed-since-last-save nil))))
 
 (defun url-have-visited-url (url)
   (url-do-setup)
--- a/lisp/url/url-util.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/url/url-util.el	Sun Dec 16 05:08:49 2007 +0000
@@ -523,6 +523,28 @@
       (set (make-local-variable 'url-current-mime-headers)
 	   (mail-header-extract)))))
 
+(defun url-make-private-file (file)
+  "Make FILE only readable and writable by the current user.
+Creates FILE and its parent directories if they do not exist."
+  (let ((dir (file-name-directory file)))
+    (when dir
+      ;; For historical reasons.
+      (make-directory dir t)))
+  ;; Based on doc-view-make-safe-dir.
+  (condition-case nil
+      (let ((umask (default-file-modes)))
+        (unwind-protect
+            (progn
+              (set-default-file-modes #o0600)
+              (with-temp-buffer
+                (write-region (point-min) (point-max)
+                              file nil 'silent nil 'excl)))
+          (set-default-file-modes umask)))
+    (file-already-exists
+     (if (file-symlink-p file)
+         (error "Danger: `%s' is a symbolic link" file))
+     (set-file-modes file #o0600))))
+
 (provide 'url-util)
 
 ;; arch-tag: 24352abc-5a5a-412e-90cd-313b26bed5c9
--- a/lisp/url/url.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/url/url.el	Sun Dec 16 05:08:49 2007 +0000
@@ -46,13 +46,16 @@
 (require 'url-parse)
 (require 'url-util)
 
-;; Fixme: customize? convert-standard-filename?
-(defvar url-configuration-directory
-  (cond
-   ((file-directory-p "~/.url") "~/.url")
-   ((file-directory-p user-emacs-directory)
-    (concat user-emacs-directory "url"))
-   (t "~/.url")))
+
+;; FIXME convert-standard-filename?
+(defcustom url-configuration-directory
+  (if (and (file-directory-p user-emacs-directory)
+           (not (file-directory-p "~/.url")))
+      (expand-file-name "url" user-emacs-directory)
+    "~/.url")
+  "Directory used by the URL package for cookies, history, etc."
+  :type 'directory
+  :group 'url)
 
 (defun url-do-setup ()
   "Setup the url package.
--- a/lisp/vc-cvs.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/vc-cvs.el	Sun Dec 16 05:08:49 2007 +0000
@@ -351,7 +351,7 @@
        ((re-search-forward "Up-to-date check failed" nil t)
 	(mapc (lambda (file) (vc-file-setprop file 'vc-state 'needs-merge))
 	      files)
-        (error (substitute-command-keys
+        (error "%s" (substitute-command-keys
                 (concat "Up-to-date check failed: "
                         "type \\[vc-next-action] to merge in changes"))))
        (t
--- a/lisp/vc-mcvs.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/vc-mcvs.el	Sun Dec 16 05:08:49 2007 +0000
@@ -294,7 +294,7 @@
        ((re-search-forward "Up-to-date check failed" nil t)
 	(mapc (lambda (file) (vc-file-setprop file 'vc-state 'needs-merge))
 	      files)
-        (error (substitute-command-keys
+        (error "%s" (substitute-command-keys
                 (concat "Up-to-date check failed: "
                         "type \\[vc-next-action] to merge in changes"))))
        (t
--- a/lisp/vc.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/vc.el	Sun Dec 16 05:08:49 2007 +0000
@@ -2619,13 +2619,13 @@
 	(vc-checkout file nil "")
       (if (eq (vc-checkout-model file) 'locking)
 	  (if (eq (vc-state file) 'edited)
-	      (error
-	       (substitute-command-keys
-		"File is locked--type \\[vc-revert] to discard changes"))
-	    (error
-	     (substitute-command-keys
-	      "Unexpected file state (%s)--type \\[vc-next-action] to correct")
-	     (vc-state file)))
+	      (error "%s"
+		     (substitute-command-keys
+		      "File is locked--type \\[vc-revert] to discard changes"))
+	    (error "Unexpected file state (%s) -- type %s"
+		   (vc-state file)
+		   (substitute-command-keys
+		    "\\[vc-next-action] to correct")))
 	(if (not (vc-find-backend-function (vc-backend file) 'merge-news))
 	    (error "Sorry, merging news is not implemented for %s"
 		   (vc-backend file))
--- a/lisp/wdired.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/wdired.el	Sun Dec 16 05:08:49 2007 +0000
@@ -492,7 +492,7 @@
   (if (and
        (buffer-modified-p)
        (not (y-or-n-p "Buffer changed. Discard changes and kill buffer? ")))
-      (error nil)))
+      (error "Error.")))
 
 (defun wdired-next-line (arg)
   "Move down lines then position at filename or the current column.
--- a/lisp/whitespace.el	Fri Dec 14 12:53:04 2007 +0000
+++ b/lisp/whitespace.el	Sun Dec 16 05:08:49 2007 +0000
@@ -789,8 +789,8 @@
 	(whitespace-cleanup-internal)
       (setq werr (whitespace-buffer)))
     (if (and whitespace-abort-on-error werr)
-	(error (concat "Abort write due to whitespaces in "
-		       buffer-file-name))))
+	(error "Abort write due to whitespaces in %s"
+		       buffer-file-name)))
   nil)
 
 (defun whitespace-unload-function ()
--- a/src/ChangeLog	Fri Dec 14 12:53:04 2007 +0000
+++ b/src/ChangeLog	Sun Dec 16 05:08:49 2007 +0000
@@ -1,3 +1,72 @@
+2007-12-14  Jason Rumney  <jasonr@gnu.org>
+
+	* w32term.c (w32_read_socket): Use MULTIBYTE_CHAR_KEYSTROKE_EVENT
+	for characters above 127.
+
+2007-12-13  Jason Rumney  <jasonr@gnu.org>
+
+	* w32fns.c (w32_wnd_proc, Fw32_reconstruct_hot_key): Range check
+	before dereferencing array.
+	(lookup_vk_code): Remove zero comparison.
+
+2007-12-14  Michael Albinus  <michael.albinus@gmx.de>
+
+	* dbusbind.c (xd_retrieve_value, xd_retrieve_arg)
+	(Fdbus_call_method, Fdbus_send_signal, xd_read_message): Use
+	`unsigned int' instead of `uint'.
+	(xd_read_message, Fdbus_register_signal): Split expressions into
+	multiple lines before operators "&&" and "||", according to the
+	GNU Coding Standards.
+
+2007-12-14  Eli Zaretskii  <eliz@gnu.org>
+
+	* dispextern.h (WINDOWS_NT): Fix incorrect spelling of WINDOWSNT.
+
+2007-12-12  Juri Linkov  <juri@jurta.org>
+
+	* buffer.c (Frename_buffer): In interactive spec replace
+	`read-buffer' with `read-string' that uses `buffer-name-history'
+	as history, and the current buffer's name as default.
+
+2007-12-10  Stefan Monnier  <monnier@iro.umontreal.ca>
+
+	* keyboard.c (Fcommand_execute): Call Qcall_interactively instead of
+	manipulating the backtrace manually.
+	(make_lispy_event): Merge the ASCII and MULTIBYTE cases.
+	(struct backtrace, backtrace_list): Remove.
+	(command_loop_1): Remove dead var `no_direct'.
+
+	* buffer.c (reset_buffer_local_variables): If permanent_too is 0, also
+	preserve non-built-in buffer-local variables.
+	(Fkill_all_local_variables): Don't re-create&re-set permanent
+	buffer-local variables.
+
+2007-12-09  Juri Linkov  <juri@jurta.org>
+
+	* buffer.c (Frename_buffer): Change interactive spec from "s" to
+	Lisp code that uses `read-buffer' with current buffer as default.
+
+2007-12-08  Michael Albinus  <michael.albinus@gmx.de>
+
+	* dbusbind.c (xd_read_message): Generate an event for every
+	registered handler.  There might be several handlers registered
+	for the same signal.
+	(Fdbus_register_signal): Don't overwrite a registration for the
+	same signal.  Add a new registration if handlers are different.
+	(Vdbus_registered_functions_table): Rework doc string.
+
+2007-12-07  Michael Albinus  <michael.albinus@gmx.de>
+
+	* dbusbind.c (Fdbus_get_unique_name, xd_read_message)
+	(Fdbus_register_signal): Use DBUS_MAXIMUM_NAME_LENGTH and
+	DBUS_MAXIMUM_MATCH_RULE_LENGTH for string lengths.
+	(Fdbus_call_method, Fdbus_send_signal, Fdbus_register_signal):
+	Unify argument lists.
+	(xd_read_message, Fdbus_register_signal) Reorder and extend event
+	arguments and hash table keys.  Use unique name for service.
+	(Fdbus_unregister_signal): Remove checks.
+	(Vdbus_registered_functions_table): Fix doc string.
+
 2007-12-05  Magnus Henoch  <mange@freemail.hu>
 
 	* process.c (make_process): Initialize pty_flag to 0.
--- a/src/buffer.c	Fri Dec 14 12:53:04 2007 +0000
+++ b/src/buffer.c	Sun Dec 16 05:08:49 2007 +0000
@@ -107,12 +107,14 @@
 
 int last_per_buffer_idx;
 
-Lisp_Object Fset_buffer ();
-void set_buffer_internal ();
-void set_buffer_internal_1 ();
-static void call_overlay_mod_hooks ();
-static void swap_out_buffer_local_variables ();
-static void reset_buffer_local_variables ();
+EXFUN (Fset_buffer, 1);
+void set_buffer_internal P_ ((struct buffer *b));
+void set_buffer_internal_1 P_ ((struct buffer *b));
+static void call_overlay_mod_hooks P_ ((Lisp_Object list, Lisp_Object overlay,
+					int after, Lisp_Object arg1,
+					Lisp_Object arg2, Lisp_Object arg3));
+static void swap_out_buffer_local_variables P_ ((struct buffer *b));
+static void reset_buffer_local_variables P_ ((struct buffer *b, int permanent_too));
 
 /* Alist of all buffer names vs the buffers. */
 /* This used to be a variable, but is no longer,
@@ -717,7 +719,7 @@
    it does not treat permanent locals consistently.
    Instead, use Fkill_all_local_variables.
 
-   If PERMANENT_TOO is 1, then we reset permanent built-in
+   If PERMANENT_TOO is 1, then we reset permanent
    buffer-local variables.  If PERMANENT_TOO is 0,
    we preserve those.  */
 
@@ -755,7 +757,23 @@
 #endif
 
   /* Reset all (or most) per-buffer variables to their defaults.  */
-  b->local_var_alist = Qnil;
+  if (permanent_too)
+    b->local_var_alist = Qnil;
+  else
+    {
+      Lisp_Object tmp, last = Qnil;
+      for (tmp = b->local_var_alist; CONSP (tmp); tmp = XCDR (tmp))
+	if (CONSP (XCAR (tmp))
+	    && SYMBOLP (XCAR (XCAR (tmp)))
+	    && !NILP (Fget (XCAR (XCAR (tmp)), Qpermanent_local)))
+	  /* If permanent-local, keep it.  */
+	  last = tmp;
+	else if (NILP (last))
+	  b->local_var_alist = XCDR (tmp);
+	else
+	  XSETCDR (last, XCDR (tmp));
+    }
+
   for (i = 0; i < last_per_buffer_idx; ++i)
     if (permanent_too || buffer_permanent_local_flags[i] == 0)
       SET_PER_BUFFER_VALUE_P (b, i, 0);
@@ -1170,7 +1188,9 @@
 }
 
 DEFUN ("rename-buffer", Frename_buffer, Srename_buffer, 1, 2,
-       "sRename buffer (to new name): \nP",
+       "(list (read-string \"Rename buffer (to new name): \" \
+	      nil 'buffer-name-history (buffer-name (current-buffer))) \
+	      current-prefix-arg)",
        doc: /* Change current buffer's name to NEWNAME (a string).
 If second arg UNIQUE is nil or omitted, it is an error if a
 buffer named NEWNAME already exists.
@@ -2467,14 +2487,10 @@
 the normal hook `change-major-mode-hook'.  */)
      ()
 {
-  register Lisp_Object alist, sym, tem;
-  Lisp_Object oalist;
-
   if (!NILP (Vrun_hooks))
     call1 (Vrun_hooks, Qchange_major_mode_hook);
-  oalist = current_buffer->local_var_alist;
-
-  /* Make sure none of the bindings in oalist
+
+  /* Make sure none of the bindings in local_var_alist
      remain swapped in, in their symbols.  */
 
   swap_out_buffer_local_variables (current_buffer);
@@ -2483,20 +2499,6 @@
 
   reset_buffer_local_variables (current_buffer, 0);
 
-  /* Any which are supposed to be permanent,
-     make local again, with the same values they had.  */
-
-  for (alist = oalist; CONSP (alist); alist = XCDR (alist))
-    {
-      sym = XCAR (XCAR (alist));
-      tem = Fget (sym, Qpermanent_local);
-      if (! NILP (tem))
-	{
-	  Fmake_local_variable (sym);
-	  Fset (sym, XCDR (XCAR (alist)));
-	}
-    }
-
   /* Force mode-line redisplay.  Useful here because all major mode
      commands call this function.  */
   update_mode_lines++;
--- a/src/dbusbind.c	Fri Dec 14 12:53:04 2007 +0000
+++ b/src/dbusbind.c	Sun Dec 16 05:08:49 2007 +0000
@@ -112,7 +112,7 @@
    message.  */
 char *
 xd_retrieve_value (dtype, object)
-     uint dtype;
+     unsigned int dtype;
      Lisp_Object object;
 {
 
@@ -146,7 +146,7 @@
    partly supported; they result always in a Lisp list.  */
 Lisp_Object
 xd_retrieve_arg (dtype, iter)
-     uint dtype;
+     unsigned int dtype;
      DBusMessageIter *iter;
 {
 
@@ -241,7 +241,7 @@
      Lisp_Object bus;
 {
   DBusConnection *connection;
-  char name[1024];
+  char name[DBUS_MAXIMUM_NAME_LENGTH];
 
   /* Check parameters.  */
   CHECK_SYMBOL (bus);
@@ -287,8 +287,8 @@
 elements of the D-Bus container.  Example:
 
 \(dbus-call-method
-  :session "GetKeyField" "org.gnome.seahorse"
-  "/org/gnome/seahorse/keys/openpgp" "org.gnome.seahorse.Keys"
+  :session "org.gnome.seahorse" "/org/gnome/seahorse/keys/openpgp"
+  "org.gnome.seahorse.Keys" "GetKeyField"
   "openpgp:657984B8C7A966DD" "simple-name")
 
   => (t ("Philip R. Zimmermann"))
@@ -297,18 +297,18 @@
 object is returned instead of a list containing this single Lisp object.
 
 \(dbus-call-method
-  :system "GetPropertyString" "org.freedesktop.Hal"
-  "/org/freedesktop/Hal/devices/computer" "org.freedesktop.Hal.Device"
+  :system "org.freedesktop.Hal" "/org/freedesktop/Hal/devices/computer"
+  "org.freedesktop.Hal.Device" "GetPropertyString"
   "system.kernel.machine")
 
   => "i686"
 
-usage: (dbus-call-method BUS METHOD SERVICE PATH INTERFACE &rest ARGS)  */)
+usage: (dbus-call-method BUS SERVICE PATH INTERFACE METHOD &rest ARGS)  */)
      (nargs, args)
      int nargs;
      register Lisp_Object *args;
 {
-  Lisp_Object bus, method, service, path, interface;
+  Lisp_Object bus, service, path, interface, method;
   Lisp_Object result;
   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
   DBusConnection *connection;
@@ -316,29 +316,29 @@
   DBusMessage *reply;
   DBusMessageIter iter;
   DBusError derror;
-  uint dtype;
+  unsigned int dtype;
   int i;
   char *value;
 
   /* Check parameters.  */
   bus = args[0];
-  method = args[1];
-  service = args[2];
-  path = args[3];
-  interface = args[4];
+  service = args[1];
+  path = args[2];
+  interface = args[3];
+  method = args[4];
 
   CHECK_SYMBOL (bus);
-  CHECK_STRING (method);
   CHECK_STRING (service);
   CHECK_STRING (path);
   CHECK_STRING (interface);
-  GCPRO5 (bus, method, service, path, interface);
+  CHECK_STRING (method);
+  GCPRO5 (bus, service, path, interface, method);
 
   XD_DEBUG_MESSAGE ("%s %s %s %s",
-		    SDATA (method),
 		    SDATA (service),
 		    SDATA (path),
-		    SDATA (interface));
+		    SDATA (interface),
+		    SDATA (method));
 
   /* Open a connection to the bus.  */
   connection = xd_initialize (bus);
@@ -447,40 +447,41 @@
 Example:
 
 \(dbus-send-signal
-  :session "Started" "org.gnu.emacs" "/org/gnu/emacs" "org.gnu.emacs")))
+  :session "org.gnu.Emacs" "/org/gnu/Emacs"
+  "org.gnu.Emacs.FileManager" "FileModified" "/home/albinus/.emacs")
 
-usage: (dbus-send-signal BUS SIGNAL SERVICE PATH INTERFACE &rest ARGS)  */)
+usage: (dbus-send-signal BUS SERVICE PATH INTERFACE SIGNAL &rest ARGS)  */)
      (nargs, args)
      int nargs;
      register Lisp_Object *args;
 {
-  Lisp_Object bus, signal, service, path, interface;
+  Lisp_Object bus, service, path, interface, signal;
   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
   DBusConnection *connection;
   DBusMessage *dmessage;
-  uint dtype;
+  unsigned int dtype;
   int i;
   char *value;
 
   /* Check parameters.  */
   bus = args[0];
-  signal = args[1];
-  service = args[2];
-  path = args[3];
-  interface = args[4];
+  service = args[1];
+  path = args[2];
+  interface = args[3];
+  signal = args[4];
 
   CHECK_SYMBOL (bus);
-  CHECK_STRING (signal);
   CHECK_STRING (service);
   CHECK_STRING (path);
   CHECK_STRING (interface);
-  GCPRO5 (bus, signal, service, path, interface);
+  CHECK_STRING (signal);
+  GCPRO5 (bus, service, path, interface, signal);
 
   XD_DEBUG_MESSAGE ("%s %s %s %s",
-		    SDATA (signal),
 		    SDATA (service),
 		    SDATA (path),
-		    SDATA (interface));
+		    SDATA (interface),
+		    SDATA (signal));
 
   /* Open a connection to the bus.  */
   connection = xd_initialize (bus);
@@ -542,14 +543,17 @@
 xd_read_message (bus)
      Lisp_Object bus;
 {
-  Lisp_Object key;
+  Lisp_Object args, key, value;
   struct gcpro gcpro1;
   static struct input_event event;
   DBusConnection *connection;
   DBusMessage *dmessage;
   DBusMessageIter iter;
-  uint dtype;
-  char service[1024], path[1024], interface[1024], member[1024];
+  unsigned int dtype;
+  char uname[DBUS_MAXIMUM_NAME_LENGTH];
+  char path[DBUS_MAXIMUM_MATCH_RULE_LENGTH]; /* Unlimited in D-Bus spec.  */
+  char interface[DBUS_MAXIMUM_NAME_LENGTH];
+  char member[DBUS_MAXIMUM_NAME_LENGTH];
 
   /* Open a connection to the bus.  */
   connection = xd_initialize (bus);
@@ -562,16 +566,11 @@
   if (dmessage == NULL)
     return;
 
-  /* There is a message in the queue.  Construct the D-Bus event.  */
   XD_DEBUG_MESSAGE ("Event received");
-  EVENT_INIT (event);
-
-  event.kind = DBUS_EVENT;
-  event.frame_or_window = Qnil;
 
   /* Collect the parameters.  */
-  event.arg = Qnil;
-  GCPRO1 (event.arg);
+  args = Qnil;
+  GCPRO1 (args);
 
   if (!dbus_message_iter_init (dmessage, &iter))
     {
@@ -583,42 +582,61 @@
   /* Loop over the resulting parameters.  Construct a list.  */
   while ((dtype = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
     {
-      event.arg = Fcons (xd_retrieve_arg (dtype, &iter), event.arg);
+      args = Fcons (xd_retrieve_arg (dtype, &iter), args);
       dbus_message_iter_next (&iter);
     }
 
   /* The arguments are stored in reverse order.  Reorder them.  */
-  event.arg = Fnreverse (event.arg);
+  args = Fnreverse (args);
 
-  /* Read service, object path interface and member from the
+  /* Read unique name, object path, interface and member from the
      message.  */
-  strcpy (service,   dbus_message_get_sender (dmessage));
+  strcpy (uname,     dbus_message_get_sender (dmessage));
   strcpy (path,      dbus_message_get_path (dmessage));
   strcpy (interface, dbus_message_get_interface (dmessage));
   strcpy (member,    dbus_message_get_member (dmessage));
 
-  /* Add them to the event.  */
-  event.arg = Fcons ((member == NULL ? Qnil : build_string (member)),
-		     event.arg);
-  event.arg = Fcons ((interface == NULL ? Qnil : build_string (interface)),
-		     event.arg);
-  event.arg = Fcons ((path == NULL ? Qnil : build_string (path)),
-		     event.arg);
-  event.arg = Fcons ((service == NULL ? Qnil : build_string (service)),
-		     event.arg);
+  /* Search for a registered function of the message.  */
+  key = list3 (bus, build_string (interface), build_string (member));
+  value = Fgethash (key, Vdbus_registered_functions_table, Qnil);
 
-  /* Add the bus symbol to the event.  */
-  event.arg = Fcons (bus, event.arg);
+  /* Loop over the registered functions.  Construct an event.  */
+  while (!NILP (value))
+    {
+      key = XCAR (value);
+      /* key has the structure (SERVICE UNAME PATH HANDLER).  */
+      if (((uname == NULL)
+	   || (NILP (XCAR (XCDR (key))))
+	   || (strcmp (uname, SDATA (XCAR (XCDR (key)))) == 0))
+	  && ((path == NULL)
+	      || (NILP (XCAR (XCDR (XCDR (key)))))
+	      || (strcmp (path, SDATA (XCAR (XCDR (XCDR (key))))) == 0))
+	  && (!NILP (XCAR (XCDR (XCDR (XCDR (key)))))))
+	{
+	  EVENT_INIT (event);
+	  event.kind = DBUS_EVENT;
+	  event.frame_or_window = Qnil;
+	  event.arg = Fcons (XCAR (XCDR (XCDR (XCDR (key)))), args);
 
-  /* Add the registered function of the message.  */
-  key = list3 (bus,
-	       (interface == NULL ? Qnil : build_string (interface)),
-	       (member == NULL ? Qnil : build_string (member)));
-  event.arg = Fcons (Fgethash (key, Vdbus_registered_functions_table, Qnil),
-		     event.arg);
+	  /* Add uname, path, interface and member to the event.  */
+	  event.arg = Fcons ((member == NULL ? Qnil : build_string (member)),
+			     event.arg);
+	  event.arg = Fcons ((interface == NULL
+			      ? Qnil : build_string (interface)),
+			     event.arg);
+	  event.arg = Fcons ((path == NULL ? Qnil : build_string (path)),
+			     event.arg);
+	  event.arg = Fcons ((uname == NULL ? Qnil : build_string (uname)),
+			     event.arg);
 
-  /* Store it into the input event queue.  */
-  kbd_buffer_store_event (&event);
+	  /* Add the bus symbol to the event.  */
+	  event.arg = Fcons (bus, event.arg);
+
+	  /* Store it into the input event queue.  */
+	  kbd_buffer_store_event (&event);
+	}
+     value = XCDR (value);
+    }
 
   /* Cleanup.  */
   dbus_message_unref (dmessage);
@@ -666,31 +684,42 @@
   (message "Device %s added" device))
 
 \(dbus-register-signal
-  :system "DeviceAdded"
-  (dbus-get-name-owner :system "org.freedesktop.Hal")
-  "/org/freedesktop/Hal/Manager" "org.freedesktop.Hal.Manager"
-  'my-signal-handler)
+  :system "org.freedesktop.Hal" "/org/freedesktop/Hal/Manager"
+  "org.freedesktop.Hal.Manager" "DeviceAdded" 'my-signal-handler)
 
-  => (:system "org.freedesktop.Hal.Manager" "DeviceAdded")
+  => (:system ":1.3" "/org/freedesktop/Hal/Manager"
+      "org.freedesktop.Hal.Manager" "DeviceAdded")
 
 `dbus-register-signal' returns an object, which can be used in
 `dbus-unregister-signal' for removing the registration.  */)
-     (bus, signal, service, path, interface, handler)
-     Lisp_Object bus, signal, service, path, interface, handler;
+     (bus, service, path, interface, signal, handler)
+     Lisp_Object bus, service, path, interface, signal, handler;
 {
-  Lisp_Object key;
+  Lisp_Object unique_name, key, value;
   DBusConnection *connection;
-  char rule[1024];
+  char rule[DBUS_MAXIMUM_MATCH_RULE_LENGTH];
   DBusError derror;
 
   /* Check parameters.  */
   CHECK_SYMBOL (bus);
-  CHECK_STRING (signal);
   if (!NILP (service)) CHECK_STRING (service);
   if (!NILP (path)) CHECK_STRING (path);
   CHECK_STRING (interface);
+  CHECK_STRING (signal);
   CHECK_SYMBOL (handler);
 
+  /* Retrieve unique name of service.  If service is a known name, we
+     will register for the corresponding unique name, if any.  Signals
+     are sent always with the unique name as sender.  Note: the unique
+     name of "org.freedesktop.DBus" is that string itself.  */
+  if ((!NILP (service))
+      && (strlen (SDATA (service)) > 0)
+      && (strcmp (SDATA (service), DBUS_SERVICE_DBUS) != 0)
+      && (strncmp (SDATA (service), ":", 1) != 0))
+    unique_name = call2 (intern ("dbus-get-name-owner"), bus, service);
+  else
+    unique_name = service;
+
   /* Open a connection to the bus.  */
   connection = xd_initialize (bus);
 
@@ -700,9 +729,9 @@
 	   SDATA (interface),
 	   SDATA (signal));
 
-  /* Add service and path to the rule if they are non-nil.  */
-  if (!NILP (service))
-    sprintf (rule, "%s,sender='%s'%", rule, SDATA (service));
+  /* Add unique name and path to the rule if they are non-nil.  */
+  if (!NILP (unique_name))
+    sprintf (rule, "%s,sender='%s'%", rule, SDATA (unique_name));
 
   if (!NILP (path))
     sprintf (rule, "%s,path='%s'", rule, SDATA (path));
@@ -717,15 +746,21 @@
 
   /* Create a hash table entry.  */
   key = list3 (bus, interface, signal);
-  Fputhash (key, handler, Vdbus_registered_functions_table);
-  XD_DEBUG_MESSAGE ("\"%s\" registered with handler \"%s\"",
-		    SDATA (format2 ("%s", key, Qnil)),
-		    SDATA (format2 ("%s", handler, Qnil)));
+  value = Fgethash (key, Vdbus_registered_functions_table, Qnil);
+
+  if (NILP (Fmember (list4 (service, unique_name, path, handler), value)))
+    Fputhash (key,
+	      Fcons (list4 (service, unique_name, path, handler), value),
+	      Vdbus_registered_functions_table);
 
   /* Return key.  */
   return key;
 }
 
+/* The current implementation removes ALL registered functions for a
+   given signal.  Shouldn't be a problem in general, but there might
+   be cases it is not desired.  Maybe we can refine the
+   implementation.  */
 DEFUN ("dbus-unregister-signal", Fdbus_unregister_signal, Sdbus_unregister_signal,
        1, 1, 0,
        doc: /* Unregister OBJECT from the D-Bus.
@@ -734,13 +769,6 @@
      Lisp_Object object;
 {
 
-  /* Check parameters.  */
-  CHECK_SYMBOL (object);
-
-  XD_DEBUG_MESSAGE ("\"%s\" unregistered with handler \"%s\"",
-		    SDATA (format2 ("%s", object, Qnil)),
-		    SDATA (format2 ("%s", Fsymbol_function (object), Qnil)));
-
   /* Unintern the signal symbol.  */
   Fremhash (object, Vdbus_registered_functions_table);
 
@@ -788,13 +816,19 @@
 
   DEFVAR_LISP ("dbus-registered-functions-table", &Vdbus_registered_functions_table,
     doc: /* Hash table of registered functions for D-Bus.
-The key in the hash table is the list (BUS INTERFACE MEMBER).  BUS is
+The key in the hash table is the list (BUS MEMBER INTERFACE).  BUS is
 either the symbol `:system' or the symbol `:session'.  INTERFACE is a
 string which denotes a D-Bus interface, and MEMBER, also a string, is
-either a method or a signal INTERFACE is offering.
+either a method or a signal INTERFACE is offering.  All arguments but
+BUS must not be nil.
 
-The value in the hash table a the function to be called when a D-Bus
-message, which matches the key criteria, arrives.  */);
+The value in the hash table is a list of triple lists
+\((SERVICE UNAME PATH HANDLER) (SERVICE UNAME PATH HANDLER) ...).
+SERVICE is the service name as registered, UNAME is the corresponding
+unique name.  PATH is the object path of the sending object.  All of
+them be nil, which means a wildcard then.  HANDLER is the function to
+be called when a D-Bus message, which matches the key criteria,
+arrives.  */);
   /* We initialize Vdbus_registered_functions_table in dbus.el,
      because we need to define a hash table function first.  */
   Vdbus_registered_functions_table = Qnil;
--- a/src/dispextern.h	Fri Dec 14 12:53:04 2007 +0000
+++ b/src/dispextern.h	Sun Dec 16 05:08:49 2007 +0000
@@ -2785,7 +2785,7 @@
 int update_window_fringes P_ ((struct window *, int));
 void compute_fringe_widths P_ ((struct frame *, int));
 
-#ifdef WINDOWS_NT
+#ifdef WINDOWSNT
 void w32_init_fringe P_ ((struct redisplay_interface *));
 void w32_reset_fringes P_ ((void));
 #endif
--- a/src/keyboard.c	Fri Dec 14 12:53:04 2007 +0000
+++ b/src/keyboard.c	Sun Dec 16 05:08:49 2007 +0000
@@ -108,21 +108,6 @@
 #define KBD_BUFFER_SIZE 4096
 #endif	/* No X-windows */
 
-/* Following definition copied from eval.c */
-
-struct backtrace
-  {
-    struct backtrace *next;
-    Lisp_Object *function;
-    Lisp_Object *args;	/* Points to vector of args. */
-    int nargs;		/* length of vector.  If nargs is UNEVALLED,
-			   args points to slot holding list of
-			   unevalled args */
-    char evalargs;
-    /* Nonzero means call value of debugger when done with this operation. */
-    char debug_on_exit;
-  };
-
 #ifdef MULTI_KBOARD
 KBOARD *initial_kboard;
 KBOARD *current_kboard;
@@ -175,8 +160,6 @@
 
 extern int message_enable_multibyte;
 
-extern struct backtrace *backtrace_list;
-
 /* If non-nil, the function that implements the display of help.
    It's called with one argument, the help string to display.  */
 
@@ -1565,7 +1548,6 @@
   int nonundocount;
   Lisp_Object keybuf[30];
   int i;
-  int no_direct;
   int prev_modiff = 0;
   struct buffer *prev_buffer = NULL;
 #if 0 /* This shouldn't be necessary anymore.  --lorentey  */
@@ -1625,8 +1607,6 @@
       while (pending_malloc_warning)
 	display_malloc_warning ();
 
-      no_direct = 0;
-
       Vdeactivate_mark = Qnil;
 
       /* If minibuffer on and echo area in use,
@@ -1787,7 +1767,7 @@
 	}
       else
 	{
-	  if (NILP (current_kboard->Vprefix_arg) && ! no_direct)
+	  if (NILP (current_kboard->Vprefix_arg))
 	    {
 	      /* In case we jump to directly_done.  */
 	      Vcurrent_prefix_arg = current_kboard->Vprefix_arg;
@@ -5558,41 +5538,32 @@
     {
       /* A simple keystroke.  */
     case ASCII_KEYSTROKE_EVENT:
-      {
-	Lisp_Object lispy_c;
-	int c = event->code & 0377;
-	/* Turn ASCII characters into control characters
-	   when proper.  */
-	if (event->modifiers & ctrl_modifier)
-	  c = make_ctrl_char (c);
-
-	/* Add in the other modifier bits.  We took care of ctrl_modifier
-	   just above, and the shift key was taken care of by the X code,
-	   and applied to control characters by make_ctrl_char.  */
-	c |= (event->modifiers
-	      & (meta_modifier | alt_modifier
-		 | hyper_modifier | super_modifier));
-	/* Distinguish Shift-SPC from SPC.  */
-	if ((event->code & 0377) == 040
-	    && event->modifiers & shift_modifier)
-	  c |= shift_modifier;
-	button_down_time = 0;
-	XSETFASTINT (lispy_c, c);
-	return lispy_c;
-      }
-
     case MULTIBYTE_CHAR_KEYSTROKE_EVENT:
       {
 	Lisp_Object lispy_c;
 	int c = event->code;
-
-	/* Add in the other modifier bits.  We took care of ctrl_modifier
-	   just above, and the shift key was taken care of by the X code,
-	   and applied to control characters by make_ctrl_char.  */
+	if (event->kind == ASCII_KEYSTROKE_EVENT)
+	  {
+	    c &= 0377;
+	    eassert (c == event->code);
+	    /* Turn ASCII characters into control characters
+	       when proper.  */
+	    if (event->modifiers & ctrl_modifier)
+	      {
+		c = make_ctrl_char (c);
+		event->modifiers &= ~ctrl_modifier;
+	      }
+	  }
+
+	/* Add in the other modifier bits.  The shift key was taken care
+	   of by the X code.  */
 	c |= (event->modifiers
 	      & (meta_modifier | alt_modifier
 		 | hyper_modifier | super_modifier | ctrl_modifier));
-	/* What about the `shift' modifier ?  */
+	/* Distinguish Shift-SPC from SPC.  */
+	if ((event->code) == 040
+	    && event->modifiers & shift_modifier)
+	  c |= shift_modifier;
 	button_down_time = 0;
 	XSETFASTINT (lispy_c, c);
 	return lispy_c;
@@ -9619,7 +9590,7 @@
 	    }
 
 	  GROW_RAW_KEYBUF;
-	  XVECTOR (raw_keybuf)->contents[raw_keybuf_count++] = key;
+	  ASET (raw_keybuf, raw_keybuf_count++, key);
 	}
 
       /* Clicks in non-text areas get prefixed by the symbol
@@ -10401,7 +10372,6 @@
   register Lisp_Object final;
   register Lisp_Object tem;
   Lisp_Object prefixarg;
-  struct backtrace backtrace;
   extern int debug_on_next_call;
 
   debug_on_next_call = 0;
@@ -10467,20 +10437,11 @@
     }
 
   if (CONSP (final) || SUBRP (final) || COMPILEDP (final))
-    {
-      backtrace.next = backtrace_list;
-      backtrace_list = &backtrace;
-      backtrace.function = &Qcall_interactively;
-      backtrace.args = &cmd;
-      backtrace.nargs = 1;
-      backtrace.evalargs = 0;
-      backtrace.debug_on_exit = 0;
-
-      tem = Fcall_interactively (cmd, record_flag, keys);
-
-      backtrace_list = backtrace.next;
-      return tem;
-    }
+    /* Don't call Fcall_interactively directly because we want to make
+       sure the backtrace has an entry for `call-interactively'.
+       For the same reason, pass `cmd' rather than `final'.  */
+      return call3 (Qcall_interactively, cmd, record_flag, keys);
+
   return Qnil;
 }
 
@@ -10591,7 +10552,7 @@
     bindings = Qnil;
 
   value = Qnil;
-  GCPRO2 (bindings, value);
+  GCPRO3 (bindings, value, function);
   value = Fcommand_execute (function, Qt, Qnil, Qnil);
 
   /* If the command has a key binding, print it now.  */
--- a/src/w32fns.c	Fri Dec 14 12:53:04 2007 +0000
+++ b/src/w32fns.c	Sun Dec 16 05:08:49 2007 +0000
@@ -2971,7 +2971,7 @@
 	     they don't produce WM_CHAR messages).  This ensures that
 	     indicator lights are toggled promptly on Windows 9x, for
 	     example.  */
-	  if (lispy_function_keys[wParam] != 0)
+	  if (wParam < 256 && lispy_function_keys[wParam])
 	    {
 	      windows_translate = 1;
 	      goto translate;
@@ -3093,7 +3093,7 @@
 	  break;
 	default:
 	  /* If not defined as a function key, change it to a WM_CHAR message. */
-	  if (lispy_function_keys[wParam] == 0)
+	  if (wParam > 255 || !lispy_function_keys[wParam])
 	    {
 	      DWORD modifiers = construct_console_modifiers ();
 
@@ -8366,7 +8366,7 @@
   int i;
 
   for (i = 0; i < 256; i++)
-    if (lispy_function_keys[i] != 0
+    if (lispy_function_keys[i]
 	&& strcmp (lispy_function_keys[i], key) == 0)
       return i;
 
@@ -8544,7 +8544,7 @@
   vk_code = HOTKEY_VK_CODE (hotkeyid);
   w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
 
-  if (lispy_function_keys[vk_code])
+  if (vk_code < 256 && lispy_function_keys[vk_code])
     key = intern (lispy_function_keys[vk_code]);
   else
     key = make_number (vk_code);
--- a/src/w32term.c	Fri Dec 14 12:53:04 2007 +0000
+++ b/src/w32term.c	Sun Dec 16 05:08:49 2007 +0000
@@ -4625,6 +4625,8 @@
 static int temp_index;
 static short temp_buffer[100];
 
+/* Temporarily store lead byte of DBCS input sequences.  */
+static char dbcs_lead = 0;
 
 /* Read events coming from the W32 shell.
    This routine is called by the SIGIO handler.