Replace last-command-char with last-command-event.
[bpt/emacs.git] / lisp / progmodes / verilog-mode.el
index 7bc4a18..8670d66 100644 (file)
@@ -1,38 +1,50 @@
 ;; verilog-mode.el --- major mode for editing verilog source in Emacs
-;;
 
-;; Copyright (C) 1996-2007 Free Software Foundation, Inc.
+;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+;;   2005, 2006, 2007, 2008, 2009  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
+;;     http://www.veripool.org
 ;; Keywords: languages
 
-;; This program is free software; you can redistribute it and/or modify
+;; Yoni Rabkin <yoni@rabkins.net> contacted the maintainer of this
+;; file on 19/3/2008, and the maintainer agreed that when a bug is
+;; filed in the Emacs bug reporting system against this file, a copy
+;; of the bug report be sent to the maintainer's email address.
+
+;;    This code supports Emacs 21.1 and later
+;;    And XEmacs 21.1 and later
+;;    Please do not make changes that break Emacs 21.  Thanks!
+;;
+;;
+
+;; 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 2 of the License, or
+;; the Free Software Foundation, either version 3 of the License, or
 ;; (at your option) any later version.
 
-;; This program is distributed in the hope that it will be useful,
+;; 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 this program; if not, write to the Free Software
-;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
 
 ;;; Commentary:
 
-;; This mode borrows heavily from the Pascal-mode and the cc-mode of emacs
+;; 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
+;; 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>
@@ -41,8 +53,8 @@
 ;; =======================
 
 ;; 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.
+;; 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.
@@ -52,7 +64,7 @@
 
 ;; 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
+;; 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.
 ;; <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
+;; 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))
+; (add-to-list 'auto-mode-alist '("\\.[ds]?v\\'" . verilog-mode))
 
 ;; 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
+;; 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.
 ;;
 
 ;;; History:
 ;;
-;; \f
+;; See commit history at http://www.veripool.org/verilog-mode.html
+;; (This section is required to appease checkdoc.)
+
 ;;; 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.")
+(defconst verilog-mode-version "436"
+  "Version of this Verilog mode.")
+(defconst verilog-mode-release-date "2008-09-02-GNU"
+  "Release date of this Verilog mode.")
+(defconst verilog-mode-release-emacs t
+  "If non-nil, this version of Verilog mode was released with Emacs itself.")
 
 (defun verilog-version ()
   "Inform caller of the version of this file."
   (interactive)
-  (message (concat "Using verilog-mode version " verilog-mode-version) ))
+  (message "Using verilog-mode version %s" verilog-mode-version))
 
 ;; Insure we have certain packages, and deal with it if we don't
+;; Be sure to note which Emacs flavor and version added each feature.
 (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))
-  (condition-case nil
-      (if (boundp 'current-menubar)
-         nil ;; great
-       (progn
-         (defmacro set-buffer-menubar (&rest args) nil)
-         (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.
+  ;; Provide stuff if we are XEmacs
+  (when (featurep 'xemacs)
+    (condition-case nil
+        (require 'easymenu)
+      (error nil))
+    (condition-case nil
+        (require 'regexp-opt)
+      (error nil))
+    ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
+    (condition-case nil
+        (load "skeleton")
+      (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))
+    (condition-case nil
+        (if (fboundp 'char-before)
+            nil ;; great
+          (defmacro char-before (&rest body)
+            (char-after (1- (point)))))
+      (error nil))
+    (condition-case nil
+        (require 'custom)
+      (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))
-    )
+            (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))
+      ))
+  ;; OK, do this stuff if we are NOT XEmacs:
+  (unless (featurep 'xemacs)
+    (unless (fboundp 'region-active-p)
+      (defmacro region-active-p ()
+       `(and transient-mark-mode mark-active))))
   )
+
 ;; 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
+  ;; The below were disabled when GNU Emacs 22 was released;
+  ;; perhaps some still need to be there to support Emacs 21.
+  (if (featurep 'xemacs)
+      (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'.
+                      (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)))
-    ))
+                        (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)))
+        )
+    ;; Emacs.
+    (defalias 'verilog-regexp-opt 'regexp-opt)))
 
-(defun verilog-regexp-words (a)
-  "Call 'regexp-opt' with word delimiters for the words A."
-  (concat "\\<" (verilog-regexp-opt a t) "\\>"))
+(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-easy-menu-filter (menu)
+  "Filter a easy-menu-define to support new features."
+  (cond ((not (featurep 'xemacs))
+        menu) ;; GNU Emacs - passthru
+       ;; Xemacs doesn't support :help.  Strip it.
+       ;; Recursively filter the a submenu
+       ((listp menu)
+        (mapcar 'verilog-easy-menu-filter menu))
+       ;; Look for [:help "blah"] and remove
+       ((vectorp menu)
+        (let ((i 0) (out []))
+          (while (< i (length menu))
+            (if (equal `:help (aref menu i))
+                (setq i (+ 2 i))
+              (setq out (vconcat out (vector (aref menu i)))
+                    i (1+ i))))
+          out))
+       (t menu))) ;; Default - ok
+;;(verilog-easy-menu-filter
+;;  `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
+;;     "----" ["MB" nil :help "Help MB"]))
 
 (defun verilog-customize ()
-  "Link to customize screen for Verilog."
+  "Customize variables and other settings used by Verilog-Mode."
   (interactive)
   (customize-group 'verilog-mode))
 
 (defun verilog-font-customize ()
-  "Link to customize fonts used for Verilog."
+  "Customize fonts used by Verilog-Mode."
   (interactive)
-  (customize-apropos "font-lock-*" 'faces))
+  (if (fboundp 'customize-apropos)
+      (customize-apropos "font-lock-*" 'faces)))
+
+(defun verilog-booleanp (value)
+  "Return t if VALUE is boolean.
+ This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
+ This function may be removed when Emacs 21 is no longer supported."
+  (or (equal value t) (equal value nil)))
+
+(defalias 'verilog-syntax-ppss
+  (if (fboundp 'syntax-ppss) 'syntax-ppss
+    (lambda (&optional pos) (parse-partial-sexp (point-min) (or pos (point))))))
 
 (defgroup verilog-mode nil
-  "Facilitates easy editing of Verilog source text"
+  "Facilitates easy editing of Verilog source text."
+  :version "22.2"
   :group 'languages)
 
 ; (defgroup verilog-mode-fonts nil
@@ -295,52 +318,56 @@ STRING should be given if the last search was by `string-match' on STRING."
 ;  :group 'verilog-mode)
 
 (defgroup verilog-mode-indent nil
-  "Customize indentation and highlighting of verilog source text"
+  "Customize indentation and highlighting of Verilog source text."
   :group 'verilog-mode)
 
 (defgroup verilog-mode-actions nil
-  "Customize actions on verilog source text"
+  "Customize actions on Verilog source text."
   :group 'verilog-mode)
 
 (defgroup verilog-mode-auto nil
-  "Customize AUTO actions when expanding verilog source text"
+  "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.
+  "*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)
+;; We don't mark it safe, as it's used as a shell command
 
 (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.
+  "*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)
+;; We don't mark it safe, as it's used as a shell command
 
 (defcustom verilog-simulator
   "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
-  "*Program and arguments to use to interpret verilog source.
+  "*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)
+;; We don't mark it safe, as it's used as a shell command
 
 (defcustom verilog-compiler
   "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
-  "*Program and arguments to use to compile verilog source.
+  "*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)
+;; We don't mark it safe, as it's used as a shell command
 
 (defvar verilog-tool 'verilog-linter
   "Which tool to use for building compiler-command.
@@ -360,24 +387,29 @@ 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)
+;; Note we don't use :safe, as that would break on Emacsen before 22.0.
+(put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
 
 (defcustom verilog-indent-level 3
   "*Indentation of Verilog statements with respect to containing block."
   :group 'verilog-mode-indent
   :type 'integer)
+(put 'verilog-indent-level 'safe-local-variable 'integerp)
 
 (defcustom verilog-indent-level-module 3
-  "*Indentation of Module level Verilog statements.  (eg always, initial)
+  "*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)
+(put 'verilog-indent-level-module 'safe-local-variable 'integerp)
 
 (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)
+(put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
 
 (defcustom verilog-indent-declaration-macros nil
   "*How to treat macro expansions in a declaration.
@@ -391,6 +423,7 @@ If non nil, treat as:
        output       c;"
   :group 'verilog-mode-indent
   :type 'boolean)
+(put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
 
 (defcustom verilog-indent-lists t
   "*How to treat indenting items in a list.
@@ -403,69 +436,81 @@ If nil, treat as:
           reset ) begin"
   :group 'verilog-mode-indent
   :type 'boolean)
+(put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
 
 (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)
+(put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
 
 (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)
+(put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
 
 (defcustom verilog-cexp-indent 2
   "*Indentation of Verilog statements split across lines."
   :group 'verilog-mode-indent
   :type 'integer)
+(put 'verilog-cexp-indent 'safe-local-variable 'integerp)
 
 (defcustom verilog-case-indent 2
   "*Indentation for case statements."
   :group 'verilog-mode-indent
   :type 'integer)
+(put 'verilog-case-indent 'safe-local-variable 'integerp)
 
 (defcustom verilog-auto-newline t
   "*True means automatically newline after semicolons."
   :group 'verilog-mode-indent
   :type 'boolean)
+(put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
 
 (defcustom verilog-auto-indent-on-newline t
   "*True means automatically indent line after newline."
   :group 'verilog-mode-indent
   :type 'boolean)
+(put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
 
 (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."
+A nil value means TAB will only reindent when at the beginning of the line."
   :group 'verilog-mode-indent
   :type 'boolean)
+(put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
 
 (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)
+(put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
 
 (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 )
+  :type 'boolean)
+(put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
 
 
 (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 )
+  :type 'boolean)
+(put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
 
 (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"
+default avoids too many redundant comments in tight quarters."
   :group 'verilog-mode-indent
   :type 'integer)
+(put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
 
 (defcustom verilog-auto-lineup '(declaration)
   "*Algorithm for lining up statements on multiple lines.
@@ -505,23 +550,35 @@ would become
 ;
 
   :group 'verilog-mode-indent
-  :type 'list )
+  :type 'list)
+(put 'verilog-auto-lineup 'safe-local-variable 'listp)
 
 (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"
+  "*True means highlight words newly reserved by IEEE-1800.
+These will appear in `verilog-font-lock-p1800-face' in order to gently
+suggest changing where these words are used as variables to something else.
+A nil value 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)
+(put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
+
+(defcustom verilog-highlight-grouping-keywords nil
+  "*True means highlight grouping keywords 'begin' and 'end' more dramatically.
+If false, these words are in the font-lock-type-face; if True then they are in
+`verilog-font-lock-ams-face'. Some find that special highlighting on these
+grouping constructs allow the structure of the code to be understood at a glance."
   :group 'verilog-mode-indent
   :type 'boolean)
+(put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
 
 (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 )
+  :type 'boolean)
+(put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
 
 (defcustom verilog-auto-read-includes nil
   "*True means to automatically read includes before AUTOs.
@@ -530,7 +587,8 @@ 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 )
+  :type 'boolean)
+(put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
 
 (defcustom verilog-auto-save-policy nil
   "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
@@ -551,16 +609,18 @@ 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)
+(put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
 
 (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.
+A nil value 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)
+(put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
 
 (defvar verilog-auto-update-tick nil
   "Modification tick at which autos were last performed.")
@@ -600,7 +660,7 @@ always be saved."
        ; 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."
+;  "*List of regexps for Verilog compilers, like verilint. See compilation-error-regexp-alist for the formatting."
 )
 
 (defvar verilog-error-font-lock-keywords
@@ -648,8 +708,7 @@ always be saved."
     ("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."
-  )
+  "*Keywords to also highlight in Verilog *compilation* buffers.")
 
 (defcustom verilog-library-flags '("")
   "*List of standard Verilog arguments to use for /*AUTOINST*/.
@@ -674,12 +733,13 @@ something like:
     // 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
+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))
+(put 'verilog-library-flags 'safe-local-variable 'listp)
 
 (defcustom verilog-library-directories '(".")
   "*List of directories when looking for files for /*AUTOINST*/.
@@ -695,16 +755,18 @@ something like:
     // 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
+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))
+(put 'verilog-library-directories 'safe-local-variable 'listp)
 
 (defcustom verilog-library-files '()
-  "*List of files to search for modules when looking for AUTOINST files.
+  "*List of files to search for modules.
+AUTOINST will use this when it needs to resolve a module name.
 This is a complete path, usually to a technology file with many standard
 cells defined in it.
 
@@ -716,18 +778,20 @@ something like:
     // 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
+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))
+(put 'verilog-library-files 'safe-local-variable 'listp)
 
-(defcustom verilog-library-extensions '(".v")
+(defcustom verilog-library-extensions '(".v" ".sv")
   "*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)
+(put 'verilog-library-extensions 'safe-local-variable 'listp)
 
 (defcustom verilog-active-low-regexp nil
   "*If set, treat signals matching this regexp as active low.
@@ -735,44 +799,87 @@ 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)
+(put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
 
 (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)
+  :group 'verilog-mode-auto
+  :type 'boolean)
+(put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
 
 (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)
+of each Verilog file that requires it, rather than being set globally."
+  :group 'verilog-mode-auto
+  :type 'boolean)
+(put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
 
 (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."
+the MSB or LSB of a signal inside an AUTORESET."
   :type 'boolean
   :group 'verilog-mode-auto)
+(put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
 
 (defcustom verilog-assignment-delay ""
   "*Text used for delays in delayed assignments.  Add a trailing space if set."
-  :type 'string
-  :group 'verilog-mode-auto)
+  :group 'verilog-mode-auto
+  :type 'string)
+(put 'verilog-assignment-delay 'safe-local-variable 'stringp)
+
+(defcustom verilog-auto-inst-param-value nil
+  "*If set, AUTOINST will replace parameters with the parameter value.
+If nil, leave parameters as symbolic names.
+
+Parameters must be in Verilog 2001 format #(...), and if a parameter is not
+listed as such there (as when the default value is acceptable), it will not
+be replaced, and will remain symbolic.
+
+For example, imagine a submodule uses parameters to declare the size of its
+inputs.  This is then used by a upper module:
+
+       module InstModule (o,i)
+          parameter WIDTH;
+          input [WIDTH-1:0] i;
+       endmodule
+
+       module ExampInst;
+          InstModule
+            #(PARAM(10))
+           instName
+            (/*AUTOINST*/
+             .i        (i[PARAM-1:0]));
+
+Note even though PARAM=10, the AUTOINST has left the parameter as a
+symbolic name.  If `verilog-auto-inst-param-value' is set, this will
+instead expand to:
+
+       module ExampInst;
+          InstModule
+            #(PARAM(10))
+           instName
+            (/*AUTOINST*/
+             .i        (i[9:0]));"
+  :group 'verilog-mode-auto
+  :type 'boolean)
+(put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
 
 (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."
+declare the wire to have the subscripts removed.)  Setting this to nil may
+speed up some simulators, but is less general and harder to read, so avoid."
   :group 'verilog-mode-auto
-  :type 'boolean )
+  :type 'boolean)
+(put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
 
 (defcustom verilog-auto-inst-template-numbers nil
   "*If true, when creating templated ports with AUTOINST, add a comment.
@@ -780,80 +887,89 @@ 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 )
+  :type 'boolean)
+(put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
 
-(defvar verilog-auto-inst-column 40
-  "Column number for first part of auto-inst.")
+(defcustom verilog-auto-inst-column 40
+  "*Indent-to column number for net name part of AUTOINST created pin."
+  :group 'verilog-mode-indent
+  :type 'integer)
+(put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
 
 (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 )
+  :type 'string)
+(put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
 
 (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 )
+  :type 'string)
+(put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
 
 (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 )
+  :type 'string)
+(put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
 
 (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 )
+  :type 'string)
+(put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
 
 (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 )
+  :type 'string)
+(put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
 
 (defcustom verilog-mode-hook   'verilog-set-compile-command
-  "*Hook (List of functions) run after verilog mode is loaded."
+  "*Hook 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)
+  :group 'verilog-mode-auto
+  :type 'hook)
 
 (defcustom verilog-before-auto-hook nil
   "*Hook run before `verilog-mode' updates AUTOs."
-  :type 'hook
-  :group 'verilog-mode-auto)
+  :group 'verilog-mode-auto
+  :type 'hook)
 
 (defcustom verilog-delete-auto-hook nil
   "*Hook run after `verilog-mode' deletes AUTOs."
-  :type 'hook
-  :group 'verilog-mode-auto)
+  :group 'verilog-mode-auto
+  :type 'hook)
 
 (defcustom verilog-before-delete-auto-hook nil
   "*Hook run before `verilog-mode' deletes AUTOs."
-  :type 'hook
-  :group 'verilog-mode-auto)
+  :group 'verilog-mode-auto
+  :type 'hook)
 
 (defcustom verilog-getopt-flags-hook nil
   "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
-  :type 'hook
-  :group 'verilog-mode-auto)
+  :group 'verilog-mode-auto
+  :type 'hook)
 
 (defcustom verilog-before-getopt-flags-hook nil
   "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
-  :type 'hook
-  :group 'verilog-mode-auto)
+  :group 'verilog-mode-auto
+  :type 'hook)
 
 (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'.")
+  "Imenu expression for Verilog mode.  See `imenu-generic-expression'.")
 
 ;;
 ;; provide a verilog-header function.
@@ -865,12 +981,14 @@ 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.
+  "*Default name of Company for Verilog header.
 If set will become buffer local.")
+(make-variable-buffer-local 'verilog-company)
 
 (defvar verilog-project nil
-  "*Default name of Project for verilog header.
+  "*Default name of Project for Verilog header.
 If set will become buffer local.")
+(make-variable-buffer-local 'verilog-project)
 
 (defvar verilog-mode-map
   (let ((map (make-sparse-keymap)))
@@ -891,7 +1009,6 @@ If set will become buffer local.")
     (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)
@@ -901,8 +1018,10 @@ If set will become buffer local.")
     (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)
+    (when (featurep 'xemacs)
+      (define-key map [(meta control h)] 'verilog-mark-defun)
+      (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)
@@ -914,144 +1033,225 @@ If set will become buffer local.")
   "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)
+(easy-menu-define
+  verilog-menu verilog-mode-map "Menu for Verilog mode"
+  (verilog-easy-menu-filter
+   '("Verilog"
+     ("Choose Compilation Action"
+      ["None"
+       (progn
+        (setq verilog-tool nil)
+        (verilog-set-compile-command))
+       :style radio
+       :selected (equal verilog-tool nil)
+       :help "When invoking compilation, use compile-command"]
+      ["Lint"
+       (progn
+        (setq verilog-tool 'verilog-linter)
+        (verilog-set-compile-command))
+       :style radio
+       :selected (equal verilog-tool `verilog-linter)
+       :help "When invoking compilation, use lint checker"]
+      ["Coverage"
+       (progn
+        (setq verilog-tool 'verilog-coverage)
+        (verilog-set-compile-command))
+       :style radio
+       :selected (equal verilog-tool `verilog-coverage)
+       :help "When invoking compilation, annotate for coverage"]
+      ["Simulator"
+       (progn
+        (setq verilog-tool 'verilog-simulator)
+        (verilog-set-compile-command))
+       :style radio
+       :selected (equal verilog-tool `verilog-simulator)
+       :help "When invoking compilation, interpret Verilog source"]
+      ["Compiler"
+       (progn
+        (setq verilog-tool 'verilog-compiler)
+        (verilog-set-compile-command))
+       :style radio
+       :selected (equal verilog-tool `verilog-compiler)
+       :help "When invoking compilation, compile Verilog source"]
+      )
+     ("Move"
+      ["Beginning of function"         verilog-beg-of-defun
+       :keys "C-M-a"
+       :help           "Move backward to the beginning of the current function or procedure"]
+      ["End of function"               verilog-end-of-defun
+       :keys "C-M-e"
+       :help           "Move forward to the end of the current function or procedure"]
+      ["Mark function"                 verilog-mark-defun
+       :keys "C-M-h"
+       :help           "Mark the current Verilog function or procedure"]
+      ["Goto function/module"          verilog-goto-defun
+       :help           "Move to specified Verilog module/task/function"]
+      ["Move to beginning of block"    electric-verilog-backward-sexp
+       :help           "Move backward over one balanced expression"]
+      ["Move to end of block"          electric-verilog-forward-sexp
+       :help           "Move forward over one balanced expression"]
+      )
+     ("Comments"
+      ["Comment Region"                        verilog-comment-region
+       :help           "Put marked area into a comment"]
+      ["UnComment Region"              verilog-uncomment-region
+       :help           "Uncomment an area commented with Comment Region"]
+      ["Multi-line comment insert"     verilog-star-comment
+       :help           "Insert Verilog /* */ comment at point"]
+      ["Lint error to comment"         verilog-lint-off
+       :help           "Convert a Verilog linter warning line into a disable statement"]
+      )
+     "----"
+     ["Compile"                                compile
+      :help            "Perform compilation-action (above) on the current buffer"]
+     ["AUTO, Save, Compile"            verilog-auto-save-compile
+      :help            "Recompute AUTOs, save buffer, and compile"]
+     ["Next Compile Error"             next-error
+      :help            "Visit next compilation error message and corresponding source code"]
+     ["Ignore Lint Warning at point"   verilog-lint-off
+      :help            "Convert a Verilog linter warning line into a disable statement"]
+     "----"
+     ["Line up declarations around point"      verilog-pretty-declarations
+      :help            "Line up declarations around point"]
+     ["Line up equations around point"         verilog-pretty-expr
+      :help            "Line up expressions around point"]
+     ["Redo/insert comments on every end"      verilog-label-be
+      :help            "Label matching begin ... end statements"]
+     ["Expand [x:y] vector line"       verilog-expand-vector
+      :help            "Take a signal vector on the current line and expand it to multiple lines"]
+     ["Insert begin-end block"         verilog-insert-block
+      :help            "Insert begin ... end"]
+     ["Complete word"                  verilog-complete-word
+      :help            "Complete word at point"]
+     "----"
+     ["Recompute AUTOs"                        verilog-auto
+      :help            "Expand AUTO meta-comment statements"]
+     ["Kill AUTOs"                     verilog-delete-auto
+      :help            "Remove AUTO expansions"]
+     ["Inject AUTOs"                   verilog-inject-auto
+      :help            "Inject AUTOs into legacy non-AUTO buffer"]
+     ("AUTO Help..."
+      ["AUTO General"                  (describe-function 'verilog-auto)
+       :help           "Help introduction on AUTOs"]
+      ["AUTO Library Flags"            (describe-variable 'verilog-library-flags)
+       :help           "Help on verilog-library-flags"]
+      ["AUTO Library Path"             (describe-variable 'verilog-library-directories)
+       :help           "Help on verilog-library-directories"]
+      ["AUTO Library Files"            (describe-variable 'verilog-library-files)
+       :help           "Help on verilog-library-files"]
+      ["AUTO Library Extensions"       (describe-variable 'verilog-library-extensions)
+       :help           "Help on verilog-library-extensions"]
+      ["AUTO `define Reading"          (describe-function 'verilog-read-defines)
+       :help           "Help on reading `defines"]
+      ["AUTO `include Reading"         (describe-function 'verilog-read-includes)
+       :help           "Help on parsing `includes"]
+      ["AUTOARG"                       (describe-function 'verilog-auto-arg)
+       :help           "Help on AUTOARG - declaring module port list"]
+      ["AUTOASCIIENUM"                 (describe-function 'verilog-auto-ascii-enum)
+       :help           "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
+      ["AUTOINOUTCOMP"                 (describe-function 'verilog-auto-inout-complement)
+       :help           "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
+      ["AUTOINOUTMODULE"               (describe-function 'verilog-auto-inout-module)
+       :help           "Help on AUTOINOUTMODULE - copying i/o from another file"]
+      ["AUTOINOUT"                     (describe-function 'verilog-auto-inout)
+       :help           "Help on AUTOINOUT - adding inouts from cells"]
+      ["AUTOINPUT"                     (describe-function 'verilog-auto-input)
+       :help           "Help on AUTOINPUT - adding inputs from cells"]
+      ["AUTOINST"                      (describe-function 'verilog-auto-inst)
+       :help           "Help on AUTOINST - adding pins for cells"]
+      ["AUTOINST (.*)"                 (describe-function 'verilog-auto-star)
+       :help           "Help on expanding Verilog-2001 .* pins"]
+      ["AUTOINSTPARAM"                 (describe-function 'verilog-auto-inst-param)
+       :help           "Help on AUTOINSTPARAM - adding parameter pins to cells"]
+      ["AUTOOUTPUT"                    (describe-function 'verilog-auto-output)
+       :help           "Help on AUTOOUTPUT - adding outputs from cells"]
+      ["AUTOOUTPUTEVERY"               (describe-function 'verilog-auto-output-every)
+       :help           "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
+      ["AUTOREG"                       (describe-function 'verilog-auto-reg)
+       :help           "Help on AUTOREG - declaring registers for non-wires"]
+      ["AUTOREGINPUT"                  (describe-function 'verilog-auto-reg-input)
+       :help           "Help on AUTOREGINPUT - declaring inputs for non-wires"]
+      ["AUTORESET"                     (describe-function 'verilog-auto-reset)
+       :help           "Help on AUTORESET - resetting always blocks"]
+      ["AUTOSENSE"                     (describe-function 'verilog-auto-sense)
+       :help           "Help on AUTOSENSE - sensitivity lists for always blocks"]
+      ["AUTOTIEOFF"                    (describe-function 'verilog-auto-tieoff)
+       :help           "Help on AUTOTIEOFF - tieing off unused outputs"]
+      ["AUTOUNUSED"                    (describe-function 'verilog-auto-unused)
+       :help           "Help on AUTOUNUSED - terminating unused inputs"]
+      ["AUTOWIRE"                      (describe-function 'verilog-auto-wire)
+       :help           "Help on AUTOWIRE - declaring wires for cells"]
+      )
+     "----"
+     ["Submit bug report"              verilog-submit-bug-report
+      :help            "Submit via mail a bug report on verilog-mode.el"]
+     ["Version and FAQ"                        verilog-faq
+      :help            "Show the current version, and where to get the FAQ etc"]
+     ["Customize Verilog Mode..."      verilog-customize
+      :help            "Customize variables and other settings used by Verilog-Mode"]
+     ["Customize Verilog Fonts & Colors"       verilog-font-customize
+      :help            "Customize fonts used by Verilog-Mode."])))
+
+(easy-menu-define
+  verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
+  (verilog-easy-menu-filter
+   '("Statements"
+     ["Header"         verilog-sk-header
+      :help            "Insert a header block at the top of file"]
+     ["Comment"                verilog-sk-comment
+      :help            "Insert a comment block"]
+     "----"
+     ["Module"         verilog-sk-module
+      :help            "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
+     ["Primitive"      verilog-sk-primitive
+      :help            "Insert a primitive .. (.. );.. endprimitive block"]
+     "----"
+     ["Input"          verilog-sk-input
+      :help            "Insert an input declaration"]
+     ["Output"         verilog-sk-output
+      :help            "Insert an output declaration"]
+     ["Inout"          verilog-sk-inout
+      :help            "Insert an inout declaration"]
+     ["Wire"           verilog-sk-wire
+      :help            "Insert a wire declaration"]
+     ["Reg"            verilog-sk-reg
+      :help            "Insert a register declaration"]
+     ["Define thing under point as a register" verilog-sk-define-signal
+      :help            "Define signal under point as a register at the top of the module"]
+     "----"
+     ["Initial"                verilog-sk-initial
+      :help            "Insert an initial begin .. end block"]
+     ["Always"         verilog-sk-always
+      :help            "Insert an always @(AS) begin .. end block"]
+     ["Function"       verilog-sk-function
+      :help            "Insert a function .. begin .. end endfunction block"]
+     ["Task"           verilog-sk-task
+      :help            "Insert a task .. begin .. end endtask block"]
+     ["Specify"                verilog-sk-specify
+      :help            "Insert a specify .. endspecify block"]
+     ["Generate"       verilog-sk-generate
+      :help            "Insert a generate .. endgenerate block"]
+     "----"
+     ["Begin"          verilog-sk-begin
+      :help            "Insert a begin .. end block"]
+     ["If"             verilog-sk-if
+      :help            "Insert an if (..) begin .. end block"]
+     ["(if) else"      verilog-sk-else-if
+      :help            "Insert an else if (..) begin .. end block"]
+     ["For"            verilog-sk-for
+      :help            "Insert a for (...) begin .. end block"]
+     ["While"          verilog-sk-while
+      :help            "Insert a while (...) begin .. end block"]
+     ["Fork"           verilog-sk-fork
+      :help            "Insert a fork begin .. end .. join block"]
+     ["Repeat"         verilog-sk-repeat
+      :help            "Insert a repeat (..) begin .. end block"]
+     ["Case"           verilog-sk-case
+      :help            "Insert a case block, prompting for details"]
+     ["Casex"          verilog-sk-casex
+      :help            "Insert a casex (...) item: begin.. end endcase block"]
+     ["Casez"          verilog-sk-casez
+      :help            "Insert a casez (...) item: begin.. end endcase block"])))
 
 (defvar verilog-mode-abbrev-table nil
   "Abbrev table in use in Verilog-mode buffers.")
@@ -1071,7 +1271,7 @@ will break, as the o's continuously replace.  xa -> x works ok though."
   (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))))
+           start (min (length string) (+ (match-beginning 0) (length to-string)))))
     string))
 
 (defsubst verilog-string-remove-spaces (string)
@@ -1084,32 +1284,34 @@ will break, as the o's continuously replace.  xa -> x works ok though."
 (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))
+  (let ((mdata '(nil nil)))  ;; So match-end will return nil if no matches found
+    (while (and
+           (re-search-forward REGEXP BOUND NOERROR)
+           (setq mdata (match-data))
+           (and (verilog-skip-forward-comment-or-string)
+                (progn
+                  (setq mdata '(nil nil))
+                  (if BOUND
+                      (< (point) BOUND)
+                    t)))))
+    (store-match-data mdata)
+    (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))
+  (let ((mdata '(nil nil)))  ;; So match-end will return nil if no matches found
+    (while (and
+           (re-search-backward REGEXP BOUND NOERROR)
+           (setq mdata (match-data))
+           (and (verilog-skip-backward-comment-or-string)
+                (progn
+                  (setq mdata '(nil nil))
+                  (if BOUND
+                      (> (point) BOUND)
+                    t)))))
+    (store-match-data mdata)
+    (match-end 0)))
 
 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
   "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
@@ -1150,9 +1352,11 @@ so there may be a large up front penalty for the first search."
   (save-excursion
     (nth 3 (parse-partial-sexp (verilog-get-beg-of-line) (point)))))
 
+(defvar compile-command)
+
 ;; compilation program
 (defun verilog-set-compile-command ()
-  "Function to compute shell command to compile verilog.
+  "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
@@ -1173,8 +1377,8 @@ 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."
+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
@@ -1204,9 +1408,13 @@ without the directory portion, will be substituted."
           "\\b__FILE__\\b" (file-name-nondirectory (buffer-file-name))
           t t compile-command))))
 
+;; Following code only gets called from compilation-mode-hook.
+(defvar compilation-error-regexp-alist)
+
 (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."
+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)
@@ -1214,10 +1422,10 @@ Called by `compilation-mode-hook'.  This allows \\[next-error] to find the error
                      (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))
+       (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))
-       )))
+            (default-value 'compilation-error-regexp-alist)))))
 
 (add-hook 'compilation-mode-hook 'verilog-error-regexp-add)
 
@@ -1345,8 +1553,7 @@ Called by `compilation-mode-hook'.  This allows \\[next-error] to find the error
        "endprogram"
        "endsequence"
        "endclocking"
-       )
-     )))
+       ))))
 
 
 (defconst verilog-endcomment-reason-re
@@ -1398,22 +1605,21 @@ Called by `compilation-mode-hook'.  This allows \\[next-error] to find the error
 ;; 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
-          "\\>"))
+  ( concat "\\(\\<begin\\>\\)"         ;1
+          "\\|\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
+          "\\|\\(\\(\\<disable\\>\\s-+\\)?fork\\>\\)" ;4,5
+          "\\|\\(\\<class\\>\\)"               ;6
+          "\\|\\(\\<table\\>\\)"               ;7
+          "\\|\\(\\<specify\\>\\)"             ;8
+          "\\|\\(\\<function\\>\\)"            ;9
+          "\\|\\(\\<task\\>\\)"                ;10
+          "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)"    ;11
+          "\\|\\(\\<generate\\>\\)"            ;15
+          "\\|\\(\\<covergroup\\>\\)"  ;16
+          "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)"     ;17
+          "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21
+          "\\|\\(\\<clocking\\>\\)"          ;22
+          ))
 
 (defconst verilog-end-block-ordered-rry
   [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
@@ -1475,6 +1681,8 @@ Called by `compilation-mode-hook'.  This allows \\[next-error] to find the error
   (eval-when-compile
     (verilog-regexp-words
      `(
+       ;; port direction (by themselves)
+       "inout" "input" "output"
        ;; integer_atom_type
        "byte" "shortint" "int" "longint" "integer" "time"
        ;; integer_vector_type
@@ -1521,8 +1729,8 @@ Called by `compilation-mode-hook'.  This allows \\[next-error] to find the error
   (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\\>\\)"))
+  (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
+                                            "function" "task"))))
 
 (defconst verilog-indent-re
   (eval-when-compile
@@ -1552,6 +1760,7 @@ Called by `compilation-mode-hook'.  This allows \\[next-error] to find the error
        "specify" "endspecify"
        "table" "endtable"
        "task" "endtask"
+       "virtual"
        "`case"
        "`default"
        "`define" "`undef"
@@ -1587,6 +1796,7 @@ Called by `compilation-mode-hook'.  This allows \\[next-error] to find the error
      `(
        "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
        ))))
+(defconst verilog-disable-fork-re "disable\\s-+fork")
 (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\\>\\)"
@@ -1670,170 +1880,50 @@ Called by `compilation-mode-hook'.  This allows \\[next-error] to find the error
  )
  "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
+(defvar verilog-mode-syntax-table
+  (let ((table (make-syntax-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)
+
+    ;; Set up TABLE to handle block and line style comments.
+    (if (featurep 'xemacs)
+       (progn
+         ;; XEmacs (formerly Lucid) has the best implementation
+         (modify-syntax-entry ?/  ". 1456" table)
+         (modify-syntax-entry ?*  ". 23"   table)
+         (modify-syntax-entry ?\n "> b"    table))
+      ;; Emacs 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))
+    table)
+  "Syntax table used in Verilog mode buffers.")
+
+(defvar verilog-font-lock-keywords nil
   "Default highlighting for Verilog mode.")
 
-(defconst verilog-font-lock-keywords-1 nil
+(defvar verilog-font-lock-keywords-1 nil
   "Subdued level highlighting for Verilog mode.")
 
-(defconst verilog-font-lock-keywords-2 nil
+(defvar 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
+(defvar 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
@@ -1882,6 +1972,20 @@ See also `verilog-font-lock-extra-types'.")
   "Font lock mode face used to highlight AMS keywords."
   :group 'font-lock-highlighting-faces)
 
+(defvar verilog-font-grouping-keywords-face
+  'verilog-font-lock-grouping-keywords-face
+  "Font to use for Verilog Grouping Keywords (such as begin..end).")
+(defface verilog-font-lock-grouping-keywords-face
+  '((((class color)
+      (background light))
+     (:foreground "red4" :bold t ))
+    (((class color)
+      (background dark))
+     (:foreground "red4" :bold t ))
+    (t (:italic t)))
+  "Font lock mode face used to highlight verilog grouping keywords."
+  :group 'font-lock-highlighting-faces)
+
 (let* ((verilog-type-font-keywords
        (eval-when-compile
          (verilog-regexp-opt
@@ -1900,7 +2004,7 @@ See also `verilog-font-lock-extra-types'.")
        (verilog-pragma-keywords
        (eval-when-compile
          (verilog-regexp-opt
-          '("surefire" "synopsys" "rtl_synthesis" "verilint" ) nil
+          '("surefire" "synopsys" "rtl_synthesis" "verilint" "leda" "0in") nil
            )))
 
        (verilog-p1800-keywords
@@ -1946,8 +2050,8 @@ See also `verilog-font-lock-extra-types'.")
        (eval-when-compile
          (verilog-regexp-opt
           '(
-            "assign" "begin" "case" "casex" "casez" "randcase" "deassign"
-            "default" "disable" "else" "end" "endcase" "endfunction"
+            "assign" "case" "casex" "casez" "randcase" "deassign"
+            "default" "disable" "else" "endcase" "endfunction"
             "endgenerate" "endinterface" "endmodule" "endprimitive"
             "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
             "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
@@ -1956,18 +2060,28 @@ See also `verilog-font-lock-extra-types'.")
             "always_latch" "posedge" "primitive" "priority" "release"
             "repeat" "specify" "table" "task" "unique" "wait" "while"
             "class" "program" "endclass" "endprogram"
-            ) nil  ))))
+            ) nil  )))
+
+       (verilog-font-grouping-keywords
+       (eval-when-compile
+         (verilog-regexp-opt
+          '( "begin" "end" ) 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_\\$]*"
-                      "\\)\\>")
+              "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
+              "\\)\\>")
         ;; Fontify all types
+        (if verilog-highlight-grouping-keywords
+            (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
+                  'verilog-font-lock-ams-face)
+          (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
+                'font-lock-type-face))
         (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
-              'font-lock-type-face)
+          'font-lock-type-face)
         ;; Fontify IEEE-P1800 keywords appropriately
         (if verilog-highlight-p1800-keywords
             (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
@@ -1976,8 +2090,7 @@ See also `verilog-font-lock-extra-types'.")
                 'font-lock-type-face))
         ;; Fontify Verilog-AMS keywords
         (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
-              'verilog-font-lock-ams-face)
-        ))
+              'verilog-font-lock-ams-face)))
 
   (setq verilog-font-lock-keywords-1
        (append verilog-font-lock-keywords
@@ -1991,15 +2104,12 @@ See also `verilog-font-lock-extra-types'.")
                 (list
                  (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
                       '(1 font-lock-keyword-face)
-                      '(3 font-lock-reference-face prepend)
-                      )
+                      '(3 font-lock-reference-face prepend))
                 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
                   (1 font-lock-keyword-face)
-                  (2 font-lock-reference-face append)
-                  )
+                  (2 font-lock-reference-face append))
                 '("\\<function\\>\\s-+\\(\\sw+\\)"
-                  1 'font-lock-reference-face append)
-                )))
+                  1 'font-lock-reference-face append))))
 
   (setq verilog-font-lock-keywords-2
        (append verilog-font-lock-keywords-1
@@ -2017,7 +2127,6 @@ See also `verilog-font-lock-extra-types'.")
                   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
@@ -2025,11 +2134,9 @@ See also `verilog-font-lock-extra-types'.")
                (when verilog-highlight-translate-off
                  (list
                   ;; Fontify things in translate off regions
-                  '(verilog-match-translate-off (0 'verilog-font-lock-translate-off-face prepend))
-                  )))
-  )
-  )
-
+                  '(verilog-match-translate-off
+                    (0 'verilog-font-lock-translate-off-face prepend))
+                  )))))
 
 
 (defun verilog-inside-comment-p ()
@@ -2038,9 +2145,13 @@ See also `verilog-font-lock-extra-types'.")
     (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))))
+               ;; 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)))))))
 
@@ -2057,17 +2168,17 @@ Use filename, if current buffer being edited shorten to just buffer name."
          ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
 
 (defun electric-verilog-backward-sexp ()
-  "Move backward over a sexp."
+  "Move backward over one balanced expression."
   (interactive)
   ;; before that see if we are in a comment
-  (verilog-backward-sexp)
-)
+  (verilog-backward-sexp))
+
 (defun electric-verilog-forward-sexp ()
-  "Move backward over a sexp."
+  "Move forward over one balanced expression."
   (interactive)
   ;; before that see if we are in a comment
-  (verilog-forward-sexp)
-)
+  (verilog-forward-sexp))
+
 ;;;used by hs-minor-mode
 (defun verilog-forward-sexp-function (arg)
   (if (< arg 0)
@@ -2079,19 +2190,16 @@ Use filename, if current buffer being edited shorten to just buffer name."
   (let ((reg)
        (elsec 1)
        (found nil)
-       (st (point))
-       )
+       (st (point)))
     (if (not (looking-at "\\<"))
        (forward-word -1))
     (cond
-     ((verilog-skip-backward-comment-or-string)
-      )
+     ((verilog-skip-backward-comment-or-string))
      ((looking-at "\\<else\\>")
       (setq reg (concat
                 verilog-end-block-re
                 "\\|\\(\\<else\\>\\)"
-                "\\|\\(\\<if\\>\\)"
-                ))
+                "\\|\\(\\<if\\>\\)"))
       (while (and (not found)
                  (verilog-re-search-backward reg nil 'move))
        (cond
@@ -2106,11 +2214,7 @@ Use filename, if current buffer being edited shorten to just buffer name."
          (setq elsec (1- elsec))
          (if (= 0 elsec)
              ;; Now previous line describes syntax
-             (setq found 't)
-           ))
-        )
-       )
-      )
+             (setq found 't))))))
      ((looking-at verilog-end-block-re)
       (verilog-leap-to-head))
      ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
@@ -2132,78 +2236,98 @@ Use filename, if current buffer being edited shorten to just buffer name."
        (backward-sexp 1))))
      (t
       (goto-char st)
-      (backward-sexp))
-     ) ;; cond
-    ))
+      (backward-sexp)))))
 
 (defun verilog-forward-sexp ()
   (let ((reg)
        (md 2)
-       (st (point)))
+       (st (point))
+       (nest 'yes))
     (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
+      (verilog-forward-syntactic-ws))
+     ((looking-at verilog-beg-block-re-ordered)
       (cond
-       ((match-end 1) ; end
-       ;; Search forward for matching begin
+       ((match-end 1);
+       ;; Search forward for matching end
        (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
-       ((match-end 2) ; endcase
-       ;; Search forward for matching case
+       ((match-end 2)
+       ;; Search forward for matching endcase
        (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
+       (setq md 3) ;; ender is third item in regexp
        )
-       ((match-end 3) ; join
-       ;; Search forward for matching fork
-       (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
-       ((match-end 4) ; endclass
-       ;; Search forward for matching class
+       ((match-end 4)
+       ;; might be "disable fork"
+       (if (or 
+            (looking-at verilog-disable-fork-re)
+            (and (looking-at "fork")
+                 (progn
+                   (forward-word -1)
+                   (looking-at verilog-disable-fork-re))))
+           (progn
+             (goto-char (match-end 0))
+             (forward-word)
+             (setq reg nil))
+         (progn
+           ;; Search forward for matching join
+           (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))
+       ((match-end 6)
+       ;; Search forward for matching endclass
        (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)
+       
+       ((match-end 7)
+       ;; Search forward for matching endtable
+       (setq reg "\\<endtable\\>" )
+       (setq nest 'no))
+      ((match-end 8)
+       ;; Search forward for matching endspecify
+       (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
+      ((match-end 9)
+       ;; Search forward for matching endfunction
+       (setq reg "\\<endfunction\\>" )
+       (setq nest 'no))
+      ((match-end 10)
+       ;; Search forward for matching endtask
+       (setq reg "\\<endtask\\>" )
+       (setq nest 'no))
+      ((match-end 11)
+       ;; Search forward for matching endtask
+       (setq reg "\\<endtask\\>" )
+       (setq nest 'no))
+      ((match-end 15)
+       ;; Search forward for matching endgenerate
+       (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
+      ((match-end 16)
+       ;; Search forward for matching endgroup
+       (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
+      ((match-end 17)
+       ;; Search forward for matching endproperty
+       (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
+      ((match-end 18)
+       ;; Search forward for matching endsequence
+       (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
+       (setq md 3)) ; 3 to get to endsequence in the reg above
+      ((match-end 19)
+       ;; Search forward for matching endclocking
+       (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
+      (if (and reg
+              (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)))))
-             )))
-      )
+           (if (eq nest 'yes) 
+               (let ((depth 1))
+                 (while (verilog-re-search-forward reg nil 'move)
+                   (cond
+                    ((match-end md) ; the closer in reg, so we are climbing out
+                     (setq depth (1- depth))
+                     (if (= 0 depth) ; we are out!
+                         (throw 'skip 1)))
+                    ((match-end 1) ; the opener in reg, so we are deeper now
+                     (setq depth (1+ depth))))))
+             (if (verilog-re-search-forward reg nil 'move)
+                 (throw 'skip 1))))))
+    
      ((looking-at (concat
                   "\\(\\<\\(macro\\)?module\\>\\)\\|"
                   "\\(\\<primitive\\>\\)\\|"
@@ -2233,17 +2357,11 @@ Use filename, if current buffer being edited shorten to just buffer name."
       (goto-char st)
       (if (= (following-char) ?\) )
          (forward-char 1)
-       (forward-sexp 1)))
-     ) ;; cond
-    ))
+       (forward-sexp 1))))))
 
 (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
@@ -2253,58 +2371,22 @@ Use filename, if current buffer being edited shorten to just buffer name."
                (when verilog-highlight-translate-off
                  (list
                   ;; Fontify things in translate off regions
-                  '(verilog-match-translate-off (0 'verilog-font-lock-translate-off-face prepend))
-                  ))
-       )
-  )
+                  '(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))))
+         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
+         ;; Function to move to beginning of reasonable region to highlight
+        verilog-beg-of-defun)))
 
 ;; 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
@@ -2340,9 +2422,10 @@ Variables controlling indentation/edit style:
    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
+   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
+   Indentation of `ifdef/`endif blocks.
  `verilog-cexp-indent'              (default 1)
    Indentation of Verilog statements broken across lines i.e.:
       if (a)
@@ -2353,13 +2436,13 @@ Variables controlling indentation/edit style:
    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
+   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,
+   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'
@@ -2402,15 +2485,15 @@ Some other functions are:
 
     \\[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-insert-block]  Insert begin ... end.
     \\[verilog-star-comment]    Insert /* ... */.
 
-    \\[verilog-sk-always]  Insert a always @(AS) begin .. end block.
+    \\[verilog-sk-always]  Insert an 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-header]  Insert a 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.
@@ -2444,14 +2527,10 @@ Key bindings specific to `verilog-mode-map' are:
   (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) 
+  (set (make-local-variable 'beginning-of-defun-function)
        'verilog-beg-of-defun)
-  (set (make-local-variable 'end-of-defun-function) 
+  (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)
@@ -2475,35 +2554,40 @@ Key bindings specific to `verilog-mode-map' are:
 
   ;; 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)
+    (easy-menu-add verilog-stmt-menu)
+    (easy-menu-add verilog-menu)
+    (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
+
+  ;; Stuff for GNU Emacs
+  (set (make-local-variable 'font-lock-defaults)
+       '((verilog-font-lock-keywords verilog-font-lock-keywords-1
+                                     verilog-font-lock-keywords-2
+                                     verilog-font-lock-keywords-3)
+         nil nil nil verilog-beg-of-defun))
   ;;------------------------------------------------------------
   ;; 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
+  (when (featurep 'xemacs)
+    (make-local-hook 'font-lock-mode-hook)
+    (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
+    (make-local-hook 'after-change-functions))
   (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 'font-lock-after-fontify-buffer-hook 'verilog-colorize-include-files-buffer t t) ; not in Emacs
   (add-hook 'after-change-functions 'verilog-colorize-include-files t t)
 
-  ;; Tell imenu how to handle verilog.
+  ;; Tell imenu how to handle Verilog.
   (make-local-variable 'imenu-generic-expression)
   (setq imenu-generic-expression verilog-imenu-generic-expression)
+  ;; Tell which-func-modes that imenu knows about verilog
+  (when (boundp 'which-function-modes)
+    (add-to-list 'which-func-modes 'verilog-mode))
   ;; 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)
+  (when (boundp 'hs-special-modes-alist)
+    (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))))
 
   ;; Stuff for autos
   (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
@@ -2520,9 +2604,7 @@ Key bindings specific to `verilog-mode-map' are:
 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)))))
+  (let ((state (save-excursion (verilog-syntax-ppss))))
     (cond
      ((nth 7 state)                    ; Inside // comment
       (if (eolp)
@@ -2531,7 +2613,7 @@ With optional ARG, remove existing end of line comments."
            (newline))
        (progn
          (newline)
-         (insert-string "// ")
+         (insert "// ")
          (beginning-of-line)))
       (verilog-indent-line))
      ((nth 4 state)                    ; Inside any comment (hence /**/)
@@ -2557,27 +2639,19 @@ With optional ARG, remove existing end of line comments."
               (progn
                 (end-of-line)
                 (delete-horizontal-space)
-                't
-                )
-              )
-            )
+                '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)
-        )
+                (verilog-pretty-expr))
+            (newline))
+        (forward-line 1))
        ;; Indent next line
        (if verilog-auto-indent-on-newline
-          (verilog-indent-line))
-       )
+          (verilog-indent-line)))
      (t
-      (newline))
-     )))
+      (newline)))))
 
 (defun electric-verilog-terminate-and-indent ()
   "Insert a newline and indent for the next statement."
@@ -2587,7 +2661,7 @@ With optional ARG, remove existing end of line comments."
 (defun electric-verilog-semi ()
   "Insert `;' character and reindent the line."
   (interactive)
-  (insert last-command-char)
+  (insert last-command-event)
 
   (if (or (verilog-in-comment-or-string-p)
          (verilog-in-escaped-name-p))
@@ -2595,8 +2669,7 @@ With optional ARG, remove existing end of line comments."
     (save-excursion
       (beginning-of-line)
       (verilog-forward-ws&directives)
-      (verilog-indent-line)
-      )
+      (verilog-indent-line))
     (if (and verilog-auto-newline
             (not (verilog-parenthesis-depth)))
        (electric-verilog-terminate-line))))
@@ -2613,7 +2686,7 @@ With optional ARG, remove existing end of line comments."
 (defun electric-verilog-colon ()
   "Insert `:' and do all indentations except line indent on this line."
   (interactive)
-  (insert last-command-char)
+  (insert last-command-event)
   ;; Do nothing if within string.
   (if (or
        (verilog-within-string)
@@ -2632,7 +2705,7 @@ With optional ARG, remove existing end of line comments."
 ;;(defun electric-verilog-equal ()
 ;;  "Insert `=', and do indentation if within block."
 ;;  (interactive)
-;;  (insert last-command-char)
+;;  (insert last-command-event)
 ;; Could auto line up expressions, but not yet
 ;;  (if (eq (car (verilog-calculate-indent)) 'block)
 ;;      (let ((verilog-tab-always-indent nil))
@@ -2642,7 +2715,7 @@ With optional ARG, remove existing end of line comments."
 (defun electric-verilog-tick ()
   "Insert back-tick, and indent to column 0 if this is a CPP directive."
   (interactive)
-  (insert last-command-char)
+  (insert last-command-event)
   (save-excursion
     (if (progn
          (beginning-of-line)
@@ -2653,36 +2726,39 @@ With optional ARG, remove existing end of line comments."
   "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)))
+  (cond
+   ;; The region is active, indent it.
+   ((and (region-active-p)
+        (not (eq (region-beginning) (region-end))))
+    (indent-region (region-beginning) (region-end) nil))
+   ((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"))))
-
+                (beginning-of-line)
+                (re-search-forward comment-start-skip oldpnt 'move)
+                (goto-char (match-beginning 0))
+                (skip-chars-backward " \t")
+                (kill-region (point) oldpnt)))))))
+   (t (progn (insert "\t")))))
+  
 \f
 
 ;;
@@ -2719,13 +2795,30 @@ To call this from the command line, see \\[verilog-batch-indent]."
   (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:
+(defun verilog-insert-1 (fmt max)
+  "Use format string FMT to insert integers 0 to MAX - 1.
+Inserts one integer per line, at the current column.  Stops early
+if it reaches the end of the buffer."
+  (let ((col (current-column))
+        (n 0))
+    (save-excursion
+      (while (< n max)
+        (insert (format fmt n))
+        (forward-line 1)
+        ;; Note that this function does not bother to check for lines
+        ;; shorter than col.
+        (if (eobp)
+            (setq n max)
+          (setq n (1+ n))
+          (move-to-column col))))))
+
+(defun verilog-insert-indices (max)
+  "Insert a set of indices into a rectangle.
+The upper left corner is defined by point.  Indices 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
@@ -2737,51 +2830,42 @@ user is prompted for a value.  The indices are surrounded by square brackets
     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))))))
-
+  (interactive "NMAX: ")
+  (verilog-insert-1 "[%3d]" max))
 
-(defun verilog-generate-numbers (MAX)
+(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
+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))))))
+    buf buf                             buf buf000
+    buf buf                             buf buf001
+    buf buf                             buf buf002
+    buf buf                             buf buf003
+    buf buf   ==> generate-numbers ==>  buf buf004
+    buf buf                             buf buf005
+    buf buf                             buf buf006
+    buf buf                             buf buf007
+    buf buf                             buf buf008"
+
+  (interactive "NMAX: ")
+  (verilog-insert-1 "%3.3d" max))
 
 (defun verilog-mark-defun ()
-  "Mark the current verilog function (or procedure).
+  "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))
+  (if (featurep 'xemacs)
+      (progn
+       (push-mark (point))
+       (verilog-end-of-defun)
+       (push-mark (point))
+       (verilog-beg-of-defun)
+       (if (fboundp 'zmacs-activate-region)
+           (zmacs-activate-region)))
+    (mark-defun)))
 
 (defun verilog-comment-region (start end)
   ; checkdoc-params: (start end)
@@ -2817,8 +2901,7 @@ The commented area starts with `verilog-exclude-str-start', and ends with
     (save-excursion
       (let ((s+1 (1+ start)))
        (while (re-search-backward "/\\*" s+1 t)
-         (replace-match "/-*" t t))))
-    ))
+         (replace-match "/-*" t t))))))
 
 (defun verilog-uncomment-region ()
   "Uncomment a commented area; change deformed comments back to normal.
@@ -2894,8 +2977,7 @@ With ARG, first kill any existing labels."
             (point-marker)))
        (e (progn
             (verilog-end-of-defun)
-            (point-marker)))
-       )
+            (point-marker))))
     (goto-char (marker-position b))
     (if (> (- e b) 200)
        (message  "Relabeling module..."))
@@ -2910,18 +2992,15 @@ With ARG, first kill any existing labels."
       (let ((indent-str (verilog-indent-line)))
        (verilog-set-auto-endcomments indent-str 't)
        (end-of-line)
-       (delete-horizontal-space)
-       )
+       (delete-horizontal-space))
       (setq cnt (1+ cnt))
       (if (= 9 (% cnt 10))
-         (message "%d..." cnt))
-      )
+         (message "%d..." cnt)))
     (goto-char oldpos)
     (if (or
         (> (- e b) 200)
         (> cnt 20))
-       (message  "%d lines auto commented" cnt))
-    ))
+       (message  "%d lines auto commented" cnt))))
 
 (defun verilog-beg-of-statement ()
   "Move backward to beginning of statement."
@@ -2944,15 +3023,13 @@ With ARG, first kill any existing labels."
             (looking-at verilog-extended-complete-re)
             (not (save-excursion
                    (verilog-backward-token)
-                   (looking-at verilog-extended-complete-re)))
-            )
+                   (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)))
-           ))
+              (looking-at verilog-preprocessor-re)))))
     (verilog-backward-syntactic-ws)
     (verilog-backward-token))
   ;; Now point is where the previous line ended.
@@ -3012,8 +3089,8 @@ With ARG, first kill any existing labels."
       pos)))
 
 (defun verilog-in-case-region-p ()
-  "Return TRUE if in a case region;
-more specifically, point @ in the line foo : @ begin"
+  "Return true if in a case region.
+More specifically, point @ in the line foo : @ begin"
   (interactive)
   (save-excursion
     (if (and
@@ -3036,33 +3113,26 @@ more specifically, point @ in the line foo : @ begin"
                (throw 'found 1))
                (setq nest (1- nest)))
               (t
-               (throw 'found (= nest 0)))
-              ))))
+               (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"
+  "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)))
+    (let* ((state (verilog-syntax-ppss))
           (depth (nth 0 state)))
       (if depth
          (progn (backward-up-list depth)
                 (verilog-beg-of-statement)
-                (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>")
-                )
-       )
-      )
-    )
-  )
+                (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"
+  "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)
-       )
+       (nest 1))
     (save-excursion
       (while (and
              (/= nest 0)
@@ -3071,17 +3141,14 @@ more specifically, after a generate and before an endgenerate"
               ((match-end 1) ; generate
                (setq nest (1- nest)))
               ((match-end 2) ; endgenerate
-               (setq nest (1+ nest)))
-              ))
-       ))
+               (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)
-       )
+       (nest 1))
     (save-excursion
       (while (and
              (/= nest 0)
@@ -3090,9 +3157,7 @@ more specifically, after a generate and before an endgenerate"
               ((match-end 1) ; fork
                (setq nest (1- nest)))
               ((match-end 2) ; join
-               (setq nest (1+ nest)))
-              ))
-       ))
+               (setq nest (1+ nest)))))))
     (= nest 0) )) ; return nest
 
 (defun verilog-backward-case-item (lim)
@@ -3124,8 +3189,7 @@ Limit search to point LIM."
              (setq colon (1- colon)))
 
             ((match-end 3) ;; :
-             (setq colon (1+ colon)))
-            ))
+             (setq colon (1+ colon)))))
          ;; Skip back to beginning of case item
          (skip-chars-backward "\t ")
          (verilog-skip-backward-comment-or-string)
@@ -3148,10 +3212,8 @@ Limit search to point LIM."
                         (t
                          (goto-char (match-end 0))
                          (verilog-forward-ws&directives)
-                         (point))
-                        ))
-                   (error "Malformed case item")
-                   )))
+                         (point))))
+                   (error "Malformed case item"))))
          (setq str (buffer-substring b e))
          (if
              (setq e
@@ -3166,7 +3228,7 @@ Limit search to point LIM."
 ;; Other functions
 ;;
 
-(defun kill-existing-comment ()
+(defun verilog-kill-existing-comment ()
   "Kill auto comment on this line."
   (save-excursion
     (let* (
@@ -3191,7 +3253,8 @@ 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."
+Insert `// NAME ' if this line ends a function, task, module,
+primitive or interface named NAME."
   (save-excursion
     (cond
      (; Comment close preprocessor directives
@@ -3203,11 +3266,10 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                   (search-backward "//" (verilog-get-beg-of-line) t)))))
       (let ((nest 1) b e
            m
-           (else (if (match-end 2) "!" " "))
-           )
+           (else (if (match-end 2) "!" " ")))
        (end-of-line)
        (if kill-existing-comment
-           (kill-existing-comment))
+           (verilog-kill-existing-comment))
        (delete-horizontal-space)
        (save-excursion
          (backward-sexp 1)
@@ -3224,8 +3286,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
             ((match-end 4) ; `ifdef
              (setq nest (1- nest)))
             ((match-end 5) ; `ifndef
-             (setq nest (1- nest)))
-            ))
+             (setq nest (1- nest)))))
          (if (match-end 0)
              (setq
               m (buffer-substring
@@ -3237,15 +3298,13 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                   (point))
               e (progn
                   (skip-chars-forward "a-zA-Z0-9_")
-                  (point)
-                  ))))
+                  (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))
-         )))
+           (ding 't)))))
 
      (; Comment close case/class/function/task/module and named block
       (and (looking-at "\\<end")
@@ -3268,8 +3327,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                    (cond
                     ((looking-at "\\<randcase\\>")
                      (setq str "randcase")
-                     (setq err nil)
-                     )
+                     (setq err nil))
                     ((match-end 0)
                      (goto-char (match-end 1))
                      (if nil
@@ -3284,11 +3342,10 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                                        (verilog-get-expr))))))
                  (end-of-line)
                  (if kill-existing-comment
-                     (kill-existing-comment))
+                     (verilog-kill-existing-comment))
                  (delete-horizontal-space)
                  (insert (concat " // " str ))
-                 (if err (ding 't))
-                 ))
+                 (if err (ding 't))))
 
               (;- This is a begin..end block
                (match-end 2) ;; of verilog-end-block-ordered-re
@@ -3296,8 +3353,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                      (err 't)
                      (here (point))
                      there
-                     cntx
-                     )
+                     cntx)
                  (save-excursion
                    (verilog-leap-to-head)
                    (setq there (point))
@@ -3306,15 +3362,13 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                          (goto-char here)
                          (end-of-line)
                          (if kill-existing-comment
-                             (kill-existing-comment))
+                             (verilog-kill-existing-comment))
                          (delete-horizontal-space)
                          (insert str)
-                         (ding 't)
-                         )
+                         (ding 't))
                      (let ((lim
                             (save-excursion (verilog-beg-of-defun) (point)))
-                           (here (point))
-                           )
+                           (here (point)))
                        (cond
                         (;-- handle named block differently
                          (looking-at verilog-named-block-re)
@@ -3363,8 +3417,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                             (;- else
                              (match-end 4)
                              (let ((nest 0)
-                                   ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)")
-                                   )
+                                   ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
                                (catch 'skip
                                  (while (verilog-re-search-backward reg nil 'move)
                                    (cond
@@ -3380,16 +3433,13 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                                            (setq err nil)
                                            (setq str (verilog-get-expr))
                                            (setq str (concat " // else: !if" str ))
-                                           (throw 'skip 1))
-                                       )))
-                                   ))))
+                                           (throw 'skip 1)))))))))
 
                             (;- end else
                              (match-end 5)
                              (goto-char there)
                              (let ((nest 0)
-                                   ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)")
-                                   )
+                                   (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
                                (catch 'skip
                                  (while (verilog-re-search-backward reg nil 'move)
                                    (cond
@@ -3405,9 +3455,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                                            (setq err nil)
                                            (setq str (verilog-get-expr))
                                            (setq str (concat " // else: !if" str ))
-                                           (throw 'skip 1))
-                                       )))
-                                   ))))
+                                           (throw 'skip 1)))))))))
 
                             (;- task/function/initial et cetera
                              t
@@ -3419,8 +3467,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                              (setq str (concat " // " cntx str )))
 
                             (;-- otherwise...
-                             (setq str " // auto-endcomment confused "))
-                            ))
+                             (setq str " // auto-endcomment confused "))))
 
                           ((and
                             (verilog-in-case-region-p) ;-- handle case item differently
@@ -3447,7 +3494,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                      (goto-char here)
                      (end-of-line)
                      (if kill-existing-comment
-                         (kill-existing-comment))
+                         (verilog-kill-existing-comment))
                      (delete-horizontal-space)
                      (if (or err
                              (> (count-lines here there) verilog-minimum-comment-distance))
@@ -3458,9 +3505,8 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                (match-end 11) ;; of verilog-end-block-ordered-re
                ;;(goto-char there)
                (let ((nest 0)
-                     ( reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
-                     string
-                     )
+                     (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
+                     string)
                  (save-excursion
                    (catch 'skip
                      (while (verilog-re-search-backward reg nil 'move)
@@ -3490,23 +3536,22 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                                (throw 'skip 1))))
                         ))))
                  (end-of-line)
-                 (insert (concat " // " string )))
-               )
+                 (insert (concat " // " string ))))
 
               (;- this is end{function,generate,task,module,primitive,table,generate}
                ;- which can not be nested.
                t
-               (let (string reg (width nil))
+               (let (string reg (name-re nil))
                  (end-of-line)
                  (if kill-existing-comment
                      (save-match-data
-                      (kill-existing-comment)))
+                      (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\\)\\)?")
+                   (setq name-re "\\w+\\s-*(")
                    )
                   ((match-end 6) ;; of verilog-end-block-ordered-re
                    (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
@@ -3529,8 +3574,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                   ((match-end 15) ;; of verilog-end-block-ordered-re
                    (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
 
-                  (t (error "Problem in verilog-set-auto-endcomments"))
-                  )
+                  (t (error "Problem in verilog-set-auto-endcomments")))
                  (let (b e)
                    (save-excursion
                      (verilog-re-search-backward reg nil 'move)
@@ -3539,11 +3583,10 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                        (setq b (progn
                                  (skip-chars-forward "^ \t")
                                  (verilog-forward-ws&directives)
-                                 (if (and width (looking-at width))
+                                 (if (and name-re (verilog-re-search-forward name-re nil 'move))
                                      (progn
-                                       (goto-char (match-end 0))
-                                       (verilog-forward-ws&directives)
-                                       ))
+                                       (goto-char (match-beginning 0))
+                                       (verilog-forward-ws&directives)))
                                  (point))
                              e (progn
                                  (skip-chars-forward "a-zA-Z0-9_")
@@ -3557,7 +3600,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                ))))))))))
 
 (defun verilog-get-expr()
-  "Grab expression at point, e.g, case ( a | b & (c ^d))"
+  "Grab expression at point, e.g, case ( a | b & (c ^d))."
   (let* ((b (progn
              (verilog-forward-syntactic-ws)
              (skip-chars-forward " \t")
@@ -3604,8 +3647,7 @@ Insert `// NAME ' if this line ends a function, task, module, primitive or inter
                b)
               ('t
                (skip-chars-forward "^: \t\n\f")
-               (point)
-               ))))
+               (point)))))
         (str (buffer-substring b e)))
     (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
        (setq str (concat (substring str 0 e) "...")))
@@ -3624,19 +3666,25 @@ Useful for creating tri's and other expanded fields."
     (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)
+      (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-start (string-to-number (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)))))
+                           (string-to-number
+                            (substring signal-string (1+ (match-beginning 3))
+                                       (match-end 3)))))
+                (vec-range
+                 (if (= (match-beginning 4) (match-end 4))
+                     1
+                   (string-to-number
+                    (substring signal-string (+ 2 (match-beginning 4))
+                               (match-end 4)))))
                 (sig-tail (match-string 5 signal-string))
                 vec)
            ;; Decode vectors
@@ -3659,14 +3707,15 @@ Useful for creating tri's and other expanded fields."
            ;;
            ;; Expand vector
            (while vec
-             (insert (concat sig-head bra (int-to-string (car vec)) ket sig-tail "\n"))
+             (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."
+  "Strip all comments from the Verilog code."
   (interactive)
   (goto-char (point-min))
   (while (re-search-forward "//" nil t)
@@ -3687,7 +3736,7 @@ Useful for creating tri's and other expanded fields."
        (delete-region bpt (point))))))
 
 (defun verilog-one-line ()
-  "Convert structural verilog instances to occupy one line."
+  "Convert structural Verilog instances to occupy one line."
   (interactive)
   (goto-char (point-min))
   (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
@@ -3712,7 +3761,7 @@ For example:
 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.
+variables is used to determine which product is being used.
 
 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
   (interactive)
@@ -3723,6 +3772,8 @@ See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
           (verilog-verilint-off))
          (t (error "Linter name not set")))))
 
+(defvar compilation-last-buffer)
+
 (defun verilog-surelint-off ()
   "Convert a SureLint warning line into a disable statement.
 Run from Verilog source window; assumes there is a *compile* buffer
@@ -3733,56 +3784,60 @@ For example:
 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 ))
-           )))))))
+  (let ((buff (if (boundp 'next-error-last-buffer)
+                  next-error-last-buffer
+                compilation-last-buffer)))
+    (when (buffer-live-p buff)
+      ;; FIXME with-current-buffer?
+      (save-excursion
+        (switch-to-buffer buff)
+        (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 (concat " " code)))))
+                 (t
+                  )))
+               ((verilog-in-star-comment-p)
+                (re-search-backward "/\*")
+                (insert (format " // surefire lint_off_line %6s" code )))
+               (t
+                (insert (format " // surefire lint_off_line %6s" code ))
+                )))))))))
 
 (defun verilog-verilint-off ()
   "Convert a Verilint warning line into a disable statement.
@@ -3822,7 +3877,7 @@ This lets programs calling batch mode to easily extract error messages."
        (progn ,@body)
      (error
       (error "%%Error: %s%s" (error-message-string err)
-            (if (featurep 'xemacs) "\n" "")))))  ;; xemacs forgets to add a newline
+            (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."
@@ -3835,18 +3890,19 @@ This lets programs calling batch mode to easily extract error messages."
    ;; 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))
+   (mapc (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))))
+                     (error
+                      (concat "File not found: " (buffer-file-name buf))))
                  (message (concat "Processing " (buffer-file-name buf)))
                  (set-buffer buf)
                  (funcall funref)
@@ -3855,7 +3911,7 @@ This lets programs calling batch mode to easily extract error messages."
 
 (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
+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."
@@ -3865,7 +3921,7 @@ line in bottom-up order."
 
 (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
+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
@@ -3873,7 +3929,7 @@ with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
 
 (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
+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."
@@ -3883,7 +3939,7 @@ line in bottom-up order."
 
 (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
+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
@@ -3926,8 +3982,8 @@ Set point to where line starts.  Limit search to point LIM."
 (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)."
+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)
@@ -3955,8 +4011,7 @@ type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
                        (not (verilog-in-coverage))
                        (verilog-in-paren))
                       (progn (setq par 1)
-                             (throw 'nesting 'block))
-                    )
+                             (throw 'nesting 'block)))
 
                   ;; See if we are continuing a previous line
                   (while t
@@ -4038,8 +4093,7 @@ type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
                                   (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
                                  ((match-end 12) ; covergroup
                                   ;; Search back for matching covergroup
-                                  (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
-                                 )
+                                  (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
                                 (catch 'skip
                                   (while (verilog-re-search-backward reg nil 'move)
                                     (cond
@@ -4049,11 +4103,8 @@ type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
                                           (throw 'skip 1)))
                                      ((match-end 2) ; end
                                       (setq nest (1+ nest)))))
-                                  )
-                                ))
-                             ))))
-                    (throw 'nesting (verilog-calc-1))
-                    )
+                                  )))))))
+                    (throw 'nesting (verilog-calc-1)))
                   );; catch nesting
                 );; type
           )
@@ -4070,14 +4121,32 @@ type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
          ((eq type 'defun)
           (list type 0))
          (t
-          (list type (verilog-current-indent-level)))))
-      )))
+          (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))))
+    (let* ((type (verilog-calc-1))
+          depth)
+      ;; Return type of block and indent level.
+      (if (not type)
+         (setq type 'cpp))
+      (if (and
+          verilog-indent-lists
+          (not (verilog-in-coverage))
+          (verilog-in-paren))
+         (setq depth 1)
+       (cond
+         ((eq type 'case)
+          (setq depth (verilog-case-indent-level)))
+         ((eq type 'statement)
+          (setq depth (current-column)))
+         ((eq type 'defun)
+          (setq depth 0))
+         (t
+          (setq depth (verilog-current-indent-level)))))
+      (message "You are at nesting %s depth %d" type depth))))
 
 (defun verilog-calc-1 ()
   (catch 'nesting
@@ -4085,8 +4154,7 @@ type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
       (cond
        ((equal (char-after) ?\{)
        (if (verilog-at-constraint-p)
-           (throw 'nesting 'block)
-         ))
+           (throw 'nesting 'block)))
        ((equal (char-after) ?\})
 
        (let ((there (verilog-at-close-constraint-p)))
@@ -4101,24 +4169,43 @@ type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
                (throw 'nesting 'case)
              (goto-char here)))
          (throw 'nesting 'case))
+        
+        ((match-end 4)  ; *sigh* could be "disable fork"
+         (let ((here (point)))
+           (verilog-beg-of-statement)
+           (if (looking-at verilog-disable-fork-re)
+               t ; is disable fork, this is a normal statement
+             (progn ; or is fork, starts a new block
+               (goto-char here)
+               (throw 'nesting 'block)))))
+
 
         ;; need to consider typedef struct here...
-        ((looking-at "\\<class\\|struct\\|function\\|task\\|property\\>")
+        ((looking-at "\\<class\\|struct\\|function\\|task\\>")
                                        ; *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))
-             )))
+         (verilog-beg-of-statement)
+         (if (looking-at verilog-beg-block-re-ordered)
+             (throw 'nesting 'block)
+           (throw 'nesting 'defun)))
+
+        ((looking-at "\\<property\\>")
+                                       ; *sigh* 
+                                       ;    {assert|assume|cover} property (); are complete
+                                       ; but
+                                        ;    property ID () ... needs end_property
+         (verilog-beg-of-statement)
+         (if (looking-at "\\(assert\\|assume\\|cover\\)\\s-+property\\>")
+             (throw 'nesting 'statement) ; We don't need an endproperty for these
+           (throw 'nesting 'block)     ;We still need a endproperty
+           ))
+        
         (t              (throw 'nesting 'block))))
 
        ((looking-at verilog-end-block-re)
@@ -4138,19 +4225,15 @@ type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
        (throw 'nesting 'cpp))
 
        ((bobp)
-       (throw 'nesting 'cpp))
-       ))
-    (throw 'nesting 'cpp)
-    )
-  )
+       (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)
-       )
+       (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
@@ -4158,8 +4241,7 @@ of the appropriate enclosing block."
       (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))
-              ))
+              (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
@@ -4191,16 +4273,21 @@ of the appropriate enclosing block."
        (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."
+  "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
+       (nesting 'yes)
        (nest 1))
     (cond
      ((looking-at "\\<end\\>")
       ;; 1: Search back for matching begin
       (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
                        "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
+     ((looking-at "\\<endtask\\>")
+      ;; 9: Search back for matching task
+      (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
+      (setq nesting 'no))
      ((looking-at "\\<endcase\\>")
       ;; 2: Search back for matching case
       (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)" ))
@@ -4222,9 +4309,6 @@ from endcase to matching case, and so on."
      ((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\\>\\)" ))
@@ -4239,40 +4323,48 @@ from endcase to matching case, and so on."
       (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
      ((looking-at "\\<endclocking\\>")
       ;; 12: Search back for matching clocking
-      (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" ))
-     )
+      (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\\)?\\>\\)" ))
-              )))))))
+         (if (eq nesting 'yes)
+             (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\\)?\\>\\)" ))
+                  )))
+           ;no nesting
+           (if (and
+                (verilog-re-search-backward reg nil 'move)         
+                (match-end 1)) ; task -> could be virtual and/or protected
+               (progn
+                 (verilog-beg-of-statement)
+                 (throw 'skip 1))
+             (throw 'skip 1)))))))
 
 (defun verilog-continued-line ()
   "Return true if this is a continued line.
-Set point to where line starts"
+Set point to where line starts."
   (let ((continued 't))
     (if (eq 0 (forward-line -1))
        (progn
@@ -4284,9 +4376,7 @@ Set point to where line starts"
                        (save-excursion
                          (skip-chars-backward " \t")
                          (not (bolp))))
-           (setq continued (verilog-backward-token))
-           ) ;; while
-           ))
+           (setq continued (verilog-backward-token)))))
       (setq continued nil))
     continued))
 
@@ -4305,15 +4395,13 @@ Set point to where line starts"
     (= (preceding-char) ?\})
     (progn
       (backward-char)
-      (verilog-at-close-constraint-p))
-    )
+      (verilog-at-close-constraint-p)))
    (;-- constraint foo { a = b }
     ;   is a complete statement. *sigh*
     (= (preceding-char) ?\{)
     (progn
       (backward-char)
-      (not (verilog-at-constraint-p)))
-    )
+      (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)
@@ -4338,10 +4426,8 @@ Set point to where line starts"
              (verilog-backward-token)
              (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
           ((= (preceding-char) ?\#)
-           (backward-char)
-           )
-          (t t))
-         )))))
+           (backward-char))
+          (t t)))))))
 
    (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
     t
@@ -4349,6 +4435,8 @@ Set point to where line starts"
     (cond
      ((looking-at "\\<else\\>")
       t)
+     ((looking-at verilog-behavioral-block-beg-re)
+      t)
      ((looking-at verilog-indent-re)
       nil)
      (t
@@ -4362,8 +4450,7 @@ Set point to where line starts"
          (backward-sexp)
          (if (looking-at verilog-nameable-item-re )
              nil
-           t)
-         )
+           t))
         ((= (preceding-char) ?\#)
          (backward-char)
          t)
@@ -4373,8 +4460,7 @@ Set point to where line starts"
 
         (t
          (goto-char back)
-         t)
-        )))))))
+         t))))))))
 
 (defun verilog-backward-syntactic-ws (&optional bound)
   "Backward skip over syntactic whitespace for Emacs 19.
@@ -4386,9 +4472,7 @@ Optional BOUND limits search."
            (narrow-to-region bound (point))
            (while (/= here (point))
              (setq here (point))
-             (verilog-skip-backward-comments)
-             )))
-      ))
+             (verilog-skip-backward-comments))))))
   t)
 
 (defun verilog-forward-syntactic-ws (&optional bound)
@@ -4396,16 +4480,13 @@ Optional BOUND limits search."
 Optional BOUND limits search."
   (save-restriction
     (let* ((bound (or bound (point-max)))
-          (here bound)
-          )
+          (here bound))
       (if (> bound (point))
          (progn
            (narrow-to-region (point) bound)
            (while (/= here (point))
              (setq here (point))
-             (forward-comment (buffer-size))
-             )))
-      )))
+             (forward-comment (buffer-size))))))))
 
 (defun verilog-backward-ws&directives (&optional bound)
   "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
@@ -4416,9 +4497,7 @@ Optional BOUND limits search."
           (p nil) )
       (if (< bound (point))
          (progn
-           (let ((state
-                  (save-excursion
-                    (parse-partial-sexp (point-min) (point)))))
+           (let ((state (save-excursion (verilog-syntax-ppss))))
              (cond
               ((nth 7 state) ;; in // comment
                (verilog-re-search-backward "//" nil 'move)
@@ -4439,9 +4518,7 @@ Optional BOUND limits search."
                        (point))
                       (t
                        nil))))
-             (if p (goto-char p))
-             )))
-      )))
+             (if p (goto-char p))))))))
 
 (defun verilog-forward-ws&directives (&optional bound)
   "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
@@ -4449,13 +4526,10 @@ Optional BOUND limits search."
   (save-restriction
     (let* ((bound (or bound (point-max)))
           (here bound)
-          jump
-          )
+          jump)
       (if (> bound (point))
          (progn
-           (let ((state
-                  (save-excursion
-                    (parse-partial-sexp (point-min) (point)))))
+           (let ((state (save-excursion (verilog-syntax-ppss))))
              (cond
               ((nth 7 state) ;; in // comment
                (verilog-re-search-forward "//" nil 'move))
@@ -4471,22 +4545,16 @@ Optional BOUND limits search."
                (if (looking-at verilog-directive-re-1)
                    (setq jump t)))
              (if jump
-                 (beginning-of-line 2))
-             )))
-      )))
+                 (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)))))
+ (let ((state (save-excursion (verilog-syntax-ppss))))
    (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)))))
+ (let ((state (save-excursion (verilog-syntax-ppss))))
    (and
     (nth 4 state)                      ; t if in a comment of style a // or b /**/
        (not
@@ -4495,16 +4563,12 @@ Optional BOUND limits search."
 
 (defun verilog-in-slash-comment-p ()
  "Return true if in a slash comment."
- (let ((state
-       (save-excursion
-         (parse-partial-sexp (point-min) (point)))))
+ (let ((state (save-excursion (verilog-syntax-ppss))))
    (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)))))
+ (let ((state (save-excursion (verilog-syntax-ppss))))
    (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
 
 (defun verilog-in-escaped-name-p ()
@@ -4518,9 +4582,7 @@ Optional BOUND limits search."
 
 (defun verilog-in-paren ()
  "Return true if in a parenthetical expression."
- (let ((state
-       (save-excursion
-         (parse-partial-sexp (point-min) (point)))))
+ (let ((state (save-excursion (verilog-syntax-ppss))))
    (> (nth 0 state) 0 )))
 
 (defun verilog-in-coverage ()
@@ -4553,29 +4615,23 @@ Optional BOUND limits search."
         (forward-list)
         (progn (backward-char 1)
                (verilog-backward-ws&directives)
-               (equal (char-before) ?\;))
-        ))
+               (equal (char-before) ?\;))))
       ;; maybe
       (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
     ;; not
-    nil
-    )
-  )
+    nil))
 
 (defun verilog-parenthesis-depth ()
  "Return non zero if in parenthetical-expression."
- (save-excursion
-   (nth 1 (parse-partial-sexp (point-min) (point)))))
+ (save-excursion (nth 1 (verilog-syntax-ppss))))
 
 
 (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)))))
+ (let ((state (save-excursion (verilog-syntax-ppss))))
    (cond
     ((nth 3 state)                     ;Inside string
-     (goto-char (nth 3 state))
+     (search-forward "\"")
      t)
     ((nth 7 state)                     ;Inside // comment
      (forward-line 1)
@@ -4587,9 +4643,7 @@ Optional BOUND limits search."
 
 (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)))))
+ (let ((state (save-excursion (verilog-syntax-ppss))))
    (cond
     ((nth 3 state)                     ;Inside string
      (search-backward "\"")
@@ -4609,9 +4663,7 @@ Optional BOUND limits search."
  (let ((more t))
    (while more
      (setq more
-          (let ((state
-                 (save-excursion
-                   (parse-partial-sexp (point-min) (point)))))
+          (let ((state (save-excursion (verilog-syntax-ppss))))
             (cond
              ((nth 7 state)                    ;Inside // comment
               (search-backward "//")
@@ -4624,8 +4676,7 @@ Optional BOUND limits search."
               t)
              ((and (not (bobp))
                    (= (char-before) ?\/)
-                   (= (char-before (1- (point))) ?\*)
-                   )
+                   (= (char-before (1- (point))) ?\*))
               (goto-char (- (point) 2))
               t)
              (t
@@ -4636,9 +4687,7 @@ Optional BOUND limits search."
   "If in comment, move to end and return true."
   (let (state)
     (progn
-      (setq state
-           (save-excursion
-             (parse-partial-sexp (point-min) (point))))
+      (setq state (save-excursion (verilog-syntax-ppss)))
       (cond
        ((nth 3 state)
        t)
@@ -4664,8 +4713,10 @@ Only look at a few lines to determine indent level."
         ((verilog-continued-line)
          (let ((sp1 (point)))
            (if (verilog-continued-line)
-               (progn (goto-char sp)
-                      (setq indent-str (list 'statement (verilog-current-indent-level))))
+               (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))
@@ -4715,16 +4766,13 @@ Only look at a few lines to determine indent level."
                             (progn
                               (forward-char 1)
                               (backward-up-list -1)
-                              (skip-chars-forward " \t")))
-                           )
+                              (skip-chars-forward " \t"))))
                           (current-column))
                       (progn
                         (goto-char fst)
-                        (+ (current-column) verilog-cexp-indent))
-                      ))))
+                        (+ (current-column) verilog-cexp-indent))))))
            (goto-char here)
-           (indent-line-to val))
-         )
+           (indent-line-to val)))
         ((= (preceding-char) ?\) )
          (goto-char here)
          (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
@@ -4738,8 +4786,7 @@ Only look at a few lines to determine indent level."
                (setq val (current-column))
              (setq val (eval (cdr (assoc type verilog-indent-alist)))))
            (goto-char here)
-           (indent-line-to val)))
-        )))
+           (indent-line-to val))))))
 
      (; handle inside parenthetical expressions
       (eq type 'cparenexp)
@@ -4749,11 +4796,8 @@ Only look at a few lines to determine indent level."
                   (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 )
@@ -4788,15 +4832,15 @@ Only look at a few lines to determine indent level."
      (;-- Everything else
       t
       (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
-       (indent-line-to val)))
-     )
+       (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."
+  "Return the indent-level of the current statement."
   (save-excursion
     (let (par-pos)
       (beginning-of-line)
@@ -4809,7 +4853,7 @@ Only look at a few lines to determine indent level."
       (current-column))))
 
 (defun verilog-case-indent-level ()
-  "Return the indent-level the current statement has.
+  "Return the indent-level of the current statement.
 Do not count named blocks or case-statements."
   (save-excursion
     (skip-chars-forward " \t")
@@ -4837,8 +4881,7 @@ Do not count named blocks or case-statements."
           (t
            (save-excursion
              (re-search-backward "//" nil t)
-             (current-column)))
-          )))
+             (current-column))))))
     (indent-line-to stcol)
     stcol))
 
@@ -4857,8 +4900,7 @@ Do not count named blocks or case-statements."
           (t
            (save-excursion
              (re-search-backward "//" nil t)
-             (current-column)))
-          )))
+             (current-column))))))
     (progn
       (indent-to stcol)
       (if (and star
@@ -4885,7 +4927,7 @@ ARG is ignored, for `comment-indent-function' compatibility."
 
 ;;
 
-(defun verilog-pretty-declarations ()
+(defun verilog-pretty-declarations (&optional quiet)
   "Line up declarations around point."
   (interactive)
   (save-excursion
@@ -4926,11 +4968,11 @@ ARG is ignored, for `comment-indent-function' compatibility."
                  (goto-char start)
                  (verilog-do-indent (verilog-calculate-indent))
                  (verilog-forward-ws&directives)
-                 (current-column)))
-              )
+                 (current-column))))
          (goto-char end)
          (goto-char start)
-         (if (> (- end start) 100)
+         (if (and (not quiet)
+                  (> (- end start) 100))
              (message "Lining up declarations..(please stand by)"))
          ;; Get the beginning of line indent first
          (while (progn (setq e (marker-position edpos))
@@ -4941,15 +4983,12 @@ ARG is ignored, for `comment-indent-function' compatibility."
               (verilog-forward-ws&directives)
               (indent-line-to base-ind)
               (verilog-forward-ws&directives)
-              (verilog-re-search-forward "[ \t\n\f]" e 'move)
-              )
+              (verilog-re-search-forward "[ \t\n\f]" e 'move))
             (t
              (just-one-space)
-             (verilog-re-search-forward "[ \t\n\f]" e 'move)
-             )
-            )
+             (verilog-re-search-forward "[ \t\n\f]" e 'move)))
+           ;;(forward-line)
            )
-           ;;(forward-line))
          ;; Now find biggest prefix
          (setq ind (verilog-get-lineup-indent start edpos))
          ;; Now indent each line.
@@ -4958,7 +4997,7 @@ ARG is ignored, for `comment-indent-function' compatibility."
                        (setq r (- e (point)))
                        (> r 0))
            (setq e (point))
-           (message "%d" r)
+           (unless quiet (message "%d" r))
            (cond
             ((or (and verilog-indent-declaration-macros
                       (looking-at verilog-declaration-re-1-macro))
@@ -4974,108 +5013,107 @@ ARG is ignored, for `comment-indent-function' compatibility."
                      (indent-to ind))
                  (progn
                    (just-one-space)
-                   (indent-to ind))
-                 )))
+                   (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)))
            (forward-line 1))
-         (message "")))))
+         (unless quiet (message ""))))))
 
-(defun verilog-pretty-expr (&optional myre)
-  "Line up expressions around point."
+(defun verilog-pretty-expr (&optional quiet myre)
+  "Line up expressions around point, or optional regexp MYRE."
   (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 myre (concat "\\(^[^;#<=>]*\\)\\(" myre "\\)"))
+    (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
+      (beginning-of-line)
+      (if (and (not (looking-at rexp ))
+              (looking-at myre))
+         (let* ((here (point))
+                (e) (r)
+                (start
+                 (progn
+                   (beginning-of-line)
                    (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))
+                   (while (and (not (looking-at rexp ))
+                               (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))
+                   (setq e (point))    ;Might be on last line
                    (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)
-           )
+                   (while (and (not (looking-at rexp ))
+                               (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 (and (not quiet)
+                    (> (- 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 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 "")
-         ))))
+           ;; Now indent each line.
+           (goto-char start)
+           (while (progn (setq e (marker-position edpos))
+                         (setq r (- e (point)))
+                         (> r 0))
+             (setq e (point))
+             (if (not quiet) (message "%d" r))
+             (cond
+              ((looking-at myre)
+               (goto-char (match-end 1))
+               (if (not (verilog-parenthesis-depth)) ;; ignore parenthsized exprs
+                   (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))
+           (unless quiet (message ""))
+           )))))
 
 (defun verilog-just-one-space (myre)
   "Remove extra spaces around regular expression MYRE."
@@ -5086,13 +5124,11 @@ ARG is ignored, for `comment-indent-function' compatibility."
            (p2 (match-end 2)))
        (progn
          (goto-char p2)
-         (if (looking-at "\\s-") (just-one-space) )
+         (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.
@@ -5106,9 +5142,9 @@ BASEIND is the base indent to offset everything."
               (point)))
        (ind)
        (val)
-       (m1 (make-marker))
-       )
-    (setq val (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
+       (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.
@@ -5123,7 +5159,9 @@ BASEIND is the base indent to offset everything."
              (skip-chars-forward " \t")
              (setq ind (current-column))
              (goto-char pos)
-             (setq val (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
+             (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))
@@ -5135,13 +5173,11 @@ BASEIND is the base indent to offset everything."
                          (just-one-space)
                          (goto-char (marker-position m1))
                          (just-one-space)
-                         (indent-to ind)
-                         )
+                         (indent-to ind))
                      (if (/= (current-column) ind)
                          (progn
                            (just-one-space)
-                           (indent-to ind))
-                       )))
+                           (indent-to ind)))))
                (if (looking-at verilog-declaration-re-2-no-macro)
                    (let ((p (match-end 0)))
                      (set-marker m1 p)
@@ -5155,14 +5191,8 @@ BASEIND is the base indent to offset everything."
                        (if (/= (current-column) ind)
                            (progn
                              (just-one-space)
-                             (indent-to ind))
-                         )))
-                 )))
-         )
-      )
-    (goto-char pos)
-    )
-  )
+                             (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.
@@ -5199,13 +5229,15 @@ Region is defined by B and EDPOS."
       ;; Get rightmost position
       (while (progn (setq e (marker-position edpos))
                    (< (point) e))
-       (if (verilog-re-search-forward myre e 'move)
+       (if (and (verilog-re-search-forward myre e 'move)
+                (not (verilog-parenthesis-depth))) ;; skip parenthsized exprs
            (progn
-             (goto-char (match-end 0))
+             (goto-char (match-beginning 2))
              (verilog-backward-syntactic-ws)
              (if (> (current-column) ind)
                  (setq ind (current-column)))
-             (goto-char (match-end 0)))))
+             (goto-char (match-end 0)))
+         ))
       (if (> ind 0)
          (1+ ind)
        ;; No lineup-string found
@@ -5260,15 +5292,15 @@ it displays a list of all possible completions.")
     "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...)")
+\(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.)
+\(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.")
+will be completed at runtime and should not be added to this list.")
 
 (defvar verilog-defun-keywords
   (append
@@ -5280,9 +5312,9 @@ will be completed runtime and should not be added to this list.")
      )
    verilog-type-keywords)
   "*Keywords to complete when at first word of a line in declarative scope.
-\(eg.  initial, always, begin, assign.)
+\(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.")
+will be completed at runtime and should not be added to this list.")
 
 (defvar verilog-block-keywords
   '(
@@ -5291,30 +5323,30 @@ will be completed runtime and should not be added to this list.")
     "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.)
+\(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.")
+will be completed at 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.)
+\(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.")
+will be completed at 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.)
+\(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.")
+will be completed at 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.")
+\(Eg. else, then.)
+Variables and function names defined within the Verilog program
+will be completed at 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."
@@ -5378,11 +5410,8 @@ for matches of `str' and adding the occurrence tp `all' through point END."
            (if (or (null verilog-pred)
                    (funcall verilog-pred match))
                (setq verilog-all (cons match verilog-all)))))
-      (forward-line 1)
-      )
-    )
-  verilog-all
-  )
+      (forward-line 1)))
+  verilog-all)
 
 (defun verilog-type-completion ()
   "Calculate all possible completions for types."
@@ -5425,11 +5454,11 @@ for matches of `str' and adding the occurrence tp `all' through point END."
   "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."
+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 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))
       ;; Set buffer to use for searching labels. This should be set
@@ -5673,18 +5702,16 @@ If search fails, other files are checked based on
        (progn
          (save-excursion
            (goto-char (point-min))
-           (setq pt (re-search-forward (verilog-build-defun-re label t) nil t)))
+           (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)
-       )))
+       (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.")))
+(defvar occur-pos-list)
 
 (defun verilog-showscopes ()
   "List all scopes in this module."
@@ -5695,8 +5722,7 @@ If search fails, other files are checked based on
        (first 1)
        (prevpos (point-min))
         (final-context-start (make-marker))
-       (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)")
-       )
+       (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
     (with-output-to-temp-buffer "*Occur*"
       (save-excursion
        (message (format "Searching for %s ..." regexp))
@@ -5843,13 +5869,13 @@ Bound search by LIMIT.  Adapted from
     (insert (user-full-name))
     (insert "  <" (user-login-name) "@" (system-name) ">")
     (search-forward "<credate>") (replace-match "" t t)
-    (insert-date)
+    (verilog-insert-date)
     (search-forward "<moddate>") (replace-match "" t t)
-    (insert-date)
+    (verilog-insert-date)
     (search-forward "<copydate>") (replace-match "" t t)
-    (insert-year)
+    (verilog-insert-year)
     (search-forward "<modhist>") (replace-match "" t t)
-    (insert-date)
+    (verilog-insert-date)
     (insert " : created")
     (goto-char start)
     (let (string)
@@ -5857,12 +5883,10 @@ Bound search by LIMIT.  Adapted from
       (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)
@@ -5871,12 +5895,11 @@ Bound search by LIMIT.  Adapted from
       (search-forward "<company>")
       (replace-match string t t)
       (search-backward "<description>")
-      (replace-match "" t t)
-      )))
+      (replace-match "" t t))))
 
-;; verilog-header Uses the insert-date function
+;; verilog-header Uses the verilog-insert-date function
 
-(defun insert-date ()
+(defun verilog-insert-date ()
   "Insert date from the system."
   (interactive)
   (let ((timpos))
@@ -5889,7 +5912,7 @@ Bound search by LIMIT.  Adapted from
     (end-of-line))
     (delete-char 1))
 
-(defun insert-year ()
+(defun verilog-insert-year ()
   "Insert year from the system."
   (interactive)
   (let ((timpos))
@@ -5940,8 +5963,8 @@ Bound search by LIMIT.  Adapted from
   (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.
+  "Return list of signals in IN-LIST that aren't also in NOT-LIST.
+Also remove any duplicates in IN-LIST.
 Signals must be in standard (base vector) form."
   (let (out-list)
     (while in-list
@@ -6011,16 +6034,16 @@ Duplicate signals are also removed.  For example A[2] and A[1] become A[2:1]."
              sv-type    (verilog-sig-type sig)
              sv-multidim (verilog-sig-multidim sig)
              combo ""
-             buswarn ""
-             ))
+             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))))
+                          (setq highbit (string-to-number (match-string 1 bus))
+                                lowbit  (string-to-number
+                                         (match-string 2 bus))))
                      (and (string-match "\\[\\([0-9]+\\)\\]" bus)
-                          (setq highbit (string-to-int (match-string 1 bus))
+                          (setq highbit (string-to-number (match-string 1 bus))
                                 lowbit  highbit))))
             ;; Combine bits in bus
             (if sv-highbit
@@ -6036,7 +6059,8 @@ Duplicate signals are also removed.  For example A[2] and A[1] become A[2:1]."
       (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 (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
@@ -6052,20 +6076,21 @@ Duplicate signals are also removed.  For example A[2] and A[1] become A[2:1]."
            ;; 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)))
-      )
+                  (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.
+  "Return tieoff expression for given SIG, with appropriate width.
 Ignore width if optional NO-WIDTH is set."
   (let* ((width (if no-width nil (verilog-sig-width sig))))
     (concat
@@ -6109,7 +6134,7 @@ Ignore width if optional NO-WIDTH is set."
       (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
+    ;; 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 ()
@@ -6117,7 +6142,7 @@ Ignore width if optional NO-WIDTH is set."
   (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
+    ;; 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 ()
@@ -6127,9 +6152,36 @@ Ignore width if optional NO-WIDTH is set."
     (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
+    ;; 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-param-value ()
+  "Return list of parameters and values 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
+    ;; If there are parameterized instantiations
+    (when (looking-at ")")
+      (let ((end-pt (point))
+           params
+           param-name paren-beg-pt param-value)
+       (verilog-backward-open-paren)
+       (while (verilog-re-search-forward-quick "\\." end-pt t)
+         (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
+         (skip-chars-backward "a-zA-Z0-9'_$")
+         (looking-at "[a-zA-Z0-9`_\$]+")
+         (setq param-name (buffer-substring-no-properties
+                           (match-beginning 0) (match-end 0)))
+         (verilog-re-search-forward-quick "(" nil nil)
+         (setq paren-beg-pt (point))
+         (verilog-forward-close-paren)
+         (setq param-value (verilog-string-remove-spaces
+                            (buffer-substring-no-properties
+                             paren-beg-pt (1- (point)))))
+         (setq params (cons (list param-name param-value) params)))
+       params))))
+
 (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."
@@ -6202,8 +6254,7 @@ Return a array of [outputs inouts inputs wire reg assign const]."
                      (forward-char 1)
                      (when (< paren sig-paren)
                        (setq expect-signal nil))   ; ) that ends variables inside v2k arg list
-                     t)
-                    )))
+                     t))))
         ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
          (goto-char (match-end 0))
          (cond (newsig ; Memory, not just width.  Patch last signal added's memory (nth 3)
@@ -6236,8 +6287,9 @@ Return a array of [outputs inouts inputs wire reg assign const]."
                     (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"))
+               ((member keywd (list "reg" "trireg"
+                                    "byte" "shortint" "int" "longint" "integer" "time"
+                                    "bit" "logic"))
                 (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")
@@ -6246,7 +6298,8 @@ Return a array of [outputs inouts inputs wire reg assign const]."
                ((or (equal keywd "supply0")
                     (equal keywd "supply1")
                     (equal keywd "supply")
-                    (equal keywd "localparam"))
+                    (equal keywd "localparam")
+                    (equal keywd "genvar"))
                 (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"))
@@ -6285,15 +6338,53 @@ Return a array of [outputs inouts inputs wire reg assign const]."
              (nreverse sigs-reg)
              (nreverse sigs-assign)
              (nreverse sigs-const)
-             (nreverse sigs-gparam)
-             ))))
+             (nreverse sigs-gparam)))))
+
+(eval-when-compile
+  ;; Prevent compile warnings; these are let's, not globals
+  ;; Do not remove the eval-when-compile
+  ;; - we want a error when we are debugging this code if they are refed.
+  (defvar sigs-in)
+  (defvar sigs-inout)
+  (defvar sigs-out))
+
+
+(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))
 
-(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."
+;; Signal reading for given module
+;; Note these all take modi's - as returned from the
+;; verilog-modi-current function.
+(defsubst verilog-decls-get-outputs (decls)
+  (aref decls 0))
+(defsubst verilog-decls-get-inouts (decls)
+  (aref decls 1))
+(defsubst verilog-decls-get-inputs (decls)
+  (aref decls 2))
+(defsubst verilog-decls-get-wires (decls)
+  (aref decls 3))
+(defsubst verilog-decls-get-regs (decls)
+  (aref decls 4))
+(defsubst verilog-decls-get-assigns (decls)
+  (aref decls 5))
+(defsubst verilog-decls-get-consts (decls)
+  (aref decls 6))
+(defsubst verilog-decls-get-gparams (decls)
+  (aref decls 7))
+(defsubst verilog-subdecls-get-outputs (subdecls)
+  (aref subdecls 0))
+(defsubst verilog-subdecls-get-inouts (subdecls)
+  (aref subdecls 1))
+(defsubst verilog-subdecls-get-inputs (subdecls)
+  (aref subdecls 2))
+
+
+(defun verilog-read-sub-decls-sig (submoddecls 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))
@@ -6303,19 +6394,19 @@ Return a array of [outputs inouts inputs wire reg assign const]."
       (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)))
+       (cond ((setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
               (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 portdata (assoc port (verilog-decls-get-outputs submoddecls)))
               (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 portdata (assoc port (verilog-decls-get-inputs submoddecls)))
               (setq sigs-in    (cons (list sig vec (concat "To " comment) nil nil
                                            (verilog-sig-signed portdata)
                                            (verilog-sig-type portdata)
@@ -6324,8 +6415,8 @@ Return a array of [outputs inouts inputs wire reg assign const]."
              ;; (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.
+(defun verilog-read-sub-decls-line (submoddecls comment)
+  "For `verilog-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
@@ -6384,11 +6475,11 @@ Return the list of signals found, using submodi to look up each port."
                      (t
                       (setq sig nil)))
                     ;; Process signals
-                    (verilog-read-sub-decls-sig submodi comment port sig vec multidim))))
+                    (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))
                (t
                 (setq sig nil)))
          ;; Process signals
-         (verilog-read-sub-decls-sig submodi comment port sig vec multidim))
+         (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))
        ;;
        (forward-line 1)))))
 
@@ -6405,7 +6496,7 @@ 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 (
+       module ModuleName (
            // Outputs
            .out (out),
            // Inputs
@@ -6416,28 +6507,30 @@ Outputs comments above subcell signals, for example:
          ;; 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)
+      (while (verilog-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)
+                  (comment (concat inst " of " submod ".v"))
+                  submodi submoddecls)
              (when (setq submodi (verilog-modi-lookup submod t))
+               (setq submoddecls (verilog-modi-get-decls submodi))
                ;; 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
+                 (verilog-read-sub-decls-line submoddecls 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
+                 (verilog-read-sub-decls-line submoddecls 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
+                 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
                )))))
       ;; Combine duplicate bits
       ;;(setq rr (vector sigs-out sigs-inout sigs-in))
@@ -6446,7 +6539,7 @@ Outputs comments above subcell signals, for example:
              (verilog-signals-combine-bus (nreverse sigs-in))))))
 
 (defun verilog-read-inst-pins ()
-  "Return a array of [ pins ] for the current instantiation at point.
+  "Return an 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
@@ -6461,7 +6554,7 @@ For example if declare A A (.B(SIG)) then B will be included in the list."
       (vector pins))))
 
 (defun verilog-read-arg-pins ()
-  "Return a array of [ pins ] for the current argument declaration at point."
+  "Return an array of [ pins ] for the current argument declaration at point."
   (save-excursion
     (let ((end-mod-point (point))      ;; presume at /*AUTOARG*/ point
          pins pin)
@@ -6503,10 +6596,15 @@ For example if declare A A (.B(SIG)) then B will be included in the list."
        (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)))
+  ;; Prevent compile warnings; these are let's, not globals
+  ;; Do not remove the eval-when-compile
+  ;; - we want a error when we are debugging this code if they are refed.
+  (defvar sigs-in)
+  (defvar sigs-out)
+  (defvar got-sig)
+  (defvar got-rvalue)
+  (defvar uses-delayed)
+  (defvar vector-skip-list))
 
 (defun verilog-read-always-signals-recurse
   (exit-keywd rvalue ignore-next)
@@ -6632,8 +6730,7 @@ IGNORE-NEXT is true to ignore next token, fake from inside case statement."
           (t
            (forward-char 1)))
          ;; End of non-comment token
-         (setq last-keywd keywd)
-         ))
+         (setq last-keywd keywd)))
       (skip-syntax-forward " "))
     ;; Append the final pending signal
     (when got-sig
@@ -6679,15 +6776,14 @@ IGNORE-NEXT is true to ignore next token, fake from inside case statement."
                  (instant (match-string 2)))
              (if (not (member module verilog-keywords))
                  (setq instants-list (cons (list module instant) instants-list)))))
-       (forward-line 1)
-       ))
+       (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)... )"
+list of ( (signal_name connection_name)... )."
   (save-excursion
     ;; Find beginning
     (let ((tpl-regexp "\\([0-9]+\\)")
@@ -6728,7 +6824,7 @@ list of ( (signal_name connection_name)... )"
                      (goto-char (match-end 0)))
                     ;; Regexp form??
                     ((looking-at
-                      ;; Regexp bug in xemacs disallows ][ inside [], and wants + last
+                      ;; 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))
@@ -6755,8 +6851,7 @@ list of ( (signal_name connection_name)... )"
                     (t
                      (error "%s: AUTO_TEMPLATE parsing error: %s"
                             (verilog-point-text)
-                            (progn (looking-at ".*$") (match-string 0))))
-                    ))
+                            (progn (looking-at ".*$") (match-string 0))))))
             ;; Return
             (vector tpl-regexp
                     (list tpl-sig-list tpl-wild-list)))
@@ -6778,8 +6873,7 @@ Optionally associate it with the specified enumeration 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)))
-    ))
+         (add-to-list enumvar defname)))))
 
 (defun verilog-read-defines (&optional filename recurse subcall)
   "Read `defines and parameters for the current file, or optional FILENAME.
@@ -6863,8 +6957,7 @@ warning message, you need to add to your .emacs file:
          (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))))
-      )))
+           (forward-comment 999)))))))
 
 (defun verilog-read-includes ()
   "Read `includes for the current file.
@@ -6906,7 +6999,7 @@ foo.v (a include):
 (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"
+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)))
@@ -6929,8 +7022,7 @@ Some macros and such are also found and included.  For dinotrace.el"
          (or (member keywd verilog-keywords)
              (member keywd sigs-all)
              (setq sigs-all (cons keywd sigs-all))))
-        (t (forward-char 1)))
-       )
+        (t (forward-char 1))))
       ;; Return list
       sigs-all)))
 
@@ -6998,14 +7090,11 @@ Some macros and such are also found and included.  For dinotrace.el"
        ((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."
+  "Read Verilog options from the specified FILENAME."
   (save-excursion
     (let ((fns (verilog-library-filenames filename (buffer-file-name)))
          (orig-buffer (current-buffer))
@@ -7013,7 +7102,7 @@ Some macros and such are also found and included.  For dinotrace.el"
       (if fns
          (set-buffer (find-file-noselect (car fns)))
        (error (concat (verilog-point-text)
-                      "Can't find verilog-getopt-file -f file: " filename)))
+                      "Can't find verilog-getopt-file -f file: " filename)))
       (goto-char (point-min))
       (while (not (eobp))
        (setq line (buffer-substring (point)
@@ -7029,10 +7118,10 @@ Some macros and such are also found and included.  For dinotrace.el"
   "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))
+    (mapc 'make-local-variable '(verilog-library-extensions
+                                 verilog-library-directories
+                                 verilog-library-files
+                                 verilog-library-flags)))
   ;; Allow user to customize
   (run-hooks 'verilog-before-getopt-flags-hook)
   ;; Process arguments
@@ -7042,13 +7131,76 @@ Some macros and such are also found and included.  For dinotrace.el"
 
 (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 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)
 
 \f
+;;
+;; Cached directory support
+;;
+
+(defvar verilog-dir-cache-preserving nil
+  "If set, the directory cache is enabled, and file system changes are ignored.
+See `verilog-dir-exists-p' and `verilog-dir-files'.")
+
+;; If adding new cached variable, add also to verilog-preserve-dir-cache
+(defvar verilog-dir-cache-list nil
+  "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
+(defvar verilog-dir-cache-lib-filenames nil
+  "Cached data for `verilog-library-filenames'.")
+
+(defmacro verilog-preserve-dir-cache (&rest body)
+  "Execute the BODY forms, allowing directory cache preservation within BODY.
+This means that changes inside BODY made to the file system will not be
+seen by the `verilog-dir-files' and related functions."
+  `(let ((verilog-dir-cache-preserving t)
+        verilog-dir-cache-list
+        verilog-dir-cache-lib-filenames)
+     (progn ,@body)))
+
+(defun verilog-dir-files (dirname)
+  "Return all filenames in the DIRNAME directory.
+Relative paths depend on the `default-directory'.
+Results are cached if inside `verilog-preserve-dir-cache'."
+  (unless verilog-dir-cache-preserving
+    (setq verilog-dir-cache-list nil)) ;; Cache disabled
+  ;; We don't use expand-file-name on the dirname to make key, as it's slow
+  (let* ((cache-key (list dirname default-directory))
+        (fass (assoc cache-key verilog-dir-cache-list))
+        exp-dirname data)
+    (cond (fass  ;; Return data from cache hit
+          (nth 1 fass))
+         (t
+          (setq exp-dirname (expand-file-name dirname)
+                data (and (file-directory-p exp-dirname)
+                          (directory-files exp-dirname nil nil nil)))
+          ;; Note we also encache nil for non-existing dirs.
+          (setq verilog-dir-cache-list (cons (list cache-key data)
+                                             verilog-dir-cache-list))
+          data))))
+;; Miss-and-hit test:
+;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
+;; (prin1 (verilog-dir-files ".")) nil)
+
+(defun verilog-dir-file-exists-p (filename)
+  "Return true if FILENAME exists.
+Like `file-exists-p' but results are cached if inside
+`verilog-preserve-dir-cache'."
+  (let* ((dirname (file-name-directory filename))
+        ;; Correct for file-name-nondirectory returning same if no slash.
+        (dirnamed (if (or (not dirname) (equal dirname filename))
+                      default-directory dirname))
+        (flist (verilog-dir-files dirnamed)))
+    (and flist
+        (member (file-name-nondirectory filename) flist)
+        t)))
+;;(verilog-dir-file-exists-p "verilog-mode.el")
+;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
+
+\f
 ;;
 ;; Module name lookup
 ;;
@@ -7057,11 +7209,8 @@ unless it is already a member of the variable's list"
   "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)))
+          (and (fboundp 'vc-backend)
+               (vc-backend filename)))
        (let (pt)
         (save-excursion
           (set-buffer (find-file-noselect filename))
@@ -7078,11 +7227,10 @@ Allows version control to check out the file if need be."
   "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)
-      ))
+      (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.
+  "Return an 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))
@@ -7117,7 +7265,7 @@ If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
     symbol))
 
 (defun verilog-symbol-detick-text (text)
-  "Return TEXT with any without any known defines.
+  "Return TEXT 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))
@@ -7137,11 +7285,13 @@ If the variable vh-{symbol} is defined, substitute that value."
 (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."
+  ;; Note this function is performance critical.
+  ;; Do not call anything that requires disk access that cannot be cached.
   (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)
+       pattern dirfile dirfiles dirname root filename rest basefile)
     (while dirnames
       (setq dirname (substitute-in-file-name (car dirnames))
            dirnames (cdr dirnames))
@@ -7155,46 +7305,62 @@ Or, just the existing dirnames themselves if there are no wildcards."
                   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)))
+                  pattern (concat "^" pattern "$")
+                  dirfiles (verilog-dir-files root))
             (while dirfiles
-              (setq dirfile (expand-file-name (concat (car dirfiles) rest))
+              (setq basefile (car dirfiles)
+                    dirfile (expand-file-name (concat root basefile rest))
                     dirfiles (cdr dirfiles))
-              (if (file-directory-p dirfile)
-                  (setq dirlist (cons dirfile dirlist))))
-            )
+              (if (and (string-match pattern basefile)
+                       ;; Don't allow abc/*/rtl to match abc/rtl via ..
+                       (not (equal basefile "."))
+                       (not (equal basefile ".."))
+                       (file-directory-p dirfile))
+                  (setq dirlist (cons dirfile dirlist)))))
            ;; Defaults
            (t
             (if (file-directory-p dirname)
-                (setq dirlist (cons dirname dirlist))))
-           ))
+                (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.
+  "Return a search path to find the given FILENAME or module 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)))
+  (unless verilog-dir-cache-preserving
+    (setq verilog-dir-cache-lib-filenames nil))
+  (let* ((cache-key (list filename current check-ext))
+        (fass (assoc cache-key verilog-dir-cache-lib-filenames))
+        chkdirs chkdir chkexts fn outlist)
+    (cond (fass  ;; Return data from cache hit
+          (nth 1 fass))
+         (t
+          ;; Note this expand can't be easily cached, as we need to
+          ;; pick up buffer-local variables for newly read sub-module files
+          (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
+          (while chkdirs
+            (setq chkdir (expand-file-name (car chkdirs)
+                                           (file-name-directory current))
+                  chkexts (if check-ext verilog-library-extensions `("")))
+            (while chkexts
+              (setq fn (expand-file-name (concat filename (car chkexts))
+                                         chkdir))
+              ;;(message "Check for %s" fn)
+              (if (verilog-dir-file-exists-p fn)
+                  (setq outlist (cons (expand-file-name
+                                       fn (file-name-directory current))
+                                      outlist)))
+                (setq chkexts (cdr chkexts)))
+            (setq chkdirs (cdr chkdirs)))
+          (setq outlist (nreverse outlist))
+          (setq verilog-dir-cache-lib-filenames
+                (cons (list cache-key outlist)
+                      verilog-dir-cache-lib-filenames))
+          outlist))))
 
 (defun verilog-module-filenames (module current)
   "Return a search path to find the given MODULE name.
@@ -7220,12 +7386,14 @@ variables to build the path."
 For speeding up verilog-modi-get-* commands.
 Buffer-local.")
 
+(make-variable-buffer-local 'verilog-modi-cache-list)
+
 (defvar verilog-modi-cache-preserve-tick nil
   "Modification tick after which the cache is still considered valid.
-Use verilog-preserve-cache's to set")
+Use `verilog-preserve-modi-cache' to set it.")
 (defvar verilog-modi-cache-preserve-buffer nil
   "Modification tick after which the cache is still considered valid.
-Use verilog-preserve-cache's to set")
+Use `verilog-preserve-modi-cache' to set it.")
 
 (defun verilog-modi-current ()
   "Return the modi structure for the module currently at point."
@@ -7275,13 +7443,11 @@ Return modi if successful, else print message unless IGNORE-ERROR is true."
                                             "")
                                           "\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")))))
-                    )
+                                          (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
-    ))
+    verilog-modi-lookup-last-modi))
 
 (defsubst verilog-modi-name (modi)
   (aref modi 0))
@@ -7291,7 +7457,7 @@ Return modi if successful, else print message unless IGNORE-ERROR is true."
   (aref modi 2))
 
 (defun verilog-modi-filename (modi)
-  "Filename of MODI, or name of buffer if its never been saved."
+  "Filename of MODI, or name of buffer if it's 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)))
@@ -7303,7 +7469,7 @@ Return modi if successful, else print message unless IGNORE-ERROR is true."
   (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
+  (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
       (verilog-mode))
   (goto-char (verilog-modi-point modi)))
 
@@ -7318,10 +7484,10 @@ Return modi if successful, else print message unless IGNORE-ERROR is true."
 (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
+  (let (fass)
+    (save-excursion  ;; Cache is buffer-local so can't avoid this.
       (verilog-modi-goto modi)
-      (if (and (setq fass (assoc (list (verilog-modi-name modi) function)
+      (if (and (setq fass (assoc (list modi function)
                                 verilog-modi-cache-list))
               ;; Destroy caching when incorrect; Modified or file changed
               (not (and verilog-cache-enabled
@@ -7333,28 +7499,26 @@ Cache the output of function so next call may have faster access."
          (setq verilog-modi-cache-list nil
                fass nil))
       (cond (fass
-            ;; Found
-            (setq func-returns (nth 3 fass)))
+            ;; Return data from cache hit
+            (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)))
+                                (font-lock-mode 0)
+                                t))
+                  func-returns)
               (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))
+              (when fontlocked (font-lock-mode t))
+              ;; Cache for next time
+              (setq verilog-modi-cache-list
+                    (cons (list (list 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.
@@ -7363,13 +7527,13 @@ 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)
+      (if (setq fass (assoc (list 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)
+(defmacro verilog-preserve-modi-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
@@ -7380,37 +7544,6 @@ and invalidating the cache."
         (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."
@@ -7427,6 +7560,17 @@ and invalidating the cache."
        (setq enumlist (cdr enumlist))))
     (nreverse out-list)))
 
+(defun verilog-signals-matching-regexp (in-list regexp)
+  "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
+  (if (not regexp)
+      in-list
+    (let (out-list)
+      (while in-list
+       (if (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))))
+
 (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)
@@ -7439,22 +7583,22 @@ and invalidating the cache."
       (nreverse out-list))))
 
 ;; Combined
-(defun verilog-modi-get-signals (modi)
+(defun verilog-decls-get-signals (decls)
   (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)
+   (verilog-decls-get-outputs decls)
+   (verilog-decls-get-inouts decls)
+   (verilog-decls-get-inputs decls)
+   (verilog-decls-get-wires decls)
+   (verilog-decls-get-regs decls)
+   (verilog-decls-get-assigns decls)
+   (verilog-decls-get-consts decls)
+   (verilog-decls-get-gparams decls)))
+
+(defun verilog-decls-get-ports (decls)
   (append
-   (verilog-modi-get-outputs modi)
-   (verilog-modi-get-inouts modi)
-   (verilog-modi-get-inputs modi)))
+   (verilog-decls-get-outputs decls)
+   (verilog-decls-get-inouts decls)
+   (verilog-decls-get-inputs decls)))
 
 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
   (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
@@ -7476,26 +7620,14 @@ and invalidating the cache."
 ;; 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."
+  "Search for the given auto text regexp 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))))
+  (while (verilog-re-search-forward search-for nil t)
+    (funcall func)))
 
 (defun verilog-insert-one-definition (sig type indent-pt)
-  "Print out a definition for SIGNAL of the given TYPE,
+  "Print out a definition for SIG of the given TYPE,
 with appropriate INDENT-PT indentation."
   (indent-to indent-pt)
   (insert type)
@@ -7599,19 +7731,42 @@ This repairs those mis-inserted by a AUTOARG."
             (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 *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
+                             range-exp)
+               (int-to-string
+                (1+ (abs (- (string-to-number (match-string 1 range-exp))
+                            (string-to-number (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 "(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-simplify-range-expression (range-exp)
+  "Return a simplified range expression with constants eliminated from RANGE-EXP."
+  (let ((out range-exp)
+       (last-pass ""))
+    (while (not (equal last-pass out))
+      (setq last-pass out)
+      (while (string-match "(\\<\\([0-9A-Z-az_]+\\)\\>)" out)
+       (setq out (replace-match "\\1" nil nil out)))
+      (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\+\\s *\\<\\([0-9]+\\)\\>" out)
+       (setq out (replace-match 
+                  (int-to-string (+ (string-to-number (match-string 1 out))
+                                    (string-to-number (match-string 2 out))))
+                  nil nil out)))
+      (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\-\\s *\\<\\([0-9]+\\)\\>" out)
+       (setq out (replace-match 
+                  (int-to-string (- (string-to-number (match-string 1 out))
+                                    (string-to-number (match-string 2 out))))
+                  nil nil out))))
+    out))
+;;(verilog-simplify-range-expression "1")
+;;(verilog-simplify-range-expression "(((16)+1)-3)")
+
 (defun verilog-typedef-name-p (variable-name)
   "Return true if the VARIABLE-NAME is a type definition."
   (when verilog-typedef-regexp
@@ -7631,12 +7786,11 @@ This repairs those mis-inserted by a AUTOARG."
       ;; End exists
       (end-of-line)
       (delete-region pt (point))
-      (forward-line 1))
-  ))
+      (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"
+  "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)
@@ -7647,8 +7801,8 @@ ignore other close parenthesis with matching open parens"
             (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"
+  "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)
@@ -7659,8 +7813,8 @@ ignore other open parenthesis with matching close parens"
             (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"
+  "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)
@@ -7745,15 +7899,28 @@ called before and after this function, respectively."
     ;; 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 have multi-line insertions, possibly with parameters
+    (verilog-auto-re-search-do
+     (concat "/\\*"
+            (eval-when-compile
+              (verilog-regexp-words
+               `("AUTOASCIIENUM" "AUTOCONCATCOMMENT" "AUTODEFINEVALUE"
+                 "AUTOINOUT" "AUTOINOUTCOMP" "AUTOINOUTMODULE"
+                 "AUTOINPUT" "AUTOOUTPUT" "AUTOOUTPUTEVERY"
+                 "AUTOREG" "AUTOREGINPUT" "AUTORESET" "AUTOTIEOFF"
+                 "AUTOUNUSED" "AUTOWIRE")))
+            "\\(\\|([^)]*)\\|(\"[^\"]*\")\\)" ; Optional parens or quoted parameter
+            "\\*/")
+     '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)
+    (verilog-auto-re-search-do
+     (concat "/\\*"
+            (eval-when-compile
+              (verilog-regexp-words
+               `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
+                 "AUTOSENSE")))
+            "\\*/")
+     '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)
@@ -7775,37 +7942,39 @@ called before and after this function, respectively."
 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.
+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);
+       module ExampInject (i, o);
          input i;
          input j;
          output o;
          always @ (i or j)
             o = i | j;
-         cell cell (.foobar(baz),
-                    .j(j));
+         InstModule instName
+            (.foobar(baz),
+            j(j));
        endmodule
 
 Typing \\[verilog-inject-auto] will make this into:
 
-       module ex_inject (i, o/*AUTOARG*/
+       module ExampInject (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));
+         InstModule instName
+            (.foobar(baz),
+            /*AUTOINST*/
+            // Outputs
+            j(j));
        endmodule"
   (interactive)
   (verilog-auto t))
@@ -7833,17 +8002,18 @@ Typing \\[verilog-inject-auto] will make this into:
   (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)
+      (let* ((start-pt (point))
+            (modi (verilog-modi-current))
+            (moddecls (verilog-modi-get-decls modi))
+            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))
+               got-sigs (verilog-auto-sense-sigs moddecls 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))
@@ -7907,8 +8077,7 @@ Typing \\[verilog-inject-auto] will make this into:
         (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))
-        ))
+        (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
@@ -7924,7 +8093,7 @@ Typing \\[verilog-inject-auto] will make this into:
 (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)
+  (make-local-variable '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)
@@ -7972,14 +8141,14 @@ Limitations:
 
 For example:
 
-       module ex_arg (/*AUTOARG*/);
+       module ExampArg (/*AUTOARG*/);
          input i;
          output o;
        endmodule
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_arg (/*AUTOARG*/
+       module ExampArg (/*AUTOARG*/
          // Outputs
          o,
          // Inputs
@@ -7991,51 +8160,52 @@ Typing \\[verilog-auto] will make this into:
 
 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.
+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)))
+    (let* ((modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
+          (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)
+                              (verilog-decls-get-outputs moddecls)
                               skip-pins)
                              "// Outputs"
                              verilog-indent-level-declaration)
       (verilog-auto-arg-ports (verilog-signals-not-in
-                              (verilog-modi-get-inouts modi)
+                              (verilog-decls-get-inouts moddecls)
                               skip-pins)
                              "// Inouts"
                              verilog-indent-level-declaration)
       (verilog-auto-arg-ports (verilog-signals-not-in
-                              (verilog-modi-get-inputs modi)
+                              (verilog-decls-get-inputs moddecls)
                               skip-pins)
                              "// Inputs"
                              verilog-indent-level-declaration)
       (verilog-repair-close-comma)
       (unless (eq (char-before) ?/ )
        (insert "\n"))
-      (indent-to verilog-indent-level-declaration)
-      )))
+      (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)
+(defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
   "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."
+@\"(expression @)\" are evaluated, with @ as a variable.
+If FOR-STAR add comment it is a .* expansion.
+If PAR-VALUES replace final strings with these parameter values."
   (let* ((port (verilog-sig-name port-st))
         (tpl-ass (or (assoc port (car tpl-list))
                      (verilog-auto-inst-port-map port-st)))
@@ -8048,12 +8218,24 @@ Insert to INDENT-PT, use template TPL-LIST.
                                      (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)
+        (case-fold-search nil)
+        (check-values par-values)
+        tpl-net)
+    ;; Replace parameters in bit-width
+    (when (and check-values
+              (not (equal vl-bits "")))
+      (while check-values
+       (setq vl-bits (verilog-string-replace-matches
+                      (concat "\\<" (nth 0 (car check-values)) "\\>")
+                      (concat "(" (nth 1 (car check-values)) ")")
+                      t t vl-bits)
+             check-values (cdr check-values)))
+      (setq vl-bits (verilog-simplify-range-expression vl-bits))) ; Not in the loop for speed
+    ;; Default net value if not found
+    (setq 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)))
@@ -8082,13 +8264,12 @@ Insert to INDENT-PT, use template TPL-LIST.
                             (prin1 (eval (car (read-from-string expr)))
                                    (lambda (ch) ())))))
                     (if (numberp value) (setq value (number-to-string value)))
-                    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))
-      )
+      (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
+    ;; Insert it
     (indent-to indent-pt)
     (insert "." port)
     (indent-to verilog-auto-inst-column)
@@ -8126,7 +8307,7 @@ Insert to INDENT-PT, use template TPL-LIST.
   "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
+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.)
 
@@ -8162,11 +8343,14 @@ Limitations:
 
   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
 
-  SystemVerilog multidimmensional input/output has only experimental support.
+  SystemVerilog multidimensional input/output has only experimental support.
+
+  Parameters referenced by the instantiation will remain symbolic, unless
+  `verilog-auto-inst-param-value' is set.
 
-For example, first take the submodule inst.v:
+For example, first take the submodule InstModule.v:
 
-       module inst (o,i)
+       module InstModule (o,i)
           output [31:0] o;
           input i;
           wire [31:0] o = {32{i}};
@@ -8174,22 +8358,24 @@ For example, first take the submodule inst.v:
 
 This is then used in a upper level module:
 
-       module ex_inst (o,i)
+       module ExampInst (o,i)
           output o;
           input i;
-          inst inst (/*AUTOINST*/);
+          InstModule instName
+            (/*AUTOINST*/);
        endmodule
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_inst (o,i)
+       module ExampInst (o,i)
           output o;
           input i;
-          inst inst (/*AUTOINST*/
-                     // Outputs
-                     .ov                       (ov[31:0]),
-                     // Inputs
-                     .i                        (i));
+          InstModule instName
+            (/*AUTOINST*/
+             // Outputs
+             .ov       (ov[31:0]),
+             // Inputs
+             .i        (i));
        endmodule
 
 Where the list of inputs and outputs came from the inst module.
@@ -8197,9 +8383,9 @@ 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.
+  something trivial like an 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
+  vrename from http://www.veripool.org.
 
   When you need to violate this suggestion there are two ways to list
   exceptions, placing them before the AUTOINST, or using templates.
@@ -8211,11 +8397,12 @@ Exceptions:
   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]));
+       InstModule instName
+          (// Inputs
+          .i           (my_i_dont_mess_with_it),
+          /*AUTOINST*/
+          // Outputs
+          .ov          (ov[31:0]));
 
 \f
 Templates:
@@ -8223,15 +8410,15 @@ Templates:
   For multiple instantiations based upon a single template, create a
   commented out template:
 
-       /* instantiating_module_name AUTO_TEMPLATE (
+       /* InstModule AUTO_TEMPLATE (
                .sig3   (sigz[]),
                );
        */
 
-  Templates go ABOVE the instantiation(s).  When a instantiation is
+  Templates go ABOVE the instantiation(s).  When an 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.
+  between the template for an 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
@@ -8252,15 +8439,15 @@ Templates:
 
   For example:
 
-       /* psm_mas AUTO_TEMPLATE (
+       /* InstModule AUTO_TEMPLATE (
                .ptl_bus        (ptl_busnew[]),
                );
        */
-       psm_mas ms2m (/*AUTOINST*/);
+       InstModule ms2m (/*AUTOINST*/);
 
   Typing \\[verilog-auto] will make this into:
 
-       psm_mas ms2m (/*AUTOINST*/
+       InstModule ms2m (/*AUTOINST*/
            // Outputs
            .NotInTemplate      (NotInTemplate),
            .ptl_bus            (ptl_busnew[3:0]),  // Templated
@@ -8271,7 +8458,7 @@ 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\"> (
+       /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
                .sig1   (sigx[@]),
                .sig2   (sigy[@\"(% (+ 1 @) 4)\"]),
                );
@@ -8293,16 +8480,16 @@ Templates:
 
   For example:
 
-       /* psm_mas AUTO_TEMPLATE (
+       /* InstModule AUTO_TEMPLATE (
                .ptl_mapvalidx          (ptl_mapvalid[@]),
                .ptl_mapvalidp1x        (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
                );
        */
-       psm_mas ms2m (/*AUTOINST*/);
+       InstModule ms2m (/*AUTOINST*/);
 
   Typing \\[verilog-auto] will make this into:
 
-       psm_mas ms2m (/*AUTOINST*/
+       InstModule ms2m (/*AUTOINST*/
            // Outputs
            .ptl_mapvalidx              (ptl_mapvalid[2]),
            .ptl_mapvalidp1x            (ptl_mapvalid[3]));
@@ -8311,21 +8498,21 @@ Templates:
 
   Alternatively, using a regular expression for @:
 
-       /* psm_mas AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
+       /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
                .ptl_mapvalidx          (@_ptl_mapvalid),
                .ptl_mapvalidp1x        (ptl_mapvalid_@),
                );
        */
-       psm_mas ms2_FOO (/*AUTOINST*/);
-       psm_mas ms2_BAR (/*AUTOINST*/);
+       InstModule ms2_FOO (/*AUTOINST*/);
+       InstModule ms2_BAR (/*AUTOINST*/);
 
   Typing \\[verilog-auto] will make this into:
 
-       psm_mas ms2_FOO (/*AUTOINST*/
+       InstModule ms2_FOO (/*AUTOINST*/
            // Outputs
            .ptl_mapvalidx              (FOO_ptl_mapvalid),
            .ptl_mapvalidp1x            (ptl_mapvalid_FOO));
-       psm_mas ms2_BAR (/*AUTOINST*/
+       InstModule ms2_BAR (/*AUTOINST*/
            // Outputs
            .ptl_mapvalidx              (BAR_ptl_mapvalid),
            .ptl_mapvalidp1x            (ptl_mapvalid_BAR));
@@ -8337,7 +8524,7 @@ Regexp Templates:
 
            .pci_req\\([0-9]+\\)_l      (pci_req_jtag_[\\1]),
 
-  will apply a Emacs style regular expression search for any port beginning
+  will apply an 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].
@@ -8366,13 +8553,13 @@ Lisp Templates:
   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])
+       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')
+       vl-cell-type   Module name/type of the cell ('InstModule').
+       vl-cell-name   Instance name of the cell ('instName').
 
   Normal Lisp variables may be used in expressions.  See
   `verilog-read-defines' which can set vh-{definename} variables for use
@@ -8385,7 +8572,7 @@ Lisp Templates:
   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; 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
@@ -8399,9 +8586,12 @@ Lisp Templates:
           (verilog-auto-inst-column (max verilog-auto-inst-column
                                          (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
           (vector-skip-list (unless verilog-auto-inst-vector
-                              (verilog-modi-get-signals modi)))
-          submod submodi inst skip-pins tpl-list tpl-num did-first)
+                              (verilog-decls-get-signals moddecls)))
+          submod submodi submoddecls
+          inst skip-pins tpl-list tpl-num did-first par-values)
+
       ;; Find module name that is instantiated
       (setq submod  (verilog-read-inst-module)
            inst (verilog-read-inst-name)
@@ -8412,9 +8602,14 @@ Lisp Templates:
       ;; Parse any AUTO_LISP() before here
       (verilog-read-auto-lisp (point-min) pt)
 
+      ;; Read parameters (after AUTO_LISP)
+      (setq par-values (and verilog-auto-inst-param-value
+                           (verilog-read-inst-param-value)))
+
       ;; Lookup position, etc of submodule
       ;; Note this may raise an error
       (when (setq submodi (verilog-modi-lookup submod t))
+       (setq submoddecls (verilog-modi-get-decls submodi))
        ;; 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))
@@ -8425,38 +8620,42 @@ Lisp Templates:
                tpl-list (aref tpl-info 1)))
        ;; Find submodule's signals and dump
        (let ((sig-list (verilog-signals-not-in
-                        (verilog-modi-get-outputs submodi)
+                        (verilog-decls-get-outputs submoddecls)
                         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)))
+            ;; Note these are searched for in verilog-read-sub-decls.
+           (insert "// Outputs\n")
+           (mapc (lambda (port)
+                    (verilog-auto-inst-port port indent-pt
+                                            tpl-list tpl-num for-star par-values))
+                  sig-list)))
        (let ((sig-list (verilog-signals-not-in
-                        (verilog-modi-get-inouts submodi)
+                        (verilog-decls-get-inouts submoddecls)
                         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)))
+           (mapc (lambda (port)
+                    (verilog-auto-inst-port port indent-pt
+                                            tpl-list tpl-num for-star par-values))
+                  sig-list)))
        (let ((sig-list (verilog-signals-not-in
-                        (verilog-modi-get-inputs submodi)
+                        (verilog-decls-get-inputs submoddecls)
                         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)))
+           (mapc (lambda (port)
+                    (verilog-auto-inst-port port indent-pt
+                                            tpl-list tpl-num for-star par-values))
+                  sig-list)))
        ;; Kill extra semi
        (save-excursion
          (cond (did-first
@@ -8468,9 +8667,7 @@ Lisp Templates:
                 (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))
-                )))
-       ))))
+                    (delete-backward-char 1)))))))))
 
 (defun verilog-auto-inst-param ()
   "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
@@ -8480,29 +8677,29 @@ 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:
+For example, first take the submodule InstModule.v:
 
-       module inst (o,i)
+       module InstModule (o,i)
           parameter PAR;
        endmodule
 
 This is then used in a upper level module:
 
-       module ex_inst (o,i)
+       module ExampInst (o,i)
           parameter PAR;
-          inst #(/*AUTOINSTPARAM*/)
-               inst (/*AUTOINST*/);
+          InstModule #(/*AUTOINSTPARAM*/)
+               instName (/*AUTOINST*/);
        endmodule
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_inst (o,i)
+       module ExampInst (o,i)
           output o;
           input i;
-          inst (/*AUTOINSTPARAM*/
-                // Parameters
-                .PAR                   (PAR));
-               inst (/*AUTOINST*/);
+          InstModule #(/*AUTOINSTPARAM*/
+                       // Parameters
+                       .PAR    (PAR));
+               instName (/*AUTOINST*/);
        endmodule
 
 Where the list of parameter connections come from the inst module.
@@ -8519,9 +8716,11 @@ Templates:
           (verilog-auto-inst-column (max verilog-auto-inst-column
                                          (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
           (vector-skip-list (unless verilog-auto-inst-vector
-                              (verilog-modi-get-signals modi)))
-          submod submodi inst skip-pins tpl-list tpl-num did-first)
+                              (verilog-decls-get-signals moddecls)))
+          submod submodi submoddecls
+          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
@@ -8541,6 +8740,7 @@ Templates:
       ;; Lookup position, etc of submodule
       ;; Note this may raise an error
       (when (setq submodi (verilog-modi-lookup submod t))
+       (setq submoddecls (verilog-modi-get-decls submodi))
        ;; 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))
@@ -8551,16 +8751,18 @@ Templates:
                tpl-list (aref tpl-info 1)))
        ;; Find submodule's signals and dump
        (let ((sig-list (verilog-signals-not-in
-                        (verilog-modi-get-gparams submodi)
+                        (verilog-decls-get-gparams submoddecls)
                         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)))
+            ;; Note these are searched for in verilog-read-sub-decls.
+           (insert "// Parameters\n")
+           (mapc (lambda (port)
+                    (verilog-auto-inst-port port indent-pt
+                                            tpl-list tpl-num nil nil))
+                  sig-list)))
        ;; Kill extra semi
        (save-excursion
          (cond (did-first
@@ -8570,9 +8772,7 @@ Templates:
                 (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))
-                )))
-       ))))
+                    (delete-backward-char 1)))))))))
 
 (defun verilog-auto-reg ()
   "Expand AUTOREG statements, as part of \\[verilog-auto].
@@ -8586,7 +8786,7 @@ Limitations:
 
 An example:
 
-       module ex_reg (o,i)
+       module ExampReg (o,i)
           output o;
           input i;
           /*AUTOREG*/
@@ -8595,12 +8795,12 @@ An example:
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_reg (o,i)
+       module ExampReg (o,i)
           output o;
           input i;
           /*AUTOREG*/
           // Beginning of automatic regs (for this module's undeclared outputs)
-          reg                  o;
+          reg          o;
           // End of automatics
           always o = i;
        endmodule"
@@ -8608,23 +8808,23 @@ Typing \\[verilog-auto] will make this into:
     ;; Point must be at insertion point.
     (let* ((indent-pt (current-indentation))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
+          (modsubdecls (verilog-modi-get-sub-decls modi))
           (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)
-                             ))))
+                     (verilog-decls-get-outputs moddecls)
+                     (append (verilog-decls-get-wires moddecls)
+                             (verilog-decls-get-regs moddecls)
+                             (verilog-decls-get-assigns moddecls)
+                             (verilog-decls-get-consts moddecls)
+                             (verilog-decls-get-gparams moddecls)
+                             (verilog-subdecls-get-outputs modsubdecls)
+                             (verilog-subdecls-get-inouts modsubdecls)))))
       (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"))
-      )))
+       (verilog-insert-indent "// End of automatics\n")))))
 
 (defun verilog-auto-reg-input ()
   "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
@@ -8639,45 +8839,47 @@ Limitations:
 
 An example (see `verilog-auto-inst' for what else is going on here):
 
-       module ex_reg_input (o,i)
+       module ExampRegInput (o,i)
           output o;
           input i;
           /*AUTOREGINPUT*/
-           inst inst (/*AUTOINST*/);
+           InstModule instName
+             (/*AUTOINST*/);
        endmodule
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_reg_input (o,i)
+       module ExampRegInput (o,i)
           output o;
           input i;
           /*AUTOREGINPUT*/
           // Beginning of automatic reg inputs (for undeclared ...
-          reg [31:0]           iv;             // From inst of inst.v
+          reg [31:0]           iv;     // From inst of inst.v
           // End of automatics
-          inst inst (/*AUTOINST*/
-                     // Outputs
-                     .o                        (o[31:0]),
-                     // Inputs
-                     .iv                       (iv));
+          InstModule instName
+             (/*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))
+          (moddecls (verilog-modi-get-decls modi))
+          (modsubdecls (verilog-modi-get-sub-decls modi))
           (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)
-                      ))))
+                      (append (verilog-subdecls-get-inputs modsubdecls)
+                              (verilog-subdecls-get-inouts modsubdecls))
+                      (verilog-decls-get-signals moddecls)))))
       (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"))
-      )))
+       (verilog-insert-indent "// End of automatics\n")))))
 
 (defun verilog-auto-wire ()
   "Expand AUTOWIRE statements, as part of \\[verilog-auto].
@@ -8692,46 +8894,49 @@ Limitations:
   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
+  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)
+       module ExampWire (o,i)
           output o;
           input i;
           /*AUTOWIRE*/
-           inst inst (/*AUTOINST*/);
+           InstModule instName
+            (/*AUTOINST*/);
        endmodule
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_wire (o,i)
+       module ExampWire (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));
+          InstModule instName
+            (/*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))
+          (moddecls (verilog-modi-get-decls modi))
+          (modsubdecls (verilog-modi-get-sub-decls modi))
           (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)
-                      ))))
+                      (append (verilog-subdecls-get-outputs modsubdecls)
+                              (verilog-subdecls-get-inouts modsubdecls))
+                      (verilog-decls-get-signals moddecls)))))
       (forward-line 1)
       (when sig-list
        (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
@@ -8741,12 +8946,11 @@ Typing \\[verilog-auto] will make this into:
        (when nil       ;; Too slow on huge modules, plus makes everyone's module change
          (beginning-of-line)
          (setq pnt (point))
-         (verilog-pretty-declarations)
+         (verilog-pretty-declarations quiet)
          (goto-char pnt)
-         (verilog-pretty-expr "//")))
-      )))
+         (verilog-pretty-expr "//"))))))
 
-(defun verilog-auto-output ()
+(defun verilog-auto-output (&optional with-params)
   "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
@@ -8767,38 +8971,52 @@ Limitations:
 
 An example (see `verilog-auto-inst' for what else is going on here):
 
-       module ex_output (ov,i)
+       module ExampOutput (ov,i)
           input i;
           /*AUTOOUTPUT*/
-          inst inst (/*AUTOINST*/);
+          InstModule instName
+            (/*AUTOINST*/);
        endmodule
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_output (ov,i)
+       module ExampOutput (ov,i)
           input i;
           /*AUTOOUTPUT*/
           // Beginning of automatic outputs (from unused autoinst outputs)
-          output [31:0]        ov;                     // From inst of inst.v
+          output [31:0]        ov;     // From inst of inst.v
           // End of automatics
-          inst inst (/*AUTOINST*/
-                     // Outputs
-                     .ov                       (ov[31:0]),
-                     // Inputs
-                     .i                        (i));
-       endmodule"
+          InstModule instName
+            (/*AUTOINST*/
+             // Outputs
+             .ov       (ov[31:0]),
+             // Inputs
+             .i        (i));
+       endmodule
+
+You may also provide an optional regular expression, in which case only
+signals matching the regular expression will be included.  For example the
+same expansion will result from only extracting outputs starting with ov:
+
+          /*AUTOOUTPUT(\"^ov\")*/"
   (save-excursion
     ;; Point must be at insertion point.
     (let* ((indent-pt (current-indentation))
+          (regexp (and with-params
+                       (nth 0 (verilog-read-auto-params 1))))
           (v2k  (verilog-in-paren))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
+          (modsubdecls (verilog-modi-get-sub-decls modi))
           (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)
-                             ))))
+                     (verilog-subdecls-get-outputs modsubdecls)
+                     (append (verilog-decls-get-outputs moddecls)
+                             (verilog-decls-get-inouts moddecls)
+                             (verilog-subdecls-get-inputs modsubdecls)
+                             (verilog-subdecls-get-inouts modsubdecls)))))
+      (when regexp
+       (setq sig-list (verilog-signals-matching-regexp
+                       sig-list regexp)))
       (setq sig-list (verilog-signals-not-matching-regexp
                      sig-list verilog-auto-output-ignore-regexp))
       (forward-line 1)
@@ -8808,8 +9026,7 @@ Typing \\[verilog-auto] will make this into:
        (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))
-      )))
+      (when v2k (verilog-repair-close-comma)))))
 
 (defun verilog-auto-output-every ()
   "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
@@ -8820,7 +9037,7 @@ won't optimize away the outputs.
 
 An example:
 
-       module ex_output_every (o,i,tempa,tempb)
+       module ExampOutputEvery (o,i,tempa,tempb)
           output o;
           input i;
           /*AUTOOUTPUTEVERY*/
@@ -8831,13 +9048,13 @@ An example:
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_output_every (o,i,tempa,tempb)
+       module ExampOutputEvery (o,i,tempa,tempb)
           output o;
           input i;
           /*AUTOOUTPUTEVERY*/
           // Beginning of automatic outputs (every signal)
-          output               tempb;
-          output               tempa;
+          output       tempb;
+          output       tempa;
           // End of automatics
           wire tempa = i;
           wire tempb = tempa;
@@ -8848,11 +9065,11 @@ Typing \\[verilog-auto] will make this into:
     (let* ((indent-pt (current-indentation))
           (v2k  (verilog-in-paren))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
           (sig-list (verilog-signals-combine-bus
                      (verilog-signals-not-in
-                      (verilog-modi-get-signals modi)
-                      (verilog-modi-get-ports modi)
-                      ))))
+                      (verilog-decls-get-signals moddecls)
+                      (verilog-decls-get-ports moddecls)))))
       (forward-line 1)
       (when v2k (verilog-repair-open-comma))
       (when sig-list
@@ -8860,10 +9077,9 @@ Typing \\[verilog-auto] will make this into:
        (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))
-      )))
+      (when v2k (verilog-repair-close-comma)))))
 
-(defun verilog-auto-input ()
+(defun verilog-auto-input (&optional with-params)
   "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
@@ -8884,41 +9100,55 @@ Limitations:
 
 An example (see `verilog-auto-inst' for what else is going on here):
 
-       module ex_input (ov,i)
+       module ExampInput (ov,i)
           output [31:0] ov;
           /*AUTOINPUT*/
-          inst inst (/*AUTOINST*/);
+          InstModule instName
+            (/*AUTOINST*/);
        endmodule
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_input (ov,i)
+       module ExampInput (ov,i)
           output [31:0] ov;
           /*AUTOINPUT*/
           // Beginning of automatic inputs (from unused autoinst inputs)
-          input                i;                      // From inst of inst.v
+          input        i;      // From inst of inst.v
           // End of automatics
-          inst inst (/*AUTOINST*/
-                     // Outputs
-                     .ov                       (ov[31:0]),
-                     // Inputs
-                     .i                        (i));
-       endmodule"
+          InstModule instName
+            (/*AUTOINST*/
+             // Outputs
+             .ov       (ov[31:0]),
+             // Inputs
+             .i        (i));
+       endmodule
+
+You may also provide an optional regular expression, in which case only
+signals matching the regular expression will be included.  For example the
+same expansion will result from only extracting inputs starting with i:
+
+          /*AUTOINPUT(\"^i\")*/"
   (save-excursion
     (let* ((indent-pt (current-indentation))
+          (regexp (and with-params
+                       (nth 0 (verilog-read-auto-params 1))))
           (v2k  (verilog-in-paren))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
+          (modsubdecls (verilog-modi-get-sub-decls modi))
           (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)
-                             ))))
+                     (verilog-subdecls-get-inputs modsubdecls)
+                     (append (verilog-decls-get-inputs moddecls)
+                             (verilog-decls-get-inouts moddecls)
+                             (verilog-decls-get-wires moddecls)
+                             (verilog-decls-get-regs moddecls)
+                             (verilog-decls-get-consts moddecls)
+                             (verilog-decls-get-gparams moddecls)
+                             (verilog-subdecls-get-outputs modsubdecls)
+                             (verilog-subdecls-get-inouts modsubdecls)))))
+      (when regexp
+       (setq sig-list (verilog-signals-matching-regexp
+                       sig-list regexp)))
       (setq sig-list (verilog-signals-not-matching-regexp
                      sig-list verilog-auto-input-ignore-regexp))
       (forward-line 1)
@@ -8928,10 +9158,9 @@ Typing \\[verilog-auto] will make this into:
        (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))
-      )))
+      (when v2k (verilog-repair-close-comma)))))
 
-(defun verilog-auto-inout ()
+(defun verilog-auto-inout (&optional with-params)
   "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.
@@ -8951,39 +9180,53 @@ Limitations:
 
 An example (see `verilog-auto-inst' for what else is going on here):
 
-       module ex_inout (ov,i)
+       module ExampInout (ov,i)
           input i;
           /*AUTOINOUT*/
-          inst inst (/*AUTOINST*/);
+          InstModule instName
+            (/*AUTOINST*/);
        endmodule
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_inout (ov,i)
+       module ExampInout (ov,i)
           input i;
           /*AUTOINOUT*/
           // Beginning of automatic inouts (from unused autoinst inouts)
-          inout [31:0] ov;                     // From inst of inst.v
+          inout [31:0] ov;     // From inst of inst.v
           // End of automatics
-          inst inst (/*AUTOINST*/
-                     // Inouts
-                     .ov                       (ov[31:0]),
-                     // Inputs
-                     .i                        (i));
-       endmodule"
+          InstModule instName
+            (/*AUTOINST*/
+             // Inouts
+             .ov       (ov[31:0]),
+             // Inputs
+             .i        (i));
+       endmodule
+
+You may also provide an optional regular expression, in which case only
+signals matching the regular expression will be included.  For example the
+same expansion will result from only extracting inouts starting with i:
+
+          /*AUTOINOUT(\"^i\")*/"
   (save-excursion
     ;; Point must be at insertion point.
     (let* ((indent-pt (current-indentation))
+          (regexp (and with-params
+                       (nth 0 (verilog-read-auto-params 1))))
           (v2k  (verilog-in-paren))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
+          (modsubdecls (verilog-modi-get-sub-decls modi))
           (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)
-                             ))))
+                     (verilog-subdecls-get-inouts modsubdecls)
+                     (append (verilog-decls-get-outputs moddecls)
+                             (verilog-decls-get-inouts moddecls)
+                             (verilog-decls-get-inputs moddecls)
+                             (verilog-subdecls-get-inputs modsubdecls)
+                             (verilog-subdecls-get-outputs modsubdecls)))))
+      (when regexp
+       (setq sig-list (verilog-signals-matching-regexp
+                       sig-list regexp)))
       (setq sig-list (verilog-signals-not-matching-regexp
                      sig-list verilog-auto-inout-ignore-regexp))
       (forward-line 1)
@@ -8993,15 +9236,14 @@ Typing \\[verilog-auto] will make this into:
        (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))
-      )))
+      (when v2k (verilog-repair-close-comma)))))
 
-(defun verilog-auto-inout-module ()
+(defun verilog-auto-inout-module (&optional complement)
   "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.
+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
@@ -9017,11 +9259,11 @@ Limitations:
 
 An example:
 
-       module ex_shell (/*AUTOARG*/)
-          /*AUTOINOUTMODULE(\"ex_main\")*/
+       module ExampShell (/*AUTOARG*/)
+          /*AUTOINOUTMODULE(\"ExampMain\")*/
        endmodule
 
-       module ex_main (i,o,io)
+       module ExampMain (i,o,io)
           input i;
           output o;
           inout io;
@@ -9029,32 +9271,54 @@ An example:
 
 Typing \\[verilog-auto] will make this into:
 
-       module ex_shell (/*AUTOARG*/i,o,io)
-          /*AUTOINOUTMODULE(\"ex_main\")*/
+       module ExampShell (/*AUTOARG*/i,o,io)
+          /*AUTOINOUTMODULE(\"ExampMain\")*/
            // Beginning of automatic in/out/inouts (from specific module)
-           input i;
            output o;
            inout io;
+           input i;
           // End of automatics
-       endmodule"
+       endmodule
+
+You may also provide an optional regular expression, in which case only
+signals matching the regular expression will be included.  For example the
+same expansion will result from only extracting signals starting with i:
+
+          /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/"
   (save-excursion
-    (let* ((submod (car (verilog-read-auto-params 1))) submodi)
+    (let* ((params (verilog-read-auto-params 1 2))
+          (submod (nth 0 params))
+          (regexp (nth 1 params))
+          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))
+              (moddecls (verilog-modi-get-decls modi))
+              (submoddecls (verilog-modi-get-decls submodi))
               (sig-list-i  (verilog-signals-not-in
-                            (verilog-modi-get-inputs submodi)
-                            (append (verilog-modi-get-inputs modi))))
+                            (if complement
+                                (verilog-decls-get-outputs submoddecls)
+                              (verilog-decls-get-inputs submoddecls))
+                            (append (verilog-decls-get-inputs moddecls))))
               (sig-list-o  (verilog-signals-not-in
-                            (verilog-modi-get-outputs submodi)
-                            (append (verilog-modi-get-outputs modi))))
+                            (if complement
+                                (verilog-decls-get-inputs submoddecls)
+                              (verilog-decls-get-outputs submoddecls))
+                            (append (verilog-decls-get-outputs moddecls))))
               (sig-list-io (verilog-signals-not-in
-                            (verilog-modi-get-inouts submodi)
-                            (append (verilog-modi-get-inouts modi)))))
+                            (verilog-decls-get-inouts submoddecls)
+                            (append (verilog-decls-get-inouts moddecls)))))
          (forward-line 1)
+         (when regexp
+           (setq sig-list-i  (verilog-signals-matching-regexp
+                              sig-list-i regexp)
+                 sig-list-o  (verilog-signals-matching-regexp
+                              sig-list-o regexp)
+                 sig-list-io (verilog-signals-matching-regexp
+                              sig-list-io regexp)))
          (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")
@@ -9066,18 +9330,68 @@ Typing \\[verilog-auto] will make this into:
            (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))
-         )))))
+         (when v2k (verilog-repair-close-comma)))))))
+
+(defun verilog-auto-inout-comp ()
+  "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
+Take input/output/inout statements from the specified module and
+insert the inverse into the current module (inputs become outputs
+and vice-versa.)  This is useful for making test and stimulus
+modules which need to have complementing 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 ExampShell (/*AUTOARG*/)
+          /*AUTOINOUTCOMP(\"ExampMain\")*/
+       endmodule
+
+       module ExampMain (i,o,io)
+          input i;
+          output o;
+          inout io;
+        endmodule
+
+Typing \\[verilog-auto] will make this into:
+
+       module ExampShell (/*AUTOARG*/i,o,io)
+          /*AUTOINOUTCOMP(\"ExampMain\")*/
+           // Beginning of automatic in/out/inouts (from specific module)
+           output i;
+           inout io;
+           input o;
+          // End of automatics
+       endmodule
+
+You may also provide an optional regular expression, in which case only
+signals matching the regular expression will be included.  For example the
+same expansion will result from only extracting signals starting with i:
 
-(defun verilog-auto-sense-sigs (modi presense-sigs)
+          /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
+  (verilog-auto-inout-module t))
+
+(defun verilog-auto-sense-sigs (moddecls 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)
+                                                   (verilog-decls-get-consts moddecls)
+                                                   (verilog-decls-get-gparams moddecls)
                                                    presense-sigs)))))
     sig-list))
 
@@ -9114,7 +9428,7 @@ OOps!
 
 An example:
 
-          always @ (/*AUTOSENSE*/) begin
+          always @ (/*AS*/) begin
              /* AUTO_CONSTANT (`constant) */
              outin = ina | inb | `constant;
              out = outin;
@@ -9122,10 +9436,18 @@ An example:
 
 Typing \\[verilog-auto] will make this into:
 
-          always @ (/*AUTOSENSE*/ina or inb) begin
+          always @ (/*AS*/ina or inb) begin
              /* AUTO_CONSTANT (`constant) */
              outin = ina | inb | `constant;
              out = outin;
+          end
+
+Note in Verilog 2001, you can often get the same result from the new @*
+operator.  (This was added to the language in part due to AUTOSENSE!)
+
+          always @* begin
+             outin = ina | inb | `constant;
+             out = outin;
           end"
   (save-excursion
     ;; Find beginning
@@ -9136,16 +9458,17 @@ Typing \\[verilog-auto] will make this into:
                        (or (and (goto-char start-pt) (1+ (current-column)))
                            (current-indentation))))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
           (sig-memories (verilog-signals-memory
                          (append
-                          (verilog-modi-get-regs modi)
-                          (verilog-modi-get-wires modi))))
+                          (verilog-decls-get-regs moddecls)
+                          (verilog-decls-get-wires moddecls))))
           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))
+      (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
       (when sig-memories
        (let ((tlen (length sig-list)))
          (setq sig-list (verilog-signals-not-in sig-list sig-memories))
@@ -9168,8 +9491,7 @@ Typing \\[verilog-auto] will make this into:
              (not-first (insert " or ")))
        (insert (verilog-sig-name (car sig-list)))
        (setq sig-list (cdr sig-list)
-             not-first t))
-      )))
+             not-first t)))))
 
 (defun verilog-auto-reset ()
   "Expand AUTORESET statements, as part of \\[verilog-auto].
@@ -9231,7 +9553,8 @@ Typing \\[verilog-auto] will make this into:
     ;; Find beginning
     (let* ((indent-pt (current-indentation))
           (modi (verilog-modi-current))
-          (all-list (verilog-modi-get-signals modi))
+          (moddecls (verilog-modi-get-decls modi))
+          (all-list (verilog-decls-get-signals moddecls))
           sigss sig-list prereset-sigs assignment-str)
       ;; Read signals in always, eliminate outputs from reset list
       (setq prereset-sigs (verilog-signals-from-signame
@@ -9264,8 +9587,7 @@ Typing \\[verilog-auto] will make this into:
                    ";\n")
            (indent-to indent-pt)
            (setq sig-list (cdr sig-list))))
-       (insert "// End of automatics"))
-      )))
+       (insert "// End of automatics")))))
 
 (defun verilog-auto-tieoff ()
   "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
@@ -9283,7 +9605,7 @@ them to a one.
 
 An example of making a stub for another module:
 
-    module FooStub (/*AUTOINST*/);
+    module ExampStub (/*AUTOINST*/);
        /*AUTOINOUTMODULE(\"Foo\")*/
         /*AUTOTIEOFF*/
         // verilator lint_off UNUSED
@@ -9295,7 +9617,7 @@ An example of making a stub for another module:
 
 Typing \\[verilog-auto] will make this into:
 
-    module FooStub (/*AUTOINST*/...);
+    module ExampStub (/*AUTOINST*/...);
        /*AUTOINOUTMODULE(\"Foo\")*/
         // Beginning of autotieoff
         output [2:0] foo;
@@ -9312,16 +9634,17 @@ Typing \\[verilog-auto] will make this into:
     ;; Find beginning
     (let* ((indent-pt (current-indentation))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
+          (modsubdecls (verilog-modi-get-sub-decls modi))
           (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)
-                             ))))
+                     (verilog-decls-get-outputs moddecls)
+                     (append (verilog-decls-get-wires moddecls)
+                             (verilog-decls-get-regs moddecls)
+                             (verilog-decls-get-assigns moddecls)
+                             (verilog-decls-get-consts moddecls)
+                             (verilog-decls-get-gparams moddecls)
+                             (verilog-subdecls-get-outputs modsubdecls)
+                             (verilog-subdecls-get-inouts modsubdecls)))))
       (when sig-list
        (forward-line 1)
        (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
@@ -9334,8 +9657,7 @@ Typing \\[verilog-auto] will make this into:
            (insert "= " (verilog-sig-tieoff sig)
                    ";\n")
            (setq sig-list (cdr sig-list))))
-       (verilog-insert-indent "// End of automatics\n")
-       ))))
+       (verilog-insert-indent "// End of automatics\n")))))
 
 (defun verilog-auto-unused ()
   "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
@@ -9366,8 +9688,8 @@ You can add signals you do not want included in AUTOUNUSED with
 
 An example of making a stub for another module:
 
-    module FooStub (/*AUTOINST*/);
-       /*AUTOINOUTMODULE(\"Foo\")*/
+    module ExampStub (/*AUTOINST*/);
+       /*AUTOINOUTMODULE(\"Examp\")*/
         /*AUTOTIEOFF*/
         // verilator lint_off UNUSED
         wire _unused_ok = &{1'b0,
@@ -9395,12 +9717,13 @@ Typing \\[verilog-auto] will make this into:
     ;; Find beginning
     (let* ((indent-pt (progn (search-backward "/*") (current-column)))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
+          (modsubdecls (verilog-modi-get-sub-decls modi))
           (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)
-                             ))))
+                     (append (verilog-decls-get-inputs moddecls)
+                             (verilog-decls-get-inouts moddecls))
+                     (append (verilog-subdecls-get-inputs modsubdecls)
+                             (verilog-subdecls-get-inouts modsubdecls)))))
       (setq sig-list (verilog-signals-not-matching-regexp
                      sig-list verilog-auto-unused-ignore-regexp))
       (when sig-list
@@ -9412,11 +9735,10 @@ Typing \\[verilog-auto] will make this into:
            (indent-to indent-pt)
            (insert (verilog-sig-name sig) ",\n")
            (setq sig-list (cdr sig-list))))
-       (verilog-insert-indent "// End of automatics\n")
-       ))))
+       (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.
+  "Convert an enum name SIGNM to an ascii string for insertion.
 Remove user provided prefix ELIM-REGEXP."
   (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
   (let ((case-fold-search t))
@@ -9489,14 +9811,15 @@ Typing \\[verilog-auto] will make this into:
           ;;
           (indent-pt (current-indentation))
           (modi (verilog-modi-current))
+          (moddecls (verilog-modi-get-decls modi))
           ;;
-          (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)))
+          (sig-list-consts (append (verilog-decls-get-consts moddecls)
+                                   (verilog-decls-get-gparams moddecls)))
+          (sig-list-all  (append (verilog-decls-get-regs moddecls)
+                                 (verilog-decls-get-outputs moddecls)
+                                 (verilog-decls-get-inouts moddecls)
+                                 (verilog-decls-get-inputs moddecls)
+                                 (verilog-decls-get-wires moddecls)))
           ;;
           (undecode-sig (or (assoc undecode-name sig-list-all)
                             (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
@@ -9547,8 +9870,7 @@ Typing \\[verilog-auto] will make this into:
       (verilog-insert-indent "endcase\n")
       (setq indent-pt (- indent-pt verilog-indent-level))
       (verilog-insert-indent "end\n"
-                            "// End of automatics\n")
-      )))
+                            "// End of automatics\n"))))
 
 (defun verilog-auto-templated-rel ()
   "Replace Templated relative line numbers with absolute line numbers.
@@ -9559,16 +9881,18 @@ being different from the final output's line numbering."
     (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
+           (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))))
+      (replace-match
+       (concat " Templated "
+              (int-to-string (+ (nth (string-to-number (match-string 1))
+                                     template-line)
+                                (string-to-number (match-string 2)))))
+       t t))))
 
 \f
 ;;
@@ -9591,12 +9915,12 @@ The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
 called before and after this function, respectively.
 
 For example:
-       module (/*AUTOARG*/)
+       module ModuleName (/*AUTOARG*/)
        /*AUTOINPUT*/
        /*AUTOOUTPUT*/
        /*AUTOWIRE*/
        /*AUTOREG*/
-       somesub sub #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
+       InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
 
 You can also update the AUTOs from the shell using:
        emacs --batch  <filenames.v>  -f verilog-batch-auto
@@ -9609,6 +9933,7 @@ Likewise, you can delete or inject AUTOs with:
 Using \\[describe-function], see also:
     `verilog-auto-arg'          for AUTOARG module instantiations
     `verilog-auto-ascii-enum'   for AUTOASCIIENUM enumeration decoding
+    `verilog-auto-inout-comp'  for AUTOINOUTCOMP copy complemented i/o
     `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
@@ -9629,10 +9954,10 @@ Using \\[describe-function], see also:
     `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."
+Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.org."
   (interactive)
   (unless noninteractive (message "Updating AUTOs..."))
-  (if (featurep 'dinotrace)
+  (if (fboundp 'dinotrace-unannotate-all)
       (dinotrace-unannotate-all))
   (let ((oldbuf (if (not (buffer-modified-p))
                    (buffer-string)))
@@ -9641,8 +9966,10 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
        ;; 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)))
+                     (font-lock-mode 0)
+                     t))
+       ;; Cache directories; we don't write new files, so can't change
+       (verilog-dir-cache-preserving t))
     (unwind-protect
        (save-excursion
          ;; If we're not in verilog-mode, change syntax table so parsing works right
@@ -9653,51 +9980,59 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
          (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)
-          )
+         ;; From here on out, we can cache anything we read from disk
+         (verilog-preserve-dir-cache
+          ;; 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-modi-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-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
+           (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
+           (verilog-auto-re-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)
+           (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP([^)]*)\\*/" 'verilog-auto-inout-comp)
+           ;; next in/outs which need previous sucked inputs first
+           (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((\"[^\"]*\")\\)\\*/"
+                                      '(lambda () (verilog-auto-output t)))
+           (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\*/" 'verilog-auto-output)
+           (verilog-auto-re-search-do "/\\*AUTOINPUT\\((\"[^\"]*\")\\)\\*/"
+                                      '(lambda () (verilog-auto-input t)))
+           (verilog-auto-re-search-do "/\\*AUTOINPUT\\*/"  'verilog-auto-input)
+           (verilog-auto-re-search-do "/\\*AUTOINOUT\\((\"[^\"]*\")\\)\\*/"
+                                      '(lambda () (verilog-auto-inout t)))
+           (verilog-auto-re-search-do "/\\*AUTOINOUT\\*/" 'verilog-auto-inout)
+           ;; Then tie off those in/outs
+           (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
+           ;; Wires/regs must be after inputs/outputs
+           (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
+           (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
+           (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
+           ;; outputevery needs AUTOOUTPUTs done first
+           (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
+           ;; After we've created all new variables
+           (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
+           ;; Must be after all inputs outputs are generated
+           (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
+           ;; Fix line numbers (comments only)
+           (verilog-auto-templated-rel)))
          ;;
          (run-hooks 'verilog-auto-hook)
          ;;
@@ -9711,14 +10046,13 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
       ;; Unwind forms
       (progn
        ;; Restore font-lock
-       (when fontlocked (font-lock-mode t)))
-      )))
+       (when fontlocked (font-lock-mode t))))))
 \f
 
 ;;
 ;; Skeleton based code insertion
 ;;
-(defvar verilog-template-map 
+(defvar verilog-template-map
   (let ((map (make-sparse-keymap)))
     (define-key map "a" 'verilog-sk-always)
     (define-key map "b" 'verilog-sk-begin)
@@ -9786,7 +10120,7 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
 (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")))
+  (setq verilog-sk-reset (read-string "name of reset: " "rst")))
 
 
 (define-skeleton verilog-sk-prompt-state-selector
@@ -9799,7 +10133,7 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
 
 (define-skeleton verilog-sk-prompt-msb
   "Prompt for least significant bit specification."
-  "msb:" str & ?: & (verilog-sk-prompt-lsb) | -1 )
+  "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
 
 (define-skeleton verilog-sk-prompt-lsb
   "Prompt for least significant bit specification."
@@ -9838,21 +10172,21 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
 (define-skeleton verilog-sk-module
   "Insert a module definition."
   ()
-  > "module " (verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
+  > "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
+  > "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
+  > "task " '(verilog-sk-prompt-name) & ?; \n
   > _ \n
   > "begin" \n
   > \n
@@ -9862,7 +10196,7 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
 (define-skeleton verilog-sk-function
   "Insert a function definition."
   ()
-  > "function [" (verilog-sk-prompt-width) | -1 (verilog-sk-prompt-name) ?; \n
+  > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
   > _ \n
   > "begin" \n
   > \n
@@ -9900,15 +10234,15 @@ for sensitivity list."
   > (- verilog-indent-level-behavioral) "endgenerate" \n > )
 
 (define-skeleton verilog-sk-begin
-  "Insert begin end block.  Uses the minibuffer to prompt for name"
+  "Insert begin end block.  Uses the minibuffer to prompt for name."
   ()
-  > "begin" (verilog-sk-prompt-name) \n
+  > "begin" '(verilog-sk-prompt-name) \n
   > _ \n
   > (- verilog-indent-level-behavioral) "end"
 )
 
 (define-skeleton verilog-sk-fork
-  "Insert an fork join block."
+  "Insert a fork join block."
   ()
   > "fork\n"
   > "begin" \n
@@ -9947,56 +10281,54 @@ and the case items."
 
 (define-skeleton verilog-sk-if
   "Insert a skeleton if statement."
-  > "if (" (verilog-sk-prompt-condition) & ")" " begin" \n
+  > "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
+  (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"
+  "Common routine to get data definition."
   ()
-  (verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
+  '(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))
+  > "input  [" '(verilog-sk-datadef))
 
 (define-skeleton verilog-sk-output
   "Insert an output definition."
   ()
-  > "output [" (verilog-sk-datadef))
+  > "output [" '(verilog-sk-datadef))
 
 (define-skeleton verilog-sk-inout
   "Insert an inout definition."
   ()
-  > "inout  [" (verilog-sk-datadef))
+  > "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) )
+  > "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_]*")
+  (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))))
-        )
+                (point)))))
     (if (not (member v1 verilog-keywords))
        (save-excursion
          (setq verilog-sk-signal v1)
@@ -10005,37 +10337,34 @@ and the case items."
          (verilog-forward-syntactic-ws)
          (verilog-sk-def-reg)
          (message "signal at point is %s" v1))
-      (message "object at point (%s) is a keyword" v1))
-    )
-  )
-
+      (message "object at point (%s) is a keyword" v1))))
 
 (define-skeleton verilog-sk-wire
   "Insert a wire definition."
   ()
-  > "wire   [" (verilog-sk-datadef))
+  > "wire   [" '(verilog-sk-datadef))
 
 (define-skeleton verilog-sk-reg
   "Insert a reg definition."
   ()
-  > "reg   [" (verilog-sk-datadef))
+  > "reg   [" '(verilog-sk-datadef))
 
 (define-skeleton verilog-sk-assign
   "Insert a skeleton assign statement."
   ()
-  > "assign " (verilog-sk-prompt-name) " = " _ ";" \n)
+  > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
 
 (define-skeleton verilog-sk-while
   "Insert a skeleton while loop statement."
   ()
-  > "while ("  (verilog-sk-prompt-condition)  ") begin" \n
+  > "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
+  > "repeat ("  '(verilog-sk-prompt-condition)  ") begin" \n
   > _ \n
   > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
 
@@ -10043,9 +10372,9 @@ and the case items."
   "Insert a skeleton while loop statement."
   ()
   > "for ("
-  (verilog-sk-prompt-init) "; "
-  (verilog-sk-prompt-condition) "; "
-  (verilog-sk-prompt-inc)
+  '(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))
@@ -10063,7 +10392,7 @@ and the case items."
   '(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
+  > "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
@@ -10074,27 +10403,10 @@ and the case items."
   > \n
   > "// Next State Logic for " verilog-sk-state \n
   > "always @ ( /*AUTOSENSE*/ ) begin\n"
-  > "case (" (verilog-sk-prompt-state-selector) ") " \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)
-
 \f
 
 ;;
@@ -10111,7 +10423,7 @@ and the case items."
   "^`include\\s-+\"\\([^\n\"]*\\)\""
   "Regexp that matches the include file.")
 
-(defvar verilog-mode-mouse-map 
+(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
@@ -10158,7 +10470,7 @@ Clicking on the middle-mouse button loads them in a buffer (as in dired)."
 
 
 (defun verilog-colorize-include-files-buffer ()
-  "Colorize a include file."
+  "Colorize an include file."
   (interactive)
   ;; delete overlays
   (let ((overlays (overlays-in (point-min) (point-max))))
@@ -10171,14 +10483,14 @@ Clicking on the middle-mouse button loads them in a buffer (as in dired)."
   ;; remake overlays
   (verilog-colorize-include-files (point-min) (point-max) nil))
 
-;; ffap-at-mouse isn't useful for verilog mode. It uses library paths.
+;; 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
+  (save-excursion ;; implement a Verilog specific ffap-at-mouse
     (mouse-set-point event)
     (beginning-of-line)
     (if (looking-at verilog-include-file-regexp)
@@ -10191,17 +10503,16 @@ Files are checked based on `verilog-library-directories'."
          (progn
            (message
             "File '%s' isn't readable, use shift-mouse2 to paste in this field"
-            (match-string 1))))
-      )))
+            (match-string 1)))))))
 
-;; ffap isn't useable for verilog mode. It uses library paths.
+;; 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
+  (save-excursion ;; implement a Verilog specific ffap
     (beginning-of-line)
     (if (looking-at verilog-include-file-regexp)
        (if (and
@@ -10210,8 +10521,7 @@ Files are checked based on `verilog-library-directories'."
             (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))))))
-      ))
+                            (match-string 1) (buffer-file-name))))))))
 
 
 ;;
@@ -10226,11 +10536,14 @@ Files are checked based on `verilog-library-directories'."
     (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 "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
     (princ "\n")
     (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
     (princ "\n")))
 
+(autoload 'reporter-submit-bug-report "reporter")
+(defvar reporter-prompt-for-summary-p)
+
 (defun verilog-submit-bug-report ()
   "Submit via mail a bug report on verilog-mode.el."
   (interactive)
@@ -10290,12 +10603,12 @@ 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.
+Snyder (wsnyder@wsnyder.org) and/or see http://www.veripool.org.
 You may also want to look at the Verilog-Mode FAQ, see
-http://www.veripool.com/verilog-mode-faq.html.
+http://www.veripool.org/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
+-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;
@@ -10310,4 +10623,5 @@ but instead, [[Fill in here]] happens!.
 ;; checkdoc-force-docstrings-flag:nil
 ;; End:
 
+;; arch-tag: 87923725-57b3-41b5-9494-be21118c6a6f
 ;;; verilog-mode.el ends here