Merge from emacs--rel--22
[bpt/emacs.git] / lisp / progmodes / verilog-mode.el
index b24ccdc..8ae43f0 100644 (file)
 ;;     http://www.veripool.com
 ;; Keywords: languages
 
+;; 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
+;; GNU Emacs is free software: you can redistribute it and/or modify
 ;; it under the terms of the GNU General Public License as published by
-;; the Free Software Foundation; either version 3, or (at your option)
-;; any later version.
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
 
 ;; GNU Emacs is distributed in the hope that it will be useful,
 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -30,9 +35,7 @@
 ;; GNU General Public License for more details.
 
 ;; You should have received a copy of the GNU General Public License
-;; along with GNU Emacs; see the file COPYING.  If not, write to the
-;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-;; Boston, MA 02110-1301, USA.
+;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
 
 ;;; Commentary:
 
 ;;; Code:
 
 ;; This variable will always hold the version number of the mode
-(defconst verilog-mode-version "404"
+(defconst verilog-mode-version "423"
   "Version of this Verilog mode.")
-(defconst verilog-mode-release-date "2008-03-02-GNU"
+(defconst verilog-mode-release-date "2008-05-07-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.")
@@ -257,13 +260,35 @@ STRING should be given if the last search was by `string-match' on STRING."
     "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)
   (if (fboundp 'customize-apropos)
       (customize-apropos "font-lock-*" 'faces)))
@@ -274,6 +299,10 @@ STRING should be given if the last search was by `string-match' on STRING."
  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."
   :version "22.2"
@@ -962,137 +991,221 @@ If set will become buffer local.")
 ;; menus
 (easy-menu-define
   verilog-menu verilog-mode-map "Menu for Verilog mode"
-  `("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
-      :keys "C-M-a"]
-     ["End of function"                 verilog-end-of-defun
-      :keys "C-M-e"]
-     ["Mark function"                   verilog-mark-defun
-      :keys "C-M-h"]
-     ["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]))
+  (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"]
+      ["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."
-  '("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]))
+  (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.")
@@ -1125,7 +1238,7 @@ 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))
+  (store-match-data '(nil nil))  ;; So match-end will return nil if no matches found
   (while (and
          (re-search-forward REGEXP BOUND NOERROR)
          (and (verilog-skip-forward-comment-or-string)
@@ -1139,7 +1252,7 @@ will break, as the o's continuously replace.  xa -> x works ok though."
 (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))
+  (store-match-data '(nil nil))  ;; So match-end will return nil if no matches found
   (while (and
          (re-search-backward REGEXP BOUND NOERROR)
          (and (verilog-skip-backward-comment-or-string)
@@ -1742,7 +1855,7 @@ find the errors."
          (modify-syntax-entry ?/  ". 1456" table)
          (modify-syntax-entry ?*  ". 23"   table)
          (modify-syntax-entry ?\n "> b"    table))
-      ;; Emacs 19 does things differently, but we can work with it
+      ;; 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))
@@ -1840,7 +1953,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
@@ -2004,13 +2117,13 @@ 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))
 
 (defun electric-verilog-forward-sexp ()
-  "Move forward over a sexp."
+  "Move forward over one balanced expression."
   (interactive)
   ;; before that see if we are in a comment
   (verilog-forward-sexp))
@@ -2308,15 +2421,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.
@@ -2381,7 +2494,7 @@ Key bindings specific to `verilog-mode-map' are:
     (easy-menu-add verilog-menu)
     (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
 
-  ;; Stuff for GNU emacs
+  ;; 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
@@ -2392,21 +2505,25 @@ Key bindings specific to `verilog-mode-map' are:
   ;; all buffer local:
   (when (featurep 'xemacs)
     (make-local-hook 'font-lock-mode-hook)
-    (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in emacs 20
+    (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
+  (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.
   (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)))
+  (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
@@ -2423,9 +2540,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)
@@ -2936,7 +3051,7 @@ More specifically, point @ in the line foo : @ begin"
 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)
@@ -3357,7 +3472,7 @@ primitive or interface named NAME."
               (;- 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
@@ -3367,7 +3482,8 @@ primitive or interface named NAME."
                  (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\\)\\>\\)"))
                   ((match-end 7) ;; of verilog-end-block-ordered-re
@@ -3398,9 +3514,9 @@ primitive or interface named NAME."
                        (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))
+                                       (goto-char (match-beginning 0))
                                        (verilog-forward-ws&directives)))
                                  (point))
                              e (progn
@@ -3692,7 +3808,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."
@@ -4273,9 +4389,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)
@@ -4307,9 +4421,7 @@ Optional BOUND limits search."
           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))
@@ -4329,16 +4441,12 @@ Optional BOUND limits search."
 
 (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
@@ -4347,16 +4455,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 ()
@@ -4370,9 +4474,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 ()
@@ -4413,18 +4515,15 @@ Optional BOUND limits search."
 
 (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)
@@ -4436,9 +4535,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 "\"")
@@ -4458,9 +4555,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 "//")
@@ -4484,9 +4579,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)
@@ -4595,10 +4688,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 )
@@ -4832,7 +4923,7 @@ ARG is ignored, for `comment-indent-function' compatibility."
     (if (or (eq myre nil)
            (string-equal myre ""))
        (setq myre "\\(<\\|:\\)?="))
-    (setq myre (concat "\\(^[^;#:<=>]*\\)\\(" myre "\\)"))
+    (setq myre (concat "\\(^[^;#<=>]*\\)\\(" myre "\\)"))
     (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
       (beginning-of-line)
       (if (and (not (looking-at rexp ))
@@ -5935,7 +6026,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 ()
@@ -5943,7 +6034,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 ()
@@ -5953,7 +6044,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-auto-params (num-param &optional max-param)
@@ -6071,7 +6162,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"))
@@ -6131,31 +6223,31 @@ Return a array of [outputs inouts inputs wire reg assign const]."
 ;; 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-read-sub-decls-sig (submodi comment port sig vec multidim)
+(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
@@ -6166,19 +6258,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)
@@ -6187,7 +6279,7 @@ 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)
+(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)
@@ -6247,11 +6339,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)))))
 
@@ -6268,7 +6360,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
@@ -6279,28 +6371,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))
@@ -6594,7 +6688,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))
@@ -6872,7 +6966,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)
@@ -6908,6 +7002,69 @@ unless it is already a member of the variable's list."
 ;;(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
 ;;
@@ -6992,11 +7149,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))
@@ -7010,18 +7169,19 @@ 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)
+              (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
@@ -7031,23 +7191,40 @@ Or, just the existing dirnames themselves if there are no wildcards."
 ;;(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.
@@ -7077,10 +7254,10 @@ Buffer-local.")
 
 (defvar verilog-modi-cache-preserve-tick nil
   "Modification tick after which the cache is still considered valid.
-Use `verilog-preserve-cache' to set it.")
+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' to set it.")
+Use `verilog-preserve-modi-cache' to set it.")
 
 (defun verilog-modi-current ()
   "Return the modi structure for the module currently at point."
@@ -7171,10 +7348,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
@@ -7186,26 +7363,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)))
+                                t))
+                  func-returns)
               (setq func-returns (funcall function))
-              (when fontlocked (font-lock-mode t)))
-            ;; Cache for next time
-            (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.
@@ -7214,13 +7391,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
@@ -7247,6 +7424,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)
@@ -7259,22 +7447,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))
@@ -7296,23 +7484,11 @@ 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 SIG of the given TYPE,
@@ -7565,15 +7741,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" "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)
@@ -7603,29 +7792,31 @@ 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))
@@ -7653,17 +7844,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))
@@ -7791,14 +7983,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
@@ -7816,21 +8008,22 @@ 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)
@@ -7980,9 +8173,9 @@ Limitations:
 
   SystemVerilog multidimensional input/output has only experimental support.
 
-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}};
@@ -7990,22 +8183,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.
@@ -8027,11 +8222,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:
@@ -8039,7 +8235,7 @@ Templates:
   For multiple instantiations based upon a single template, create a
   commented out template:
 
-       /* instantiating_module_name AUTO_TEMPLATE (
+       /* InstModule AUTO_TEMPLATE (
                .sig3   (sigz[]),
                );
        */
@@ -8068,15 +8264,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
@@ -8087,7 +8283,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)\"]),
                );
@@ -8109,16 +8305,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]));
@@ -8127,21 +8323,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));
@@ -8187,8 +8383,8 @@ Lisp Templates:
        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
@@ -8215,9 +8411,11 @@ 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)
       ;; Find module name that is instantiated
       (setq submod  (verilog-read-inst-module)
            inst (verilog-read-inst-name)
@@ -8231,6 +8429,7 @@ Lisp 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))
@@ -8241,7 +8440,7 @@ 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
@@ -8254,7 +8453,7 @@ Lisp Templates:
                                             tpl-list tpl-num for-star))
                   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
@@ -8266,7 +8465,7 @@ Lisp Templates:
                                             tpl-list tpl-num for-star))
                   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
@@ -8298,29 +8497,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.
@@ -8337,9 +8536,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
@@ -8359,6 +8560,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))
@@ -8369,7 +8571,7 @@ 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
@@ -8404,7 +8606,7 @@ Limitations:
 
 An example:
 
-       module ex_reg (o,i)
+       module ExampReg (o,i)
           output o;
           input i;
           /*AUTOREG*/
@@ -8413,12 +8615,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"
@@ -8426,15 +8628,17 @@ 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")
@@ -8455,37 +8659,41 @@ 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")
@@ -8513,38 +8721,42 @@ Limitations:
 
 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")
@@ -8558,7 +8770,7 @@ Typing \\[verilog-auto] will make this into:
          (goto-char pnt)
          (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
@@ -8579,37 +8791,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)
@@ -8630,7 +8857,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*/
@@ -8641,13 +8868,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;
@@ -8658,10 +8885,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
@@ -8671,7 +8899,7 @@ Typing \\[verilog-auto] will make this into:
        (verilog-insert-indent "// End of automatics\n"))
       (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
@@ -8692,40 +8920,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)
@@ -8737,7 +8980,7 @@ Typing \\[verilog-auto] will make this into:
        (verilog-insert-indent "// End of automatics\n"))
       (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.
@@ -8757,38 +9000,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)
@@ -8821,11 +9079,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;
@@ -8833,32 +9091,50 @@ 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;
           // 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))))
+                            (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))))
+                            (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")
@@ -8872,15 +9148,15 @@ Typing \\[verilog-auto] will make this into:
            (verilog-insert-indent "// End of automatics\n"))
          (when v2k (verilog-repair-close-comma)))))))
 
-(defun verilog-auto-sense-sigs (modi presense-sigs)
+(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))
 
@@ -8917,7 +9193,7 @@ OOps!
 
 An example:
 
-          always @ (/*AUTOSENSE*/) begin
+          always @ (/*AS*/) begin
              /* AUTO_CONSTANT (`constant) */
              outin = ina | inb | `constant;
              out = outin;
@@ -8925,10 +9201,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
@@ -8939,16 +9223,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))
@@ -9033,7 +9318,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
@@ -9084,7 +9370,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
@@ -9096,7 +9382,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;
@@ -9113,15 +9399,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")
@@ -9165,8 +9453,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,
@@ -9194,11 +9482,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
@@ -9286,14 +9576,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)))
@@ -9389,12 +9680,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
@@ -9440,7 +9731,9 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
        (fontlocked (when (and (boundp 'font-lock-mode)
                               font-lock-mode)
                      (font-lock-mode nil)
-                     t)))
+                     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
@@ -9451,50 +9744,58 @@ 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)
+           ;; 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)
          ;;
@@ -9504,11 +9805,11 @@ Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
          (cond ((and oldbuf (equal oldbuf (buffer-string)))
                 (set-buffer-modified-p nil)
                 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
-               (t (unless noninteractive (message "Updating AUTOs...done")))))
+               (t (unless noninteractive (message "Updating AUTOs...done"))))))
       ;; Unwind forms
       (progn
        ;; Restore font-lock
-       (when fontlocked (font-lock-mode t))))))
+       (when fontlocked (font-lock-mode t)))))
 \f
 
 ;;