]> git.rkrishnan.org Git - .emacs.d.git/blob - emacs/verilog-mode.el
remove toolbar and menubar
[.emacs.d.git] / emacs / verilog-mode.el
1 ;; verilog-mode.el --- major mode for editing verilog source in Emacs
2 ;;
3 ;; $Id: verilog-mode.el 344 2007-07-10 15:49:18Z wsnyder $
4
5 ;; Copyright (C) 1996-2007 Free Software Foundation, Inc.
6
7 ;; Author: Michael McNamara (mac@verilog.com)
8 ;;  http://www.verilog.com
9 ;;
10 ;; AUTO features, signal, modsig; by: Wilson Snyder
11 ;;      (wsnyder@wsnyder.org)
12 ;;      http://www.veripool.com
13 ;; Keywords: languages
14
15 ;; This program is free software; you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation; either version 2 of the License, or
18 ;; (at your option) any later version.
19
20 ;; This program is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 ;; GNU General Public License for more details.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with this program; if not, write to the Free Software
27 ;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28
29 ;;; Commentary:
30
31 ;; This mode borrows heavily from the Pascal-mode and the cc-mode of emacs
32
33 ;; USAGE
34 ;; =====
35
36 ;; A major mode for editing Verilog HDL source code. When you have
37 ;; entered Verilog mode, you may get more info by pressing C-h m. You
38 ;; may also get online help describing various functions by: C-h f
39 ;; <Name of function you want described>
40
41 ;; You can get step by step help in installing this file by going to
42 ;; <http://www.verilog.com/emacs_install.html>
43
44 ;; The short list of installation instructions are: To set up
45 ;; automatic verilog mode, put this file in your load path, and put
46 ;; the following in code (please un comment it first!) in your
47 ;; .emacs, or in your site's site-load.el
48
49 ; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
50 ; (setq auto-mode-alist (cons  '("\\.v\\'" . verilog-mode) auto-mode-alist))
51 ; (setq auto-mode-alist (cons  '("\\.dv\\'" . verilog-mode) auto-mode-alist))
52
53 ;; If you want to customize Verilog mode to fit your needs better,
54 ;; you may add these lines (the values of the variables presented
55 ;; here are the defaults). Note also that if you use an emacs that
56 ;; supports custom, it's probably better to use the custom menu to
57 ;; edit these.
58 ;;
59 ;; Be sure to examine at the help for verilog-auto, and the other
60 ;; verilog-auto-* functions for some major coding time savers.
61 ;;
62 ; ;; User customization for Verilog mode
63 ; (setq verilog-indent-level             3
64 ;       verilog-indent-level-module      3
65 ;       verilog-indent-level-declaration 3
66 ;       verilog-indent-level-behavioral  3
67 ;       verilog-indent-level-directive   1
68 ;       verilog-case-indent              2
69 ;       verilog-auto-newline             t
70 ;       verilog-auto-indent-on-newline   t
71 ;       verilog-tab-always-indent        t
72 ;       verilog-auto-endcomments         t
73 ;       verilog-minimum-comment-distance 40
74 ;       verilog-indent-begin-after-if    t
75 ;       verilog-auto-lineup              '(all)
76 ;       verilog-linter                   "my_lint_shell_command"
77 ;       )
78
79 ;; KNOWN BUGS / BUG REPORTS
80 ;; =======================
81 ;; This is beta code, and likely has bugs. Please report any and all
82 ;; bugs to me at mac@verilog.com.  Use
83 ;; verilog-submit-bug-report to submit a report.
84 ;; \f
85
86 ;;; History:
87 ;;
88 ;; \f
89 ;;; Code:
90
91 (provide 'verilog-mode)
92
93 ;; This variable will always hold the version number of the mode
94 (defconst verilog-mode-version (substring "$$Revision: 344 $$" 12 -3)
95   "Version of this verilog mode.")
96 (defconst verilog-mode-release-date (substring "$$Date: 2007-07-10 08:49:18 -0700 (Tue, 10 Jul 2007) $$" 8 -3)
97   "Version of this verilog mode.")
98
99 (defconst verilog-running-on-xemacs (string-match "XEmacs" emacs-version))
100 (defun verilog-version ()
101   "Inform caller of the version of this file."
102   (interactive)
103   (message (concat "Using verilog-mode version " verilog-mode-version) ))
104
105 ;; Insure we have certain packages, and deal with it if we don't
106 (if (fboundp 'eval-when-compile)
107     (eval-when-compile
108       (require 'verilog-mode)
109       (condition-case nil
110           (require 'imenu)
111         (error nil))
112       (condition-case nil
113           (require 'reporter)
114         (error nil))
115       (condition-case nil
116           (require 'easymenu)
117         (error nil))
118       (condition-case nil
119           (require 'regexp-opt)
120         (error nil))
121       (condition-case nil
122           (load "skeleton") ;; bug in 19.28 through 19.30 skeleton.el, not provided.
123         (error nil))
124       (condition-case nil
125           (require 'vc)
126         (error nil))
127       (condition-case nil
128           (if (fboundp 'when)
129               nil ;; fab
130             (defmacro when (var &rest body)
131               (` (cond ( (, var) (,@ body))))))
132         (error nil))
133       (condition-case nil
134           (if (fboundp 'unless)
135               nil ;; fab
136             (defmacro unless (var &rest body)
137               (` (if (, var) nil (,@ body)))))
138         (error nil))
139       (condition-case nil
140           (if (fboundp 'store-match-data)
141               nil ;; fab
142             (defmacro store-match-data (&rest args) nil))
143         (error nil))
144       (condition-case nil
145           (if (boundp 'current-menubar)
146               nil ;; great
147             (progn
148              (defmacro set-buffer-menubar (&rest args) nil)
149              (defmacro add-submenu (&rest args) nil))
150             )
151         (error nil))
152       (condition-case nil
153           (if (fboundp 'zmacs-activate-region)
154               nil ;; great
155             (defmacro zmacs-activate-region (&rest args) nil))
156         (error nil))
157       (condition-case nil
158           (if (fboundp 'char-before)
159               nil ;; great
160             (defmacro char-before (&rest body)
161               (` (char-after (1- (point))))))
162         (error nil))
163       ;; Requires to define variables that would be "free" warnings
164       (condition-case nil
165           (require 'font-lock)
166         (error nil))
167       (condition-case nil
168           (require 'compile)
169         (error nil))
170       (condition-case nil
171           (require 'custom)
172         (error nil))
173       (condition-case nil
174           (require 'dinotrace)
175         (error nil))
176       (condition-case nil
177           (if (fboundp 'dinotrace-unannotate-all)
178               nil ;; great
179             (defun dinotrace-unannotate-all (&rest args) nil))
180         (error nil))
181       (condition-case nil
182           (if (fboundp 'customize-apropos)
183               nil ;; great
184             (defun customize-apropos (&rest args) nil))
185         (error nil))
186       (condition-case nil
187           (if (fboundp 'match-string-no-properties)
188               nil ;; great
189             (defsubst match-string-no-properties (num &optional string)
190               "Return string of text matched by last search, without text properties.
191 NUM specifies which parenthesized expression in the last regexp.
192  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
193 Zero means the entire text matched by the whole regexp or whole string.
194 STRING should be given if the last search was by `string-match' on STRING."
195               (if (match-beginning num)
196                   (if string
197                       (let ((result
198                              (substring string (match-beginning num) (match-end num))))
199                         (set-text-properties 0 (length result) nil result)
200                         result)
201                     (buffer-substring-no-properties (match-beginning num)
202                                                     (match-end num)
203                                                     (current-buffer)
204                                                     )))))
205         (error nil))
206       (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
207           nil ;; We've got what we needed
208         ;; We have the old custom-library, hack around it!
209         (defmacro defgroup (&rest args)  nil)
210         (defmacro customize (&rest args)
211           (message "Sorry, Customize is not available with this version of emacs"))
212         (defmacro defcustom (var value doc &rest args)
213           (` (defvar (, var) (, value) (, doc))))
214         )
215       (if (fboundp 'defface)
216           nil ; great!
217         (defmacro defface (var value doc &rest args)
218           (` (make-face (, var))))
219         )
220
221       (if (and (featurep 'custom) (fboundp 'customize-group))
222           nil ;; We've got what we needed
223         ;; We have an intermediate custom-library, hack around it!
224         (defmacro customize-group (var &rest args)
225           (`(customize (, var) )))
226         )
227
228       ))
229 ;; Provide a regular expression optimization routine, using regexp-opt
230 ;; if provided by the user's elisp libraries
231 (eval-and-compile
232   (if (fboundp 'regexp-opt)
233       ;; regexp-opt is defined, does it take 3 or 2 arguments?
234       (if (fboundp 'function-max-args)
235           (case (function-max-args `regexp-opt)
236             ( 3 ;; It takes 3
237               (condition-case nil       ; Hide this defun from emacses
238                                         ;with just a two input regexp
239                   (defun verilog-regexp-opt (a b)
240                     "Deal with differing number of required arguments for  `regexp-opt'.
241          Call 'regexp-opt' on A and B."
242                     (regexp-opt a b 't)
243                     )
244                 (error nil))
245               )
246               ( 2 ;; It takes 2
247               (defun verilog-regexp-opt (a b)
248                 "Call 'regexp-opt' on A and B."
249                 (regexp-opt a b))
250               )
251             ( t nil))
252         ;; We can't tell; assume it takes 2
253         (defun verilog-regexp-opt (a b)
254           "Call 'regexp-opt' on A and B."
255           (regexp-opt a b))
256         )
257     ;; There is no regexp-opt, provide our own
258     (defun verilog-regexp-opt (strings &optional paren shy)
259       (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
260         (concat open (mapconcat 'regexp-quote strings "\\|") close)))
261     ))
262
263 (eval-when-compile
264   (defun verilog-regexp-words (a)
265     "Call 'regexp-opt' with word delimiters."
266     (concat "\\<" (verilog-regexp-opt a t) "\\>")))
267
268 (defun verilog-regexp-words (a)
269   "Call 'regexp-opt' with word delimiters for the words A."
270   (concat "\\<" (verilog-regexp-opt a t) "\\>"))
271
272 (defun verilog-customize ()
273   "Link to customize screen for Verilog."
274   (interactive)
275   (customize-group 'verilog-mode))
276
277 (defun verilog-font-customize ()
278   "Link to customize fonts used for Verilog."
279   (interactive)
280   (customize-apropos "font-lock-*" 'faces))
281
282 (defgroup verilog-mode nil
283   "Facilitates easy editing of Verilog source text"
284   :group 'languages)
285
286 ; (defgroup verilog-mode-fonts nil
287 ;   "Facilitates easy customization fonts used in Verilog source text"
288 ;   :link '(customize-apropos "font-lock-*" 'faces)
289 ;  :group 'verilog-mode)
290
291 (defgroup verilog-mode-indent nil
292   "Customize indentation and highlighting of verilog source text"
293   :group 'verilog-mode)
294
295 (defgroup verilog-mode-actions nil
296   "Customize actions on verilog source text"
297   :group 'verilog-mode)
298
299 (defgroup verilog-mode-auto nil
300   "Customize AUTO actions when expanding verilog source text"
301   :group 'verilog-mode)
302
303 (defcustom verilog-linter
304   "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
305   "*Unix program and arguments to call to run a lint checker on verilog source.
306 Depending on the `verilog-set-compile-command', this may be invoked when
307 you type \\[compile]. When the compile completes, \\[next-error] will take
308 you to the next lint error."
309   :type 'string
310   :group 'verilog-mode-actions)
311
312 (defcustom verilog-coverage
313   "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
314   "*Program and arguments to use to annotate for coverage verilog source.
315 Depending on the `verilog-set-compile-command', this may be invoked when
316 you type \\[compile]. When the compile completes, \\[next-error] will take
317 you to the next lint error."
318   :type 'string
319   :group 'verilog-mode-actions)
320
321 (defcustom verilog-simulator
322   "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
323   "*Program and arguments to use to interpret verilog source.
324 Depending on the `verilog-set-compile-command', this may be invoked when
325 you type \\[compile]. When the compile completes, \\[next-error] will take
326 you to the next lint error."
327   :type 'string
328   :group 'verilog-mode-actions)
329
330 (defcustom verilog-compiler
331   "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
332   "*Program and arguments to use to compile verilog source.
333 Depending on the `verilog-set-compile-command', this may be invoked when
334 you type \\[compile]. When the compile completes, \\[next-error] will take
335 you to the next lint error."
336   :type 'string
337   :group 'verilog-mode-actions)
338
339 (defvar verilog-tool 'verilog-linter
340   "Which tool to use for building compiler-command.
341 Either nil, `verilog-linter, `verilog-coverage, `verilog-simulator, or
342 `verilog-compiler.  Alternatively use the \"Choose Compilation Action\"
343 menu.  See `verilog-set-compile-command' for more information.")
344
345 (defcustom verilog-highlight-translate-off nil
346   "*Non-nil means background-highlight code excluded from translation.
347 That is, all code between \"// synopsys translate_off\" and
348 \"// synopsys translate_on\" is highlighted using a different background color
349 \(face `verilog-font-lock-translate-off-face').
350
351 Note: This will slow down on-the-fly fontification (and thus editing).
352
353 Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
354 entry \"Fontify Buffer\").  XEmacs: turn off and on font locking."
355   :type 'boolean
356   :group 'verilog-mode-indent)
357
358 (defcustom verilog-indent-level 3
359   "*Indentation of Verilog statements with respect to containing block."
360   :group 'verilog-mode-indent
361   :type 'integer)
362
363 (defcustom verilog-indent-level-module 3
364   "*Indentation of Module level Verilog statements.  (eg always, initial)
365 Set to 0 to get initial and always statements lined up on the left side of
366 your screen."
367   :group 'verilog-mode-indent
368   :type 'integer)
369
370 (defcustom verilog-indent-level-declaration 3
371   "*Indentation of declarations with respect to containing block.
372 Set to 0 to get them list right under containing block."
373   :group 'verilog-mode-indent
374   :type 'integer)
375
376 (defcustom verilog-indent-declaration-macros nil
377   "*How to treat macro expansions in a declaration.
378 If nil, indent as:
379         input [31:0] a;
380         input        `CP;
381         output       c;
382 If non nil, treat as:
383         input [31:0] a;
384         input `CP    ;
385         output       c;"
386   :group 'verilog-mode-indent
387   :type 'boolean)
388
389 (defcustom verilog-indent-lists t
390   "*How to treat indenting items in a list.
391 If t (the default), indent as:
392         always @( posedge a or
393                   reset ) begin
394
395 If nil, treat as:
396         always @( posedge a or
397            reset ) begin"
398   :group 'verilog-mode-indent
399   :type 'boolean)
400
401 (defcustom verilog-indent-level-behavioral 3
402   "*Absolute indentation of first begin in a task or function block.
403 Set to 0 to get such code to start at the left side of the screen."
404   :group 'verilog-mode-indent
405   :type 'integer)
406
407 (defcustom verilog-indent-level-directive 1
408   "*Indentation to add to each level of `ifdef declarations.
409 Set to 0 to have all directives start at the left side of the screen."
410   :group 'verilog-mode-indent
411   :type 'integer)
412
413 (defcustom verilog-cexp-indent 2
414   "*Indentation of Verilog statements split across lines."
415   :group 'verilog-mode-indent
416   :type 'integer)
417
418 (defcustom verilog-case-indent 2
419   "*Indentation for case statements."
420   :group 'verilog-mode-indent
421   :type 'integer)
422
423 (defcustom verilog-auto-newline t
424   "*True means automatically newline after semicolons."
425   :group 'verilog-mode-indent
426   :type 'boolean)
427
428 (defcustom verilog-auto-indent-on-newline t
429   "*True means automatically indent line after newline."
430   :group 'verilog-mode-indent
431   :type 'boolean)
432
433 (defcustom verilog-tab-always-indent t
434   "*True means TAB should always re-indent the current line.
435 Nil means TAB will only reindent when at the beginning of the line."
436   :group 'verilog-mode-indent
437   :type 'boolean)
438
439 (defcustom verilog-tab-to-comment nil
440   "*True means TAB moves to the right hand column in preparation for a comment."
441   :group 'verilog-mode-actions
442   :type 'boolean)
443
444 (defcustom verilog-indent-begin-after-if t
445   "*If true, indent begin statements following if, else, while, for and repeat.
446 Otherwise, line them up."
447   :group 'verilog-mode-indent
448   :type 'boolean )
449
450
451 (defcustom verilog-align-ifelse nil
452   "*If true, align `else' under matching `if'.
453 Otherwise else is lined up with first character on line holding matching if."
454   :group 'verilog-mode-indent
455   :type 'boolean )
456
457 (defcustom verilog-minimum-comment-distance 10
458   "*Minimum distance (in lines) between begin and end required before a comment.
459 Setting this variable to zero results in every end acquiring a comment; the
460 default avoids too many redundant comments in tight quarters"
461   :group 'verilog-mode-indent
462   :type 'integer)
463
464 (defcustom verilog-auto-lineup '(declaration)
465   "*Algorithm for lining up statements on multiple lines.
466
467 If this list contains the symbol 'all', then all line ups described below
468 are done.
469
470 If this list contains the symbol 'declaration', then declarations are lined up
471 with any preceding declarations, taking into account widths and the like, so
472 for example the code:
473         reg [31:0] a;
474         reg b;
475 would become
476         reg [31:0] a;
477         reg        b;
478
479 If this list contains the symbol 'assignment', then assignments are lined up
480 with any preceding assignments, so for example the code
481         a_long_variable = b + c;
482         d = e + f;
483 would become
484         a_long_variable = b + c;
485         d               = e + f;"
486
487 ;; The following is not implemented:
488 ;If this list contains the symbol 'case', then case items are lined up
489 ;with any preceding case items, so for example the code
490 ;       case (a) begin
491 ;        a_long_state : a = 3;
492 ;        b: a = 4;
493 ;       endcase
494 ;would become
495 ;       case (a) begin
496 ;        a_long_state : a = 3;
497 ;        b            : a = 4;
498 ;       endcase
499 ;
500
501   :group 'verilog-mode-indent
502   :type 'list )
503
504 (defcustom verilog-auto-endcomments t
505   "*True means insert a comment /* ... */ after 'end's.
506 The name of the function or case will be set between the braces."
507   :group 'verilog-mode-actions
508   :type 'boolean )
509
510 (defcustom verilog-auto-read-includes nil
511   "*True means to automatically read includes before AUTOs.
512 This will do a `verilog-read-defines' and `verilog-read-includes' before
513 each AUTO expansion.  This makes it easier to embed defines and includes,
514 but can result in very slow reading times if there are many or large
515 include files."
516   :group 'verilog-mode-actions
517   :type 'boolean )
518
519 (defcustom verilog-auto-save-policy nil
520   "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
521 A value of `force' will always do a \\[verilog-auto] automatically if
522 needed on every save.  A value of `detect' will do \\[verilog-auto]
523 automatically when it thinks necessary.  A value of `ask' will query the
524 user when it thinks updating is needed.
525
526 You should not rely on the 'ask or 'detect policies, they are safeguards
527 only.  They do not detect when AUTOINSTs need to be updated because a
528 sub-module's port list has changed."
529   :group 'verilog-mode-actions
530   :type '(choice (const nil) (const ask) (const detect) (const force)))
531
532 (defcustom verilog-auto-star-expand t
533   "*Non-nil indicates to expand a SystemVerilog .* instance ports.
534 They will be expanded in the same way as if there was a AUTOINST in the
535 instantiation.  See also `verilog-auto-star' and `verilog-auto-star-save'."
536   :group 'verilog-mode-actions
537   :type 'boolean)
538
539 (defcustom verilog-auto-star-save nil
540   "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
541 Nil indicates direct connections will be removed before saving.  Only
542 meaningful to those created due to `verilog-auto-star-expand' being set.
543
544 Instead of setting this, you may want to use /*AUTOINST*/, which will
545 always be saved."
546   :group 'verilog-mode-actions
547   :type 'boolean)
548
549 (defvar verilog-auto-update-tick nil
550   "Modification tick at which autos were last performed.")
551
552 (defvar verilog-auto-last-file-locals nil
553   "Text from file-local-variables during last evaluation.")
554
555 (defvar verilog-error-regexp-add-didit nil)
556 (defvar verilog-error-regexp nil)
557 (setq verilog-error-regexp-add-didit nil
558  verilog-error-regexp
559   '(
560         ; SureLint
561 ;;    ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
562         ; Most SureFire tools
563     ("\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\), \\(line \\|\\)\\([0-9]+\\):" 2 4 )
564     ("\
565 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
566 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
567         ; xsim
568         ; Error! in file /homes/mac/Axis/Xsim/test.v at line 13         [OBJ_NOT_DECLARED]
569     ("\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
570         ; vcs
571     ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
572     ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
573     ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
574     ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
575         ; Verilator
576     ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
577     ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
578        ; vxl
579     ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
580     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 2)               ; vxl
581     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 2)
582         ; nc-verilog
583     (".*\\*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 2)
584        ; Leda
585     ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 2)
586     )
587 ;  "*List of regexps for verilog compilers, like verilint. See compilation-error-regexp-alist for the formatting."
588 )
589
590 (defvar verilog-error-font-lock-keywords
591   '(
592     ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
593     ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
594
595     ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
596     ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
597
598     ("\
599 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
600 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
601     ("\
602 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
603 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
604
605     ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
606     ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
607
608     ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
609     ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
610
611     ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
612     ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
613
614     ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
615     ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
616
617     ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
618     ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
619        ; vxl
620     ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
621     ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
622
623     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 bold t)
624     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 2 bold t)
625
626     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 bold t)
627     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 2 bold t)
628         ; nc-verilog
629     (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 bold t)
630     (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
631        ; Leda
632     ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 bold t)
633     ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 2 bold t)
634     )
635   "*Keywords to also highlight in Verilog *compilation* buffers."
636   )
637
638 (defcustom verilog-library-flags '("")
639   "*List of standard Verilog arguments to use for /*AUTOINST*/.
640 These arguments are used to find files for `verilog-auto', and match
641 the flags accepted by a standard Verilog-XL simulator.
642
643     -f filename     Reads more `verilog-library-flags' from the filename.
644     +incdir+dir     Adds the directory to `verilog-library-directories'.
645     -Idir           Adds the directory to `verilog-library-directories'.
646     -y dir          Adds the directory to `verilog-library-directories'.
647     +libext+.v      Adds the extensions to `verilog-library-extensions'.
648     -v filename     Adds the filename to `verilog-library-files'.
649
650     filename        Adds the filename to `verilog-library-files'.
651                     This is not recommended, -v is a better choice.
652
653 You might want these defined in each file; put at the *END* of your file
654 something like:
655
656     // Local Variables:
657     // verilog-library-flags:(\"-y dir -y otherdir\")
658     // End:
659
660 Verilog-mode attempts to detect changes to this local variable, but they
661 are only insured to be correct when the file is first visited. Thus if you
662 have problems, use \\[find-alternate-file] RET to have these take effect.
663
664 See also the variables mentioned above."
665   :group 'verilog-mode-auto
666   :type '(repeat string))
667
668 (defcustom verilog-library-directories '(".")
669   "*List of directories when looking for files for /*AUTOINST*/.
670 The directory may be relative to the current file, or absolute.
671 Environment variables are also expanded in the directory names.
672 Having at least the current directory is a good idea.
673
674 You might want these defined in each file; put at the *END* of your file
675 something like:
676
677     // Local Variables:
678     // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
679     // End:
680
681 Verilog-mode attempts to detect changes to this local variable, but they
682 are only insured to be correct when the file is first visited. Thus if you
683 have problems, use \\[find-alternate-file] RET to have these take effect.
684
685 See also `verilog-library-flags', `verilog-library-files'
686 and `verilog-library-extensions'."
687   :group 'verilog-mode-auto
688   :type '(repeat file))
689
690 (defcustom verilog-library-files '()
691   "*List of files to search for modules when looking for AUTOINST files.
692 This is a complete path, usually to a technology file with many standard
693 cells defined in it.
694
695 You might want these defined in each file; put at the *END* of your file
696 something like:
697
698     // Local Variables:
699     // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
700     // End:
701
702 Verilog-mode attempts to detect changes to this local variable, but they
703 are only insured to be correct when the file is first visited. Thus if you
704 have problems, use \\[find-alternate-file] RET to have these take effect.
705
706 See also `verilog-library-flags', `verilog-library-directories'."
707   :group 'verilog-mode-auto
708   :type '(repeat directory))
709
710 (defcustom verilog-library-extensions '(".v")
711   "*List of extensions to use when looking for files for /*AUTOINST*/.
712 See also `verilog-library-flags', `verilog-library-directories'."
713   :type '(repeat string)
714   :group 'verilog-mode-auto)
715
716 (defcustom verilog-active-low-regexp nil
717   "*If set, treat signals matching this regexp as active low.
718 This is used for AUTORESET and AUTOTIEOFF.  For proper behavior,
719 you will probably also need `verilog-auto-reset-widths' set."
720   :group 'verilog-mode-auto
721   :type 'string)
722
723 (defcustom verilog-auto-sense-include-inputs nil
724   "*If true, AUTOSENSE should include all inputs.
725 If nil, only inputs that are NOT output signals in the same block are
726 included."
727   :type 'boolean
728   :group 'verilog-mode-auto)
729
730 (defcustom verilog-auto-sense-defines-constant nil
731   "*If true, AUTOSENSE should assume all defines represent constants.
732 When true, the defines will not be included in sensitivity lists.  To
733 maintain compatibility with other sites, this should be set at the bottom
734 of each verilog file that requires it, rather then being set globally."
735   :type 'boolean
736   :group 'verilog-mode-auto)
737
738 (defcustom verilog-auto-reset-widths t
739   "*If true, AUTORESET should determine the width of signals.
740 This is then used to set the width of the zero (32'h0 for example).  This
741 is required by some lint tools that aren't smart enough to ignore widths of
742 the constant zero.  This may result in ugly code when parameters determine
743 the MSB or LSB of a signal inside a AUTORESET."
744   :type 'boolean
745   :group 'verilog-mode-auto)
746
747 (defcustom verilog-assignment-delay ""
748   "*Text used for delays in delayed assignments.  Add a trailing space if set."
749   :type 'string
750   :group 'verilog-mode-auto)
751
752 (defcustom verilog-auto-inst-vector t
753   "*If true, when creating default ports with AUTOINST, use bus subscripts.
754 If nil, skip the subscript when it matches the entire bus as declared in
755 the module (AUTOWIRE signals always are subscripted, you must manually
756 declare the wire to have the subscripts removed.)  Nil may speed up some
757 simulators, but is less general and harder to read, so avoid."
758   :group 'verilog-mode-auto
759   :type 'boolean )
760
761 (defcustom verilog-auto-inst-template-numbers nil
762   "*If true, when creating templated ports with AUTOINST, add a comment.
763 The comment will add the line number of the template that was used for that
764 port declaration.  Setting this aids in debugging, but nil is suggested for
765 regular use to prevent large numbers of merge conflicts."
766   :group 'verilog-mode-auto
767   :type 'boolean )
768
769 (defvar verilog-auto-inst-column 40
770   "Column number for first part of auto-inst.")
771
772 (defcustom verilog-auto-input-ignore-regexp nil
773   "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
774 See the \\[verilog-faq] for examples on using this."
775   :group 'verilog-mode-auto
776   :type 'string )
777
778 (defcustom verilog-auto-inout-ignore-regexp nil
779   "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
780 See the \\[verilog-faq] for examples on using this."
781   :group 'verilog-mode-auto
782   :type 'string )
783
784 (defcustom verilog-auto-output-ignore-regexp nil
785   "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
786 See the \\[verilog-faq] for examples on using this."
787   :group 'verilog-mode-auto
788   :type 'string )
789
790 (defcustom verilog-auto-unused-ignore-regexp nil
791   "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
792 See the \\[verilog-faq] for examples on using this."
793   :group 'verilog-mode-auto
794   :type 'string )
795
796 (defcustom verilog-typedef-regexp nil
797   "*If non-nil, regular expression that matches Verilog-2001 typedef names.
798 For example, \"_t$\" matches typedefs named with _t, as in the C language."
799   :group 'verilog-mode-auto
800   :type 'string )
801
802 (defcustom verilog-mode-hook   'verilog-set-compile-command
803   "*Hook (List of functions) run after verilog mode is loaded."
804   :type 'hook
805   :group 'verilog-mode)
806
807 (defcustom verilog-auto-hook nil
808   "*Hook run after `verilog-mode' updates AUTOs."
809   :type 'hook
810   :group 'verilog-mode-auto)
811
812 (defcustom verilog-before-auto-hook nil
813   "*Hook run before `verilog-mode' updates AUTOs."
814   :type 'hook
815   :group 'verilog-mode-auto)
816
817 (defcustom verilog-delete-auto-hook nil
818   "*Hook run after `verilog-mode' deletes AUTOs."
819   :type 'hook
820   :group 'verilog-mode-auto)
821
822 (defcustom verilog-before-delete-auto-hook nil
823   "*Hook run before `verilog-mode' deletes AUTOs."
824   :type 'hook
825   :group 'verilog-mode-auto)
826
827 (defcustom verilog-getopt-flags-hook nil
828   "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
829   :type 'hook
830   :group 'verilog-mode-auto)
831
832 (defcustom verilog-before-getopt-flags-hook nil
833   "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
834   :type 'hook
835   :group 'verilog-mode-auto)
836
837 (defvar verilog-imenu-generic-expression
838   '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
839     ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
840   "Imenu expression for Verilog-mode.  See `imenu-generic-expression'.")
841
842 ;;
843 ;; provide a verilog-header function.
844 ;; Customization variables:
845 ;;
846 (defvar verilog-date-scientific-format nil
847   "*If non-nil, dates are written in scientific format (e.g.  1997/09/17).
848 If nil, in European format (e.g.  17.09.1997).  The brain-dead American
849 format (e.g.  09/17/1997) is not supported.")
850
851 (defvar verilog-company nil
852   "*Default name of Company for verilog header.
853 If set will become buffer local.")
854
855 (defvar verilog-project nil
856   "*Default name of Project for verilog header.
857 If set will become buffer local.")
858
859 (define-abbrev-table 'verilog-mode-abbrev-table ())
860
861 (defvar verilog-mode-map ()
862   "Keymap used in Verilog mode.")
863 (if verilog-mode-map
864     ()
865   (setq verilog-mode-map (make-sparse-keymap))
866   (define-key verilog-mode-map ";"        'electric-verilog-semi)
867   (define-key verilog-mode-map [(control 59)]    'electric-verilog-semi-with-comment)
868   (define-key verilog-mode-map ":"        'electric-verilog-colon)
869   ;;(define-key verilog-mode-map "="        'electric-verilog-equal)
870   (define-key verilog-mode-map "\`"       'electric-verilog-tick)
871   (define-key verilog-mode-map "\t"       'electric-verilog-tab)
872   (define-key verilog-mode-map "\r"       'electric-verilog-terminate-line)
873   ;; backspace/delete key bindings
874   (define-key verilog-mode-map [backspace]    'backward-delete-char-untabify)
875   (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
876     (define-key verilog-mode-map [delete]       'delete-char)
877     (define-key verilog-mode-map [(meta delete)] 'kill-word))
878   (define-key verilog-mode-map "\M-\C-b"  'electric-verilog-backward-sexp)
879   (define-key verilog-mode-map "\M-\C-f"  'electric-verilog-forward-sexp)
880   (define-key verilog-mode-map "\M-\r"    `electric-verilog-terminate-and-indent)
881   (define-key verilog-mode-map "\M-\t"    'verilog-complete-word)
882   (define-key verilog-mode-map "\M-?"     'verilog-show-completions)
883   (define-key verilog-mode-map [(meta control h)] 'verilog-mark-defun)
884   (define-key verilog-mode-map "\C-c\`"   'verilog-lint-off)
885   (define-key verilog-mode-map "\C-c\*"   'verilog-delete-auto-star-implicit)
886   (define-key verilog-mode-map "\C-c\C-r" 'verilog-label-be)
887   (define-key verilog-mode-map "\C-c\C-i" 'verilog-pretty-declarations)
888   (define-key verilog-mode-map "\C-c="    'verilog-pretty-expr)
889   (define-key verilog-mode-map "\C-c\C-b" 'verilog-submit-bug-report)
890   (define-key verilog-mode-map "\M-*"     'verilog-star-comment)
891   (define-key verilog-mode-map "\C-c\C-c" 'verilog-comment-region)
892   (define-key verilog-mode-map "\C-c\C-u" 'verilog-uncomment-region)
893   (define-key verilog-mode-map "\M-\C-a"  'verilog-beg-of-defun)
894   (define-key verilog-mode-map "\M-\C-e"  'verilog-end-of-defun)
895   (define-key verilog-mode-map "\C-c\C-d" 'verilog-goto-defun)
896   (define-key verilog-mode-map "\C-c\C-k" 'verilog-delete-auto)
897   (define-key verilog-mode-map "\C-c\C-a" 'verilog-auto)
898   (define-key verilog-mode-map "\C-c\C-s" 'verilog-auto-save-compile)
899   (define-key verilog-mode-map "\C-c\C-z" 'verilog-inject-auto)
900   (define-key verilog-mode-map "\C-c\C-e" 'verilog-expand-vector)
901   (define-key verilog-mode-map "\C-c\C-h" 'verilog-header)
902   )
903
904 ;; menus
905 (defvar verilog-xemacs-menu
906   '("Verilog"
907     ("Choose Compilation Action"
908      ["None"
909       (progn
910         (setq verilog-tool nil)
911         (verilog-set-compile-command))
912       :style radio
913       :selected (equal verilog-tool nil)]
914      ["Lint"
915       (progn
916         (setq verilog-tool 'verilog-linter)
917         (verilog-set-compile-command))
918       :style radio
919       :selected (equal verilog-tool `verilog-linter)]
920      ["Coverage"
921       (progn
922         (setq verilog-tool 'verilog-coverage)
923         (verilog-set-compile-command))
924       :style radio
925       :selected (equal verilog-tool `verilog-coverage)]
926      ["Simulator"
927       (progn
928         (setq verilog-tool 'verilog-simulator)
929         (verilog-set-compile-command))
930       :style radio
931       :selected (equal verilog-tool `verilog-simulator)]
932      ["Compiler"
933       (progn
934         (setq verilog-tool 'verilog-compiler)
935         (verilog-set-compile-command))
936       :style radio
937       :selected (equal verilog-tool `verilog-compiler)]
938      )
939     ("Move"
940      ["Beginning of function"           verilog-beg-of-defun t]
941      ["End of function"                 verilog-end-of-defun t]
942      ["Mark function"                   verilog-mark-defun t]
943      ["Goto function/module"            verilog-goto-defun t]
944      ["Move to beginning of block"      electric-verilog-backward-sexp t]
945      ["Move to end of block"            electric-verilog-forward-sexp t]
946      )
947     ("Comments"
948      ["Comment Region"                  verilog-comment-region t]
949      ["UnComment Region"                        verilog-uncomment-region t]
950      ["Multi-line comment insert"       verilog-star-comment t]
951      ["Lint error to comment"           verilog-lint-off t]
952      )
953     "----"
954     ["Compile"                          compile t]
955     ["AUTO, Save, Compile"              verilog-auto-save-compile t]
956     ["Next Compile Error"               next-error t]
957     ["Ignore Lint Warning at point"     verilog-lint-off t]
958     "----"
959     ["Line up declarations around point"        verilog-pretty-declarations t]
960     ["Line up equations around point"           verilog-pretty-expr t]
961     ["Redo/insert comments on every end"        verilog-label-be t]
962     ["Expand [x:y] vector line"         verilog-expand-vector t]
963     ["Insert begin-end block"           verilog-insert-block t]
964     ["Complete word"                    verilog-complete-word t]
965     "----"
966     ["Recompute AUTOs"                  verilog-auto t]
967     ["Kill AUTOs"                       verilog-delete-auto t]
968     ["Inject AUTOs"                     verilog-inject-auto t]
969     ("AUTO Help..."
970      ["AUTO General"                    (describe-function 'verilog-auto) t]
971      ["AUTO Library Flags"              (describe-variable 'verilog-library-flags) t]
972      ["AUTO Library Path"               (describe-variable 'verilog-library-directories) t]
973      ["AUTO Library Files"              (describe-variable 'verilog-library-files) t]
974      ["AUTO Library Extensions"         (describe-variable 'verilog-library-extensions) t]
975      ["AUTO `define Reading"            (describe-function 'verilog-read-defines) t]
976      ["AUTO `include Reading"           (describe-function 'verilog-read-includes) t]
977      ["AUTOARG"                         (describe-function 'verilog-auto-arg) t]
978      ["AUTOASCIIENUM"                   (describe-function 'verilog-auto-ascii-enum) t]
979      ["AUTOINOUTMODULE"                 (describe-function 'verilog-auto-inout-module) t]
980      ["AUTOINOUT"                       (describe-function 'verilog-auto-inout) t]
981      ["AUTOINPUT"                       (describe-function 'verilog-auto-input) t]
982      ["AUTOINST"                        (describe-function 'verilog-auto-inst) t]
983      ["AUTOINST (.*)"                   (describe-function 'verilog-auto-star) t]
984      ["AUTOINSTPARAM"                   (describe-function 'verilog-auto-inst-param) t]
985      ["AUTOOUTPUT"                      (describe-function 'verilog-auto-output) t]
986      ["AUTOOUTPUTEVERY"                 (describe-function 'verilog-auto-output-every) t]
987      ["AUTOREG"                         (describe-function 'verilog-auto-reg) t]
988      ["AUTOREGINPUT"                    (describe-function 'verilog-auto-reg-input) t]
989      ["AUTORESET"                       (describe-function 'verilog-auto-reset) t]
990      ["AUTOSENSE"                       (describe-function 'verilog-auto-sense) t]
991      ["AUTOTIEOFF"                      (describe-function 'verilog-auto-tieoff) t]
992      ["AUTOUNUSED"                      (describe-function 'verilog-auto-unused) t]
993      ["AUTOWIRE"                        (describe-function 'verilog-auto-wire) t]
994      )
995     "----"
996     ["Submit bug report"                verilog-submit-bug-report t]
997     ["Version and FAQ"                  verilog-faq t]
998     ["Customize Verilog Mode..."        verilog-customize t]
999     ["Customize Verilog Fonts & Colors" verilog-font-customize t]
1000     )
1001   "Emacs menu for VERILOG mode."
1002   )
1003 (defvar verilog-statement-menu
1004   '("Statements"
1005     ["Header"           verilog-sk-header  t]
1006     ["Comment"          verilog-sk-comment t]
1007     "----"
1008     ["Module"           verilog-sk-module t]
1009     ["Primitive"        verilog-sk-primitive t]
1010     "----"
1011     ["Input"            verilog-sk-input t]
1012     ["Output"           verilog-sk-output t]
1013     ["Inout"            verilog-sk-inout t]
1014     ["Wire"             verilog-sk-wire t]
1015     ["Reg"              verilog-sk-reg t]
1016     ["Define thing under point as a register" verilog-sk-define-signal t]
1017     "----"
1018     ["Initial"          verilog-sk-initial t]
1019     ["Always"           verilog-sk-always t]
1020     ["Function"         verilog-sk-function t]
1021     ["Task"             verilog-sk-task t]
1022     ["Specify"          verilog-sk-specify t]
1023     ["Generate"         verilog-sk-generate t]
1024     "----"
1025     ["Begin"            verilog-sk-begin t]
1026     ["If"               verilog-sk-if t]
1027     ["(if) else"        verilog-sk-else-if t]
1028     ["For"              verilog-sk-for t]
1029     ["While"            verilog-sk-while t]
1030     ["Fork"             verilog-sk-fork t]
1031     ["Repeat"           verilog-sk-repeat t]
1032     ["Case"             verilog-sk-case t]
1033     ["Casex"            verilog-sk-casex t]
1034     ["Casez"            verilog-sk-casez t]
1035     )
1036   "Menu for statement templates in Verilog."
1037   )
1038
1039 (easy-menu-define verilog-menu verilog-mode-map "Menu for Verilog mode"
1040                   verilog-xemacs-menu)
1041 (easy-menu-define verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
1042                   verilog-statement-menu)
1043
1044 (defvar verilog-mode-abbrev-table nil
1045   "Abbrev table in use in Verilog-mode buffers.")
1046
1047 (define-abbrev-table 'verilog-mode-abbrev-table ())
1048
1049 ;; compilation program
1050 (defun verilog-set-compile-command ()
1051   "Function to compute shell command to compile verilog.
1052
1053 This reads `verilog-tool' and sets `compile-command'.  This specifies the
1054 program that executes when you type \\[compile] or
1055 \\[verilog-auto-save-compile].
1056
1057 By default `verilog-tool' uses a Makefile if one exists in the current
1058 directory.  If not, it is set to the `verilog-linter', `verilog-coverage',
1059 `verilog-simulator', or `verilog-compiler' variables, as selected with the
1060 Verilog -> \"Choose Compilation Action\" menu.
1061
1062 You should set `verilog-tool' or the other variables to the path and
1063 arguments for your Verilog simulator.  For example:
1064     \"vcs -p123 -O\"
1065 or a string like:
1066     \"(cd /tmp; surecov %s)\".
1067
1068 In the former case, the path to the current buffer is concat'ed to the
1069 value of `verilog-tool'; in the later, the path to the current buffer is
1070 substituted for the %s.
1071
1072 Where __FILE__ appears in the string, the buffer-file-name of the current
1073 buffer, without the directory portion, will be substituted."
1074   (interactive)
1075   (cond
1076    ((or (file-exists-p "makefile")      ;If there is a makefile, use it
1077         (file-exists-p "Makefile"))
1078     (make-local-variable 'compile-command)
1079     (setq compile-command "make "))
1080    (t
1081     (make-local-variable 'compile-command)
1082     (setq compile-command
1083           (if verilog-tool
1084               (if (string-match "%s" (eval verilog-tool))
1085                   (format (eval verilog-tool) (or buffer-file-name ""))
1086                 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1087             ""))))
1088   (verilog-modify-compile-command))
1089
1090 (defun verilog-modify-compile-command ()
1091   "Replace meta-information in `compile-command'.
1092 Where __FILE__ appears in the string, the current buffer's file-name,
1093 without the directory portion, will be substituted."
1094   (when (string-match "\\b__FILE__\\b" compile-command)
1095     (make-local-variable 'compile-command)
1096     (setq compile-command
1097           (verilog-string-replace-matches
1098            "\\b__FILE__\\b" (file-name-nondirectory (buffer-file-name))
1099            t t compile-command))))
1100
1101 (defun verilog-error-regexp-add ()
1102   "Add the messages to the `compilation-error-regexp-alist'.
1103 Called by `compilation-mode-hook'.  This allows \\[next-error] to find the errors."
1104   (if (not verilog-error-regexp-add-didit)
1105       (progn
1106         (setq verilog-error-regexp-add-didit t)
1107         (setq-default compilation-error-regexp-alist
1108                       (append verilog-error-regexp
1109                               (default-value 'compilation-error-regexp-alist)))
1110         ;; Could be buffer local at this point; maybe also in let; change all three
1111         (setq compilation-error-regexp-alist (default-value 'compilation-error-regexp-alist))
1112         (set (make-local-variable 'compilation-error-regexp-alist)
1113              (default-value 'compilation-error-regexp-alist))
1114         )))
1115
1116 (add-hook 'compilation-mode-hook 'verilog-error-regexp-add)
1117
1118 (defconst verilog-directive-re
1119   ;; "`case" "`default" "`define" "`define" "`else" "`endfor" "`endif"
1120   ;; "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1121   ;; "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1122   ;; "`time_scale" "`undef" "`while"
1123   "\\<`\\(case\\|def\\(ault\\|ine\\(\\)?\\)\\|e\\(lse\\|nd\\(for\\|if\\|protect\\|switch\\|while\\)\\)\\|for\\(mat\\)?\\|i\\(f\\(def\\|ndef\\)?\\|nclude\\)\\|let\\|protect\\|switch\\|time\\(_scale\\|scale\\)\\|undef\\|while\\)\\>")
1124
1125 (defconst verilog-directive-begin
1126   "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1127
1128 (defconst verilog-directive-middle
1129   "\\<`\\(else\\|default\\|case\\)\\>")
1130
1131 (defconst verilog-directive-end
1132   "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1133
1134 (defconst verilog-directive-re-1
1135   (concat "[ \t]*"  verilog-directive-re))
1136
1137 ;;
1138 ;; Regular expressions used to calculate indent, etc.
1139 ;;
1140 (defconst verilog-symbol-re      "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
1141 (defconst verilog-case-re        "\\(\\<case[xz]?\\>\\|\\<randcase\\>\\)")
1142 ;; Want to match
1143 ;; aa :
1144 ;; aa,bb :
1145 ;; a[34:32] :
1146 ;; a,
1147 ;;   b :
1148
1149 (defconst verilog-no-indent-begin-re
1150   "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1151
1152 (defconst verilog-ends-re
1153   ;; Parenthesis indicate type of keyword found
1154   (concat
1155    "\\(\\<else\\>\\)\\|"                ; 1
1156    "\\(\\<if\\>\\)\\|"                  ; 2
1157    "\\(\\<end\\>\\)\\|"                 ; 3
1158    "\\(\\<endcase\\>\\)\\|"             ; 4
1159    "\\(\\<endfunction\\>\\)\\|"         ; 5
1160    "\\(\\<endtask\\>\\)\\|"             ; 6
1161    "\\(\\<endspecify\\>\\)\\|"          ; 7
1162    "\\(\\<endtable\\>\\)\\|"            ; 8
1163    "\\(\\<endgenerate\\>\\)\\|"         ; 9
1164    "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1165    "\\(\\<endclass\\>\\)\\|"            ; 11
1166    "\\(\\<endgroup\\>\\)"               ; 12
1167    ))
1168
1169 (defconst verilog-auto-end-comment-lines-re
1170   ;; Matches to names in this list cause auto-end-commentation
1171   ;;
1172   ;; "macromodule" "module" "primitive" "interface" "end" "endcase" "endfunction"
1173   ;; "endtask" "endmodule" "endprimitive" "endinterface" "endspecify" "endtable" "join"
1174   ;; "begin" "else" `{directives}
1175   (concat "\\("
1176           verilog-directive-re "\\)\\|\\("
1177           (eval-when-compile
1178             (verilog-regexp-words
1179              `( "begin"
1180                 "else"
1181                 "end"
1182                 "endcase"
1183                 "endclass"
1184                 "endgroup"
1185                 "endfunction"
1186                 "endmodule"
1187                 "endprogram"
1188                 "endprimitive"
1189                 "endinterface"
1190                 "endpackage"
1191                 "endsequence"
1192                 "endspecify"
1193                 "endtable"
1194                 "endtask"
1195                 "join"
1196                 "join_any"
1197                 "join_none"
1198                 "module"
1199                 "macromodule"
1200                 "primitive"
1201                 "interface"
1202                 "package")))
1203           "\\)"))
1204
1205 ;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1206 ;;; verilog-end-block-ordered-re matches exactly the same strings.
1207 (defconst verilog-end-block-ordered-re
1208   ;; Parenthesis indicate type of keyword found
1209   (concat "\\(\\<endcase\\>\\)\\|" ; 1
1210           "\\(\\<end\\>\\)\\|"     ; 2
1211           "\\(\\<end"              ; 3, but not used
1212           "\\("                    ; 4, but not used
1213           "\\(function\\)\\|"      ; 5
1214           "\\(task\\)\\|"          ; 6
1215           "\\(module\\)\\|"        ; 7
1216           "\\(primitive\\)\\|"     ; 8
1217           "\\(interface\\)\\|"     ; 9
1218           "\\(package\\)\\|"       ; 10
1219           "\\(class\\)\\|"         ; 11
1220           "\\(group\\)\\|"    ; 12
1221           "\\(program\\)\\|"       ; 13
1222           "\\(sequence\\)\\|"      ; 14
1223           "\\)\\>\\)"))
1224 (defconst verilog-end-block-re
1225   (eval-when-compile
1226     (verilog-regexp-words
1227
1228      `("end"  ;; closes begin
1229        "endcase" ;; closes any of case, casex casez or randcase
1230        "join" "join_any" "join_none" ;; closes fork
1231        "endclass"
1232        "endtable"
1233        "endspecify"
1234        "endfunction"
1235        "endgenerate"
1236        "endtask"
1237        "endgroup"
1238        "endproperty"
1239        "endinterface"
1240        "endpackage"
1241        "endprogram"
1242        "endsequence"
1243        )
1244      )))
1245
1246
1247 (defconst verilog-endcomment-reason-re
1248   ;; Parenthesis indicate type of keyword found
1249   (concat
1250    "\\(\\<fork\\>\\)\\|"
1251    "\\(\\<begin\\>\\)\\|"
1252    "\\(\\<if\\>\\)\\|"
1253    "\\(\\<else\\>\\)\\|"
1254    "\\(\\<end\\>.*\\<else\\>\\)\\|"
1255    "\\(\\<task\\>\\)\\|"
1256    "\\(\\<function\\>\\)\\|"
1257    "\\(\\<initial\\>\\)\\|"
1258    "\\(\\<interface\\>\\)\\|"
1259    "\\(\\<package\\>\\)\\|"
1260    "\\(\\<final\\>\\)\\|"
1261    "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
1262    "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|"
1263    "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|"
1264    "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|"
1265    "\\(@\\)\\|"
1266    "\\(\\<while\\>\\)\\|"
1267    "\\(\\<for\\(ever\\)?\\>\\)\\|"
1268    "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1269    "#"))
1270
1271 (defconst verilog-named-block-re  "begin[ \t]*:")
1272
1273 ;; These words begin a block which can occur inside a module which should be indented,
1274 ;; and closed with the respective word from the end-block list
1275
1276 (defconst verilog-beg-block-re
1277   (eval-when-compile
1278     (verilog-regexp-words
1279      `("begin"
1280        "case" "casex" "casez" "randcase"
1281        "generate"
1282        "fork"
1283        "function"
1284        "property"
1285        "specify"
1286        "table"
1287        "task"
1288        ))))
1289 ;; These are the same words, in a specific order in the regular
1290 ;; expression so that matching will work nicely for
1291 ;; verilog-forward-sexp and verilog-calc-indent
1292
1293 (defconst verilog-beg-block-re-ordered
1294   ( concat "\\<"
1295            "\\(begin\\)\\|"             ;1
1296            "\\(randcase\\|case[xz]?\\)\\|" ; 2
1297            "\\(fork\\)\\|"              ;3
1298            "\\(class\\)\\|"             ;4
1299            "\\(table\\)\\|"             ;5
1300            "\\(specify\\)\\|"           ;6
1301            "\\(function\\)\\|"          ;7
1302            "\\(task\\)\\|"              ;8
1303            "\\(generate\\)\\|"          ;9
1304            "\\(covergroup\\)\\|"        ;10
1305            "\\(property\\)\\|"          ;11
1306            "\\(\\(rand\\)?sequence\\)"  ;12
1307            "\\>"))
1308
1309 (defconst verilog-end-block-ordered-rry
1310   [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1311     "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
1312     "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1313     "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
1314     "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
1315     "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
1316     "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
1317     "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
1318     "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
1319     "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
1320     "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
1321     "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
1322     ] )
1323
1324 (defconst verilog-nameable-item-re
1325   (eval-when-compile
1326     (verilog-regexp-words
1327      `("begin"
1328        "fork"
1329        "join" "join_any" "join_none"
1330        "end"
1331        "endcase"
1332        "endconfig"
1333        "endclass"
1334        "endfunction"
1335        "endgenerate"
1336        "endmodule"
1337        "endprimative"
1338        "endinterface"
1339        "endpackage"
1340        "endspecify"
1341        "endtable"
1342        "endtask" )
1343      )))
1344
1345 (defconst verilog-declaration-opener
1346   (eval-when-compile
1347     (verilog-regexp-words
1348      `("module" "begin" "task" "function"))))
1349
1350 (defconst verilog-declaration-re
1351   (eval-when-compile
1352     (verilog-regexp-words
1353      `("assign" "defparam" "event" "inout" "input" "integer" "localparam" "output"
1354        "parameter" "real" "realtime" "reg" "supply" "supply0" "supply1" "time"
1355        "tri" "tri0" "tri1" "triand" "trior" "trireg" "wand" "wire" "typedef"
1356        "struct" "logic" "bit" "genvar" "wor"))))
1357 (defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
1358 (defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
1359 (defconst verilog-optional-signed-range-re
1360   (concat
1361    "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
1362 (defconst verilog-macroexp-re "`\\sw+")
1363
1364 (defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
1365 (defconst verilog-declaration-re-2-no-macro
1366   (concat "\\s-*" verilog-declaration-re
1367           "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1368 ;         "\\|\\(" verilog-macroexp-re "\\)"
1369           "\\)?"))
1370 (defconst verilog-declaration-re-2-macro
1371   (concat "\\s-*" verilog-declaration-re
1372           "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1373           "\\|\\(" verilog-macroexp-re "\\)"
1374           "\\)?"))
1375 (defconst verilog-declaration-re-1-macro
1376   (concat "^" verilog-declaration-re-2-macro))
1377 ;  (concat
1378 ;   "^\\s-*\\<\\(in\\(?:out\\|put\\|teger\\)\\|output\\|re\\(?:al\\(?:time\\)?\\|g\\)\\|t\\(?:ime\\|ri\\(?:and\\|or\\|reg\\|[01]\\)?\\|ypedef\\)\\|w\\(?:and\\|ire\\|or\\)\\)\\>"
1379 ;   "\\s-*"
1380 ;   "\\("
1381 ;   "\\("
1382 ;   "\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?"
1383 ;   "\\(\\<signed\\>\\s-*\\)?"
1384 ;   "\\(\\(\\[[^]]*\\]\\)+\\)?"
1385 ;   "\\)"
1386 ;   "\\|"
1387 ;     "\\(#\\s-*\\("
1388 ;       "\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)"
1389 ;       "\\|\\(([^()]*)\\)"
1390 ;       "\\|\\(\\sw+\\)"
1391 ;     "\\)"
1392 ;   "\\)"
1393 ;   "\\|\\(`\\sw+\\)\\)?"
1394 ;   ))
1395
1396 (defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
1397 (defconst verilog-defun-re
1398   (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
1399 (defconst verilog-end-defun-re
1400   (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
1401 (defconst verilog-zero-indent-re
1402   (concat verilog-defun-re "\\|" verilog-end-defun-re))
1403
1404 (defconst verilog-behavioral-block-beg-re
1405   (concat "\\(\\<initial\\>\\|\\<final\\>\\|\\<always\\>\\|\\<always_comb\\>\\|\\<always_ff\\>\\|"
1406           "\\<always_latch\\>\\|\\<function\\>\\|\\<task\\>\\)"))
1407
1408 (defconst verilog-indent-re
1409   (eval-when-compile
1410     (verilog-regexp-words
1411      `(
1412        "always" "always_latch" "always_ff" "always_comb"
1413        "begin" "end"
1414        "case" "casex" "casez" "randcase" "endcase"
1415        "class" "endclass"
1416        "config" "endconfig"
1417        "covergroup" "endgroup"
1418        "fork" "join" "join_any" "join_none"
1419        "function" "endfunction"
1420        "final"
1421        "generate" "endgenerate"
1422        "initial"
1423        "interface" "endinterface"
1424        "module" "macromodule" "endmodule"
1425        "package" "endpackage"
1426        "primitive" "endprimative"
1427        "program" "endprogram"
1428        "property" "endproperty"
1429        "sequence" "randsequence" "endsequence"
1430        "specify" "endspecify"
1431        "table" "endtable"
1432        "task" "endtask"
1433        "`case"
1434        "`default"
1435        "`define" "`undef"
1436        "`if" "`ifdef" "`ifndef" "`else" "`endif"
1437        "`while" "`endwhile"
1438        "`for" "`endfor"
1439        "`format"
1440        "`include"
1441        "`let"
1442        "`protect" "`endprotect"
1443        "`switch" "`endswitch"
1444        "`timescale"
1445        "`time_scale"
1446        ))))
1447
1448 (defconst verilog-defun-level-re
1449   (eval-when-compile
1450     (verilog-regexp-words
1451      `(
1452        "module" "macromodule" "primitive" "class" "program" "initial" "final" "always" "always_comb"
1453        "always_ff" "always_latch" "endtask" "endfunction" "interface" "package"
1454        "config"))))
1455
1456 (defconst verilog-defun-level-not-generate-re
1457   (eval-when-compile
1458     (verilog-regexp-words
1459      `(
1460        "module" "macromodule" "primitive" "class" "program" "interface" "package" "config"))))
1461
1462 (defconst verilog-cpp-level-re
1463   (eval-when-compile
1464     (verilog-regexp-words
1465      `(
1466        "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
1467        ))))
1468
1469 (defconst verilog-complete-reg
1470   (concat
1471    "\\(extern\\s-+\\|virtual\\s-+\\|protected\\s-+\\)*\\(function\\|task\\)\\|"
1472    "\\(typedef\\s-+\\)*\\(struct\\|union\\|class\\)\\|"
1473    (eval-when-compile
1474      (verilog-regexp-words
1475       `(
1476         "always" "assign" "always_latch" "always_ff" "always_comb" "constraint" 
1477         "import" "initial" "final" "repeat" "case" "casex" "casez" "randcase" "while"
1478         "if" "for" "forever" "else" "parameter" "do" "foreach"
1479         )))))
1480   
1481 (defconst verilog-end-statement-re
1482   (concat "\\(" verilog-beg-block-re "\\)\\|\\("
1483           verilog-end-block-re "\\)"))
1484
1485 (defconst verilog-endcase-re
1486   (concat verilog-case-re "\\|"
1487           "\\(endcase\\)\\|"
1488           verilog-defun-re
1489           ))
1490
1491 (defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
1492   "String used to mark beginning of excluded text.")
1493 (defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
1494   "String used to mark end of excluded text.")
1495
1496 (defconst verilog-keywords
1497   '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
1498      "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1499      "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1500      "`time_scale" "`undef" "`while"
1501
1502      "alias" "always" "always_comb" "always_ff" "always_latch" "and"
1503      "assert" "assign" "assume" "automatic" "before" "begin" "bind"
1504      "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
1505      "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
1506      "config" "const" "constraint" "context" "continue" "cover"
1507      "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
1508      "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
1509      "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
1510      "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
1511      "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
1512      "endtask" "enum" "event" "expect" "export" "extends" "extern"
1513      "final" "first_match" "for" "force" "foreach" "forever" "fork"
1514      "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
1515      "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
1516      "include" "initial" "inout" "input" "inside" "instance" "int"
1517      "integer" "interface" "intersect" "join" "join_any" "join_none"
1518      "large" "liblist" "library" "local" "localparam" "logic"
1519      "longint" "macromodule" "matches" "medium" "modport" "module"
1520      "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
1521      "notif0" "notif1" "null" "or" "output" "package" "packed"
1522      "parameter" "pmos" "posedge" "primitive" "priority" "program"
1523      "property" "protected" "pull0" "pull1" "pulldown" "pullup"
1524      "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
1525      "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
1526      "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
1527      "rtranif1" "scalared" "sequence" "shortint" "shortreal"
1528      "showcancelled" "signed" "small" "solve" "specify" "specparam"
1529      "static" "string" "strong0" "strong1" "struct" "super" "supply0"
1530      "supply1" "table" "tagged" "task" "this" "throughout" "time"
1531      "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
1532      "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
1533      "unique" "unsigned" "use" "var" "vectored" "virtual" "void"
1534      "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
1535      "wire" "with" "within" "wor" "xnor" "xor"
1536  )
1537  "List of Verilog keywords.")
1538
1539
1540 (defconst verilog-emacs-features
1541   ;; Documentation at the bottom
1542   (let ((major (and (boundp 'emacs-major-version)
1543                     emacs-major-version))
1544         (minor (and (boundp 'emacs-minor-version)
1545                     emacs-minor-version))
1546         flavor comments flock-syntax)
1547     ;; figure out version numbers if not already discovered
1548     (and (or (not major) (not minor))
1549          (string-match "\\([0-9]+\\).\\([0-9]+\\)" emacs-version)
1550          (setq major (string-to-int (substring emacs-version
1551                                                (match-beginning 1)
1552                                                (match-end 1)))
1553                minor (string-to-int (substring emacs-version
1554                                                (match-beginning 2)
1555                                                (match-end 2)))))
1556     (if (not (and major minor))
1557         (error "Cannot figure out the major and minor version numbers"))
1558     ;; calculate the major version
1559     (cond
1560      ((= major 4)  (setq major 'v18))   ;Epoch 4
1561      ((= major 18) (setq major 'v18))   ;Emacs 18
1562      ((= major 19) (setq major 'v19     ;Emacs 19
1563                          flavor (if (or (string-match "Lucid" emacs-version)
1564                                         (string-match "XEmacs" emacs-version))
1565                                     'XEmacs 'FSF)))
1566      ((> major 19) (setq major 'v20
1567                          flavor (if (or (string-match "Lucid" emacs-version)
1568                                         (string-match "XEmacs" emacs-version))
1569                                     'XEmacs 'FSF)))
1570      ;; I don't know
1571      (t (error "Cannot recognize major version number: %s" major)))
1572     ;; XEmacs 19 uses 8-bit modify-syntax-entry flags, as do all
1573     ;; patched Emacs 19, Emacs 18, Epoch 4's.  Only Emacs 19 uses a
1574     ;; 1-bit flag.  Let's be as smart as we can about figuring this
1575     ;; out.
1576     (if (or (eq major 'v20) (eq major 'v19))
1577         (let ((table (copy-syntax-table)))
1578           (modify-syntax-entry ?a ". 12345678" table)
1579           (cond
1580            ;; XEmacs pre 20 and Emacs pre 19.30 use vectors for syntax tables.
1581            ((vectorp table)
1582             (if (= (logand (lsh (aref table ?a) -16) 255) 255)
1583                 (setq comments '8-bit)
1584               (setq comments '1-bit)))
1585            ;; XEmacs 20 is known to be 8-bit
1586            ((eq flavor 'XEmacs) (setq comments '8-bit))
1587            ;; Emacs 19.30 and beyond are known to be 1-bit
1588            ((eq flavor 'FSF) (setq comments '1-bit))
1589            ;; Don't know what this is
1590            (t (error "Couldn't figure out syntax table format"))
1591            ))
1592       ;; Emacs 18 has no support for dual comments
1593       (setq comments 'no-dual-comments))
1594     ;; determine whether to use old or new font lock syntax
1595     ;; We can assume 8-bit syntax table emacsen support new syntax, otherwise
1596     ;; look for version > 19.30
1597     (setq flock-syntax
1598         (if (or (equal comments '8-bit)
1599                 (equal major 'v20)
1600                 (and (equal major 'v19) (> minor 30)))
1601             'flock-syntax-after-1930
1602           'flock-syntax-before-1930))
1603     ;; lets do some minimal sanity checking.
1604     (if (or
1605          ;; Emacs before 19.6 had bugs
1606          (and (eq major 'v19) (eq flavor 'XEmacs) (< minor 6))
1607          ;; Emacs 19 before 19.21 has known bugs
1608          (and (eq major 'v19) (eq flavor 'FSF) (< minor 21))
1609          )
1610         (with-output-to-temp-buffer "*verilog-mode warnings*"
1611           (print (format
1612   "The version of Emacs that you are running, %s,
1613 has known bugs in its syntax parsing routines which will affect the
1614 performance of verilog-mode. You should strongly consider upgrading to the
1615 latest available version.  verilog-mode may continue to work, after a
1616 fashion, but strange indentation errors could be encountered."
1617                      emacs-version))))
1618     ;; Emacs 18, with no patch is not too good
1619     (if (and (eq major 'v18) (eq comments 'no-dual-comments))
1620         (with-output-to-temp-buffer "*verilog-mode warnings*"
1621           (print (format
1622   "The version of Emacs 18 you are running, %s,
1623 has known deficiencies in its ability to handle the dual verilog
1624 (and C++) comments, (e.g. the // and /* */ comments). This will
1625 not be much of a problem for you if you only use the /* */ comments,
1626 but you really should strongly consider upgrading to one of the latest
1627 Emacs 19's.  In Emacs 18, you may also experience performance degradations.
1628 Emacs 19 has some new built-in routines which will speed things up for you.
1629 Because of these inherent problems, verilog-mode is not supported
1630 on emacs-18."
1631                             emacs-version))))
1632     ;; Emacs 18 with the syntax patches are no longer supported
1633     (if (and (eq major 'v18) (not (eq comments 'no-dual-comments)))
1634         (with-output-to-temp-buffer "*verilog-mode warnings*"
1635           (print (format
1636   "You are running a syntax patched Emacs 18 variant.  While this should
1637 work for you, you may want to consider upgrading to Emacs 19.
1638 The syntax patches are no longer supported either for verilog-mode."))))
1639     (list major comments flock-syntax))
1640   "A list of features extant in the Emacs you are using.
1641 There are many flavors of Emacs out there, each with different
1642 features supporting those needed by `verilog-mode'.  Here's the current
1643 supported list, along with the values for this variable:
1644
1645  Vanilla Emacs 18/Epoch 4:   (v18 no-dual-comments flock-syntax-before-1930)
1646  Emacs 18/Epoch 4 (patch2):  (v18 8-bit flock-syntax-after-1930)
1647  XEmacs (formerly Lucid) 19: (v19 8-bit flock-syntax-after-1930)
1648  XEmacs 20:                  (v20 8-bit flock-syntax-after-1930)
1649  Emacs 19.1-19.30:           (v19 8-bit flock-syntax-before-1930)
1650  Emacs 19.31-19.xx:          (v19 8-bit flock-syntax-after-1930)
1651  Emacs20        :            (v20 1-bit flock-syntax-after-1930).")
1652
1653 (defconst verilog-comment-start-regexp "//\\|/\\*"
1654   "Dual comment value for `comment-start-regexp'.")
1655
1656 (defun verilog-populate-syntax-table (table)
1657   "Populate the syntax TABLE."
1658   (modify-syntax-entry ?\\ "\\" table)
1659   (modify-syntax-entry ?+ "." table)
1660   (modify-syntax-entry ?- "." table)
1661   (modify-syntax-entry ?= "." table)
1662   (modify-syntax-entry ?% "." table)
1663   (modify-syntax-entry ?< "." table)
1664   (modify-syntax-entry ?> "." table)
1665   (modify-syntax-entry ?& "." table)
1666   (modify-syntax-entry ?| "." table)
1667   (modify-syntax-entry ?` "w" table)
1668   (modify-syntax-entry ?_ "w" table)
1669   (modify-syntax-entry ?\' "." table)
1670 )
1671
1672 (defun verilog-setup-dual-comments (table)
1673   "Set up TABLE to handle block and line style comments."
1674   (cond
1675    ((memq '8-bit verilog-emacs-features)
1676     ;; XEmacs (formerly Lucid) has the best implementation
1677     (modify-syntax-entry ?/  ". 1456" table)
1678     (modify-syntax-entry ?*  ". 23"   table)
1679     (modify-syntax-entry ?\n "> b"    table)
1680     )
1681    ((memq '1-bit verilog-emacs-features)
1682     ;; Emacs 19 does things differently, but we can work with it
1683     (modify-syntax-entry ?/  ". 124b" table)
1684     (modify-syntax-entry ?*  ". 23"   table)
1685     (modify-syntax-entry ?\n "> b"    table)
1686     )
1687    ))
1688
1689 (defvar verilog-mode-syntax-table nil
1690   "Syntax table used in `verilog-mode' buffers.")
1691
1692 (defconst verilog-font-lock-keywords nil
1693   "Default highlighting for Verilog mode.")
1694
1695 (defconst verilog-font-lock-keywords-1 nil
1696   "Subdued level highlighting for Verilog mode.")
1697
1698 (defconst verilog-font-lock-keywords-2 nil
1699   "Medium level highlighting for Verilog mode.
1700 See also `verilog-font-lock-extra-types'.")
1701
1702 (defconst verilog-font-lock-keywords-3 nil
1703   "Gaudy level highlighting for Verilog mode.
1704 See also `verilog-font-lock-extra-types'.")
1705 (defvar  verilog-font-lock-translate-off-face
1706   'verilog-font-lock-translate-off-face
1707   "Font to use for translated off regions.")
1708 (defface verilog-font-lock-translate-off-face
1709   '((((class color)
1710       (background light))
1711      (:background "gray90" :italic t ))
1712     (((class color)
1713       (background dark))
1714      (:background "gray10" :italic t ))
1715     (((class grayscale) (background light))
1716      (:foreground "DimGray" :italic t))
1717     (((class grayscale) (background dark))
1718      (:foreground "LightGray" :italic t))
1719     (t (:italis t)))
1720   "Font lock mode face used to background highlight translate-off regions."
1721   :group 'font-lock-highlighting-faces)
1722
1723 (defvar verilog-font-lock-p1800-face
1724   'verilog-font-lock-p1800-face
1725   "Font to use for p1800 keywords.")
1726 (defface verilog-font-lock-p1800-face
1727   '((((class color)
1728       (background light))
1729      (:foreground "DarkOrange3" :bold t ))
1730     (((class color)
1731       (background dark))
1732      (:foreground "orange1" :bold t ))
1733     (t (:italic t)))
1734   "Font lock mode face used to highlight P1800 keywords."
1735   :group 'font-lock-highlighting-faces)
1736
1737 (defvar verilog-font-lock-ams-face
1738   'verilog-font-lock-ams-face
1739   "Font to use for Analog/Mixed Signal keywords.")
1740 (defface verilog-font-lock-ams-face
1741   '((((class color)
1742       (background light))
1743      (:foreground "Purple" :bold t ))
1744     (((class color)
1745       (background dark))
1746      (:foreground "orange1" :bold t ))
1747     (t (:italic t)))
1748   "Font lock mode face used to highlight P1800 keywords."
1749   :group 'font-lock-highlighting-faces)
1750
1751 (let* ((verilog-type-font-keywords
1752         (eval-when-compile
1753           (verilog-regexp-opt
1754            '(
1755              "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
1756              "event" "genvar" "inout" "input" "integer" "localparam"
1757              "logic" "nand" "nmos" "not" "notif0" "notif1" "or"
1758              "output" "parameter" "pmos" "pull0" "pull1" "pullup"
1759              "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
1760              "rtranif0" "rtranif1" "signed" "struct" "supply"
1761              "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
1762              "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
1763              "vectored" "wand" "wire" "wor" "xnor" "xor"
1764              ) nil  )))
1765
1766        (verilog-pragma-keywords
1767         (eval-when-compile
1768           (verilog-regexp-opt
1769            '("surefire" "synopsys" "rtl_synthesis" "verilint" ) nil
1770             )))
1771
1772        (verilog-p1800-keywords
1773         (eval-when-compile
1774           (verilog-regexp-opt
1775            '("alias" "assert" "assume" "automatic" "before" "bind"
1776              "bins" "binsof" "break" "byte" "cell" "chandle" "class"
1777              "clocking" "config" "const" "constraint" "context" "continue"
1778              "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
1779              "dist" "do" "edge" "endclass" "endclocking" "endconfig"
1780              "endgroup" "endprogram" "endproperty" "endsequence" "enum"
1781              "expect" "export" "extends" "extern" "first_match" "foreach"
1782              "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
1783              "illegal_bins" "import" "incdir" "include" "inside" "instance"
1784              "int" "intersect" "large" "liblist" "library" "local" "longint"
1785              "matches" "medium" "modport" "new" "noshowcancelled" "null"
1786              "packed" "program" "property" "protected" "pull0" "pull1"
1787              "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
1788              "randcase" "randsequence" "ref" "release" "return" "scalared"
1789              "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
1790              "specparam" "static" "string" "strong0" "strong1" "struct"
1791              "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
1792              "type" "union" "unsigned" "use" "var" "virtual" "void"
1793              "wait_order" "weak0" "weak1" "wildcard" "with" "within"
1794              ) nil )))
1795
1796        (verilog-ams-keywords
1797         (eval-when-compile
1798           (verilog-regexp-opt
1799            '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
1800              "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
1801              "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
1802              "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
1803              "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
1804              "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
1805              "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
1806              "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
1807              "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
1808              "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
1809              "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
1810
1811        (verilog-font-keywords
1812         (eval-when-compile
1813           (verilog-regexp-opt
1814            '(
1815              "assign" "begin" "case" "casex" "casez" "randcase" "deassign"
1816              "default" "disable" "else" "end" "endcase" "endfunction"
1817              "endgenerate" "endinterface" "endmodule" "endprimitive"
1818              "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break" 
1819              "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
1820              "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
1821              "package" "endpackage" "always" "always_comb" "always_ff"
1822              "always_latch" "posedge" "primitive" "priority" "release"
1823              "repeat" "specify" "table" "task" "unique" "wait" "while"
1824              "class" "program" "endclass" "endprogram"
1825              ) nil  ))))
1826
1827   (setq verilog-font-lock-keywords
1828         (list
1829          ;; Fontify all builtin keywords
1830          (concat "\\<\\(" verilog-font-keywords "\\|"
1831                        ;; And user/system tasks and functions
1832                        "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
1833                        "\\)\\>")
1834          ;; Fontify all types
1835          (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
1836                'font-lock-type-face)
1837          ;; Fontify IEEE-P1800 keywords
1838          (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
1839                'verilog-font-lock-p1800-face)
1840          ;; Fontify Verilog-AMS keywords
1841          (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
1842                'verilog-font-lock-ams-face)
1843
1844          ))
1845
1846   (setq verilog-font-lock-keywords-1
1847         (append verilog-font-lock-keywords
1848                 (list
1849                  ;; Fontify module definitions
1850                  (list
1851                   "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
1852                   '(1 font-lock-keyword-face)
1853                   '(3 font-lock-function-name-face 'prepend))
1854                  ;; Fontify function definitions
1855                  (list
1856                   (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
1857                        '(1 font-lock-keyword-face)
1858                        '(3 font-lock-reference-face prepend)
1859                        )
1860                  '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
1861                    (1 font-lock-keyword-face)
1862                    (2 font-lock-reference-face append)
1863                    )
1864                  '("\\<function\\>\\s-+\\(\\sw+\\)"
1865                    1 'font-lock-reference-face append)
1866                  )))
1867
1868   (setq verilog-font-lock-keywords-2
1869         (append verilog-font-lock-keywords-1
1870                 (list
1871                  ;; Fontify pragmas
1872                  (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
1873                  ;; Fontify escaped names
1874                  '("\\(\\\\\\S-*\\s-\\)"  0 font-lock-function-name-face)
1875                  ;; Fontify macro definitions/ uses
1876                  '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 font-lock-preprocessor-face)
1877                  ;; Fontify delays/numbers
1878                  '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
1879                    0 font-lock-type-face append)
1880                  ;; Fontify instantiation names
1881                  '("\\([A-Za-z][A-Za-z0-9_]+\\)\\s-*(" 1 font-lock-function-name-face)
1882
1883                  )))
1884
1885   (setq verilog-font-lock-keywords-3
1886         (append verilog-font-lock-keywords-2
1887                 (when verilog-highlight-translate-off
1888                   (list
1889                    ;; Fontify things in translate off regions
1890                    '(verilog-match-translate-off (0 'verilog-font-lock-translate-off-face prepend))
1891                    )))
1892   )
1893   )
1894
1895
1896
1897 (defun verilog-inside-comment-p ()
1898   "Check if point inside a nested comment."
1899   (save-excursion
1900     (let ((st-point (point)) hitbeg)
1901       (or (search-backward "//" (verilog-get-beg-of-line) t)
1902           (if (progn
1903                 ;; This is for tricky case //*, we keep searching if /* is proceeded by // on same line
1904                 (while (and (setq hitbeg (search-backward "/*" nil t))
1905                             (progn (forward-char 1) (search-backward "//" (verilog-get-beg-of-line) t))))
1906                 hitbeg)
1907               (not (search-forward "*/" st-point t)))))))
1908
1909 (defun verilog-declaration-end ()
1910   (search-forward ";"))
1911
1912 (defun verilog-point-text (&optional pointnum)
1913   "Return text describing where POINTNUM or current point is (for errors).
1914 Use filename, if current buffer being edited shorten to just buffer name."
1915   (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
1916                    (buffer-name))
1917               buffer-file-name
1918               (buffer-name))
1919           ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
1920
1921 (defun electric-verilog-backward-sexp ()
1922   "Move backward over a sexp."
1923   (interactive)
1924   ;; before that see if we are in a comment
1925   (verilog-backward-sexp)
1926 )
1927 (defun electric-verilog-forward-sexp ()
1928   "Move backward over a sexp."
1929   (interactive)
1930   ;; before that see if we are in a comment
1931   (verilog-forward-sexp)
1932 )
1933 ;;;used by hs-minor-mode
1934 (defun verilog-forward-sexp-function (arg)
1935   (if (< arg 0)
1936       (verilog-backward-sexp)
1937     (verilog-forward-sexp)))
1938
1939
1940 (defun verilog-backward-sexp ()
1941   (let ((reg)
1942         (elsec 1)
1943         (found nil)
1944         (st (point))
1945         )
1946     (if (not (looking-at "\\<"))
1947         (forward-word -1))
1948     (cond
1949      ((verilog-skip-backward-comment-or-string)
1950       )
1951      ((looking-at "\\<else\\>")
1952       (setq reg (concat
1953                  verilog-end-block-re
1954                  "\\|\\(\\<else\\>\\)"
1955                  "\\|\\(\\<if\\>\\)"
1956                  ))
1957       (while (and (not found)
1958                   (verilog-re-search-backward reg nil 'move))
1959         (cond
1960          ((match-end 1) ; matched verilog-end-block-re
1961         ; try to leap back to matching outward block by striding across
1962         ; indent level changing tokens then immediately
1963         ; previous line governs indentation.
1964           (verilog-leap-to-head))
1965          ((match-end 2) ; else, we're in deep
1966           (setq elsec (1+ elsec)))
1967          ((match-end 3) ; found it
1968           (setq elsec (1- elsec))
1969           (if (= 0 elsec)
1970               ;; Now previous line describes syntax
1971               (setq found 't)
1972             ))
1973          )
1974         )
1975       )
1976      ((looking-at verilog-end-block-re)
1977       (verilog-leap-to-head))
1978      ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
1979       (cond
1980        ((match-end 1)
1981         (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
1982        ((match-end 2)
1983         (verilog-re-search-backward "\\<primitive\\>" nil 'move))
1984        ((match-end 3)
1985         (verilog-re-search-backward "\\<class\\>" nil 'move))
1986        ((match-end 4)
1987         (verilog-re-search-backward "\\<program\\>" nil 'move))
1988        ((match-end 5)
1989         (verilog-re-search-backward "\\<interface\\>" nil 'move))
1990        ((match-end 6)
1991         (verilog-re-search-backward "\\<package\\>" nil 'move))
1992        (t
1993         (goto-char st)
1994         (backward-sexp 1))))
1995      (t
1996       (goto-char st)
1997       (backward-sexp))
1998      ) ;; cond
1999     ))
2000
2001 (defun verilog-forward-sexp ()
2002   (let ((reg)
2003         (md 2)
2004         (st (point)))
2005     (if (not (looking-at "\\<"))
2006         (forward-word -1))
2007     (cond
2008      ((verilog-skip-forward-comment-or-string)
2009       (verilog-forward-syntactic-ws)
2010       )
2011      ((looking-at verilog-beg-block-re-ordered);; begin|case|fork|class|table|specify|function|task|generate|covergroup|property|sequence
2012       (cond
2013        ((match-end 1) ; end
2014         ;; Search forward for matching begin
2015         (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
2016        ((match-end 2) ; endcase
2017         ;; Search forward for matching case
2018         (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2019         )
2020        ((match-end 3) ; join
2021         ;; Search forward for matching fork
2022         (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
2023        ((match-end 4) ; endclass
2024         ;; Search forward for matching class
2025         (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
2026        ((match-end 5) ; endtable
2027         ;; Search forward for matching table
2028         (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
2029        ((match-end 6) ; endspecify
2030         ;; Search forward for matching specify
2031         (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2032        ((match-end 7) ; endfunction
2033         ;; Search forward for matching function
2034         (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
2035        ((match-end 8) ; endtask
2036         ;; Search forward for matching task
2037         (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
2038        ((match-end 9) ; endgenerate
2039         ;; Search forward for matching generate
2040         (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
2041        ((match-end 10) ; endgroup
2042         ;; Search forward for matching covergroup
2043         (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
2044        ((match-end 11) ; endproperty
2045         ;; Search forward for matching property
2046         (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
2047        ((match-end 12) ; endsequence
2048         ;; Search forward for matching sequence
2049         (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2050         (setq md 3) ; 3 to get to endsequence in the reg above
2051         )
2052        
2053        )
2054       (if (forward-word 1)
2055           (catch 'skip
2056             (let ((nest 1))
2057               (while (verilog-re-search-forward reg nil 'move)
2058                 (cond
2059                  ((match-end md) ; the closer in reg
2060                   (setq nest (1- nest))
2061                   (if (= 0 nest)
2062                       (throw 'skip 1)))
2063                  ((match-end 1) ; begin
2064                   (setq nest (1+ nest)))))
2065               )))
2066       )
2067      ((looking-at (concat
2068                    "\\(\\<\\(macro\\)?module\\>\\)\\|"
2069                    "\\(\\<primitive\\>\\)\\|"
2070                    "\\(\\<class\\>\\)\\|"
2071                    "\\(\\<program\\>\\)\\|"
2072                    "\\(\\<interface\\>\\)\\|"
2073                    "\\(\\<package\\>\\)"))
2074       (cond
2075        ((match-end 1)
2076         (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2077        ((match-end 2)
2078         (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2079        ((match-end 3)
2080         (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2081        ((match-end 4)
2082         (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2083        ((match-end 5)
2084         (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2085        ((match-end 6)
2086         (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2087        (t
2088         (goto-char st)
2089         (if (= (following-char) ?\) )
2090             (forward-char 1)
2091           (forward-sexp 1)))))
2092      (t
2093       (goto-char st)
2094       (if (= (following-char) ?\) )
2095           (forward-char 1)
2096         (forward-sexp 1)))
2097      ) ;; cond
2098     ))
2099
2100 (defun verilog-declaration-beg ()
2101   (verilog-re-search-backward verilog-declaration-re (bobp) t))
2102
2103 ;;
2104 ;;  Macros
2105 ;;
2106
2107 (defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
2108   "Replace occurrences of FROM-STRING with TO-STRING.
2109 FIXEDCASE and LITERAL as in `replace-match`.  STRING is what to replace.
2110 The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
2111 will break, as the o's continuously replace.  xa -> x works ok though."
2112   ;; Hopefully soon to a emacs built-in
2113   (let ((start 0))
2114     (while (string-match from-string string start)
2115       (setq string (replace-match to-string fixedcase literal string)
2116             start (min (length string) (match-end 0))))
2117     string))
2118
2119 (defsubst verilog-string-remove-spaces (string)
2120   "Remove spaces surrounding STRING."
2121   (save-match-data
2122     (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
2123     (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
2124     string))
2125
2126 (defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
2127   ; checkdoc-params: (REGEXP BOUND NOERROR)
2128   "Like `re-search-forward', but skips over match in comments or strings."
2129   (store-match-data '(nil nil))
2130   (while (and
2131           (re-search-forward REGEXP BOUND NOERROR)
2132           (and (verilog-skip-forward-comment-or-string)
2133                (progn
2134                  (store-match-data '(nil nil))
2135                  (if BOUND
2136                      (< (point) BOUND)
2137                    t)
2138                  ))))
2139   (match-end 0))
2140
2141 (defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
2142   ; checkdoc-params: (REGEXP BOUND NOERROR)
2143   "Like `re-search-backward', but skips over match in comments or strings."
2144   (store-match-data '(nil nil))
2145   (while (and
2146           (re-search-backward REGEXP BOUND NOERROR)
2147           (and (verilog-skip-backward-comment-or-string)
2148                (progn
2149                  (store-match-data '(nil nil))
2150                  (if BOUND
2151                      (> (point) BOUND)
2152                    t)
2153                  ))))
2154   (match-end 0))
2155
2156 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
2157   "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
2158 but trashes match data and is faster for REGEXP that doesn't match often.
2159 This may at some point use text properties to ignore comments,
2160 so there may be a large up front penalty for the first search."
2161   (let (pt)
2162     (while (and (not pt)
2163                 (re-search-forward regexp bound noerror))
2164       (if (not (verilog-inside-comment-p))
2165           (setq pt (match-end 0))))
2166     pt))
2167
2168 (defsubst verilog-re-search-backward-quick (regexp bound noerror)
2169   ; checkdoc-params: (REGEXP BOUND NOERROR)
2170   "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
2171 but trashes match data and is faster for REGEXP that doesn't match often.
2172 This may at some point use text properties to ignore comments,
2173 so there may be a large up front penalty for the first search."
2174   (let (pt)
2175     (while (and (not pt)
2176                 (re-search-backward regexp bound noerror))
2177       (if (not (verilog-inside-comment-p))
2178           (setq pt (match-end 0))))
2179     pt))
2180
2181 (defsubst verilog-get-beg-of-line (&optional arg)
2182   (save-excursion
2183     (beginning-of-line arg)
2184     (point)))
2185
2186 (defsubst verilog-get-end-of-line (&optional arg)
2187   (save-excursion
2188     (end-of-line arg)
2189     (point)))
2190
2191 (defsubst verilog-within-string ()
2192   (save-excursion
2193     (nth 3 (parse-partial-sexp (verilog-get-beg-of-line) (point)))))
2194
2195 (require 'font-lock)
2196 (defvar verilog-need-fld 1)
2197 (defvar font-lock-defaults-alist nil)   ;In case we are XEmacs
2198
2199 (defun verilog-font-lock-init ()
2200   "Initialize fontification."
2201   ;; highlight keywords and standardized types, attributes, enumeration
2202   ;; values, and subprograms
2203   (setq verilog-font-lock-keywords-3
2204         (append verilog-font-lock-keywords-2
2205                 (when verilog-highlight-translate-off
2206                   (list
2207                    ;; Fontify things in translate off regions
2208                    '(verilog-match-translate-off (0 'verilog-font-lock-translate-off-face prepend))
2209                    ))
2210         )
2211   )
2212   (put 'verilog-mode 'font-lock-defaults
2213        '((verilog-font-lock-keywords
2214           verilog-font-lock-keywords-1
2215           verilog-font-lock-keywords-2
2216           verilog-font-lock-keywords-3
2217           )
2218          nil ;; nil means highlight strings & comments as well as keywords
2219          nil ;; nil means keywords must match case
2220          nil ;; syntax table handled elsewhere
2221          verilog-beg-of-defun ;; function to move to beginning of reasonable region to highlight
2222          ))
2223   (if verilog-need-fld
2224       (let ((verilog-mode-defaults
2225              '((verilog-font-lock-keywords
2226                 verilog-font-lock-keywords-1
2227                 verilog-font-lock-keywords-2
2228                 verilog-font-lock-keywords-3
2229                 )
2230                nil ;; nil means highlight strings & comments as well as keywords
2231                nil ;; nil means keywords must match case
2232                nil ;; syntax table handled elsewhere
2233                verilog-beg-of-defun ;; function to move to beginning of reasonable region to highlight
2234                )))
2235         (setq font-lock-defaults-alist
2236               (append
2237                font-lock-defaults-alist
2238                (list (cons 'verilog-mode  verilog-mode-defaults))))
2239         (setq verilog-need-fld 0))))
2240
2241 ;; initialize fontification for Verilog Mode
2242 (verilog-font-lock-init)
2243 ;; start up message
2244 (defconst verilog-startup-message-lines
2245   '("Please use \\[verilog-submit-bug-report] to report bugs."
2246     "Visit http://www.verilog.com to check for updates"
2247     ))
2248 (defconst verilog-startup-message-displayed t)
2249 (defun verilog-display-startup-message ()
2250   (if (not verilog-startup-message-displayed)
2251       (if (sit-for 5)
2252           (let ((lines verilog-startup-message-lines))
2253             (message "verilog-mode version %s, released %s; type \\[describe-mode] for help"
2254                      verilog-mode-version verilog-mode-release-date)
2255             (setq verilog-startup-message-displayed t)
2256             (while (and (sit-for 4) lines)
2257               (message (substitute-command-keys (car lines)))
2258               (setq lines (cdr lines)))))
2259     (message "")))
2260 ;;
2261 ;;
2262 ;;  Mode
2263 ;;
2264
2265 ;;###autoload
2266 (defun verilog-mode ()
2267   "Major mode for editing Verilog code.
2268 \\<verilog-mode-map>
2269 See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2270 AUTOs can improve coding efficiency.
2271
2272 Use \\[verilog-faq] for a pointer to frequently asked questions.
2273
2274 NEWLINE, TAB indents for Verilog code.
2275 Delete converts tabs to spaces as it moves back.
2276
2277 Supports highlighting.
2278
2279 Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
2280 with no args, if that value is non-nil.
2281
2282 Variables controlling indentation/edit style:
2283
2284  variable `verilog-indent-level'      (default 3)
2285    Indentation of Verilog statements with respect to containing block.
2286  `verilog-indent-level-module'        (default 3)
2287    Absolute indentation of Module level Verilog statements.
2288    Set to 0 to get initial and always statements lined up
2289    on the left side of your screen.
2290  `verilog-indent-level-declaration'   (default 3)
2291    Indentation of declarations with respect to containing block.
2292    Set to 0 to get them list right under containing block.
2293  `verilog-indent-level-behavioral'    (default 3)
2294    Indentation of first begin in a task or function block
2295    Set to 0 to get such code to lined up underneath the task or function keyword
2296  `verilog-indent-level-directive'     (default 1)
2297    Indentation of `ifdef/`endif blocks
2298  `verilog-cexp-indent'              (default 1)
2299    Indentation of Verilog statements broken across lines i.e.:
2300       if (a)
2301         begin
2302  `verilog-case-indent'              (default 2)
2303    Indentation for case statements.
2304  `verilog-auto-newline'             (default nil)
2305    Non-nil means automatically newline after semicolons and the punctuation
2306    mark after an end.
2307  `verilog-auto-indent-on-newline'   (default t)
2308    Non-nil means automatically indent line after newline
2309  `verilog-tab-always-indent'        (default t)
2310    Non-nil means TAB in Verilog mode should always reindent the current line,
2311    regardless of where in the line point is when the TAB command is used.
2312  `verilog-indent-begin-after-if'    (default t)
2313    Non-nil means to indent begin statements following a preceding
2314    if, else, while, for and repeat statements, if any.  otherwise,
2315    the begin is lined up with the preceding token.  If t, you get:
2316       if (a)
2317          begin // amount of indent based on `verilog-cexp-indent'
2318    otherwise you get:
2319       if (a)
2320       begin
2321  `verilog-auto-endcomments'         (default t)
2322    Non-nil means a comment /* ... */ is set after the ends which ends
2323    cases, tasks, functions and modules.
2324    The type and name of the object will be set between the braces.
2325  `verilog-minimum-comment-distance' (default 10)
2326    Minimum distance (in lines) between begin and end required before a comment
2327    will be inserted.  Setting this variable to zero results in every
2328    end acquiring a comment; the default avoids too many redundant
2329    comments in tight quarters.
2330  `verilog-auto-lineup'              (default `(all))
2331    List of contexts where auto lineup of code should be done.
2332
2333 Variables controlling other actions:
2334
2335  `verilog-linter'                   (default surelint)
2336    Unix program to call to run the lint checker.  This is the default
2337    command for \\[compile-command] and \\[verilog-auto-save-compile].
2338
2339 See \\[customize] for the complete list of variables.
2340
2341 AUTO expansion functions are, in part:
2342
2343     \\[verilog-auto]  Expand AUTO statements.
2344     \\[verilog-delete-auto]  Remove the AUTOs.
2345     \\[verilog-inject-auto]  Insert AUTOs for the first time.
2346
2347 Some other functions are:
2348
2349     \\[verilog-complete-word]    Complete word with appropriate possibilities.
2350     \\[verilog-mark-defun]  Mark function.
2351     \\[verilog-beg-of-defun]  Move to beginning of current function.
2352     \\[verilog-end-of-defun]  Move to end of current function.
2353     \\[verilog-label-be]  Label matching begin ... end, fork ... join, etc statements.
2354
2355     \\[verilog-comment-region]  Put marked area in a comment.
2356     \\[verilog-uncomment-region]  Uncomment an area commented with \\[verilog-comment-region].
2357     \\[verilog-insert-block]  Insert begin ... end;.
2358     \\[verilog-star-comment]    Insert /* ... */.
2359
2360     \\[verilog-sk-always]  Insert a always @(AS) begin .. end block.
2361     \\[verilog-sk-begin]  Insert a begin .. end block.
2362     \\[verilog-sk-case]  Insert a case block, prompting for details.
2363     \\[verilog-sk-for]  Insert a for (...) begin .. end block, prompting for details.
2364     \\[verilog-sk-generate]  Insert a generate .. endgenerate block.
2365     \\[verilog-sk-header]  Insert a nice header block at the top of file.
2366     \\[verilog-sk-initial]  Insert an initial begin .. end block.
2367     \\[verilog-sk-fork]  Insert a fork begin .. end .. join block.
2368     \\[verilog-sk-module]  Insert a module .. (/*AUTOARG*/);.. endmodule block.
2369     \\[verilog-sk-primitive]  Insert a primitive .. (.. );.. endprimitive block.
2370     \\[verilog-sk-repeat]  Insert a repeat (..) begin .. end block.
2371     \\[verilog-sk-specify]  Insert a specify .. endspecify block.
2372     \\[verilog-sk-task]  Insert a task .. begin .. end endtask block.
2373     \\[verilog-sk-while]  Insert a while (...) begin .. end block, prompting for details.
2374     \\[verilog-sk-casex]  Insert a casex (...) item: begin.. end endcase block, prompting for details.
2375     \\[verilog-sk-casez]  Insert a casez (...) item: begin.. end endcase block, prompting for details.
2376     \\[verilog-sk-if]  Insert an if (..) begin .. end block.
2377     \\[verilog-sk-else-if]  Insert an else if (..) begin .. end block.
2378     \\[verilog-sk-comment]  Insert a comment block.
2379     \\[verilog-sk-assign]  Insert an assign .. = ..; statement.
2380     \\[verilog-sk-function]  Insert a function .. begin .. end endfunction block.
2381     \\[verilog-sk-input]  Insert an input declaration, prompting for details.
2382     \\[verilog-sk-output]  Insert an output declaration, prompting for details.
2383     \\[verilog-sk-state-machine]  Insert a state machine definition, prompting for details.
2384     \\[verilog-sk-inout]  Insert an inout declaration, prompting for details.
2385     \\[verilog-sk-wire]  Insert a wire declaration, prompting for details.
2386     \\[verilog-sk-reg]  Insert a register declaration, prompting for details.
2387     \\[verilog-sk-define-signal]  Define signal under point as a register at the top of the module.
2388
2389 All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
2390 Key bindings specific to `verilog-mode-map' are:
2391
2392 \\{verilog-mode-map}"
2393   (interactive)
2394   (kill-all-local-variables)
2395   (use-local-map verilog-mode-map)
2396   (setq major-mode 'verilog-mode)
2397   (setq mode-name "Verilog")
2398   (setq local-abbrev-table verilog-mode-abbrev-table)
2399   (setq verilog-mode-syntax-table (make-syntax-table))
2400   (verilog-populate-syntax-table verilog-mode-syntax-table)
2401   ;; add extra comment syntax
2402   (verilog-setup-dual-comments verilog-mode-syntax-table)
2403   (set-syntax-table verilog-mode-syntax-table)
2404   (make-local-variable 'indent-line-function)
2405   (setq indent-line-function 'verilog-indent-line-relative)
2406   (setq comment-indent-function 'verilog-comment-indent)
2407   (make-local-variable 'parse-sexp-ignore-comments)
2408   (setq parse-sexp-ignore-comments nil)
2409   (make-local-variable 'comment-start)
2410   (make-local-variable 'comment-end)
2411   (make-local-variable 'comment-multi-line)
2412   (make-local-variable 'comment-start-skip)
2413   (setq comment-start "// "
2414         comment-end ""
2415         comment-start-skip "/\\*+ *\\|// *"
2416         comment-multi-line nil)
2417   ;; Set up for compilation
2418   (setq verilog-which-tool 1)
2419   (setq verilog-tool 'verilog-linter)
2420   (verilog-set-compile-command)
2421   (when (boundp 'hack-local-variables-hook)  ;; Also modify any file-local-variables
2422     (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
2423
2424   ;; Setting up things for font-lock
2425   (if verilog-running-on-xemacs
2426       (progn
2427         (if (and current-menubar
2428                  (not (assoc "Verilog" current-menubar)))
2429             (progn
2430               ;; (set-buffer-menubar (copy-sequence current-menubar))
2431               (add-submenu nil verilog-xemacs-menu)
2432               (add-submenu nil verilog-stmt-menu)
2433               )
2434           )
2435         ))
2436   ;; Stuff for GNU emacs
2437   (make-local-variable 'font-lock-defaults)
2438   ;;------------------------------------------------------------
2439   ;; now hook in 'verilog-colorize-include-files (eldo-mode.el&spice-mode.el)
2440   ;; all buffer local:
2441   (make-local-hook 'font-lock-mode-hook)
2442   (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in emacs 20
2443   (add-hook 'font-lock-mode-hook 'verilog-colorize-include-files-buffer t t)
2444   (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-colorize-include-files-buffer t t) ; not in emacs 20
2445   (make-local-hook 'after-change-functions)
2446   (add-hook 'after-change-functions 'verilog-colorize-include-files t t)
2447
2448   ;; Tell imenu how to handle verilog.
2449   (make-local-variable 'imenu-generic-expression)
2450   (setq imenu-generic-expression verilog-imenu-generic-expression)
2451   ;; hideshow support
2452   (unless (assq 'verilog-mode hs-special-modes-alist)
2453     (setq hs-special-modes-alist
2454           (cons '(verilog-mode-mode  "\\<begin\\>" "\\<end\\>" nil
2455                              verilog-forward-sexp-function)
2456                 hs-special-modes-alist)))
2457   ;; Display version splash information.
2458   (verilog-display-startup-message)
2459
2460   ;; Stuff for autos
2461   (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
2462 ;;  (verilog-auto-reeval-locals t)   ; Save locals in case user changes them
2463 ;;  (verilog-getopt-flags)
2464   (run-hooks 'verilog-mode-hook))
2465 \f
2466
2467 ;;
2468 ;;  Electric functions
2469 ;;
2470 (defun electric-verilog-terminate-line (&optional arg)
2471   "Terminate line and indent next line.
2472 With optional ARG, remove existing end of line comments."
2473   (interactive)
2474   ;; before that see if we are in a comment
2475   (let ((state
2476          (save-excursion
2477            (parse-partial-sexp (point-min) (point)))))
2478     (cond
2479      ((nth 7 state)                     ; Inside // comment
2480       (if (eolp)
2481           (progn
2482             (delete-horizontal-space)
2483             (newline))
2484         (progn
2485           (newline)
2486           (insert-string "// ")
2487           (beginning-of-line)))
2488       (verilog-indent-line))
2489      ((nth 4 state)                     ; Inside any comment (hence /**/)
2490       (newline)
2491       (verilog-more-comment))
2492      ((eolp)
2493        ;; First, check if current line should be indented
2494        (if (save-excursion
2495              (delete-horizontal-space)
2496              (beginning-of-line)
2497              (skip-chars-forward " \t")
2498              (if (looking-at verilog-auto-end-comment-lines-re)
2499                  (let ((indent-str (verilog-indent-line)))
2500                    ;; Maybe we should set some endcomments
2501                    (if verilog-auto-endcomments
2502                        (verilog-set-auto-endcomments indent-str arg))
2503                    (end-of-line)
2504                    (delete-horizontal-space)
2505                    (if arg
2506                        ()
2507                      (newline))
2508                    nil)
2509                (progn
2510                  (end-of-line)
2511                  (delete-horizontal-space)
2512                  't
2513                  )
2514                )
2515              )
2516            ;; see if we should line up assignments
2517            (progn
2518              (if (or (memq 'all verilog-auto-lineup)
2519                      (memq 'assignments verilog-auto-lineup))
2520                  (verilog-pretty-expr)
2521                )
2522              (newline)
2523              )
2524          (forward-line 1)
2525          )
2526        ;; Indent next line
2527        (if verilog-auto-indent-on-newline
2528            (verilog-indent-line))
2529        )
2530      (t
2531       (newline))
2532      )))
2533
2534 (defun electric-verilog-terminate-and-indent ()
2535   "Insert a newline and indent for the next statement."
2536   (interactive)
2537   (electric-verilog-terminate-line 1))
2538
2539 (defun electric-verilog-semi ()
2540   "Insert `;' character and reindent the line."
2541   (interactive)
2542   (insert last-command-char)
2543
2544   (if (or (verilog-in-comment-or-string-p)
2545           (verilog-in-escaped-name-p))
2546       ()
2547     (save-excursion
2548       (beginning-of-line)
2549       (verilog-forward-ws&directives)
2550       (verilog-indent-line)
2551       )
2552     (if (and verilog-auto-newline
2553              (not (verilog-parenthesis-depth)))
2554         (electric-verilog-terminate-line))))
2555
2556 (defun electric-verilog-semi-with-comment ()
2557   "Insert `;' character, reindent the line and indent for comment."
2558   (interactive)
2559   (insert "\;")
2560   (save-excursion
2561     (beginning-of-line)
2562     (verilog-indent-line))
2563   (indent-for-comment))
2564
2565 (defun electric-verilog-colon ()
2566   "Insert `:' and do all indentations except line indent on this line."
2567   (interactive)
2568   (insert last-command-char)
2569   ;; Do nothing if within string.
2570   (if (or
2571        (verilog-within-string)
2572        (not (verilog-in-case-region-p)))
2573       ()
2574     (save-excursion
2575       (let ((p (point))
2576             (lim (progn (verilog-beg-of-statement) (point))))
2577         (goto-char p)
2578         (verilog-backward-case-item lim)
2579         (verilog-indent-line)))
2580 ;;    (let ((verilog-tab-always-indent nil))
2581 ;;      (verilog-indent-line))
2582     ))
2583
2584 ;;(defun electric-verilog-equal ()
2585 ;;  "Insert `=', and do indentation if within block."
2586 ;;  (interactive)
2587 ;;  (insert last-command-char)
2588 ;; Could auto line up expressions, but not yet
2589 ;;  (if (eq (car (verilog-calculate-indent)) 'block)
2590 ;;      (let ((verilog-tab-always-indent nil))
2591 ;;      (verilog-indent-command)))
2592 ;;  )
2593
2594 (defun electric-verilog-tick ()
2595   "Insert back-tick, and indent to column 0 if this is a CPP directive."
2596   (interactive)
2597   (insert last-command-char)
2598   (save-excursion
2599     (if (progn
2600           (beginning-of-line)
2601           (looking-at verilog-directive-re-1))
2602         (verilog-indent-line))))
2603
2604 (defun electric-verilog-tab ()
2605   "Function called when TAB is pressed in Verilog mode."
2606   (interactive)
2607   ;; If verilog-tab-always-indent, indent the beginning of the line.
2608   (if (or verilog-tab-always-indent
2609           (save-excursion
2610             (skip-chars-backward " \t")
2611             (bolp)))
2612       (let* ((oldpnt (point))
2613              (boi-point
2614               (save-excursion
2615                 (beginning-of-line)
2616                 (skip-chars-forward " \t")
2617                 (verilog-indent-line)
2618                 (back-to-indentation)
2619                 (point))))
2620         (if (< (point) boi-point)
2621             (back-to-indentation)
2622           (cond ((not verilog-tab-to-comment))
2623                 ((not (eolp))
2624                  (end-of-line))
2625                 (t
2626                  (indent-for-comment)
2627                  (when (and (eolp) (= oldpnt (point)))
2628                                         ; kill existing comment
2629                    (beginning-of-line)
2630                    (re-search-forward comment-start-skip oldpnt 'move)
2631                    (goto-char (match-beginning 0))
2632                    (skip-chars-backward " \t")
2633                    (kill-region (point) oldpnt)
2634                    ))))
2635         )
2636     (progn (insert "\t"))))
2637
2638 \f
2639
2640 ;;
2641 ;; Interactive functions
2642 ;;
2643
2644 (defun verilog-indent-buffer ()
2645   "Indent-region the entire buffer as Verilog code.
2646 To call this from the command line, see \\[verilog-batch-indent]."
2647   (interactive)
2648   (verilog-mode)
2649   (indent-region (point-min) (point-max) nil))
2650
2651 (defun verilog-insert-block ()
2652   "Insert Verilog begin ... end; block in the code with right indentation."
2653   (interactive)
2654   (verilog-indent-line)
2655   (insert "begin")
2656   (electric-verilog-terminate-line)
2657   (save-excursion
2658     (electric-verilog-terminate-line)
2659     (insert "end")
2660     (beginning-of-line)
2661     (verilog-indent-line)))
2662
2663 (defun verilog-star-comment ()
2664   "Insert Verilog star comment at point."
2665   (interactive)
2666   (verilog-indent-line)
2667   (insert "/*")
2668   (save-excursion
2669     (newline)
2670     (insert " */"))
2671   (newline)
2672   (insert " * "))
2673
2674 (defun verilog-insert-indices (MAX)
2675   "Insert a set of indices at into the rectangle.
2676 The upper left corner is defined by the current point.  Indices always
2677 begin with 0 and extend to the MAX - 1.  If no prefix arg is given, the
2678 user is prompted for a value.  The indices are surrounded by square brackets
2679 [].  For example, the following code with the point located after the first
2680 'a' gives:
2681
2682     a = b                           a[  0] = b
2683     a = b                           a[  1] = b
2684     a = b                           a[  2] = b
2685     a = b                           a[  3] = b
2686     a = b   ==> insert-indices ==>  a[  4] = b
2687     a = b                           a[  5] = b
2688     a = b                           a[  6] = b
2689     a = b                           a[  7] = b
2690     a = b                           a[  8] = b"
2691
2692   (interactive "NMAX?")
2693   (save-excursion
2694   (let ((n 0))
2695     (while (< n MAX)
2696       (save-excursion
2697       (insert (format "[%3d]" n)))
2698       (next-line 1)
2699       (setq n (1+ n))))))
2700
2701
2702 (defun verilog-generate-numbers (MAX)
2703   "Insert a set of generated numbers into a rectangle.
2704 The upper left corner is defined by point.  The numbers are padded to three
2705 digits, starting with 000 and extending to (MAX - 1).  If no prefix argument
2706 is supplied, then the user is prompted for the MAX number.  consider the
2707 following code fragment:
2708
2709     buf buf                           buf buf000
2710     buf buf                           buf buf001
2711     buf buf                           buf buf002
2712     buf buf                           buf buf003
2713     buf buf   ==> insert-indices ==>  buf buf004
2714     buf buf                           buf buf005
2715     buf buf                           buf buf006
2716     buf buf                           buf buf007
2717     buf buf                           buf buf008"
2718
2719   (interactive "NMAX?")
2720   (save-excursion
2721   (let ((n 0))
2722     (while (< n MAX)
2723       (save-excursion
2724       (insert (format "%3.3d" n)))
2725       (next-line 1)
2726       (setq n (1+ n))))))
2727
2728 (defun verilog-mark-defun ()
2729   "Mark the current verilog function (or procedure).
2730 This puts the mark at the end, and point at the beginning."
2731   (interactive)
2732   (push-mark (point))
2733   (verilog-end-of-defun)
2734   (push-mark (point))
2735   (verilog-beg-of-defun)
2736   (zmacs-activate-region))
2737
2738 (defun verilog-comment-region (start end)
2739   ; checkdoc-params: (start end)
2740   "Put the region into a Verilog comment.
2741 The comments that are in this area are \"deformed\":
2742 `*)' becomes `!(*' and `}' becomes `!{'.
2743 These deformed comments are returned to normal if you use
2744 \\[verilog-uncomment-region] to undo the commenting.
2745
2746 The commented area starts with `verilog-exclude-str-start', and ends with
2747 `verilog-exclude-str-end'.  But if you change these variables,
2748 \\[verilog-uncomment-region] won't recognize the comments."
2749   (interactive "r")
2750   (save-excursion
2751     ;; Insert start and endcomments
2752     (goto-char end)
2753     (if (and (save-excursion (skip-chars-forward " \t") (eolp))
2754              (not (save-excursion (skip-chars-backward " \t") (bolp))))
2755         (forward-line 1)
2756       (beginning-of-line))
2757     (insert verilog-exclude-str-end)
2758     (setq end (point))
2759     (newline)
2760     (goto-char start)
2761     (beginning-of-line)
2762     (insert verilog-exclude-str-start)
2763     (newline)
2764     ;; Replace end-comments within commented area
2765     (goto-char end)
2766     (save-excursion
2767       (while (re-search-backward "\\*/" start t)
2768         (replace-match "*-/" t t)))
2769     (save-excursion
2770       (let ((s+1 (1+ start)))
2771         (while (re-search-backward "/\\*" s+1 t)
2772           (replace-match "/-*" t t))))
2773     ))
2774
2775 (defun verilog-uncomment-region ()
2776   "Uncomment a commented area; change deformed comments back to normal.
2777 This command does nothing if the pointer is not in a commented
2778 area.  See also `verilog-comment-region'."
2779   (interactive)
2780   (save-excursion
2781     (let ((start (point))
2782           (end (point)))
2783       ;; Find the boundaries of the comment
2784       (save-excursion
2785         (setq start (progn (search-backward verilog-exclude-str-start nil t)
2786                            (point)))
2787         (setq end (progn (search-forward verilog-exclude-str-end nil t)
2788                          (point))))
2789       ;; Check if we're really inside a comment
2790       (if (or (equal start (point)) (<= end (point)))
2791           (message "Not standing within commented area.")
2792         (progn
2793           ;; Remove endcomment
2794           (goto-char end)
2795           (beginning-of-line)
2796           (let ((pos (point)))
2797             (end-of-line)
2798             (delete-region pos (1+ (point))))
2799           ;; Change comments back to normal
2800           (save-excursion
2801             (while (re-search-backward "\\*-/" start t)
2802               (replace-match "*/" t t)))
2803           (save-excursion
2804             (while (re-search-backward "/-\\*" start t)
2805               (replace-match "/*" t t)))
2806           ;; Remove start comment
2807           (goto-char start)
2808           (beginning-of-line)
2809           (let ((pos (point)))
2810             (end-of-line)
2811             (delete-region pos (1+ (point)))))))))
2812
2813 (defun verilog-beg-of-defun ()
2814   "Move backward to the beginning of the current function or procedure."
2815   (interactive)
2816   (verilog-re-search-backward verilog-defun-re nil 'move))
2817
2818 (defun verilog-end-of-defun ()
2819   "Move forward to the end of the current function or procedure."
2820   (interactive)
2821   (verilog-re-search-forward verilog-end-defun-re nil 'move))
2822
2823 (defun verilog-get-beg-of-defun (&optional warn)
2824   (save-excursion
2825     (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
2826            (point))
2827           (t
2828            (error "%s: Can't find module beginning" (verilog-point-text))
2829            (point-max)))))
2830 (defun verilog-get-end-of-defun (&optional warn)
2831   (save-excursion
2832     (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
2833            (point))
2834           (t
2835            (error "%s: Can't find endmodule" (verilog-point-text))
2836            (point-max)))))
2837
2838 (defun verilog-label-be (&optional arg)
2839   "Label matching begin ... end, fork ... join and case ... endcase statements.
2840 With ARG, first kill any existing labels."
2841   (interactive)
2842   (let ((cnt 0)
2843         (oldpos (point))
2844         (b (progn
2845              (verilog-beg-of-defun)
2846              (point-marker)))
2847         (e (progn
2848              (verilog-end-of-defun)
2849              (point-marker)))
2850         )
2851     (goto-char (marker-position b))
2852     (if (> (- e b) 200)
2853         (message  "Relabeling module..."))
2854     (while (and
2855             (> (marker-position e) (point))
2856             (verilog-re-search-forward
2857              (concat
2858               "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
2859               "\\|\\(`endif\\)\\|\\(`else\\)")
2860              nil 'move))
2861       (goto-char (match-beginning 0))
2862       (let ((indent-str (verilog-indent-line)))
2863         (verilog-set-auto-endcomments indent-str 't)
2864         (end-of-line)
2865         (delete-horizontal-space)
2866         )
2867       (setq cnt (1+ cnt))
2868       (if (= 9 (% cnt 10))
2869           (message "%d..." cnt))
2870       )
2871     (goto-char oldpos)
2872     (if (or
2873          (> (- e b) 200)
2874          (> cnt 20))
2875         (message  "%d lines auto commented" cnt))
2876     ))
2877
2878 (defun verilog-beg-of-statement ()
2879   "Move backward to beginning of statement."
2880   (interactive)
2881   (while (save-excursion
2882            (not (looking-at verilog-complete-reg))
2883            (verilog-backward-syntactic-ws)
2884            (not (or
2885                  (bolp)
2886                  (= (preceding-char) ?\;)
2887                  (save-excursion
2888                    (verilog-backward-token)
2889                    (looking-at verilog-end-block-re))
2890                  )))
2891     (skip-chars-backward " \t")
2892     (verilog-backward-token))
2893   (let ((last (point)))
2894     (while (progn
2895              (setq last (point))
2896              (and (not (looking-at verilog-complete-reg))
2897                   (verilog-continued-line))))
2898     (goto-char last)
2899     (verilog-forward-syntactic-ws)))
2900
2901 (defun verilog-beg-of-statement-1 ()
2902   "Move backward to beginning of statement."
2903   (interactive)
2904   (let ((pt (point)))
2905
2906     (while (and (not (looking-at verilog-complete-reg))
2907                 (setq pt (point))
2908                 (verilog-backward-token)
2909                 (not (looking-at verilog-complete-reg))
2910                 (verilog-backward-syntactic-ws)
2911                 (setq pt (point))
2912                 (not (bolp))
2913                 (not (= (preceding-char) ?\;))))
2914 ;    (while (progn
2915 ;            (setq pt (point))
2916 ;            (and (not (looking-at verilog-complete-reg))
2917 ;                 (not (= (preceding-char) ?\;))
2918 ;                 (verilog-continued-line))))
2919     (goto-char pt)
2920     (verilog-forward-ws&directives)))
2921
2922 (defun verilog-end-of-statement ()
2923   "Move forward to end of current statement."
2924   (interactive)
2925   (let ((nest 0) pos)
2926     (or (looking-at verilog-beg-block-re)
2927         ;; Skip to end of statement
2928         (setq pos (catch 'found
2929                     (while t
2930                       (forward-sexp 1)
2931                       (verilog-skip-forward-comment-or-string)
2932                       (cond ((looking-at "[ \t]*;")
2933                              (skip-chars-forward "^;")
2934                              (forward-char 1)
2935                              (throw 'found (point)))
2936                             ((save-excursion
2937                                (forward-sexp -1)
2938                                (looking-at verilog-beg-block-re))
2939                              (goto-char (match-beginning 0))
2940                              (throw 'found nil))
2941                             ((eobp)
2942                              (throw 'found (point))))))))
2943     (if (not pos)
2944         ;; Skip a whole block
2945         (catch 'found
2946           (while t
2947             (verilog-re-search-forward verilog-end-statement-re nil 'move)
2948             (setq nest (if (match-end 1)
2949                            (1+ nest)
2950                          (1- nest)))
2951             (cond ((eobp)
2952                    (throw 'found (point)))
2953                   ((= 0 nest)
2954                    (throw 'found (verilog-end-of-statement))))))
2955       pos)))
2956
2957 (defun verilog-in-case-region-p ()
2958   "Return TRUE if in a case region;
2959 more specifically, point @ in the line foo : @ begin"
2960   (interactive)
2961   (save-excursion
2962     (if (and
2963          (progn (verilog-forward-syntactic-ws)
2964                 (looking-at "\\<begin\\>"))
2965          (progn (verilog-backward-syntactic-ws)
2966                 (= (preceding-char) ?\:)))
2967         (catch 'found
2968           (let ((nest 1))
2969             (while t
2970               (verilog-re-search-backward
2971                (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
2972                        "\\(\\<endcase\\>\\)\\>")
2973                nil 'move)
2974               (cond
2975                ((match-end 3)
2976                 (setq nest (1+ nest)))
2977                ((match-end 2)
2978                 (if (= nest 1)
2979                 (throw 'found 1))
2980                 (setq nest (1- nest)))
2981                (t
2982                 (throw 'found (= nest 0)))
2983                ))))
2984       nil)))
2985 (defun verilog-in-struct-region-p ()
2986   "Return TRUE if in a struct region;
2987 more specifically, in a list after a struct|union keyword"
2988   (interactive)
2989   (save-excursion
2990     (let* ((state (parse-partial-sexp (point-min) (point)))
2991            (depth (nth 0 state)))
2992       (if depth
2993           (progn (backward-up-list depth)
2994                  (verilog-beg-of-statement)
2995                  (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>")
2996                  )
2997         )
2998       )
2999     )
3000   )
3001
3002 (defun verilog-in-generate-region-p ()
3003   "Return TRUE if in a generate region;
3004 more specifically, after a generate and before an endgenerate"
3005   (interactive)
3006   (let ((lim (save-excursion (verilog-beg-of-defun)  (point)))
3007         (nest 1)
3008         )
3009     (save-excursion
3010       (while (and
3011               (/= nest 0)
3012               (verilog-re-search-backward "\\<\\(generate\\)\\|\\(endgenerate\\)\\>" lim 'move)
3013               (cond
3014                ((match-end 1) ; generate
3015                 (setq nest (1- nest)))
3016                ((match-end 2) ; endgenerate
3017                 (setq nest (1+ nest)))
3018                ))
3019         ))
3020     (= nest 0) )) ; return nest
3021
3022 (defun verilog-in-fork-region-p ()
3023   "Return true if between a fork and join."
3024   (interactive)
3025   (let ((lim (save-excursion (verilog-beg-of-defun)  (point)))
3026         (nest 1)
3027         )
3028     (save-excursion
3029       (while (and
3030               (/= nest 0)
3031               (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
3032               (cond
3033                ((match-end 1) ; fork
3034                 (setq nest (1- nest)))
3035                ((match-end 2) ; join
3036                 (setq nest (1+ nest)))
3037                ))
3038         ))
3039     (= nest 0) )) ; return nest
3040
3041 (defun verilog-backward-case-item (lim)
3042   "Skip backward to nearest enclosing case item.
3043 Limit search to point LIM."
3044   (interactive)
3045   (let ((str 'nil)
3046         (lim1
3047          (progn
3048            (save-excursion
3049              (verilog-re-search-backward verilog-endcomment-reason-re
3050                                          lim 'move)
3051              (point)))))
3052     ;; Try to find the real :
3053     (if (save-excursion (search-backward ":" lim1 t))
3054         (let ((colon 0)
3055               b e )
3056           (while
3057               (and
3058                (< colon 1)
3059                (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
3060                                            lim1 'move))
3061             (cond
3062              ((match-end 1) ;; [
3063               (setq colon (1+ colon))
3064               (if (>= colon 0)
3065                   (error "%s: unbalanced [" (verilog-point-text))))
3066              ((match-end 2) ;; ]
3067               (setq colon (1- colon)))
3068
3069              ((match-end 3) ;; :
3070               (setq colon (1+ colon)))
3071              ))
3072           ;; Skip back to beginning of case item
3073           (skip-chars-backward "\t ")
3074           (verilog-skip-backward-comment-or-string)
3075           (setq e (point))
3076           (setq b
3077                 (progn
3078                   (if
3079                       (verilog-re-search-backward
3080                        "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3081                       (progn
3082                         (cond
3083                          ((match-end 1)
3084                           (goto-char (match-end 1))
3085                           (verilog-forward-ws&directives)
3086                           (if (looking-at "(")
3087                               (progn
3088                                 (forward-sexp)
3089                                 (verilog-forward-ws&directives)))
3090                           (point))
3091                          (t
3092                           (goto-char (match-end 0))
3093                           (verilog-forward-ws&directives)
3094                           (point))
3095                          ))
3096                     (error "Malformed case item")
3097                     )))
3098           (setq str (buffer-substring b e))
3099           (if
3100               (setq e
3101                     (string-match
3102                      "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3103               (setq str (concat (substring str 0 e) "...")))
3104           str)
3105       'nil)))
3106 \f
3107
3108 ;;
3109 ;; Other functions
3110 ;;
3111
3112 (defun kill-existing-comment ()
3113   "Kill auto comment on this line."
3114   (save-excursion
3115     (let* (
3116            (e (progn
3117                 (end-of-line)
3118                 (point)))
3119            (b (progn
3120                 (beginning-of-line)
3121                 (search-forward "//" e t))))
3122       (if b
3123           (delete-region (- b 2) e)))))
3124
3125 (defconst verilog-directive-nest-re
3126   (concat "\\(`else\\>\\)\\|"
3127           "\\(`endif\\>\\)\\|"
3128           "\\(`if\\>\\)\\|"
3129           "\\(`ifdef\\>\\)\\|"
3130           "\\(`ifndef\\>\\)"))
3131 (defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3132   "Add ending comment with given INDENT-STR.
3133 With KILL-EXISTING-COMMENT, remove what was there before.
3134 Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3135 Insert `// case expr ' if this line ends a case block.
3136 Insert `// ifdef FOO ' if this line ends code conditional on FOO.
3137 Insert `// NAME ' if this line ends a function, task, module, primitive or interface named NAME."
3138   (save-excursion
3139     (cond
3140      (; Comment close preprocessor directives
3141       (and
3142        (looking-at "\\(`endif\\)\\|\\(`else\\)")
3143        (or  kill-existing-comment
3144             (not (save-excursion
3145                    (end-of-line)
3146                    (search-backward "//" (verilog-get-beg-of-line) t)))))
3147       (let ((nest 1) b e
3148             m
3149             (else (if (match-end 2) "!" " "))
3150             )
3151         (end-of-line)
3152         (if kill-existing-comment
3153             (kill-existing-comment))
3154         (delete-horizontal-space)
3155         (save-excursion
3156           (backward-sexp 1)
3157           (while (and (/= nest 0)
3158                       (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3159             (cond
3160              ((match-end 1) ; `else
3161               (if (= nest 1)
3162                   (setq else "!")))
3163              ((match-end 2) ; `endif
3164               (setq nest (1+ nest)))
3165              ((match-end 3) ; `if
3166               (setq nest (1- nest)))
3167              ((match-end 4) ; `ifdef
3168               (setq nest (1- nest)))
3169              ((match-end 5) ; `ifndef
3170               (setq nest (1- nest)))
3171              ))
3172           (if (match-end 0)
3173               (setq
3174                m (buffer-substring
3175                   (match-beginning 0)
3176                   (match-end 0))
3177                b (progn
3178                    (skip-chars-forward "^ \t")
3179                    (verilog-forward-syntactic-ws)
3180                    (point))
3181                e (progn
3182                    (skip-chars-forward "a-zA-Z0-9_")
3183                    (point)
3184                    ))))
3185         (if b
3186             (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3187                 (insert (concat " // " else m " " (buffer-substring b e))))
3188           (progn
3189             (insert " // unmatched `else or `endif")
3190             (ding 't))
3191           )))
3192
3193      (; Comment close case/class/function/task/module and named block
3194       (and (looking-at "\\<end")
3195            (or kill-existing-comment
3196                (not (save-excursion
3197                       (end-of-line)
3198                       (search-backward "//" (verilog-get-beg-of-line) t)))))
3199       (let ((type (car indent-str)))
3200         (unless (eq type 'declaration)
3201           (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3202             (if (looking-at verilog-end-block-ordered-re)
3203               (cond
3204                (;- This is a case block; search back for the start of this case
3205                 (match-end 1) ;; of verilog-end-block-ordered-re
3206
3207                 (let ((err 't)
3208                       (str "UNMATCHED!!"))
3209                   (save-excursion
3210                     (verilog-leap-to-head)
3211                     (cond
3212                      ((looking-at "\\<randcase\\>")
3213                       (setq str "randcase")
3214                       (setq err nil)
3215                       )
3216                      ((match-end 0)
3217                       (goto-char (match-end 1))
3218                       (if nil
3219                           (let (s f)
3220                             (setq s (match-beginning 1))
3221                             (setq f (progn (end-of-line)
3222                                            (point)))
3223                             (setq str  (buffer-substring s f)))
3224                         (setq err nil))
3225                       (setq str (concat (buffer-substring (match-beginning 1) (match-end 1))
3226                                         " "
3227                                         (verilog-get-expr))))))
3228                   (end-of-line)
3229                   (if kill-existing-comment
3230                       (kill-existing-comment))
3231                   (delete-horizontal-space)
3232                   (insert (concat " // " str ))
3233                   (if err (ding 't))
3234                   ))
3235
3236                (;- This is a begin..end block
3237                 (match-end 2) ;; of verilog-end-block-ordered-re
3238                 (let ((str " // UNMATCHED !!")
3239                       (err 't)
3240                       (here (point))
3241                       there
3242                       cntx
3243                       )
3244                   (save-excursion
3245                     (verilog-leap-to-head)
3246                     (setq there (point))
3247                     (if (not (match-end 0))
3248                         (progn
3249                           (goto-char here)
3250                           (end-of-line)
3251                           (if kill-existing-comment
3252                               (kill-existing-comment))
3253                           (delete-horizontal-space)
3254                           (insert str)
3255                           (ding 't)
3256                           )
3257                       (let ((lim
3258                              (save-excursion (verilog-beg-of-defun) (point)))
3259                             (here (point))
3260                             )
3261                         (cond
3262                          (;-- handle named block differently
3263                           (looking-at verilog-named-block-re)
3264                           (search-forward ":")
3265                           (setq there (point))
3266                           (setq str (verilog-get-expr))
3267                           (setq err nil)
3268                           (setq str (concat " // block: " str )))
3269
3270                          ((verilog-in-case-region-p) ;-- handle case item differently
3271                           (goto-char here)
3272                           (setq str (verilog-backward-case-item lim))
3273                           (setq there (point))
3274                           (setq err nil)
3275                           (setq str (concat " // case: " str )))
3276
3277                          (;- try to find "reason" for this begin
3278                           (cond
3279                            (;
3280                             (eq here (progn
3281                                        (verilog-backward-token)
3282                                        (verilog-beg-of-statement-1)
3283                                        (point)))
3284                             (setq err nil)
3285                             (setq str ""))
3286                            ((looking-at verilog-endcomment-reason-re)
3287                             (setq there (match-end 0))
3288                             (setq cntx (concat
3289                                         (buffer-substring (match-beginning 0) (match-end 0)) " "))
3290                             (cond
3291                              (;- begin
3292                               (match-end 2)
3293                               (setq err nil)
3294                               (save-excursion
3295                                 (if (and (verilog-continued-line)
3296                                          (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
3297                                     (progn
3298                                       (goto-char (match-end 0))
3299                                       (setq there (point))
3300                                       (setq str
3301                                             (concat " // "
3302                                                     (buffer-substring (match-beginning 0) (match-end 0)) " "
3303                                                     (verilog-get-expr))))
3304                                   (setq str ""))))
3305
3306                              (;- else
3307                               (match-end 4)
3308                               (let ((nest 0)
3309                                     ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)")
3310                                     )
3311                                 (catch 'skip
3312                                   (while (verilog-re-search-backward reg nil 'move)
3313                                     (cond
3314                                      ((match-end 1) ; begin
3315                                       (setq nest (1- nest)))
3316                                      ((match-end 2)                       ; end
3317                                       (setq nest (1+ nest)))
3318                                      ((match-end 3)
3319                                       (if (= 0 nest)
3320                                           (progn
3321                                             (goto-char (match-end 0))
3322                                             (setq there (point))
3323                                             (setq err nil)
3324                                             (setq str (verilog-get-expr))
3325                                             (setq str (concat " // else: !if" str ))
3326                                             (throw 'skip 1))
3327                                         )))
3328                                     ))))
3329
3330                              (;- end else
3331                               (match-end 5)
3332                               (goto-char there)
3333                               (let ((nest 0)
3334                                     ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)")
3335                                     )
3336                                 (catch 'skip
3337                                   (while (verilog-re-search-backward reg nil 'move)
3338                                     (cond
3339                                      ((match-end 1) ; begin
3340                                       (setq nest (1- nest)))
3341                                      ((match-end 2)                       ; end
3342                                       (setq nest (1+ nest)))
3343                                      ((match-end 3)
3344                                       (if (= 0 nest)
3345                                           (progn
3346                                             (goto-char (match-end 0))
3347                                             (setq there (point))
3348                                             (setq err nil)
3349                                             (setq str (verilog-get-expr))
3350                                             (setq str (concat " // else: !if" str ))
3351                                             (throw 'skip 1))
3352                                         )))
3353                                     ))))
3354
3355                              (;- task/function/initial et cetera
3356                               t
3357                               (match-end 0)
3358                               (goto-char (match-end 0))
3359                               (setq there (point))
3360                               (setq err nil)
3361                               (setq str (verilog-get-expr))
3362                               (setq str (concat " // " cntx str )))
3363
3364                              (;-- otherwise...
3365                               (setq str " // auto-endcomment confused "))
3366                              ))
3367
3368                            ((and
3369                              (verilog-in-case-region-p) ;-- handle case item differently
3370                              (progn
3371                                (setq there (point))
3372                                (goto-char here)
3373                                (setq str (verilog-backward-case-item lim))))
3374                             (setq err nil)
3375                             (setq str (concat " // case: " str )))
3376
3377                            ((verilog-in-fork-region-p)
3378                             (setq err nil)
3379                             (setq str " // fork branch" ))
3380
3381                            ((looking-at "\\<end\\>")
3382                             ;; HERE
3383                             (forward-word 1)
3384                             (verilog-forward-syntactic-ws)
3385                             (setq err nil)
3386                             (setq str (verilog-get-expr))
3387                             (setq str (concat " // " cntx str )))
3388
3389                            ))))
3390                       (goto-char here)
3391                       (end-of-line)
3392                       (if kill-existing-comment
3393                           (kill-existing-comment))
3394                       (delete-horizontal-space)
3395                       (if (or err
3396                               (> (count-lines here there) verilog-minimum-comment-distance))
3397                           (insert str))
3398                       (if err (ding 't))
3399                       ))))
3400                (;- this is endclass, which can be nested
3401                 (match-end 11) ;; of verilog-end-block-ordered-re
3402                 ;;(goto-char there)
3403                 (let ((nest 0)
3404                       ( reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
3405                       string
3406                       )
3407                   (save-excursion
3408                     (catch 'skip
3409                       (while (verilog-re-search-backward reg nil 'move)
3410                         (cond
3411                          ((match-end 3) ; endclass
3412                           (ding 't)
3413                           (setq string "unmatched endclass")
3414                           (throw 'skip 1))
3415
3416                          ((match-end 2) ; endclass
3417                           (setq nest (1+ nest)))
3418
3419                          ((match-end 1) ; class
3420                           (setq nest (1- nest))
3421                           (if (< nest 0)
3422                               (progn
3423                                 (goto-char (match-end 0))
3424                                 (let (b e)
3425                                   (setq b (progn
3426                                             (skip-chars-forward "^ \t")
3427                                             (verilog-forward-ws&directives)
3428                                             (point))
3429                                         e (progn
3430                                             (skip-chars-forward "a-zA-Z0-9_")
3431                                             (point)))
3432                                   (setq string (buffer-substring b e)))
3433                                 (throw 'skip 1))))
3434                          ))))
3435                   (end-of-line)
3436                   (insert (concat " // " string )))
3437                 )
3438
3439                (;- this is end{function,generate,task,module,primitive,table,generate}
3440                 ;- which can not be nested.
3441                 t
3442                 (let (string reg (width nil))
3443                   (end-of-line)
3444                   (if kill-existing-comment
3445                       (save-match-data
3446                        (kill-existing-comment)))
3447                   (delete-horizontal-space)
3448                   (backward-sexp)
3449                   (cond
3450                    ((match-end 5) ;; of verilog-end-block-ordered-re
3451                     (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
3452                     (setq width "\\(\\s-*\\(\\[[^]]*\\]\\)\\|\\(real\\(time\\)?\\)\\|\\(integer\\)\\|\\(time\\)\\)?")
3453                     )
3454                    ((match-end 6) ;; of verilog-end-block-ordered-re
3455                     (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
3456                    ((match-end 7) ;; of verilog-end-block-ordered-re
3457                     (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
3458                    ((match-end 8) ;; of verilog-end-block-ordered-re
3459                     (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3460                    ((match-end 9) ;; of verilog-end-block-ordered-re
3461                     (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
3462                    ((match-end 10) ;; of verilog-end-block-ordered-re
3463                     (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3464                    ((match-end 11) ;; of verilog-end-block-ordered-re
3465                     (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3466                    ((match-end 12) ;; of verilog-end-block-ordered-re
3467                     (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3468                    ((match-end 13) ;; of verilog-end-block-ordered-re
3469                     (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3470                    ((match-end 14) ;; of verilog-end-block-ordered-re
3471                     (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3472                    )
3473                   (let (b e)
3474                     (save-excursion
3475                       (verilog-re-search-backward reg nil 'move)
3476                       (cond
3477                        ((match-end 1)
3478                         (setq b (progn
3479                                   (skip-chars-forward "^ \t")
3480                                   (verilog-forward-ws&directives)
3481                                   (if (and width (looking-at width))
3482                                       (progn
3483                                         (goto-char (match-end 0))
3484                                         (verilog-forward-ws&directives)
3485                                         ))
3486                                   (point))
3487                               e (progn
3488                                   (skip-chars-forward "a-zA-Z0-9_")
3489                                   (point)))
3490                         (setq string (buffer-substring b e)))
3491                        (t
3492                         (ding 't)
3493                         (setq string "unmatched end(function|task|module|primitive|interface|package|class)")))))
3494                   (end-of-line)
3495                   (insert (concat " // " string )))
3496                 ))))))))))
3497
3498 (defun verilog-get-expr()
3499   "Grab expression at point, e.g, case ( a | b & (c ^d))"
3500   (let* ((b (progn
3501               (verilog-forward-syntactic-ws)
3502               (skip-chars-forward " \t")
3503               (point)))
3504          (e (let ((par 1))
3505               (cond
3506                ((looking-at "@")
3507                 (forward-char 1)
3508                 (verilog-forward-syntactic-ws)
3509                 (if (looking-at "(")
3510                     (progn
3511                       (forward-char 1)
3512                       (while (and (/= par 0)
3513                                   (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3514                         (cond
3515                          ((match-end 1)
3516                           (setq par (1+ par)))
3517                          ((match-end 2)
3518                           (setq par (1- par)))))))
3519                 (point))
3520                ((looking-at "(")
3521                 (forward-char 1)
3522                 (while (and (/= par 0)
3523                             (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3524                   (cond
3525                    ((match-end 1)
3526                     (setq par (1+ par)))
3527                    ((match-end 2)
3528                     (setq par (1- par)))))
3529                 (point))
3530                ((looking-at "\\[")
3531                 (forward-char 1)
3532                 (while (and (/= par 0)
3533                             (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
3534                   (cond
3535                    ((match-end 1)
3536                     (setq par (1+ par)))
3537                    ((match-end 2)
3538                     (setq par (1- par)))))
3539                 (verilog-forward-syntactic-ws)
3540                 (skip-chars-forward "^ \t\n\f")
3541                 (point))
3542                ((looking-at "/[/\\*]")
3543                 b)
3544                ('t
3545                 (skip-chars-forward "^: \t\n\f")
3546                 (point)
3547                 ))))
3548          (str (buffer-substring b e)))
3549     (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3550         (setq str (concat (substring str 0 e) "...")))
3551     str))
3552
3553 (defun verilog-expand-vector ()
3554   "Take a signal vector on the current line and expand it to multiple lines.
3555 Useful for creating tri's and other expanded fields."
3556   (interactive)
3557   (verilog-expand-vector-internal "[" "]"))
3558
3559 (defun verilog-expand-vector-internal (bra ket)
3560   "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
3561   (save-excursion
3562     (forward-line 0)
3563     (let ((signal-string (buffer-substring (point)
3564                                            (progn
3565                                              (end-of-line) (point)))))
3566       (if (string-match (concat "\\(.*\\)"
3567                                 (regexp-quote bra)
3568                                 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
3569                                 (regexp-quote ket)
3570                                 "\\(.*\\)$") signal-string)
3571           (let* ((sig-head (match-string 1 signal-string))
3572                  (vec-start (string-to-int (match-string 2 signal-string)))
3573                  (vec-end (if (= (match-beginning 3) (match-end 3))
3574                               vec-start
3575                             (string-to-int (substring signal-string (1+ (match-beginning 3)) (match-end 3)))))
3576                  (vec-range (if (= (match-beginning 4) (match-end 4))
3577                                 1
3578                               (string-to-int (substring signal-string (+ 2 (match-beginning 4)) (match-end 4)))))
3579                  (sig-tail (match-string 5 signal-string))
3580                  vec)
3581             ;; Decode vectors
3582             (setq vec nil)
3583             (if (< vec-range 0)
3584                 (let ((tmp vec-start))
3585                   (setq vec-start vec-end
3586                         vec-end tmp
3587                         vec-range (- vec-range))))
3588             (if (< vec-end vec-start)
3589                 (while (<= vec-end vec-start)
3590                   (setq vec (append vec (list vec-start)))
3591                   (setq vec-start (- vec-start vec-range)))
3592               (while (<= vec-start vec-end)
3593                 (setq vec (append vec (list vec-start)))
3594                 (setq vec-start (+ vec-start vec-range))))
3595             ;;
3596             ;; Delete current line
3597             (delete-region (point) (progn (forward-line 0) (point)))
3598             ;;
3599             ;; Expand vector
3600             (while vec
3601               (insert (concat sig-head bra (int-to-string (car vec)) ket sig-tail "\n"))
3602               (setq vec (cdr vec)))
3603             (delete-char -1)
3604             ;;
3605             )))))
3606
3607 (defun verilog-strip-comments ()
3608   "Strip all comments from the verilog code."
3609   (interactive)
3610   (goto-char (point-min))
3611   (while (re-search-forward "//" nil t)
3612     (if (verilog-within-string)
3613         (re-search-forward "\"" nil t)
3614       (if (verilog-in-star-comment-p)
3615           (re-search-forward "\*/" nil t)
3616         (let ((bpt (- (point) 2)))
3617           (end-of-line)
3618           (delete-region bpt (point))))))
3619     ;;
3620   (goto-char (point-min))
3621   (while (re-search-forward "/\\*" nil t)
3622     (if (verilog-within-string)
3623         (re-search-forward "\"" nil t)
3624       (let ((bpt (- (point) 2)))
3625         (re-search-forward "\\*/")
3626         (delete-region bpt (point))))))
3627
3628 (defun verilog-one-line ()
3629   "Convert structural verilog instances to occupy one line."
3630   (interactive)
3631   (goto-char (point-min))
3632   (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
3633         (replace-match "\\1 " nil nil)))
3634
3635 (defun verilog-linter-name ()
3636   "Return name of linter, either surelint or verilint."
3637   (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
3638                                                        compile-command))
3639         (lint-word1    (verilog-string-replace-matches "\\s .*$" "" nil nil
3640                                                        verilog-linter)))
3641     (cond ((equal compile-word1 "surelint") `surelint)
3642           ((equal compile-word1 "verilint") `verilint)
3643           ((equal lint-word1 "surelint")    `surelint)
3644           ((equal lint-word1 "verilint")    `verilint)
3645           (t `surelint))))  ;; back compatibility
3646
3647 (defun verilog-lint-off ()
3648   "Convert a Verilog linter warning line into a disable statement.
3649 For example:
3650         pci_bfm_null.v, line  46: Unused input: pci_rst_
3651 becomes a comment for the appropriate tool.
3652
3653 The first word of the `compile-command' or `verilog-linter'
3654 variables are used to determine which product is being used.
3655
3656 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
3657   (interactive)
3658   (let ((linter (verilog-linter-name)))
3659     (cond ((equal linter `surelint)
3660            (verilog-surelint-off))
3661           ((equal linter `verilint)
3662            (verilog-verilint-off))
3663           (t (error "Linter name not set")))))
3664
3665 (defun verilog-surelint-off ()
3666   "Convert a SureLint warning line into a disable statement.
3667 Run from Verilog source window; assumes there is a *compile* buffer
3668 with point set appropriately.
3669
3670 For example:
3671         WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
3672 becomes:
3673         // surefire lint_line_off UDDONX"
3674   (interactive)
3675   (save-excursion
3676     (switch-to-buffer compilation-last-buffer)
3677     (beginning-of-line)
3678     (when
3679         (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
3680       (let* ((code (match-string 2))
3681              (file (match-string 3))
3682              (line (match-string 4))
3683              (buffer (get-file-buffer file))
3684              dir filename)
3685         (unless buffer
3686           (progn
3687             (setq buffer
3688                   (and (file-exists-p file)
3689                        (find-file-noselect file)))
3690             (or buffer
3691                 (let* ((pop-up-windows t))
3692                   (let ((name (expand-file-name
3693                                (read-file-name
3694                                 (format "Find this error in: (default %s) "
3695                                         file)
3696                                 dir file t))))
3697                     (if (file-directory-p name)
3698                         (setq name (expand-file-name filename name)))
3699                     (setq buffer
3700                           (and (file-exists-p name)
3701                                (find-file-noselect name))))))))
3702         (switch-to-buffer buffer)
3703         (goto-line (string-to-number line))
3704         (end-of-line)
3705         (catch 'already
3706           (cond
3707            ((verilog-in-slash-comment-p)
3708             (re-search-backward "//")
3709             (cond
3710              ((looking-at "// surefire lint_off_line ")
3711               (goto-char (match-end 0))
3712               (let ((lim (save-excursion (end-of-line) (point))))
3713                 (if (re-search-forward code lim 'move)
3714                     (throw 'already t)
3715                   (insert-string (concat " " code)))))
3716              (t
3717               )))
3718            ((verilog-in-star-comment-p)
3719             (re-search-backward "/\*")
3720             (insert-string (format " // surefire lint_off_line %6s" code ))
3721             )
3722            (t
3723             (insert-string (format " // surefire lint_off_line %6s" code ))
3724             )))))))
3725
3726 (defun verilog-verilint-off ()
3727   "Convert a Verilint warning line into a disable statement.
3728
3729 For example:
3730         (W240)  pci_bfm_null.v, line  46: Unused input: pci_rst_
3731 becomes:
3732         //Verilint 240 off // WARNING: Unused input"
3733   (interactive)
3734   (save-excursion
3735     (beginning-of-line)
3736     (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
3737       (replace-match (format
3738                       ;; %3s makes numbers 1-999 line up nicely
3739                       "\\1//Verilint %3s off // WARNING: \\3"
3740                       (match-string 2)))
3741       (beginning-of-line)
3742       (verilog-indent-line))))
3743
3744 (defun verilog-auto-save-compile ()
3745   "Update automatics with \\[verilog-auto], save the buffer, and compile."
3746   (interactive)
3747   (verilog-auto)        ; Always do it for safety
3748   (save-buffer)
3749   (compile compile-command))
3750
3751 \f
3752
3753 ;;
3754 ;; Batch
3755 ;;
3756
3757 (defmacro verilog-batch-error-wrapper (&rest body)
3758   "Execute BODY and add error prefix to any errors found.
3759 This lets programs calling batch mode to easily extract error messages."
3760   (` (condition-case err
3761          (progn (,@ body))
3762        (error
3763         (error "%%Error: %s%s" (error-message-string err)
3764                (if verilog-running-on-xemacs "\n" ""))))))  ;; xemacs forgets to add a newline
3765
3766 (defun verilog-batch-execute-func (funref)
3767   "Internal processing of a batch command, running FUNREF on all command arguments."
3768   (verilog-batch-error-wrapper
3769    ;; General globals needed
3770    (setq make-backup-files nil)
3771    (setq-default make-backup-files nil)
3772    (setq enable-local-variables t)
3773    (setq enable-local-eval t)
3774    ;; Make sure any sub-files we read get proper mode
3775    (setq default-major-mode `verilog-mode)
3776    ;; Ditto files already read in
3777    (mapcar '(lambda (buf)
3778               (when (buffer-file-name buf)
3779                 (save-excursion
3780                   (set-buffer buf)
3781                   (verilog-mode))))
3782            (buffer-list))
3783    ;; Process the files
3784    (mapcar '(lambda (buf)
3785               (when (buffer-file-name buf)
3786                 (save-excursion
3787                   (if (not (file-exists-p (buffer-file-name buf)))
3788                       (error (concat "File not found: " (buffer-file-name buf))))
3789                   (message (concat "Processing " (buffer-file-name buf)))
3790                   (set-buffer buf)
3791                   (funcall funref)
3792                   (save-buffer))))
3793            (buffer-list))))
3794
3795 (defun verilog-batch-auto ()
3796   "For use with --batch, perform automatic expansions as a stand-alone tool.
3797 This sets up the appropriate Verilog-Mode environment, updates automatics
3798 with \\[verilog-auto] on all command-line files, and saves the buffers.
3799 For proper results, multiple filenames need to be passed on the command
3800 line in bottom-up order."
3801   (unless noninteractive
3802     (error "Use verilog-batch-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
3803   (verilog-batch-execute-func `verilog-auto))
3804
3805 (defun verilog-batch-delete-auto ()
3806   "For use with --batch, perform automatic deletion as a stand-alone tool.
3807 This sets up the appropriate Verilog-Mode environment, deletes automatics
3808 with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
3809   (unless noninteractive
3810     (error "Use verilog-batch-delete-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
3811   (verilog-batch-execute-func `verilog-delete-auto))
3812
3813 (defun verilog-batch-inject-auto ()
3814   "For use with --batch, perform automatic injection as a stand-alone tool.
3815 This sets up the appropriate Verilog-Mode environment, injects new automatics
3816 with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
3817 For proper results, multiple filenames need to be passed on the command
3818 line in bottom-up order."
3819   (unless noninteractive
3820     (error "Use verilog-batch-inject-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
3821   (verilog-batch-execute-func `verilog-inject-auto))
3822
3823 (defun verilog-batch-indent ()
3824   "For use with --batch, reindent an a entire file as a stand-alone tool.
3825 This sets up the appropriate Verilog-Mode environment, calls
3826 \\[verilog-indent-buffer] on all command-line files, and saves the buffers."
3827   (unless noninteractive
3828     (error "Use verilog-batch-indent only with --batch"))  ;; Otherwise we'd mess up buffer modes
3829   (verilog-batch-execute-func `verilog-indent-buffer))
3830 \f
3831
3832 ;;
3833 ;; Indentation
3834 ;;
3835 (defconst verilog-indent-alist
3836   '((block       . (+ ind verilog-indent-level))
3837     (case        . (+ ind verilog-case-indent))
3838     (cparenexp   . (+ ind verilog-indent-level))
3839     (cexp        . (+ ind verilog-cexp-indent))
3840     (defun       . verilog-indent-level-module)
3841     (declaration . verilog-indent-level-declaration)
3842     (directive   . (verilog-calculate-indent-directive))
3843     (tf          . verilog-indent-level)
3844     (behavioral  . (+ verilog-indent-level-behavioral verilog-indent-level-module))
3845     (statement   . ind)
3846     (cpp         . 0)
3847     (comment     . (verilog-comment-indent))
3848     (unknown     . 3)
3849     (string      . 0)))
3850
3851 (defun verilog-continued-line-1 (lim)
3852   "Return true if this is a continued line.
3853 Set point to where line starts.  Limit search to point LIM."
3854   (let ((continued 't))
3855     (if (eq 0 (forward-line -1))
3856         (progn
3857           (end-of-line)
3858           (verilog-backward-ws&directives lim)
3859           (if (bobp)
3860               (setq continued nil)
3861             (setq continued (verilog-backward-token))))
3862       (setq continued nil))
3863     continued))
3864
3865 (defun verilog-calculate-indent ()
3866   "Calculate the indent of the current Verilog line.
3867 Examine previous lines.  Once a line is found that is definitive as to the
3868 type of the current line, return that lines' indent level and its
3869 type.  Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
3870   (save-excursion
3871     (let* ((starting_position (point))
3872            (par 0)
3873            (begin (looking-at "[ \t]*begin\\>"))
3874            (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
3875            (type (catch 'nesting
3876                    ;; Keep working backwards until we can figure out
3877                    ;; what type of statement this is.
3878                    ;; Basically we need to figure out
3879                    ;; 1) if this is a continuation of the previous line;
3880                    ;; 2) are we in a block scope (begin..end)
3881
3882                    ;; if we are in a comment, done.
3883                    (if (verilog-in-star-comment-p)
3884                        (throw 'nesting 'comment))
3885
3886                    ;; if we have a directive, done.
3887                    (if (save-excursion (beginning-of-line) (looking-at verilog-directive-re-1))
3888                        (throw 'nesting 'directive))
3889
3890                    ;; if we are in a parenthesized list, and the user likes to indent these, return.
3891                    (if (verilog-in-paren)
3892                        (if verilog-indent-lists
3893                            (progn (setq par 1)
3894                                   (throw 'nesting 'block))
3895                          ()
3896                           )
3897                      )
3898
3899                    ;; See if we are continuing a previous line
3900                    (while t
3901                      ;; trap out if we crawl off the top of the buffer
3902                      (if (bobp) (throw 'nesting 'cpp))
3903
3904                      (if (verilog-continued-line-1 lim)
3905                          (let ((sp (point)))
3906                            (if (and
3907                                 (not (looking-at verilog-complete-reg))
3908                                 (verilog-continued-line-1 lim))
3909                                (progn (goto-char sp)
3910                                       (throw 'nesting 'cexp))
3911
3912                              (goto-char sp))
3913
3914                            (if (and begin
3915                                     (not verilog-indent-begin-after-if)
3916                                     (looking-at verilog-no-indent-begin-re))
3917                                (progn
3918                                  (beginning-of-line)
3919                                  (skip-chars-forward " \t")
3920                                  (throw 'nesting 'statement))
3921                              (progn
3922                                (throw 'nesting 'cexp))))
3923                        ;; not a continued line
3924                        (goto-char starting_position))
3925
3926                      (if (looking-at "\\<else\\>")
3927                          ;; search back for governing if, striding across begin..end pairs
3928                          ;; appropriately
3929                          (let ((elsec 1))
3930                            (while (verilog-re-search-backward verilog-ends-re nil 'move)
3931                              (cond
3932                               ((match-end 1) ; else, we're in deep
3933                                (setq elsec (1+ elsec)))
3934                               ((match-end 2) ; if
3935                                (setq elsec (1- elsec))
3936                                (if (= 0 elsec)
3937                                    (if verilog-align-ifelse
3938                                        (throw 'nesting 'statement)
3939                                      (progn ;; back up to first word on this line
3940                                        (beginning-of-line)
3941                                        (verilog-forward-syntactic-ws)
3942                                        (throw 'nesting 'statement)))))
3943                               (t ; endblock
3944                                 ; try to leap back to matching outward block by striding across
3945                                 ; indent level changing tokens then immediately
3946                                 ; previous line governs indentation.
3947                                (let (( reg) (nest 1))
3948 ;;       verilog-ends =>  else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
3949                                  (cond
3950                                   ((match-end 3) ; end
3951                                    ;; Search back for matching begin
3952                                    (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
3953                                   ((match-end 4) ; endcase
3954                                    ;; Search back for matching case
3955                                    (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
3956                                   ((match-end 5) ; endfunction
3957                                    ;; Search back for matching function
3958                                    (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
3959                                   ((match-end 6) ; endtask
3960                                    ;; Search back for matching task
3961                                    (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
3962                                   ((match-end 7) ; endspecify
3963                                    ;; Search back for matching specify
3964                                    (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
3965                                   ((match-end 8) ; endtable
3966                                    ;; Search back for matching table
3967                                    (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
3968                                   ((match-end 9) ; endgenerate
3969                                    ;; Search back for matching generate
3970                                    (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
3971                                   ((match-end 10) ; joins
3972                                    ;; Search back for matching fork
3973                                    (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
3974                                   ((match-end 11) ; class
3975                                    ;; Search back for matching class
3976                                    (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
3977                                   ((match-end 12) ; covergroup
3978                                    ;; Search back for matching covergroup
3979                                    (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
3980                                   )
3981                                  (catch 'skip
3982                                    (while (verilog-re-search-backward reg nil 'move)
3983                                      (cond
3984                                       ((match-end 1) ; begin
3985                                        (setq nest (1- nest))
3986                                        (if (= 0 nest)
3987                                            (throw 'skip 1)))
3988                                       ((match-end 2) ; end
3989                                        (setq nest (1+ nest)))))
3990                                    )
3991                                  ))
3992                               ))))
3993                      (throw 'nesting (verilog-calc-1))
3994                      )
3995                    );; catch nesting
3996                  );; type
3997            )
3998       ;; Return type of block and indent level.
3999       (if (not type)
4000           (setq type 'cpp))
4001       (if (> par 0)                     ; Unclosed Parenthesis
4002           (list 'cparenexp par)
4003         (cond
4004           ((eq type 'case)
4005            (list type (verilog-case-indent-level)))
4006           ((eq type 'statement)
4007            (list type (current-column)))
4008           ((eq type 'defun)
4009            (list type 0))
4010           (t
4011            (list type (verilog-current-indent-level)))))
4012       )))
4013 (defun verilog-wai ()
4014   "Show matching nesting block for debugging."
4015   (interactive)
4016   (save-excursion
4017     (let ((nesting (verilog-calc-1)))
4018       (message "You are at nesting %s" nesting))))
4019
4020 (defun verilog-calc-1 ()
4021   (catch 'nesting
4022     (while (verilog-re-search-backward verilog-indent-re nil 'move)
4023       (cond
4024        ((looking-at verilog-beg-block-re-ordered)
4025         (cond
4026          ((match-end 2)  (throw 'nesting 'case))
4027          ;; need to conside typedef struct here...
4028          ((looking-at "\\<class\\|struct\\|function\\|task\\|property\\>")
4029                                         ; *sigh* These words have an optional prefix:
4030                                         ; extern {virtual|protected}? function a();
4031                                         ; assert property (p_1);
4032                                         ; typedef class foo;
4033                                         ; and we don't want to confuse this with
4034                                         ; function a();
4035                                         ; property
4036                                         ; ...
4037                                         ; endfunction
4038           (let ((here (point)))
4039             (save-excursion
4040               (verilog-beg-of-statement)
4041               (if (= (point) here)
4042                   (throw 'nesting 'block))
4043               )))
4044          (t              (throw 'nesting 'block))))
4045
4046        ((looking-at verilog-end-block-re)
4047         (verilog-leap-to-head)
4048         (if (verilog-in-case-region-p)
4049             (progn
4050               (verilog-leap-to-case-head)
4051               (if (looking-at verilog-case-re)
4052                   (throw 'nesting 'case)))))
4053
4054        ((looking-at (if (verilog-in-generate-region-p)
4055                         verilog-defun-level-not-generate-re
4056                       verilog-defun-level-re))
4057         (throw 'nesting 'defun))
4058
4059        ((looking-at verilog-cpp-level-re)
4060         (throw 'nesting 'cpp))
4061
4062        ((bobp)
4063         (throw 'nesting 'cpp))
4064        ))))
4065
4066 (defun verilog-calculate-indent-directive ()
4067   "Return indentation level for directive.
4068 For speed, the searcher looks at the last directive, not the indent
4069 of the appropriate enclosing block."
4070   (let ((base -1)       ;; Indent of the line that determines our indentation
4071         (ind 0)         ;; Relative offset caused by other directives (like `endif on same line as `else)
4072         )
4073     ;; Start at current location, scan back for another directive
4074
4075     (save-excursion
4076       (beginning-of-line)
4077       (while (and (< base 0)
4078                   (verilog-re-search-backward verilog-directive-re nil t))
4079         (cond ((save-excursion (skip-chars-backward " \t") (bolp))
4080                (setq base (current-indentation))
4081                ))
4082         (cond ((and (looking-at verilog-directive-end) (< base 0))  ;; Only matters when not at BOL
4083                (setq ind (- ind verilog-indent-level-directive)))
4084               ((and (looking-at verilog-directive-middle) (>= base 0))  ;; Only matters when at BOL
4085                (setq ind (+ ind verilog-indent-level-directive)))
4086               ((looking-at verilog-directive-begin)
4087                (setq ind (+ ind verilog-indent-level-directive)))))
4088       ;; Adjust indent to starting indent of critical line
4089       (setq ind (max 0 (+ ind base))))
4090
4091     (save-excursion
4092       (beginning-of-line)
4093       (skip-chars-forward " \t")
4094       (cond ((or (looking-at verilog-directive-middle)
4095                  (looking-at verilog-directive-end))
4096              (setq ind (max 0 (- ind verilog-indent-level-directive))))))
4097    ind))
4098
4099 (defun verilog-leap-to-case-head ()
4100   (let ((nest 1))
4101     (while (/= 0 nest)
4102       (verilog-re-search-backward "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" nil 'move)
4103       (cond
4104        ((match-end 1)
4105         (setq nest (1- nest)))
4106        ((match-end 2)
4107         (setq nest (1+ nest)))
4108        ((bobp)
4109         (ding 't)
4110         (setq nest 0))))))
4111
4112 (defun verilog-leap-to-head ()
4113   "Move point to the head of this block; jump from end to matching begin,
4114 from endcase to matching case, and so on."
4115   (let ((reg nil)
4116         snest
4117         (nest 1))
4118     (cond
4119      ((looking-at "\\<end\\>")
4120       ;; 1: Search back for matching begin
4121       (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
4122                         "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
4123      ((looking-at "\\<endcase\\>")
4124       ;; 2: Search back for matching case
4125       (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)" ))
4126      ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
4127       ;; 3: Search back for matching fork
4128       (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4129      ((looking-at "\\<endclass\\>")
4130       ;; 4: Search back for matching class
4131       (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4132      ((looking-at "\\<endtable\\>")
4133       ;; 5: Search back for matching table
4134       (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4135      ((looking-at "\\<endspecify\\>")
4136       ;; 6: Search back for matching specify
4137       (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4138      ((looking-at "\\<endfunction\\>")
4139       ;; 7: Search back for matching function
4140       (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4141      ((looking-at "\\<endgenerate\\>")
4142       ;; 8: Search back for matching generate
4143       (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4144      ((looking-at "\\<endtask\\>")
4145       ;; 9: Search back for matching task
4146       (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
4147      ((looking-at "\\<endgroup\\>")
4148       ;; 10: Search back for matching covergroup
4149       (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
4150      ((looking-at "\\<endproperty\\>")
4151       ;; 11: Search back for matching property
4152       (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
4153      ((looking-at "\\<endinterface\\>")
4154       ;; 12: Search back for matching interface
4155       (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
4156      ((looking-at "\\<endsequence\\>")
4157       ;; 12: Search back for matching interface
4158       (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
4159      )
4160     (if reg
4161         (catch 'skip
4162           (let (sreg)
4163             (while (verilog-re-search-backward reg nil 'move)
4164               (cond
4165                ((match-end 1) ; begin
4166                 (setq nest (1- nest))
4167                 (if (= 0 nest)
4168                     ;; Now previous line describes syntax
4169                     (throw 'skip 1))
4170                 (if (and snest
4171                          (= snest nest))
4172                     (setq reg sreg)))
4173                ((match-end 2) ; end
4174                 (setq nest (1+ nest)))
4175                ((match-end 3)
4176                 ;; endcase, jump to case
4177                 (setq snest nest)
4178                 (setq nest (1+ nest))
4179                 (setq sreg reg)
4180                 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4181                ((match-end 4)
4182                 ;; join, jump to fork
4183                 (setq snest nest)
4184                 (setq nest (1+ nest))
4185                 (setq sreg reg)
4186                 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4187                )))))))
4188
4189 (defun verilog-continued-line ()
4190   "Return true if this is a continued line.
4191 Set point to where line starts"
4192   (let ((continued 't))
4193     (if (eq 0 (forward-line -1))
4194         (progn
4195           (end-of-line)
4196           (verilog-backward-ws&directives)
4197           (if (bobp)
4198               (setq continued nil)
4199             (while (and continued
4200                         (save-excursion
4201                           (skip-chars-backward " \t")
4202                           (not (bolp))))
4203             (setq continued (verilog-backward-token))
4204             ) ;; while
4205             ))
4206       (setq continued nil))
4207     continued))
4208
4209 (defun verilog-backward-token ()
4210   "Step backward token, returning true if we are now at an end of line token."
4211   (verilog-backward-syntactic-ws)
4212   (cond
4213    ((bolp)
4214     nil)
4215    (;-- Anything ending in a ; is complete
4216     (= (preceding-char) ?\;)
4217     nil)
4218    (;-- constraint foo { a = b }
4219     ;   is a complete statement. *sigh*
4220     (= (preceding-char) ?\})
4221     (progn
4222       (backward-char)
4223       (backward-up-list 1)
4224       (verilog-backward-syntactic-ws)
4225       (forward-word -1) ; label for the (possible) constraint
4226       (verilog-backward-syntactic-ws)
4227       (forward-word -1)
4228       (not (looking-at "\\<constraint\\>")))
4229     )
4230    (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
4231     ;   also could be simply '@(foo)'
4232     ;   or foo u1 #(a=8)
4233     ;            (b, ... which ISN'T complete
4234     ;;;; Do we need this???
4235     (= (preceding-char) ?\))
4236     (progn
4237       (backward-char)
4238       (backward-up-list 1)
4239       (verilog-backward-syntactic-ws)
4240       (let ((back (point)))
4241         (forward-word -1)
4242         (cond
4243          ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
4244           (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
4245          (t
4246           (goto-char back)
4247           (cond
4248            ((= (preceding-char) ?\@)
4249             (backward-char)
4250             (save-excursion
4251               (verilog-backward-token)
4252               (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
4253            ((= (preceding-char) ?\#)
4254             t)
4255            (t t))
4256           )))))
4257
4258    (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
4259     t
4260     (forward-word -1)
4261     (cond
4262      ((looking-at "\\(else\\)\\|\\(initial\\>\\)\\|\\(always\\(_latch\\|_ff\\|_comb\\)?\\>\\)")
4263       t)
4264      ((looking-at verilog-indent-re)
4265       nil)
4266      (t
4267       (let
4268           ((back (point)))
4269         (verilog-backward-syntactic-ws)
4270         (cond
4271          ((= (preceding-char) ?\:)
4272           (backward-char)
4273           (verilog-backward-syntactic-ws)
4274           (backward-sexp)
4275           (if (looking-at verilog-nameable-item-re )
4276               nil
4277             t)
4278           )
4279          ((= (preceding-char) ?\#)
4280           (backward-char)
4281           t)
4282          ((= (preceding-char) ?\`)
4283           (backward-char)
4284           t)
4285
4286          (t
4287           (goto-char back)
4288           t)
4289          )))))))
4290
4291 (defun verilog-backward-syntactic-ws (&optional bound)
4292   "Backward skip over syntactic whitespace for Emacs 19.
4293 Optional BOUND limits search."
4294   (save-restriction
4295     (let* ((bound (or bound (point-min))) (here bound) )
4296       (if (< bound (point))
4297           (progn
4298             (narrow-to-region bound (point))
4299             (while (/= here (point))
4300               (setq here (point))
4301               (verilog-skip-backward-comments)
4302               )))
4303       ))
4304   t)
4305
4306 (defun verilog-forward-syntactic-ws (&optional bound)
4307   "Forward skip over syntactic whitespace for Emacs 19.
4308 Optional BOUND limits search."
4309   (save-restriction
4310     (let* ((bound (or bound (point-max)))
4311            (here bound)
4312            )
4313       (if (> bound (point))
4314           (progn
4315             (narrow-to-region (point) bound)
4316             (while (/= here (point))
4317               (setq here (point))
4318               (forward-comment (buffer-size))
4319               )))
4320       )))
4321
4322 (defun verilog-backward-ws&directives (&optional bound)
4323   "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
4324 Optional BOUND limits search."
4325   (save-restriction
4326     (let* ((bound (or bound (point-min)))
4327            (here bound)
4328            (p nil) )
4329       (if (< bound (point))
4330           (progn
4331             (let ((state
4332                    (save-excursion
4333                      (parse-partial-sexp (point-min) (point)))))
4334               (cond
4335                ((nth 7 state) ;; in // comment
4336                 (verilog-re-search-backward "//" nil 'move)
4337                 (skip-chars-backward "/"))
4338                ((nth 4 state) ;; in /* */ comment
4339                 (verilog-re-search-backward "/\*" nil 'move))))
4340             (narrow-to-region bound (point))
4341             (while (/= here (point))
4342               (setq here (point))
4343               (verilog-skip-backward-comments)
4344               (setq p
4345                     (save-excursion
4346                       (beginning-of-line)
4347                       (cond
4348                        ((verilog-within-translate-off)
4349                         (verilog-back-to-start-translate-off (point-min)))
4350                        ((looking-at verilog-directive-re-1)
4351                         (point))
4352                        (t
4353                         nil))))
4354               (if p (goto-char p))
4355               )))
4356       )))
4357
4358 (defun verilog-forward-ws&directives (&optional bound)
4359   "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
4360 Optional BOUND limits search."
4361   (save-restriction
4362     (let* ((bound (or bound (point-max)))
4363            (here bound)
4364            jump
4365            )
4366       (if (> bound (point))
4367           (progn
4368             (let ((state
4369                    (save-excursion
4370                      (parse-partial-sexp (point-min) (point)))))
4371               (cond
4372                ((nth 7 state) ;; in // comment
4373                 (verilog-re-search-forward "//" nil 'move))
4374                ((nth 4 state) ;; in /* */ comment
4375                 (verilog-re-search-forward "/\*" nil 'move))))
4376             (narrow-to-region (point) bound)
4377             (while (/= here (point))
4378               (setq here (point)
4379                     jump nil)
4380               (forward-comment (buffer-size))
4381               (save-excursion
4382                 (beginning-of-line)
4383                 (if (looking-at verilog-directive-re-1)
4384                     (setq jump t)))
4385               (if jump
4386                   (beginning-of-line 2))
4387               )))
4388       )))
4389
4390 (defun verilog-in-comment-p ()
4391  "Return true if in a star or // comment."
4392  (let ((state
4393         (save-excursion
4394           (parse-partial-sexp (point-min) (point)))))
4395    (or (nth 4 state) (nth 7 state))))
4396
4397 (defun verilog-in-star-comment-p ()
4398  "Return true if in a star comment."
4399  (let ((state
4400         (save-excursion
4401           (parse-partial-sexp (point-min) (point)))))
4402    (and
4403     (nth 4 state)                       ; t if in a comment of style a // or b /**/
4404         (not
4405          (nth 7 state)                  ; t if in a comment of style b /**/
4406          ))))
4407
4408 (defun verilog-in-slash-comment-p ()
4409  "Return true if in a slash comment."
4410  (let ((state
4411         (save-excursion
4412           (parse-partial-sexp (point-min) (point)))))
4413    (nth 7 state)))
4414
4415 (defun verilog-in-comment-or-string-p ()
4416  "Return true if in a string or comment."
4417  (let ((state
4418         (save-excursion
4419           (parse-partial-sexp (point-min) (point)))))
4420    (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
4421
4422 (defun verilog-in-escaped-name-p ()
4423  "Return true if in an escaped name."
4424  (save-excursion
4425    (backward-char)
4426    (skip-chars-backward "^ \t\n\f")
4427    (if (= (char-after (point) ) ?\\ )
4428        t
4429      nil)))
4430
4431 (defun verilog-in-paren ()
4432  "Return true if in a parenthetical expression."
4433  (let ((state
4434         (save-excursion
4435           (parse-partial-sexp (point-min) (point)))))
4436    (/= 0 (nth 0 state))))
4437
4438 (defun verilog-parenthesis-depth ()
4439  "Return non zero if in parenthetical-expression."
4440  (save-excursion
4441    (nth 1 (parse-partial-sexp (point-min) (point)))))
4442
4443
4444 (defun verilog-skip-forward-comment-or-string ()
4445  "Return true if in a string or comment."
4446  (let ((state
4447         (save-excursion
4448           (parse-partial-sexp (point-min) (point)))))
4449    (cond
4450     ((nth 3 state)                      ;Inside string
4451      (goto-char (nth 3 state))
4452      t)
4453     ((nth 7 state)                      ;Inside // comment
4454      (forward-line 1)
4455      t)
4456     ((nth 4 state)                      ;Inside any comment (hence /**/)
4457      (search-forward "*/"))
4458     (t
4459      nil))))
4460
4461 (defun verilog-skip-backward-comment-or-string ()
4462  "Return true if in a string or comment."
4463  (let ((state
4464         (save-excursion
4465           (parse-partial-sexp (point-min) (point)))))
4466    (cond
4467     ((nth 3 state)                      ;Inside string
4468      (search-backward "\"")
4469      t)
4470     ((nth 7 state)                      ;Inside // comment
4471      (search-backward "//")
4472      (skip-chars-backward "/")
4473      t)
4474     ((nth 4 state)                      ;Inside /* */ comment
4475      (search-backward "/*")
4476      t)
4477     (t
4478      nil))))
4479
4480 (defun verilog-skip-backward-comments ()
4481  "Return true if a comment was skipped."
4482  (let ((more t))
4483    (while more
4484      (setq more
4485            (let ((state
4486                   (save-excursion
4487                     (parse-partial-sexp (point-min) (point)))))
4488              (cond
4489               ((nth 7 state)                    ;Inside // comment
4490                (search-backward "//")
4491                (skip-chars-backward "/")
4492                (skip-chars-backward " \t\n\f")
4493                t)
4494               ((nth 4 state)                    ;Inside /* */ comment
4495                (search-backward "/*")
4496                (skip-chars-backward " \t\n\f")
4497                t)
4498               ((and (not (bobp))
4499                     (= (char-before) ?\/)
4500                     (= (char-before (1- (point))) ?\*)
4501                     )
4502                (goto-char (- (point) 2))
4503                t)
4504               (t
4505                (skip-chars-backward " \t\n\f")
4506                nil)))))))
4507
4508 (defun verilog-skip-forward-comment-p ()
4509   "If in comment, move to end and return true."
4510   (let (state)
4511     (progn
4512       (setq state
4513             (save-excursion
4514               (parse-partial-sexp (point-min) (point))))
4515       (cond
4516        ((nth 3 state)
4517         t)
4518        ((nth 7 state)                   ;Inside // comment
4519         (end-of-line)
4520         (forward-char 1)
4521         t)
4522        ((nth 4 state)                   ;Inside any comment
4523         t)
4524        (t
4525         nil)))))
4526
4527 (defun verilog-indent-line-relative ()
4528   "Cheap version of indent line.
4529 Only look at a few lines to determine indent level."
4530   (interactive)
4531   (let ((indent-str)
4532         (sp (point)))
4533     (if (looking-at "^[ \t]*$")
4534         (cond  ;- A blank line; No need to be too smart.
4535          ((bobp)
4536           (setq indent-str (list 'cpp 0)))
4537          ((verilog-continued-line)
4538           (let ((sp1 (point)))
4539             (if (verilog-continued-line)
4540                 (progn (goto-char sp)
4541                        (setq indent-str (list 'statement (verilog-current-indent-level))))
4542               (goto-char sp1)
4543               (setq indent-str (list 'block (verilog-current-indent-level)))))
4544           (goto-char sp))
4545          ((goto-char sp)
4546           (setq indent-str (verilog-calculate-indent))))
4547       (progn (skip-chars-forward " \t")
4548              (setq indent-str (verilog-calculate-indent))))
4549     (verilog-do-indent indent-str)))
4550
4551 (defun verilog-indent-line ()
4552   "Indent for special part of code."
4553   (verilog-do-indent (verilog-calculate-indent)))
4554
4555 (defun verilog-do-indent (indent-str)
4556   (let ((type (car indent-str))
4557         (ind (car (cdr indent-str))))
4558     (cond
4559      (; handle continued exp
4560       (eq type 'cexp)
4561       (let ((here (point)))
4562         (verilog-backward-syntactic-ws)
4563         (cond
4564          ((or
4565            (= (preceding-char) ?\,)
4566            (= (preceding-char) ?\])
4567            (save-excursion
4568              (verilog-beg-of-statement-1)
4569              (looking-at verilog-declaration-re)))
4570           (let* ( fst
4571                   (val
4572                    (save-excursion
4573                      (backward-char 1)
4574                      (verilog-beg-of-statement-1)
4575                      (setq fst (point))
4576                      (if (looking-at verilog-declaration-re)
4577                          (progn ;; we have multiple words
4578                            (goto-char (match-end 0))
4579                            (skip-chars-forward " \t")
4580                            (cond
4581                             ((and verilog-indent-declaration-macros
4582                                   (= (following-char) ?\`))
4583                              (progn
4584                                (forward-char 1)
4585                                (forward-word 1)
4586                                (skip-chars-forward " \t")))
4587                             ((= (following-char) ?\[)
4588                              (progn
4589                                (forward-char 1)
4590                                (backward-up-list -1)
4591                                (skip-chars-forward " \t")))
4592                             )
4593                            (current-column))
4594                        (progn
4595                          (goto-char fst)
4596                          (+ (current-column) verilog-cexp-indent))
4597                        ))))
4598             (goto-char here)
4599             (indent-line-to val))
4600           )
4601          ((= (preceding-char) ?\) )
4602           (goto-char here)
4603           (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4604             (indent-line-to val)))
4605          (t
4606           (goto-char here)
4607           (let ((val))
4608             (verilog-beg-of-statement-1)
4609             (if (and (< (point) here)
4610                      (verilog-re-search-forward "=[ \\t]*" here 'move))
4611                 (setq val (current-column))
4612               (setq val (eval (cdr (assoc type verilog-indent-alist)))))
4613             (goto-char here)
4614             (indent-line-to val)))
4615          )))
4616
4617      (; handle inside parenthetical expressions
4618       (eq type 'cparenexp)
4619       (let ((val (save-excursion
4620                    (backward-up-list 1)
4621                    (forward-char 1)
4622                    (skip-chars-forward " \t")
4623                    (current-column))))
4624         (indent-line-to val)
4625         (if (and (not (verilog-in-struct-region-p))
4626                  (looking-at verilog-declaration-re))
4627             (verilog-indent-declaration ind))
4628         ))
4629
4630      (;-- Handle the ends
4631       (looking-at verilog-end-block-re )
4632       (let ((val (if (eq type 'statement)
4633                      (- ind verilog-indent-level)
4634                    ind)))
4635         (indent-line-to val)))
4636
4637      (;-- Case -- maybe line 'em up
4638       (and (eq type 'case) (not (looking-at "^[ \t]*$")))
4639       (progn
4640         (cond
4641          ((looking-at "\\<endcase\\>")
4642           (indent-line-to ind))
4643          (t
4644           (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4645             (indent-line-to val))))))
4646
4647      (;-- defun
4648       (and (eq type 'defun)
4649            (looking-at verilog-zero-indent-re))
4650       (indent-line-to 0))
4651
4652      (;-- declaration
4653       (and (or
4654             (eq type 'defun)
4655             (eq type 'block))
4656            (looking-at verilog-declaration-re))
4657       (verilog-indent-declaration ind))
4658
4659      (;-- Everything else
4660       t
4661       (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4662         (indent-line-to val)))
4663      )
4664     (if (looking-at "[ \t]+$")
4665         (skip-chars-forward " \t"))
4666     indent-str                          ; Return indent data
4667     ))
4668
4669 (defun verilog-current-indent-level ()
4670   "Return the indent-level the current statement has."
4671   (save-excursion
4672     (let (par-pos)
4673       (beginning-of-line)
4674       (setq par-pos (verilog-parenthesis-depth))
4675       (while par-pos
4676         (goto-char par-pos)
4677         (beginning-of-line)
4678         (setq par-pos (verilog-parenthesis-depth)))
4679       (skip-chars-forward " \t")
4680       (current-column))))
4681
4682 (defun verilog-case-indent-level ()
4683   "Return the indent-level the current statement has.
4684 Do not count named blocks or case-statements."
4685   (save-excursion
4686     (skip-chars-forward " \t")
4687     (cond
4688      ((looking-at verilog-named-block-re)
4689       (current-column))
4690      ((and (not (looking-at verilog-case-re))
4691            (looking-at "^[^:;]+[ \t]*:"))
4692       (verilog-re-search-forward ":" nil t)
4693       (skip-chars-forward " \t")
4694       (current-column))
4695      (t
4696       (current-column)))))
4697
4698 (defun verilog-indent-comment ()
4699   "Indent current line as comment."
4700   (let* ((stcol
4701           (cond
4702            ((verilog-in-star-comment-p)
4703             (save-excursion
4704               (re-search-backward "/\\*" nil t)
4705               (1+(current-column))))
4706            (comment-column
4707              comment-column )
4708            (t
4709             (save-excursion
4710               (re-search-backward "//" nil t)
4711               (current-column)))
4712            )))
4713     (indent-line-to stcol)
4714     stcol))
4715
4716 (defun verilog-more-comment ()
4717   "Make more comment lines like the previous."
4718   (let* ((star 0)
4719          (stcol
4720           (cond
4721            ((verilog-in-star-comment-p)
4722             (save-excursion
4723               (setq star 1)
4724               (re-search-backward "/\\*" nil t)
4725               (1+(current-column))))
4726            (comment-column
4727             comment-column )
4728            (t
4729             (save-excursion
4730               (re-search-backward "//" nil t)
4731               (current-column)))
4732            )))
4733     (progn
4734       (indent-to stcol)
4735       (if (and star
4736                (save-excursion
4737                  (forward-line -1)
4738                  (skip-chars-forward " \t")
4739                  (looking-at "\*")))
4740           (insert "* ")))))
4741
4742 (defun verilog-comment-indent (&optional arg)
4743   "Return the column number the line should be indented to.
4744 ARG is ignored, for `comment-indent-function' compatibility."
4745   (cond
4746    ((verilog-in-star-comment-p)
4747     (save-excursion
4748       (re-search-backward "/\\*" nil t)
4749       (1+(current-column))))
4750    ( comment-column
4751      comment-column )
4752    (t
4753     (save-excursion
4754       (re-search-backward "//" nil t)
4755       (current-column)))))
4756
4757 ;;
4758
4759 (defun verilog-pretty-declarations ()
4760   "Line up declarations around point."
4761   (interactive)
4762   (save-excursion
4763     (if (progn
4764           (verilog-beg-of-statement-1)
4765           (looking-at verilog-declaration-re))
4766         (let* ((m1 (make-marker))
4767                (e) (r)
4768                (here (point))
4769                (start
4770                 (progn
4771                   (verilog-beg-of-statement-1)
4772                   (while (looking-at verilog-declaration-re)
4773                     (beginning-of-line)
4774                     (setq e (point))
4775                     (verilog-backward-syntactic-ws)
4776                     (backward-char)
4777                     (verilog-beg-of-statement-1)) ;Ack, need to grok `define
4778                   e))
4779                (end
4780                 (progn
4781                   (goto-char here)
4782                   (verilog-end-of-statement)
4783                   (setq e (point))      ;Might be on last line
4784                   (verilog-forward-syntactic-ws)
4785                   (while (looking-at verilog-declaration-re)
4786                     (beginning-of-line)
4787                     (verilog-end-of-statement)
4788                     (setq e (point))
4789                     (verilog-forward-syntactic-ws))
4790                   e))
4791                (edpos (set-marker (make-marker) end))
4792                (ind)
4793                (base-ind
4794                 (progn
4795                   (goto-char start)
4796                   (verilog-do-indent (verilog-calculate-indent))
4797                   (verilog-forward-ws&directives)
4798                   (current-column)))
4799                )
4800           (goto-char end)
4801           (goto-char start)
4802           (if (> (- end start) 100)
4803               (message "Lining up declarations..(please stand by)"))
4804           ;; Get the beginning of line indent first
4805           (while (progn (setq e (marker-position edpos))
4806                         (< (point) e))
4807             (cond
4808              ( (save-excursion (skip-chars-backward " \t")
4809                                (bolp))
4810                (verilog-forward-ws&directives)
4811                (indent-line-to base-ind)
4812                (verilog-forward-ws&directives)
4813                (verilog-re-search-forward "[ \t\n\f]" e 'move)
4814                )
4815              (t
4816               (just-one-space)
4817               (verilog-re-search-forward "[ \t\n\f]" e 'move)
4818               )
4819              )
4820             )
4821             ;;(forward-line))
4822           ;; Now find biggest prefix
4823           (setq ind (verilog-get-lineup-indent start edpos))
4824           ;; Now indent each line.
4825           (goto-char start)
4826           (while (progn (setq e (marker-position edpos))
4827                         (setq r (- e (point)))
4828                         (> r 0))
4829             (setq e (point))
4830             (message "%d" r)
4831             (cond
4832              ((or (and verilog-indent-declaration-macros
4833                        (looking-at verilog-declaration-re-1-macro))
4834                   (looking-at verilog-declaration-re-1-no-macro))
4835               (let ((p (match-end 0)))
4836                 (set-marker m1 p)
4837                 (if (verilog-re-search-forward "[[#`]" p 'move)
4838                     (progn
4839                       (forward-char -1)
4840                       (just-one-space)
4841                       (goto-char (marker-position m1))
4842                       (just-one-space)
4843                       (indent-to ind))
4844                   (progn
4845                     (just-one-space)
4846                     (indent-to ind))
4847                   )))
4848              ((verilog-continued-line-1 start)
4849               (goto-char e)
4850               (indent-line-to ind))
4851              (t         ; Must be comment or white space
4852               (goto-char e)
4853               (verilog-forward-ws&directives)
4854               (forward-line -1))
4855              )
4856             (forward-line 1))
4857           (message "")))))
4858
4859 (defun verilog-pretty-expr (&optional myre)
4860   "Line up expressions around point."
4861   (interactive "sRegular Expression: (<?=) ")
4862   (save-excursion
4863     (if (or (eq myre nil)
4864             (string-equal myre ""))
4865         (setq myre "<="))
4866     (setq myre (concat "\\(^[^;" myre "]*\\)\\([" myre "]\\)"))
4867     (beginning-of-line)
4868     (if (and (not (looking-at (concat "^\\s-*" verilog-complete-reg)))
4869              (looking-at myre))
4870         (let* ((here (point))
4871                (e) (r)
4872                (start
4873                 (progn
4874                   (beginning-of-line)
4875                   (setq e (point))
4876                   (verilog-backward-syntactic-ws)
4877                   (beginning-of-line)
4878                   (while (and (not(looking-at (concat "^\\s-*" verilog-complete-reg)))
4879                               (looking-at myre))
4880                     (setq e (point))
4881                     (verilog-backward-syntactic-ws)
4882                     (beginning-of-line)
4883                     ) ;Ack, need to grok `define
4884                   e))
4885                (end
4886                 (progn
4887                   (goto-char here)
4888                   (end-of-line)
4889                   (setq e (point))      ;Might be on last line
4890                   (verilog-forward-syntactic-ws)
4891                   (beginning-of-line)
4892                   (while (and (not(looking-at (concat "^\\s-*" verilog-complete-reg)))
4893                               (looking-at myre))
4894                     (end-of-line)
4895                     (setq e (point))
4896                     (verilog-forward-syntactic-ws)
4897                     (beginning-of-line)
4898                     )
4899                   e))
4900                (edpos (set-marker (make-marker) end))
4901                (ind)
4902                )
4903           (goto-char start)
4904           (verilog-do-indent (verilog-calculate-indent))
4905           (if (> (- end start) 100)
4906               (message "Lining up expressions..(please stand by)"))
4907
4908           ;; Set indent to minimum throughout region
4909           (while (< (point) (marker-position edpos))
4910             (beginning-of-line)
4911             (verilog-just-one-space myre)
4912             (end-of-line)
4913             (verilog-forward-syntactic-ws)
4914             )
4915
4916           ;; Now find biggest prefix
4917           (setq ind (verilog-get-lineup-indent-2 myre start edpos))
4918
4919           ;; Now indent each line.
4920           (goto-char start)
4921           (while (progn (setq e (marker-position edpos))
4922                         (setq r (- e (point)))
4923                         (> r 0))
4924             (setq e (point))
4925             (message "%d" r)
4926             (cond
4927              ((looking-at myre)
4928               (goto-char (match-end 1))
4929               (if (eq (char-after) ?=)
4930                   (indent-to (1+ ind))  ; line up the = of the <= with surrounding =
4931                 (indent-to ind)
4932                 )
4933               )
4934              ((verilog-continued-line-1 start)
4935               (goto-char e)
4936               (indent-line-to ind))
4937              (t         ; Must be comment or white space
4938               (goto-char e)
4939               (verilog-forward-ws&directives)
4940               (forward-line -1))
4941              )
4942             (forward-line 1))
4943           (message "")
4944           ))))
4945
4946 (defun verilog-just-one-space (myre)
4947   "Remove extra spaces around regular expression MYRE."
4948   (interactive)
4949   (if (and (not(looking-at verilog-complete-reg))
4950            (looking-at myre))
4951       (let ((p1 (match-end 1))
4952             (p2 (match-end 2)))
4953         (progn
4954           (goto-char p2)
4955           (if (looking-at "\\s-") (just-one-space) )
4956           (goto-char p1)
4957           (forward-char -1)
4958           (if (looking-at "\\s-") (just-one-space))
4959           )
4960         ))
4961   (message ""))
4962
4963 (defun verilog-indent-declaration (baseind)
4964   "Indent current lines as declaration.
4965 Line up the variable names based on previous declaration's indentation.
4966 BASEIND is the base indent to offset everything."
4967   (interactive)
4968   (let ((pos (point-marker))
4969         (lim (save-excursion
4970                ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
4971                (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
4972                (point)))
4973         (ind)
4974         (val)
4975         (m1 (make-marker))
4976         )
4977     (setq val (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
4978     (indent-line-to val)
4979
4980     ;; Use previous declaration (in this module) as template.
4981     (if (or (memq 'all verilog-auto-lineup)
4982             (memq 'declaration verilog-auto-lineup))
4983         (if (verilog-re-search-backward (or (and verilog-indent-declaration-macros
4984                                                  verilog-declaration-re-1-macro)
4985                                             verilog-declaration-re-1-no-macro) lim t)
4986             (progn
4987               (goto-char (match-end 0))
4988               (skip-chars-forward " \t")
4989               (setq ind (current-column))
4990               (goto-char pos)
4991               (setq val (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
4992               (indent-line-to val)
4993               (if (and verilog-indent-declaration-macros
4994                        (looking-at verilog-declaration-re-2-macro))
4995                   (let ((p (match-end 0)))
4996                     (set-marker m1 p)
4997                     (if (verilog-re-search-forward "[[#`]" p 'move)
4998                         (progn
4999                           (forward-char -1)
5000                           (just-one-space)
5001                           (goto-char (marker-position m1))
5002                           (just-one-space)
5003                           (indent-to ind)
5004                           )
5005                       (if (/= (current-column) ind)
5006                           (progn
5007                             (just-one-space)
5008                             (indent-to ind))
5009                         )))
5010                 (if (looking-at verilog-declaration-re-2-no-macro)
5011                     (let ((p (match-end 0)))
5012                       (set-marker m1 p)
5013                       (if (verilog-re-search-forward "[[`#]" p 'move)
5014                           (progn
5015                             (forward-char -1)
5016                             (just-one-space)
5017                             (goto-char (marker-position m1))
5018                             (just-one-space)
5019                             (indent-to ind))
5020                         (if (/= (current-column) ind)
5021                             (progn
5022                               (just-one-space)
5023                               (indent-to ind))
5024                           )))
5025                   )))
5026           )
5027       )
5028     (goto-char pos)
5029     )
5030   )
5031
5032 (defun verilog-get-lineup-indent (b edpos)
5033   "Return the indent level that will line up several lines within the region.
5034 Region is defined by B and EDPOS."
5035   (save-excursion
5036     (let ((ind 0) e)
5037       (goto-char b)
5038       ;; Get rightmost position
5039       (while (progn (setq e (marker-position edpos))
5040                     (< (point) e))
5041         (if (verilog-re-search-forward (or (and verilog-indent-declaration-macros
5042                                                 verilog-declaration-re-1-macro)
5043                                            verilog-declaration-re-1-no-macro) e 'move)
5044             (progn
5045               (goto-char (match-end 0))
5046               (verilog-backward-syntactic-ws)
5047               (if (> (current-column) ind)
5048                   (setq ind (current-column)))
5049               (goto-char (match-end 0)))))
5050       (if (> ind 0)
5051           (1+ ind)
5052         ;; No lineup-string found
5053         (goto-char b)
5054         (end-of-line)
5055         (skip-chars-backward " \t")
5056         (1+ (current-column))))))
5057
5058 (defun verilog-get-lineup-indent-2 (myre b edpos)
5059   "Return the indent level that will line up several lines within the region."
5060   (save-excursion
5061     (let ((ind 0) e)
5062       (goto-char b)
5063       ;; Get rightmost position
5064       (while (progn (setq e (marker-position edpos))
5065                     (< (point) e))
5066         (if (verilog-re-search-forward myre e 'move)
5067             (progn
5068               (goto-char (match-end 0))
5069               (verilog-backward-syntactic-ws)
5070               (if (> (current-column) ind)
5071                   (setq ind (current-column)))
5072               (goto-char (match-end 0)))))
5073       (if (> ind 0)
5074           (1+ ind)
5075         ;; No lineup-string found
5076         (goto-char b)
5077         (end-of-line)
5078         (skip-chars-backward " \t")
5079         (1+ (current-column))))))
5080
5081 (defun verilog-comment-depth (type val)
5082   "A useful mode debugging aide.  TYPE and VAL are comments for insertion."
5083   (save-excursion
5084     (let
5085         ((b (prog2
5086                 (beginning-of-line)
5087                 (point-marker)
5088               (end-of-line)))
5089          (e (point-marker)))
5090       (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
5091           (progn
5092             (replace-match " /* -#  ## */")
5093             (end-of-line))
5094         (progn
5095           (end-of-line)
5096           (insert " /* ##  ## */"))))
5097     (backward-char 6)
5098     (insert
5099      (format "%s %d" type val))))
5100
5101 ;; \f
5102 ;;
5103 ;; Completion
5104 ;;
5105 (defvar verilog-str nil)
5106 (defvar verilog-all nil)
5107 (defvar verilog-pred nil)
5108 (defvar verilog-buffer-to-use nil)
5109 (defvar verilog-flag nil)
5110 (defvar verilog-toggle-completions nil
5111   "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
5112 Repeated use of \\[verilog-complete-word] will show you all of them.
5113 Normally, when there is more than one possible completion,
5114 it displays a list of all possible completions.")
5115
5116
5117 (defvar verilog-type-keywords
5118   '(
5119     "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
5120     "integer" "localparam" "logic" "nand" "nmos" "nor" "not" "notif0"
5121     "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pullup"
5122     "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
5123     "rtranif1" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
5124     "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
5125     )
5126   "*Keywords for types used when completing a word in a declaration or parmlist.
5127 \(eg.  integer, real, reg...)")
5128
5129 (defvar verilog-cpp-keywords
5130   '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
5131     "endif")
5132   "*Keywords to complete when at first word of a line in declarative scope.
5133 \(eg.  initial, always, begin, assign.)
5134 The procedures and variables defined within the Verilog program
5135 will be completed runtime and should not be added to this list.")
5136
5137 (defvar verilog-defun-keywords
5138   (append
5139    '(
5140      "always" "always_comb" "always_ff" "always_latch" "assign"
5141      "begin" "end" "generate" "endgenerate" "module" "endmodule"
5142      "specify" "endspecify" "function" "endfunction" "initial" "final"
5143      "task" "endtask" "primitive" "endprimitive"
5144      )
5145    verilog-type-keywords)
5146   "*Keywords to complete when at first word of a line in declarative scope.
5147 \(eg.  initial, always, begin, assign.)
5148 The procedures and variables defined within the Verilog program
5149 will be completed runtime and should not be added to this list.")
5150
5151 (defvar verilog-block-keywords
5152   '(
5153     "begin" "break" "case" "continue" "else" "end" "endfunction"
5154     "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
5155     "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
5156     "while")
5157   "*Keywords to complete when at first word of a line in behavioral scope.
5158 \(eg.  begin, if, then, else, for, fork.)
5159 The procedures and variables defined within the Verilog program
5160 will be completed runtime and should not be added to this list.")
5161
5162 (defvar verilog-tf-keywords
5163   '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
5164   "*Keywords to complete when at first word of a line in a task or function.
5165 \(eg.  begin, if, then, else, for, fork.)
5166 The procedures and variables defined within the Verilog program
5167 will be completed runtime and should not be added to this list.")
5168
5169 (defvar verilog-case-keywords
5170   '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
5171   "*Keywords to complete when at first word of a line in case scope.
5172 \(eg.  begin, if, then, else, for, fork.)
5173 The procedures and variables defined within the Verilog program
5174 will be completed runtime and should not be added to this list.")
5175
5176 (defvar verilog-separator-keywords
5177   '("else" "then" "begin")
5178   "*Keywords to complete when NOT standing at the first word of a statement.
5179 \(eg.  else, then.)
5180 Variables and function names defined within the
5181 Verilog program are completed runtime and should not be added to this list.")
5182
5183 (defun verilog-string-diff (str1 str2)
5184   "Return index of first letter where STR1 and STR2 differs."
5185   (catch 'done
5186     (let ((diff 0))
5187       (while t
5188         (if (or (> (1+ diff) (length str1))
5189                 (> (1+ diff) (length str2)))
5190             (throw 'done diff))
5191         (or (equal (aref str1 diff) (aref str2 diff))
5192             (throw 'done diff))
5193         (setq diff (1+ diff))))))
5194
5195 ;; Calculate all possible completions for functions if argument is `function',
5196 ;; completions for procedures if argument is `procedure' or both functions and
5197 ;; procedures otherwise.
5198
5199 (defun verilog-func-completion (type)
5200   "Build regular expression for module/task/function names.
5201 TYPE is 'module, 'tf for task or function, or t if unknown."
5202   (if (string= verilog-str "")
5203       (setq verilog-str "[a-zA-Z_]"))
5204   (let ((verilog-str (concat (cond
5205                              ((eq type 'module) "\\<\\(module\\)\\s +")
5206                              ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
5207                              (t "\\<\\(task\\|function\\|module\\)\\s +"))
5208                             "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
5209         match)
5210
5211     (if (not (looking-at verilog-defun-re))
5212         (verilog-re-search-backward verilog-defun-re nil t))
5213     (forward-char 1)
5214
5215     ;; Search through all reachable functions
5216     (goto-char (point-min))
5217     (while (verilog-re-search-forward verilog-str (point-max) t)
5218       (progn (setq match (buffer-substring (match-beginning 2)
5219                                            (match-end 2)))
5220              (if (or (null verilog-pred)
5221                      (funcall verilog-pred match))
5222                  (setq verilog-all (cons match verilog-all)))))
5223     (if (match-beginning 0)
5224         (goto-char (match-beginning 0)))))
5225
5226 (defun verilog-get-completion-decl (end)
5227   "Macro for searching through current declaration (var, type or const)
5228 for matches of `str' and adding the occurrence tp `all' through point END."
5229   (let ((re (or (and verilog-indent-declaration-macros
5230                      verilog-declaration-re-2-macro)
5231                 verilog-declaration-re-2-no-macro))
5232         decl-end match)
5233     ;; Traverse lines
5234     (while (and (< (point) end)
5235                 (verilog-re-search-forward re end t))
5236       ;; Traverse current line
5237       (setq decl-end (save-excursion (verilog-declaration-end)))
5238       (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
5239                   (not (match-end 1)))
5240         (setq match (buffer-substring (match-beginning 0) (match-end 0)))
5241         (if (string-match (concat "\\<" verilog-str) match)
5242             (if (or (null verilog-pred)
5243                     (funcall verilog-pred match))
5244                 (setq verilog-all (cons match verilog-all)))))
5245       (forward-line 1)
5246       )
5247     )
5248   verilog-all
5249   )
5250
5251 (defun verilog-type-completion ()
5252   "Calculate all possible completions for types."
5253   (let ((start (point))
5254         goon)
5255     ;; Search for all reachable type declarations
5256     (while (or (verilog-beg-of-defun)
5257                (setq goon (not goon)))
5258       (save-excursion
5259         (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
5260                                                  (point))
5261                             (forward-char 1)))
5262                  (verilog-re-search-forward
5263                   "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
5264                   start t)
5265                  (not (match-end 1)))
5266             ;; Check current type declaration
5267             (verilog-get-completion-decl start))))))
5268
5269 (defun verilog-var-completion ()
5270   "Calculate all possible completions for variables (or constants)."
5271   (let ((start (point)))
5272     ;; Search for all reachable var declarations
5273     (verilog-beg-of-defun)
5274     (save-excursion
5275       ;; Check var declarations
5276       (verilog-get-completion-decl start))))
5277
5278 (defun verilog-keyword-completion (keyword-list)
5279   "Give list of all possible completions of keywords in KEYWORD-LIST."
5280   (mapcar '(lambda (s)
5281              (if (string-match (concat "\\<" verilog-str) s)
5282                  (if (or (null verilog-pred)
5283                          (funcall verilog-pred s))
5284                      (setq verilog-all (cons s verilog-all)))))
5285           keyword-list))
5286
5287
5288 (defun verilog-completion (verilog-str verilog-pred verilog-flag)
5289   "Function passed to `completing-read', `try-completion' or `all-completions'.
5290 Called to get completion on VERILOG-STR.  If VERILOG-PRED is non-nil, it
5291 must be a function to be called for every match to check if this should
5292 really be a match.  If VERILOG-FLAG is t, the function returns a list of all
5293 possible completions.  If VERILOG-FLAG is nil it returns a string, the
5294 longest possible completion, or t if STR is an exact match.  If VERILOG-FLAG
5295 is 'lambda, the function returns t if STR is an exact match, nil
5296 otherwise."
5297   (save-excursion
5298     (let ((verilog-all nil))
5299       ;; Set buffer to use for searching labels. This should be set
5300       ;; within functions which use verilog-completions
5301       (set-buffer verilog-buffer-to-use)
5302
5303       ;; Determine what should be completed
5304       (let ((state (car (verilog-calculate-indent))))
5305         (cond ((eq state 'defun)
5306                (save-excursion (verilog-var-completion))
5307                (verilog-func-completion 'module)
5308                (verilog-keyword-completion verilog-defun-keywords))
5309
5310               ((eq state 'behavioral)
5311                (save-excursion (verilog-var-completion))
5312                (verilog-func-completion 'module)
5313                (verilog-keyword-completion verilog-defun-keywords))
5314
5315               ((eq state 'block)
5316                (save-excursion (verilog-var-completion))
5317                (verilog-func-completion 'tf)
5318                (verilog-keyword-completion verilog-block-keywords))
5319
5320               ((eq state 'case)
5321                (save-excursion (verilog-var-completion))
5322                (verilog-func-completion 'tf)
5323                (verilog-keyword-completion verilog-case-keywords))
5324
5325               ((eq state 'tf)
5326                (save-excursion (verilog-var-completion))
5327                (verilog-func-completion 'tf)
5328                (verilog-keyword-completion verilog-tf-keywords))
5329
5330               ((eq state 'cpp)
5331                (save-excursion (verilog-var-completion))
5332                (verilog-keyword-completion verilog-cpp-keywords))
5333
5334               ((eq state 'cparenexp)
5335                (save-excursion (verilog-var-completion)))
5336
5337               (t;--Anywhere else
5338                (save-excursion (verilog-var-completion))
5339                (verilog-func-completion 'both)
5340                (verilog-keyword-completion verilog-separator-keywords))))
5341
5342       ;; Now we have built a list of all matches. Give response to caller
5343       (verilog-completion-response))))
5344
5345 (defun verilog-completion-response ()
5346   (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
5347          ;; This was not called by all-completions
5348          (if (null verilog-all)
5349              ;; Return nil if there was no matching label
5350              nil
5351            ;; Get longest string common in the labels
5352            (let* ((elm (cdr verilog-all))
5353                   (match (car verilog-all))
5354                   (min (length match))
5355                   tmp)
5356              (if (string= match verilog-str)
5357                  ;; Return t if first match was an exact match
5358                  (setq match t)
5359                (while (not (null elm))
5360                  ;; Find longest common string
5361                  (if (< (setq tmp (verilog-string-diff match (car elm))) min)
5362                      (progn
5363                        (setq min tmp)
5364                        (setq match (substring match 0 min))))
5365                  ;; Terminate with match=t if this is an exact match
5366                  (if (string= (car elm) verilog-str)
5367                      (progn
5368                        (setq match t)
5369                        (setq elm nil))
5370                    (setq elm (cdr elm)))))
5371              ;; If this is a test just for exact match, return nil ot t
5372              (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
5373                  nil
5374                match))))
5375         ;; If flag is t, this was called by all-completions. Return
5376         ;; list of all possible completions
5377         (verilog-flag
5378          verilog-all)))
5379
5380 (defvar verilog-last-word-numb 0)
5381 (defvar verilog-last-word-shown nil)
5382 (defvar verilog-last-completions nil)
5383
5384 (defun verilog-complete-word ()
5385   "Complete word at current point.
5386 \(See also `verilog-toggle-completions', `verilog-type-keywords',
5387 and `verilog-separator-keywords'.)"
5388   (interactive)
5389   (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5390          (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5391          (verilog-str (buffer-substring b e))
5392          ;; The following variable is used in verilog-completion
5393          (verilog-buffer-to-use (current-buffer))
5394          (allcomp (if (and verilog-toggle-completions
5395                            (string= verilog-last-word-shown verilog-str))
5396                       verilog-last-completions
5397                     (all-completions verilog-str 'verilog-completion)))
5398          (match (if verilog-toggle-completions
5399                     "" (try-completion
5400                         verilog-str (mapcar '(lambda (elm)
5401                                               (cons elm 0)) allcomp)))))
5402     ;; Delete old string
5403     (delete-region b e)
5404
5405     ;; Toggle-completions inserts whole labels
5406     (if verilog-toggle-completions
5407         (progn
5408           ;; Update entry number in list
5409           (setq verilog-last-completions allcomp
5410                 verilog-last-word-numb
5411                 (if (>= verilog-last-word-numb (1- (length allcomp)))
5412                     0
5413                   (1+ verilog-last-word-numb)))
5414           (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
5415           ;; Display next match or same string if no match was found
5416           (if (not (null allcomp))
5417               (insert "" verilog-last-word-shown)
5418             (insert "" verilog-str)
5419             (message "(No match)")))
5420       ;; The other form of completion does not necessarily do that.
5421
5422       ;; Insert match if found, or the original string if no match
5423       (if (or (null match) (equal match 't))
5424           (progn (insert "" verilog-str)
5425                  (message "(No match)"))
5426         (insert "" match))
5427       ;; Give message about current status of completion
5428       (cond ((equal match 't)
5429              (if (not (null (cdr allcomp)))
5430                  (message "(Complete but not unique)")
5431                (message "(Sole completion)")))
5432             ;; Display buffer if the current completion didn't help
5433             ;; on completing the label.
5434             ((and (not (null (cdr allcomp))) (= (length verilog-str)
5435                                                 (length match)))
5436              (with-output-to-temp-buffer "*Completions*"
5437                (display-completion-list allcomp))
5438              ;; Wait for a key press. Then delete *Completion*  window
5439              (momentary-string-display "" (point))
5440              (delete-window (get-buffer-window (get-buffer "*Completions*")))
5441              )))))
5442
5443 (defun verilog-show-completions ()
5444   "Show all possible completions at current point."
5445   (interactive)
5446   (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5447          (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5448          (verilog-str (buffer-substring b e))
5449          ;; The following variable is used in verilog-completion
5450          (verilog-buffer-to-use (current-buffer))
5451          (allcomp (if (and verilog-toggle-completions
5452                            (string= verilog-last-word-shown verilog-str))
5453                       verilog-last-completions
5454                     (all-completions verilog-str 'verilog-completion))))
5455     ;; Show possible completions in a temporary buffer.
5456     (with-output-to-temp-buffer "*Completions*"
5457       (display-completion-list allcomp))
5458     ;; Wait for a key press. Then delete *Completion*  window
5459     (momentary-string-display "" (point))
5460     (delete-window (get-buffer-window (get-buffer "*Completions*")))))
5461
5462
5463 (defun verilog-get-default-symbol ()
5464   "Return symbol around current point as a string."
5465   (save-excursion
5466     (buffer-substring (progn
5467                         (skip-chars-backward " \t")
5468                         (skip-chars-backward "a-zA-Z0-9_")
5469                         (point))
5470                       (progn
5471                         (skip-chars-forward "a-zA-Z0-9_")
5472                         (point)))))
5473
5474 (defun verilog-build-defun-re (str &optional arg)
5475   "Return function/task/module starting with STR as regular expression.
5476 With optional second ARG non-nil, STR is the complete name of the instruction."
5477   (if arg
5478       (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
5479     (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
5480
5481 (defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
5482   "Function passed to `completing-read', `try-completion' or `all-completions'.
5483 Returns a completion on any function name based on VERILOG-STR prefix.  If
5484 VERILOG-PRED is non-nil, it must be a function to be called for every match
5485 to check if this should really be a match.  If VERILOG-FLAG is t, the
5486 function returns a list of all possible completions.  If it is nil it
5487 returns a string, the longest possible completion, or t if VERILOG-STR is
5488 an exact match.  If VERILOG-FLAG is 'lambda, the function returns t if
5489 VERILOG-STR is an exact match, nil otherwise."
5490   (save-excursion
5491     (let ((verilog-all nil)
5492           match)
5493
5494       ;; Set buffer to use for searching labels. This should be set
5495       ;; within functions which use verilog-completions
5496       (set-buffer verilog-buffer-to-use)
5497
5498       (let ((verilog-str verilog-str))
5499         ;; Build regular expression for functions
5500         (if (string= verilog-str "")
5501             (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
5502           (setq verilog-str (verilog-build-defun-re verilog-str)))
5503         (goto-char (point-min))
5504
5505         ;; Build a list of all possible completions
5506         (while (verilog-re-search-forward verilog-str nil t)
5507           (setq match (buffer-substring (match-beginning 2) (match-end 2)))
5508           (if (or (null verilog-pred)
5509                   (funcall verilog-pred match))
5510               (setq verilog-all (cons match verilog-all)))))
5511
5512       ;; Now we have built a list of all matches. Give response to caller
5513       (verilog-completion-response))))
5514
5515 (defun verilog-goto-defun ()
5516   "Move to specified Verilog module/task/function.
5517 The default is a name found in the buffer around point.
5518 If search fails, other files are checked based on
5519 `verilog-library-flags'."
5520   (interactive)
5521   (let* ((default (verilog-get-default-symbol))
5522          ;; The following variable is used in verilog-comp-function
5523          (verilog-buffer-to-use (current-buffer))
5524          (label (if (not (string= default ""))
5525                     ;; Do completion with default
5526                     (completing-read (concat "Label: (default " default ") ")
5527                                      'verilog-comp-defun nil nil "")
5528                   ;; There is no default value. Complete without it
5529                   (completing-read "Label: "
5530                                    'verilog-comp-defun nil nil "")))
5531          pt)
5532     ;; If there was no response on prompt, use default value
5533     (if (string= label "")
5534         (setq label default))
5535     ;; Goto right place in buffer if label is not an empty string
5536     (or (string= label "")
5537         (progn
5538           (save-excursion
5539             (goto-char (point-min))
5540             (setq pt (re-search-forward (verilog-build-defun-re label t) nil t)))
5541           (when pt
5542             (goto-char pt)
5543             (beginning-of-line))
5544           pt)
5545         (verilog-goto-defun-file label)
5546         )))
5547
5548 ;; Eliminate compile warning
5549 (eval-when-compile
5550   (if (not (boundp 'occur-pos-list))
5551       (defvar occur-pos-list nil "Backward compatibility occur positions.")))
5552
5553 (defun verilog-showscopes ()
5554   "List all scopes in this module."
5555   (interactive)
5556   (let ((buffer (current-buffer))
5557         (linenum 1)
5558         (nlines 0)
5559         (first 1)
5560         (prevpos (point-min))
5561         (final-context-start (make-marker))
5562         (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)")
5563         )
5564     (with-output-to-temp-buffer "*Occur*"
5565       (save-excursion
5566         (message (format "Searching for %s ..." regexp))
5567         ;; Find next match, but give up if prev match was at end of buffer.
5568         (while (and (not (= prevpos (point-max)))
5569                     (verilog-re-search-forward regexp nil t))
5570           (goto-char (match-beginning 0))
5571           (beginning-of-line)
5572           (save-match-data
5573             (setq linenum (+ linenum (count-lines prevpos (point)))))
5574           (setq prevpos (point))
5575           (goto-char (match-end 0))
5576           (let* ((start (save-excursion
5577                           (goto-char (match-beginning 0))
5578                           (forward-line (if (< nlines 0) nlines (- nlines)))
5579                           (point)))
5580                  (end (save-excursion
5581                         (goto-char (match-end 0))
5582                         (if (> nlines 0)
5583                             (forward-line (1+ nlines))
5584                             (forward-line 1))
5585                         (point)))
5586                  (tag (format "%3d" linenum))
5587                  (empty (make-string (length tag) ?\ ))
5588                  tem)
5589             (save-excursion
5590               (setq tem (make-marker))
5591               (set-marker tem (point))
5592               (set-buffer standard-output)
5593               (setq occur-pos-list (cons tem occur-pos-list))
5594               (or first (zerop nlines)
5595                   (insert "--------\n"))
5596               (setq first nil)
5597               (insert-buffer-substring buffer start end)
5598               (backward-char (- end start))
5599               (setq tem (if (< nlines 0) (- nlines) nlines))
5600               (while (> tem 0)
5601                 (insert empty ?:)
5602                 (forward-line 1)
5603                 (setq tem (1- tem)))
5604               (let ((this-linenum linenum))
5605                 (set-marker final-context-start
5606                             (+ (point) (- (match-end 0) (match-beginning 0))))
5607                 (while (< (point) final-context-start)
5608                   (if (null tag)
5609                       (setq tag (format "%3d" this-linenum)))
5610                   (insert tag ?:)))))))
5611       (set-buffer-modified-p nil))))
5612
5613
5614 ;; Highlight helper functions
5615 (defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
5616 (defun verilog-within-translate-off ()
5617   "Return point if within translate-off region, else nil."
5618   (and (save-excursion
5619          (re-search-backward
5620           (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
5621           nil t))
5622        (equal "off" (match-string 2))
5623        (point)))
5624
5625 (defun verilog-start-translate-off (limit)
5626   "Return point before translate-off directive if before LIMIT, else nil."
5627   (when (re-search-forward
5628           (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
5629           limit t)
5630     (match-beginning 0)))
5631
5632 (defun verilog-back-to-start-translate-off (limit)
5633   "Return point before translate-off directive if before LIMIT, else nil."
5634   (when (re-search-backward
5635           (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
5636           limit t)
5637     (match-beginning 0)))
5638
5639 (defun verilog-end-translate-off (limit)
5640   "Return point after translate-on directive if before LIMIT, else nil."
5641
5642   (re-search-forward (concat
5643                       "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
5644
5645 (defun verilog-match-translate-off (limit)
5646   "Match a translate-off block, setting `match-data' and returning t, else nil.
5647 Bound search by LIMIT."
5648   (when (< (point) limit)
5649     (let ((start (or (verilog-within-translate-off)
5650                      (verilog-start-translate-off limit)))
5651           (case-fold-search t))
5652       (when start
5653         (let ((end (or (verilog-end-translate-off limit) limit)))
5654           (set-match-data (list start end))
5655           (goto-char end))))))
5656
5657 (defun verilog-font-lock-match-item (limit)
5658   "Match, and move over, any declaration item after point.
5659 Bound search by LIMIT.  Adapted from
5660 `font-lock-match-c-style-declaration-item-and-skip-to-next'."
5661   (condition-case nil
5662       (save-restriction
5663         (narrow-to-region (point-min) limit)
5664         ;; match item
5665         (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
5666           (save-match-data
5667             (goto-char (match-end 1))
5668             ;; move to next item
5669             (if (looking-at "\\(\\s-*,\\)")
5670                 (goto-char (match-end 1))
5671               (end-of-line) t))))
5672     (error nil)))
5673
5674
5675 ;; Added by Subbu Meiyappan for Header
5676
5677 (defun verilog-header ()
5678   "Insert a standard Verilog file header."
5679   (interactive)
5680   (let ((start (point)))
5681   (insert "\
5682 //-----------------------------------------------------------------------------
5683 // Title         : <title>
5684 // Project       : <project>
5685 //-----------------------------------------------------------------------------
5686 // File          : <filename>
5687 // Author        : <author>
5688 // Created       : <credate>
5689 // Last modified : <moddate>
5690 //-----------------------------------------------------------------------------
5691 // Description :
5692 // <description>
5693 //-----------------------------------------------------------------------------
5694 // Copyright (c) <copydate> by <company> This model is the confidential and
5695 // proprietary property of <company> and the possession or use of this
5696 // file requires a written license from <company>.
5697 //------------------------------------------------------------------------------
5698 // Modification history :
5699 // <modhist>
5700 //-----------------------------------------------------------------------------
5701
5702 ")
5703     (goto-char start)
5704     (search-forward "<filename>")
5705     (replace-match (buffer-name) t t)
5706     (search-forward "<author>") (replace-match "" t t)
5707     (insert (user-full-name))
5708     (insert "  <" (user-login-name) "@" (system-name) ">")
5709     (search-forward "<credate>") (replace-match "" t t)
5710     (insert-date)
5711     (search-forward "<moddate>") (replace-match "" t t)
5712     (insert-date)
5713     (search-forward "<copydate>") (replace-match "" t t)
5714     (insert-year)
5715     (search-forward "<modhist>") (replace-match "" t t)
5716     (insert-date)
5717     (insert " : created")
5718     (goto-char start)
5719     (let (string)
5720       (setq string (read-string "title: "))
5721       (search-forward "<title>")
5722       (replace-match string t t)
5723       (setq string (read-string "project: " verilog-project))
5724       (make-variable-buffer-local 'verilog-project)
5725       (setq verilog-project string)
5726       (search-forward "<project>")
5727       (replace-match string t t)
5728       (setq string (read-string "Company: " verilog-company))
5729       (make-variable-buffer-local 'verilog-company)
5730       (setq verilog-company string)
5731       (search-forward "<company>")
5732       (replace-match string t t)
5733       (search-forward "<company>")
5734       (replace-match string t t)
5735       (search-forward "<company>")
5736       (replace-match string t t)
5737       (search-backward "<description>")
5738       (replace-match "" t t)
5739       )))
5740
5741 ;; verilog-header Uses the insert-date function
5742
5743 (defun insert-date ()
5744   "Insert date from the system."
5745   (interactive)
5746   (let ((timpos))
5747     (setq timpos (point))
5748     (if verilog-date-scientific-format
5749         (shell-command  "date \"+@%Y/%m/%d\"" t)
5750       (shell-command  "date \"+@%d.%m.%Y\"" t))
5751     (search-forward "@")
5752     (delete-region timpos (point))
5753     (end-of-line))
5754     (delete-char 1))
5755
5756 (defun insert-year ()
5757   "Insert year from the system."
5758   (interactive)
5759   (let ((timpos))
5760     (setq timpos (point))
5761     (shell-command  "date \"+@%Y\"" t)
5762     (search-forward "@")
5763     (delete-region timpos (point))
5764     (end-of-line))
5765   (delete-char 1))
5766
5767 \f
5768 ;;
5769 ;; Signal list parsing
5770 ;;
5771
5772 ;; Elements of a signal list
5773 (defsubst verilog-sig-name (sig)
5774   (car sig))
5775 (defsubst verilog-sig-bits (sig)
5776   (nth 1 sig))
5777 (defsubst verilog-sig-comment (sig)
5778   (nth 2 sig))
5779 (defsubst verilog-sig-memory (sig)
5780   (nth 3 sig))
5781 (defsubst verilog-sig-enum (sig)
5782   (nth 4 sig))
5783 (defsubst verilog-sig-signed (sig)
5784   (nth 5 sig))
5785 (defsubst verilog-sig-type (sig)
5786   (nth 6 sig))
5787 (defsubst verilog-sig-multidim (sig)
5788   (nth 7 sig))
5789 (defsubst verilog-sig-multidim-string (sig)
5790   (if (verilog-sig-multidim sig)
5791       (let ((str "") (args (verilog-sig-multidim sig)))
5792         (while args
5793           (setq str (concat str (car args)))
5794           (setq args (cdr args)))
5795         str)))
5796 (defsubst verilog-sig-width (sig)
5797   (verilog-make-width-expression (verilog-sig-bits sig)))
5798
5799 (defsubst verilog-alw-get-inputs (sigs)
5800   (nth 2 sigs))
5801 (defsubst verilog-alw-get-outputs (sigs)
5802   (nth 0 sigs))
5803 (defsubst verilog-alw-get-uses-delayed (sigs)
5804   (nth 3 sigs))
5805
5806 (defun verilog-signals-not-in (in-list not-list)
5807   "Return list of signals in IN-LIST that aren't also in NOT-LIST.
5808 Signals must be in standard (base vector) form."
5809   (let (out-list)
5810     (while in-list
5811       (if (not (assoc (car (car in-list)) not-list))
5812           (setq out-list (cons (car in-list) out-list)))
5813       (setq in-list (cdr in-list)))
5814     (nreverse out-list)))
5815 ;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
5816
5817 (defun verilog-signals-in (in-list other-list)
5818   "Return list of signals in IN-LIST that are also in OTHER-LIST.
5819 Signals must be in standard (base vector) form."
5820   (let (out-list)
5821     (while in-list
5822       (if (assoc (car (car in-list)) other-list)
5823           (setq out-list (cons (car in-list) out-list)))
5824       (setq in-list (cdr in-list)))
5825     (nreverse out-list)))
5826 ;;(verilog-signals-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
5827
5828 (defun verilog-signals-memory (in-list)
5829   "Return list of signals in IN-LIST that are memoried (multidimensional)."
5830   (let (out-list)
5831     (while in-list
5832       (if (nth 3 (car in-list))
5833           (setq out-list (cons (car in-list) out-list)))
5834       (setq in-list (cdr in-list)))
5835     out-list))
5836 ;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
5837
5838 (defun verilog-signals-sort-compare (a b)
5839   "Compare signal A and B for sorting."
5840   (string< (car a) (car b)))
5841
5842 (defun verilog-signals-not-params (in-list)
5843   "Return list of signals in IN-LIST that aren't parameters or numeric constants."
5844   (let (out-list)
5845     (while in-list
5846       (unless (boundp (intern (concat "vh-" (car (car in-list)))))
5847         (setq out-list (cons (car in-list) out-list)))
5848       (setq in-list (cdr in-list)))
5849     (nreverse out-list)))
5850
5851 (defun verilog-signals-combine-bus (in-list)
5852   "Return a list of signals in IN-LIST, with busses combined.
5853 Duplicate signals are also removed.  For example A[2] and A[1] become A[2:1]."
5854   (let (combo
5855         out-list
5856         sig highbit lowbit              ; Temp information about current signal
5857         sv-name sv-highbit sv-lowbit    ; Details about signal we are forming
5858         sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
5859         bus)
5860     ;; Shove signals so duplicated signals will be adjacent
5861     (setq in-list (sort in-list `verilog-signals-sort-compare))
5862     (while in-list
5863       (setq sig (car in-list))
5864       ;; No current signal; form from existing details
5865       (unless sv-name
5866         (setq sv-name    (verilog-sig-name sig)
5867               sv-highbit nil
5868               sv-busstring nil
5869               sv-comment (verilog-sig-comment sig)
5870               sv-memory  (verilog-sig-memory sig)
5871               sv-enum    (verilog-sig-enum sig)
5872               sv-signed  (verilog-sig-signed sig)
5873               sv-type    (verilog-sig-type sig)
5874               sv-multidim (verilog-sig-multidim sig)
5875               combo ""
5876               ))
5877       ;; Extract bus details
5878       (setq bus (verilog-sig-bits sig))
5879       (cond ((and bus
5880                   (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
5881                            (setq highbit (string-to-int (match-string 1 bus))
5882                                  lowbit  (string-to-int (match-string 2 bus))))
5883                       (and (string-match "\\[\\([0-9]+\\)\\]" bus)
5884                            (setq highbit (string-to-int (match-string 1 bus))
5885                                  lowbit  highbit))))
5886              ;; Combine bits in bus
5887              (if sv-highbit
5888                  (setq sv-highbit (max highbit sv-highbit)
5889                        sv-lowbit  (min lowbit  sv-lowbit))
5890                (setq sv-highbit highbit
5891                      sv-lowbit  lowbit)))
5892             (bus
5893              ;; String, probably something like `preproc:0
5894              (setq sv-busstring bus)))
5895       ;; Peek ahead to next signal
5896       (setq in-list (cdr in-list))
5897       (setq sig (car in-list))
5898       (cond ((and sig (equal sv-name (verilog-sig-name sig)))
5899              ;; Combine with this signal
5900              (if (and sv-busstring (not (equal sv-busstring (verilog-sig-bits sig))))
5901                  (message (concat "Warning, can't merge into single bus "
5902                                   sv-name bus
5903                                   ", the AUTOs may be wrong")))
5904              (if (verilog-sig-comment sig) (setq combo ", ..."))
5905              (setq sv-memory (or sv-memory (verilog-sig-memory sig))
5906                    sv-enum   (or sv-enum   (verilog-sig-enum sig))
5907                    sv-signed (or sv-signed (verilog-sig-signed sig))
5908                    sv-type   (or sv-type   (verilog-sig-type sig))
5909                    sv-multidim (or sv-multidim (verilog-sig-multidim sig))))
5910             ;; Doesn't match next signal, add to que, zero in prep for next
5911             ;; Note sig may also be nil for the last signal in the list
5912             (t
5913              (setq out-list
5914                    (cons (list sv-name
5915                                (or sv-busstring
5916                                    (if sv-highbit
5917                                        (concat "[" (int-to-string sv-highbit) ":" (int-to-string sv-lowbit) "]")))
5918                                (concat sv-comment combo)
5919                                sv-memory sv-enum sv-signed sv-type sv-multidim)
5920                          out-list)
5921                    sv-name nil)))
5922       )
5923     ;;
5924     out-list))
5925
5926 (defun verilog-sig-tieoff (sig &optional no-width)
5927   "Return tieoff expression for given SIGNAL, with appropriate width.
5928 Ignore width if optional NO-WIDTH is set."
5929   (let* ((width (if no-width nil (verilog-sig-width sig))))
5930     (concat
5931      (if (and verilog-active-low-regexp
5932               (string-match verilog-active-low-regexp (verilog-sig-name sig)))
5933          "~" "")
5934      (cond ((not width)
5935             "0")
5936            ((string-match "^[0-9]+$" width)
5937             (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
5938            (t
5939             (concat "{" width "{1'b0}}"))))))
5940
5941 ;;
5942 ;; Port/Wire/Etc Reading
5943 ;;
5944
5945 (defun verilog-read-inst-backward-name ()
5946   "Internal.  Move point back to beginning of inst-name."
5947     (verilog-backward-open-paren)
5948     (let (done)
5949       (while (not done)
5950         (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil)  ; ] isn't word boundary
5951         (cond ((looking-at ")")
5952                (verilog-backward-open-paren))
5953               (t (setq done t)))))
5954     (while (looking-at "\\]")
5955       (verilog-backward-open-bracket)
5956       (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
5957     (skip-chars-backward "a-zA-Z0-9`_$"))
5958
5959 (defun verilog-read-inst-module ()
5960   "Return module_name when point is inside instantiation."
5961   (save-excursion
5962     (verilog-read-inst-backward-name)
5963     ;; Skip over instantiation name
5964     (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil)  ; ) isn't word boundary
5965     ;; Check for parameterized instantiations
5966     (when (looking-at ")")
5967       (verilog-backward-open-paren)
5968       (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
5969     (skip-chars-backward "a-zA-Z0-9'_$")
5970     (looking-at "[a-zA-Z0-9`_\$]+")
5971     ;; Important: don't use match string, this must work with emacs 19 font-lock on
5972     (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
5973
5974 (defun verilog-read-inst-name ()
5975   "Return instance_name when point is inside instantiation."
5976   (save-excursion
5977     (verilog-read-inst-backward-name)
5978     (looking-at "[a-zA-Z0-9`_\$]+")
5979     ;; Important: don't use match string, this must work with emacs 19 font-lock on
5980     (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
5981
5982 (defun verilog-read-module-name ()
5983   "Return module name when after its ( or ;."
5984   (save-excursion
5985     (re-search-backward "[(;]")
5986     (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
5987     (skip-chars-backward "a-zA-Z0-9`_$")
5988     (looking-at "[a-zA-Z0-9`_\$]+")
5989     ;; Important: don't use match string, this must work with emacs 19 font-lock on
5990     (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
5991
5992 (defun verilog-read-auto-params (num-param &optional max-param)
5993   "Return parameter list inside auto.
5994 Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
5995   (let ((olist))
5996     (save-excursion
5997       ;; /*AUTOPUNT("parameter", "parameter")*/
5998       (search-backward "(")
5999       (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
6000         (setq olist (cons (match-string 1) olist))
6001         (goto-char (match-end 0))))
6002     (or (eq nil num-param)
6003         (<= num-param (length olist))
6004         (error "%s: Expected %d parameters" (verilog-point-text) num-param))
6005     (if (eq max-param nil) (setq max-param num-param))
6006     (or (eq nil max-param)
6007         (>= max-param (length olist))
6008         (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
6009     (nreverse olist)))
6010
6011 (defun verilog-read-decls ()
6012   "Compute signal declaration information for the current module at point.
6013 Return a array of [outputs inouts inputs wire reg assign const]."
6014   (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
6015         (functask 0) (paren 0)
6016         sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const sigs-gparam
6017         vec expect-signal keywd newsig rvalue enum io signed typedefed multidim)
6018     (save-excursion
6019       (verilog-beg-of-defun)
6020       (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
6021       (while (< (point) end-mod-point)
6022         ;;(if dbg (setq dbg (cons (format "Pt %s  Vec %s   Kwd'%s'\n" (point) vec keywd) dbg)))
6023         (cond
6024          ((looking-at "//")
6025           (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6026               (setq enum (match-string 1)))
6027           (search-forward "\n"))
6028          ((looking-at "/\\*")
6029           (forward-char 2)
6030           (if (looking-at "[^*]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6031               (setq enum (match-string 1)))
6032           (or (search-forward "*/")
6033               (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6034          ((looking-at "(\\*")
6035           (forward-char 2)
6036           (or (looking-at "\\s-*)")   ; It's a "always @ (*)"
6037               (search-forward "*)")
6038               (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
6039          ((eq ?\" (following-char))
6040           (or (re-search-forward "[^\\]\"" nil t)       ;; don't forward-char first, since we look for a non backslash first
6041               (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
6042          ((eq ?\; (following-char))
6043           (setq vec nil  io nil  expect-signal nil  newsig nil  paren 0  rvalue nil)
6044           (forward-char 1))
6045          ((eq ?= (following-char))
6046           (setq rvalue t newsig nil)
6047           (forward-char 1))
6048          ((and rvalue
6049                (cond ((and (eq ?, (following-char))
6050                            (eq paren 0))
6051                       (setq rvalue nil)
6052                       (forward-char 1)
6053                       t)
6054                      ;; ,'s can occur inside {} & funcs
6055                      ((looking-at "[{(]")
6056                       (setq paren (1+ paren))
6057                       (forward-char 1)
6058                       t)
6059                      ((looking-at "[})]")
6060                       (setq paren (1- paren))
6061                       (forward-char 1)
6062                       t)
6063                      )))
6064          ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
6065           (goto-char (match-end 0))
6066           (cond (newsig ; Memory, not just width.  Patch last signal added's memory (nth 3)
6067                  (setcar (cdr (cdr (cdr newsig))) (match-string 1)))
6068                 (vec ;; Multidimensional
6069                  (setq multidim (cons vec multidim))
6070                  (setq vec (verilog-string-replace-matches
6071                             "\\s-+" "" nil nil (match-string 1))))
6072                 (t ;; Bit width
6073                  (setq vec (verilog-string-replace-matches
6074                             "\\s-+" "" nil nil (match-string 1))))))
6075          ;; Normal or escaped identifier -- note we remember the \ if escaped
6076          ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
6077           (goto-char (match-end 0))
6078           (setq keywd (match-string 1))
6079           (when (string-match "^\\\\" keywd)
6080             (setq keywd (concat keywd " ")))  ;; Escaped ID needs space at end
6081           (cond ((equal keywd "input")
6082                  (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  io t  expect-signal 'sigs-in))
6083                 ((equal keywd "output")
6084                  (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  io t  expect-signal 'sigs-out))
6085                 ((equal keywd "inout")
6086                  (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  io t  expect-signal 'sigs-inout))
6087                 ((or (equal keywd "wire")
6088                      (equal keywd "tri")
6089                      (equal keywd "tri0")
6090                      (equal keywd "tri1"))
6091                  (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  expect-signal 'sigs-wire)))
6092                 ((or (equal keywd "reg")
6093                      (equal keywd "trireg"))
6094                  (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  expect-signal 'sigs-reg)))
6095                 ((equal keywd "assign")
6096                  (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  expect-signal 'sigs-assign))
6097                 ((or (equal keywd "supply0")
6098                      (equal keywd "supply1")
6099                      (equal keywd "supply")
6100                      (equal keywd "localparam"))
6101                  (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  expect-signal 'sigs-const)))
6102                 ((or (equal keywd "parameter"))
6103                  (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  expect-signal 'sigs-gparam)))
6104                 ((equal keywd "signed")
6105                  (setq signed "signed"))
6106                 ((or (equal keywd "function")
6107                      (equal keywd "task"))
6108                  (setq functask (1+ functask)))
6109                 ((or (equal keywd "endfunction")
6110                      (equal keywd "endtask"))
6111                  (setq functask (1- functask)))
6112                 ((or (equal keywd "`ifdef")
6113                      (equal keywd "`ifndef"))
6114                  (setq rvalue t))
6115                 ((verilog-typedef-name-p keywd)
6116                  (setq typedefed keywd))
6117                 ((and expect-signal
6118                       (eq functask 0)
6119                       (not (member keywd verilog-keywords))
6120                       (not rvalue))
6121                  ;; Add new signal to expect-signal's variable
6122                  (setq newsig (list keywd vec nil nil enum signed typedefed multidim))
6123                  (set expect-signal (cons newsig
6124                                           (symbol-value expect-signal))))))
6125          (t
6126           (forward-char 1)))
6127         (skip-syntax-forward " "))
6128       ;; Return arguments
6129       (vector (nreverse sigs-out)
6130               (nreverse sigs-inout)
6131               (nreverse sigs-in)
6132               (nreverse sigs-wire)
6133               (nreverse sigs-reg)
6134               (nreverse sigs-assign)
6135               (nreverse sigs-const)
6136               (nreverse sigs-gparam)
6137               ))))
6138
6139 (defvar sigs-in nil) ; Prevent compile warning
6140 (defvar sigs-inout nil) ; Prevent compile warning
6141 (defvar sigs-out nil) ; Prevent compile warning
6142
6143 (defun verilog-read-sub-decls-sig (submodi comment port sig vec multidim)
6144   "For verilog-read-sub-decls-line, add a signal."
6145   (let (portdata)
6146     (when sig
6147       (setq port (verilog-symbol-detick-denumber port))
6148       (setq sig  (verilog-symbol-detick-denumber sig))
6149       (if sig (setq sig  (verilog-string-replace-matches "^[---+~!|&]+" "" nil nil sig)))
6150       (if vec (setq vec  (verilog-symbol-detick-denumber vec)))
6151       (if multidim (setq multidim  (mapcar `verilog-symbol-detick-denumber multidim)))
6152       (unless (or (not sig)
6153                   (equal sig ""))  ;; Ignore .foo(1'b1) assignments
6154         (cond ((setq portdata (assoc port (verilog-modi-get-inouts submodi)))
6155                (setq sigs-inout (cons (list sig vec (concat "To/From " comment) nil nil
6156                                             (verilog-sig-signed portdata)
6157                                             (verilog-sig-type portdata)
6158                                             multidim)
6159                                       sigs-inout)))
6160               ((setq portdata (assoc port (verilog-modi-get-outputs submodi)))
6161                (setq sigs-out   (cons (list sig vec (concat "From " comment) nil nil
6162                                             (verilog-sig-signed portdata)
6163                                             (verilog-sig-type portdata)
6164                                             multidim)
6165                                       sigs-out)))
6166               ((setq portdata (assoc port (verilog-modi-get-inputs submodi)))
6167                (setq sigs-in    (cons (list sig vec (concat "To " comment) nil nil
6168                                             (verilog-sig-signed portdata)
6169                                             (verilog-sig-type portdata)
6170                                             multidim)
6171                                       sigs-in)))
6172               ;; (t  -- warning pin isn't defined.)   ; Leave for lint tool
6173               )))))
6174
6175 (defun verilog-read-sub-decls-line (submodi comment)
6176   "For read-sub-decls, read lines of port defs until none match anymore.
6177 Return the list of signals found, using submodi to look up each port."
6178   (let (done port sig vec multidim)
6179     (save-excursion
6180       (forward-line 1)
6181       (while (not done)
6182         ;; Get port name
6183         (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
6184                (setq port (match-string 1))
6185                (goto-char (match-end 0)))
6186               ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
6187                (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
6188                (goto-char (match-end 0)))
6189               ((looking-at "\\s-*\\.[^(]*(")
6190                (setq port nil) ;; skip this line
6191                (goto-char (match-end 0)))
6192               (t
6193                (setq port nil  done t))) ;; Unknown, ignore rest of line
6194         ;; Get signal name
6195         (when port
6196           (setq multidim nil)
6197           (cond ((looking-at "\\(\\\\[^ \t\n\f]*\\)\\s-*)")
6198                  (setq sig (concat (match-string 1) " ") ;; escaped id's need trailing space
6199                        vec nil))
6200                 ; We intentionally ignore (non-escaped) signals with .s in them
6201                 ; this prevents AUTOWIRE etc from noticing hierarchical sigs.
6202                 ((looking-at "\\([^[({).]*\\)\\s-*)")
6203                  (setq sig (verilog-string-remove-spaces (match-string 1))
6204                        vec nil))
6205                 ((looking-at "\\([^[({).]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
6206                  (setq sig (verilog-string-remove-spaces (match-string 1))
6207                        vec (match-string 2)))
6208                 ((looking-at "\\([^[({).]*\\)\\s-*/\\*\\(\\[[^*]+\\]\\)\\*/\\s-*)")
6209                  (setq sig (verilog-string-remove-spaces (match-string 1))
6210                        vec nil)
6211                  (let ((parse (match-string 2)))
6212                    (while (string-match "^\\(\\[[^]]+\\]\\)\\(.*\\)$" parse)
6213                      (when vec (setq multidim (cons vec multidim)))
6214                      (setq vec (match-string 1 parse))
6215                      (setq parse (match-string 2 parse)))))
6216                 ((looking-at "{\\(.*\\)}.*\\s-*)")
6217                  (let ((mlst (split-string (match-string 1) ","))
6218                        mstr)
6219                    (while (setq mstr (pop mlst))
6220                      ;;(unless noninteractive (message "sig: %s " mstr))
6221                      (cond
6222                       ((string-match "\\(['`a-zA-Z0-9_$]+\\)\\s-*$" mstr)
6223                        (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
6224                              vec nil)
6225                        ;;(unless noninteractive (message "concat sig1: %s %s" mstr (match-string 1 mstr)))
6226                        )
6227                       ((string-match "\\([^[({).]+\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*" mstr)
6228                        (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
6229                              vec (match-string 2 mstr))
6230                        ;;(unless noninteractive (message "concat sig2: '%s' '%s' '%s'" mstr (match-string 1 mstr) (match-string 2 mstr)))
6231                        )
6232                       (t
6233                        (setq sig nil)))
6234                      ;; Process signals
6235                      (verilog-read-sub-decls-sig submodi comment port sig vec multidim))))
6236                 (t
6237                  (setq sig nil)))
6238           ;; Process signals
6239           (verilog-read-sub-decls-sig submodi comment port sig vec multidim))
6240         ;;
6241         (forward-line 1)))))
6242
6243 (defun verilog-read-sub-decls ()
6244   "Internally parse signals going to modules under this module.
6245 Return a array of [ outputs inouts inputs ] signals for modules that are
6246 instantiated in this module.  For example if declare A A (.B(SIG)) and SIG
6247 is a output, then SIG will be included in the list.
6248
6249 This only works on instantiations created with /*AUTOINST*/ converted by
6250 \\[verilog-auto-inst].  Otherwise, it would have to read in the whole
6251 component library to determine connectivity of the design.
6252
6253 One work around for this problem is to manually create // Inputs and //
6254 Outputs comments above subcell signals, for example:
6255
6256         module1 instance1x (
6257             // Outputs
6258             .out (out),
6259             // Inputs
6260             .in  (in));"
6261   (save-excursion
6262     (let ((end-mod-point (verilog-get-end-of-defun t))
6263           st-point end-inst-point
6264           ;; below 3 modified by verilog-read-sub-decls-line
6265           sigs-out sigs-inout sigs-in)
6266       (verilog-beg-of-defun)
6267       (while (re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
6268         (save-excursion
6269           (goto-char (match-beginning 0))
6270           (unless (verilog-inside-comment-p)
6271             ;; Attempt to snarf a comment
6272             (let* ((submod (verilog-read-inst-module))
6273                    (inst (verilog-read-inst-name))
6274                    (comment (concat inst " of " submod ".v")) submodi)
6275               (when (setq submodi (verilog-modi-lookup submod t))
6276                 ;; This could have used a list created by verilog-auto-inst
6277                 ;; However I want it to be runnable even on user's manually added signals
6278                 (verilog-backward-open-paren)
6279                 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
6280                       st-point (point))
6281                 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
6282                   (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-out
6283                 (goto-char st-point)
6284                 (while (re-search-forward "\\s *// Inouts" end-inst-point t)
6285                   (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-inout
6286                 (goto-char st-point)
6287                 (while (re-search-forward "\\s *// Inputs" end-inst-point t)
6288                   (verilog-read-sub-decls-line submodi comment)) ;; Modifies sigs-in
6289                 )))))
6290       ;; Combine duplicate bits
6291       ;;(setq rr (vector sigs-out sigs-inout sigs-in))
6292       (vector (verilog-signals-combine-bus (nreverse sigs-out))
6293               (verilog-signals-combine-bus (nreverse sigs-inout))
6294               (verilog-signals-combine-bus (nreverse sigs-in))))))
6295
6296 (defun verilog-read-inst-pins ()
6297   "Return a array of [ pins ] for the current instantiation at point.
6298 For example if declare A A (.B(SIG)) then B will be included in the list."
6299   (save-excursion
6300     (let ((end-mod-point (point))       ;; presume at /*AUTOINST*/ point
6301           pins pin)
6302       (verilog-backward-open-paren)
6303       (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
6304         (setq pin (match-string 1))
6305         (unless (verilog-inside-comment-p)
6306           (setq pins (cons (list pin) pins))
6307           (when (looking-at "(")
6308             (forward-sexp 1))))
6309       (vector pins))))
6310
6311 (defun verilog-read-arg-pins ()
6312   "Return a array of [ pins ] for the current argument declaration at point."
6313   (save-excursion
6314     (let ((end-mod-point (point))       ;; presume at /*AUTOARG*/ point
6315           pins pin)
6316       (verilog-backward-open-paren)
6317       (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
6318         (setq pin (match-string 1))
6319         (unless (verilog-inside-comment-p)
6320           (setq pins (cons (list pin) pins))))
6321       (vector pins))))
6322
6323 (defun verilog-read-auto-constants (beg end-mod-point)
6324   "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
6325   ;; Insert new
6326   (save-excursion
6327     (let (sig-list tpl-end-pt)
6328       (goto-char beg)
6329       (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
6330         (if (not (looking-at "\\s *("))
6331             (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
6332         (search-forward "(" end-mod-point)
6333         (setq tpl-end-pt (save-excursion
6334                            (backward-char 1)
6335                            (forward-sexp 1)   ;; Moves to paren that closes argdecl's
6336                            (backward-char 1)
6337                            (point)))
6338         (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
6339           (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
6340       sig-list)))
6341
6342 (defun verilog-read-auto-lisp (start end)
6343   "Look for and evaluate a AUTO_LISP between START and END."
6344   (save-excursion
6345     (goto-char start)
6346     (while (re-search-forward "\\<AUTO_LISP(" end t)
6347       (backward-char)
6348       (let* ((beg-pt (prog1 (point)
6349                        (forward-sexp 1)))       ;; Closing paren
6350              (end-pt (point)))
6351         (eval-region beg-pt end-pt nil)))))
6352
6353 (eval-when-compile
6354   ;; These are passed in a let, not global
6355   (if (not (boundp 'sigs-in))
6356       (defvar sigs-in nil) (defvar sigs-out nil)
6357       (defvar got-sig nil) (defvar got-rvalue nil) (defvar uses-delayed nil)))
6358
6359 (defun verilog-read-always-signals-recurse
6360   (exit-keywd rvalue ignore-next)
6361   "Recursive routine for parentheses/bracket matching.
6362 EXIT-KEYWD is expression to stop at, nil if top level.
6363 RVALUE is true if at right hand side of equal.
6364 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
6365   (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
6366          keywd last-keywd sig-tolk sig-last-tolk gotend end-else-check)
6367     ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue ignore-next))))
6368     (while (not (or (eobp) gotend))
6369       (cond
6370        ((looking-at "//")
6371         (search-forward "\n"))
6372        ((looking-at "/\\*")
6373         (or (search-forward "*/")
6374             (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6375        ((looking-at "(\\*")
6376         (or (looking-at "(\\*\\s-*)")   ; It's a "always @ (*)"
6377             (search-forward "*)")
6378             (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
6379        (t (setq keywd (buffer-substring-no-properties
6380                        (point)
6381                        (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
6382                                          (forward-char 1))
6383                                        (point)))
6384                 sig-last-tolk sig-tolk
6385                 sig-tolk nil)
6386           ;;(if dbg (setq dbg (concat dbg (format "\tPt %S %S\t%S %S %S\n" (point) keywd rvalue ignore-next end-else-check))))
6387           (cond
6388            ((equal keywd "\"")
6389             (or (re-search-forward "[^\\]\"" nil t)
6390                 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
6391            ;; else at top level loop, keep parsing
6392            ((and end-else-check (equal keywd "else"))
6393             ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
6394             ;; no forward movement, want to see else in lower loop
6395             (setq end-else-check nil))
6396            ;; End at top level loop
6397            ((and end-else-check (looking-at "[^ \t\n\f]"))
6398             ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
6399             (setq gotend t))
6400            ;; Final statement?
6401            ((and exit-keywd (equal keywd exit-keywd))
6402             (setq gotend t)
6403             (forward-char (length keywd)))
6404            ;; Standard tokens...
6405            ((equal keywd ";")
6406             (setq ignore-next nil rvalue semi-rvalue)
6407             ;; Final statement at top level loop?
6408             (when (not exit-keywd)
6409               ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
6410               (setq end-else-check t))
6411             (forward-char 1))
6412            ((equal keywd "'")
6413             (if (looking-at "'s?[hdxbo][0-9a-fA-F_xz? \t]*")
6414                 (goto-char (match-end 0))
6415               (forward-char 1)))
6416            ((equal keywd ":")   ;; Case statement, begin/end label, x?y:z
6417             (cond ((equal "endcase" exit-keywd)  ;; case x: y=z; statement next
6418                    (setq ignore-next nil rvalue nil))
6419                   ((not rvalue) ;; begin label
6420                    (setq ignore-next t rvalue nil)))
6421             (forward-char 1))
6422            ((equal keywd "=")
6423             (if (eq (char-before) ?< )
6424                 (setq uses-delayed 1))
6425             (setq ignore-next nil rvalue t)
6426             (forward-char 1))
6427            ((equal keywd "?")
6428             (forward-char 1)
6429             (verilog-read-always-signals-recurse ":" rvalue nil))
6430            ((equal keywd "[")
6431             (forward-char 1)
6432             (verilog-read-always-signals-recurse "]" t nil))
6433            ((equal keywd "(")
6434             (forward-char 1)
6435             (cond (sig-last-tolk        ;; Function call; zap last signal
6436                    (setq got-sig nil)))
6437             (cond ((equal last-keywd "for")
6438                    (verilog-read-always-signals-recurse ";" nil nil)
6439                    (verilog-read-always-signals-recurse ";" t nil)
6440                    (verilog-read-always-signals-recurse ")" nil nil))
6441                   (t (verilog-read-always-signals-recurse ")" t nil))))
6442            ((equal keywd "begin")
6443             (skip-syntax-forward "w_")
6444             (verilog-read-always-signals-recurse "end" nil nil)
6445             ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
6446             (setq ignore-next nil rvalue semi-rvalue)
6447             (if (not exit-keywd) (setq end-else-check t)))
6448            ((or (equal keywd "case")
6449                 (equal keywd "casex")
6450                 (equal keywd "casez"))
6451             (skip-syntax-forward "w_")
6452             (verilog-read-always-signals-recurse "endcase" t nil)
6453             (setq ignore-next nil rvalue semi-rvalue)
6454             (if (not exit-keywd) (setq gotend t)))      ;; top level begin/end
6455            ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
6456             (cond ((or (equal keywd "`ifdef")
6457                        (equal keywd "`ifndef"))
6458                    (setq ignore-next t))
6459                   ((or ignore-next
6460                        (member keywd verilog-keywords)
6461                        (string-match "^\\$" keywd))     ;; PLI task
6462                    (setq ignore-next nil))
6463                   (t
6464                    (setq keywd (verilog-symbol-detick-denumber keywd))
6465                    (if got-sig (if got-rvalue
6466                                    (setq sigs-in (cons got-sig sigs-in))
6467                                  (setq sigs-out (cons got-sig sigs-out))))
6468                    (setq got-rvalue rvalue
6469                          got-sig (if (or (not keywd)
6470                                          (assoc keywd (if got-rvalue sigs-in sigs-out)))
6471                                      nil (list keywd nil nil))
6472                          sig-tolk t)))
6473             (skip-chars-forward "a-zA-Z0-9$_.%`"))
6474            (t
6475             (forward-char 1)))
6476           ;; End of non-comment token
6477           (setq last-keywd keywd)
6478           ))
6479       (skip-syntax-forward " "))
6480     ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
6481     ))
6482
6483 (defun verilog-read-always-signals ()
6484   "Parse always block at point and return list of (outputs inout inputs)."
6485   ;; Insert new
6486   (save-excursion
6487     (let* (;;(dbg "")
6488            sigs-in sigs-out
6489            got-sig got-rvalue
6490            uses-delayed)        ;; Found signal/rvalue; push if not function
6491       (search-forward ")")
6492       (verilog-read-always-signals-recurse nil nil nil)
6493       ;; Return what was found
6494       (if got-sig (if got-rvalue
6495                       (setq sigs-in (cons got-sig sigs-in))
6496                     (setq sigs-out (cons got-sig sigs-out))))
6497       ;;(if dbg (message dbg))
6498       (list sigs-out nil sigs-in uses-delayed))))
6499
6500 (defun verilog-read-instants ()
6501   "Parse module at point and return list of ( ( file instance ) ... )."
6502   (verilog-beg-of-defun)
6503   (let* ((end-mod-point (verilog-get-end-of-defun t))
6504          (state nil)
6505          (instants-list nil))
6506     (save-excursion
6507       (while (< (point) end-mod-point)
6508         ;; Stay at level 0, no comments
6509         (while (progn
6510                  (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
6511                  (or (> (car state) 0)  ; in parens
6512                      (nth 5 state)              ; comment
6513                      ))
6514           (forward-line 1))
6515         (beginning-of-line)
6516         (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
6517             ;;(if (looking-at "^\\(.+\\)$")
6518             (let ((module (match-string 1))
6519                   (instant (match-string 2)))
6520               (if (not (member module verilog-keywords))
6521                   (setq instants-list (cons (list module instant) instants-list)))))
6522         (forward-line 1)
6523         ))
6524     instants-list))
6525
6526
6527 (defun verilog-read-auto-template (module)
6528   "Look for a auto_template for the instantiation of the given MODULE.
6529 If found returns the signal name connections.  Return REGEXP and
6530 list of ( (signal_name connection_name)... )"
6531   (save-excursion
6532     ;; Find beginning
6533     (let ((tpl-regexp "\\([0-9]+\\)")
6534           (lineno 0)
6535           (templateno 0)
6536           tpl-sig-list tpl-wild-list tpl-end-pt rep)
6537       (cond ((or
6538                (re-search-backward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
6539                (progn
6540                  (goto-char (point-min))
6541                  (re-search-forward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
6542              (goto-char (match-end 0))
6543              ;; Parse "REGEXP"
6544              ;; We reserve @"..." for future lisp expressions that evaluate once-per-AUTOINST
6545              (when (looking-at "\\s-*\"\\([^\"]*)\\)\"")
6546                (setq tpl-regexp (match-string 1))
6547                (goto-char (match-end 0)))
6548              (search-forward "(")
6549              ;; Parse lines in the template
6550              (when verilog-auto-inst-template-numbers
6551                (save-excursion
6552                  (goto-char (point-min))
6553                  (while (search-forward "AUTO_TEMPLATE" nil t)
6554                    (setq templateno (1+ templateno)))))
6555              (setq tpl-end-pt (save-excursion
6556                                 (backward-char 1)
6557                                 (forward-sexp 1)   ;; Moves to paren that closes argdecl's
6558                                 (backward-char 1)
6559                                 (point)))
6560              ;;
6561              (while (< (point) tpl-end-pt)
6562                (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
6563                       (setq tpl-sig-list (cons (list
6564                                                 (match-string-no-properties 1)
6565                                                 (match-string-no-properties 2)
6566                                                 templateno lineno)
6567                                                tpl-sig-list))
6568                       (goto-char (match-end 0)))
6569                      ;; Regexp form??
6570                      ((looking-at
6571                        ;; Regexp bug in xemacs disallows ][ inside [], and wants + last
6572                        "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
6573                       (setq rep (match-string-no-properties 3))
6574                       (goto-char (match-end 0))
6575                       (setq tpl-wild-list
6576                             (cons (list
6577                                    (concat "^"
6578                                            (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
6579                                                                            (match-string 1))
6580                                            "$")
6581                                    rep
6582                                    templateno lineno)
6583                                   tpl-wild-list)))
6584                      ((looking-at "[ \t\f]+")
6585                       (goto-char (match-end 0)))
6586                      ((looking-at "\n")
6587                       (setq lineno (1+ lineno))
6588                       (goto-char (match-end 0)))
6589                      ((looking-at "//")
6590                       (search-forward "\n"))
6591                      ((looking-at "/\\*")
6592                       (forward-char 2)
6593                       (or (search-forward "*/")
6594                           (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6595                      (t
6596                       (error "%s: AUTO_TEMPLATE parsing error: %s"
6597                              (verilog-point-text)
6598                              (progn (looking-at ".*$") (match-string 0))))
6599                      ))
6600              ;; Return
6601              (vector tpl-regexp
6602                      (list tpl-sig-list tpl-wild-list)))
6603             ;; If no template found
6604             (t (vector tpl-regexp nil))))))
6605 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
6606
6607 (defun verilog-set-define (defname defvalue &optional buffer enumname)
6608   "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
6609 Optionally associate it with the specified enumeration ENUMNAME."
6610   (save-excursion
6611     (set-buffer (or buffer (current-buffer)))
6612     (let ((mac (intern (concat "vh-" defname))))
6613       ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
6614       ;; Need to define to a constant if no value given
6615       (set (make-variable-buffer-local mac)
6616            (if (equal defvalue "") "1" defvalue)))
6617     (if enumname
6618         (let ((enumvar (intern (concat "venum-" enumname))))
6619           ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
6620           (make-variable-buffer-local enumvar)
6621           (add-to-list enumvar defname)))
6622     ))
6623
6624 (defun verilog-read-defines (&optional filename recurse subcall)
6625   "Read `defines and parameters for the current file, or optional FILENAME.
6626 If the filename is provided, `verilog-library-flags' will be used to
6627 resolve it.  If optional RECURSE is non-nil, recurse through `includes.
6628
6629 Parameters must be simple assignments to constants, or have their own
6630 \"parameter\" label rather then a list of parameters.  Thus:
6631
6632     parameter X = 5, Y = 10;    // Ok
6633     parameter X = {1'b1, 2'h2}; // Ok
6634     parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
6635
6636 Defines must be simple text substitutions, one on a line, starting
6637 at the beginning of the line.  Any ifdefs or multiline comments around the
6638 define are ignored.
6639
6640 Defines are stored inside Emacs variables using the name vh-{definename}.
6641
6642 This function is useful for setting vh-* variables.  The file variables
6643 feature can be used to set defines that `verilog-mode' can see; put at the
6644 *END* of your file something like:
6645
6646     // Local Variables:
6647     // vh-macro:\"macro_definition\"
6648     // End:
6649
6650 If macros are defined earlier in the same file and you want their values,
6651 you can read them automatically (provided `enable-local-eval' is on):
6652
6653     // Local Variables:
6654     // eval:(verilog-read-defines)
6655     // eval:(verilog-read-defines \"group_standard_includes.v\")
6656     // End:
6657
6658 Note these are only read when the file is first visited, you must use
6659 \\[find-alternate-file] RET  to have these take effect after editing them!
6660
6661 If you want to disable the \"Process `eval' or hook local variables\"
6662 warning message, you need to add to your .emacs file:
6663
6664     (setq enable-local-eval t)"
6665   (let ((origbuf (current-buffer)))
6666     (save-excursion
6667       (unless subcall (verilog-getopt-flags))
6668       (when filename
6669         (let ((fns (verilog-library-filenames filename (buffer-file-name))))
6670           (if fns
6671               (set-buffer (find-file-noselect (car fns)))
6672             (error (concat (verilog-point-text)
6673                            ": Can't find verilog-read-defines file: " filename)))))
6674       (when recurse
6675         (goto-char (point-min))
6676         (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
6677           (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string-no-properties 1))))
6678             (unless (verilog-inside-comment-p)
6679               (verilog-read-defines inc recurse t)))))
6680       ;; Read `defines
6681       ;; note we don't use verilog-re... it's faster this way, and that
6682       ;; function has problems when comments are at the end of the define
6683       (goto-char (point-min))
6684       (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
6685         (let ((defname (match-string-no-properties 1))
6686               (defvalue (match-string-no-properties 2)))
6687           (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
6688           (verilog-set-define defname defvalue origbuf)))
6689       ;; Hack: Read parameters
6690       (goto-char (point-min))
6691       (while (re-search-forward
6692               "^\\s-*\\(parameter\\|localparam\\)\\(\\(\\s-*\\[[^]]*\\]\\|\\)\\s-+\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\|\\)\\s-*" nil t)
6693         (let ((var (match-string-no-properties 4))
6694               (val (match-string-no-properties 5))
6695               enumname)
6696           ;; The primary way of getting defines is verilog-read-decls
6697           ;; However, that isn't called yet for included files, so we'll add another scheme
6698           (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6699               (setq enumname (match-string-no-properties 1)))
6700           (if var
6701             (verilog-set-define var val origbuf enumname))
6702           (forward-comment 999)
6703           (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
6704             (verilog-set-define (match-string-no-properties 1) (match-string-no-properties 2) origbuf enumname)
6705             (goto-char (match-end 0))
6706             (forward-comment 999))))
6707       )))
6708
6709 (defun verilog-read-includes ()
6710   "Read `includes for the current file.
6711 This will find all of the `includes which are at the beginning of lines,
6712 ignoring any ifdefs or multiline comments around them.
6713 `verilog-read-defines' is then performed on the current and each included
6714 file.
6715
6716 It is often useful put at the *END* of your file something like:
6717
6718     // Local Variables:
6719     // eval:(verilog-read-defines)
6720     // eval:(verilog-read-includes)
6721     // End:
6722
6723 Note includes are only read when the file is first visited, you must use
6724 \\[find-alternate-file] RET  to have these take effect after editing them!
6725
6726 It is good to get in the habit of including all needed files in each .v
6727 file that needs it, rather then waiting for compile time.  This will aid
6728 this process, Verilint, and readability.  To prevent defining the same
6729 variable over and over when many modules are compiled together, put a test
6730 around the inside each include file:
6731
6732 foo.v (a include):
6733         `ifdef _FOO_V   // include if not already included
6734         `else
6735         `define _FOO_V
6736         ... contents of file
6737         `endif // _FOO_V"
6738 ;;slow:  (verilog-read-defines nil t))
6739   (save-excursion
6740     (verilog-getopt-flags)
6741     (goto-char (point-min))
6742     (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
6743       (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
6744         (verilog-read-defines inc nil t)))))
6745
6746 (defun verilog-read-signals (&optional start end)
6747   "Return a simple list of all possible signals in the file.
6748 Bounded by optional region from START to END.  Overly aggressive but fast.
6749 Some macros and such are also found and included.  For dinotrace.el"
6750   (let (sigs-all keywd)
6751     (progn;save-excursion
6752       (goto-char (or start (point-min)))
6753       (setq end (or end (point-max)))
6754       (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
6755         (forward-char -1)
6756         (cond
6757          ((looking-at "//")
6758           (search-forward "\n"))
6759          ((looking-at "/\\*")
6760           (search-forward "*/"))
6761          ((looking-at "(\\*")
6762           (or (looking-at "(\\*\\s-*)")   ; It's a "always @ (*)"
6763               (search-forward "*)")))
6764          ((eq ?\" (following-char))
6765           (re-search-forward "[^\\]\""))        ;; don't forward-char first, since we look for a non backslash first
6766          ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
6767           (goto-char (match-end 0))
6768           (setq keywd (match-string-no-properties 1))
6769           (or (member keywd verilog-keywords)
6770               (member keywd sigs-all)
6771               (setq sigs-all (cons keywd sigs-all))))
6772          (t (forward-char 1)))
6773         )
6774       ;; Return list
6775       sigs-all)))
6776
6777 ;;
6778 ;; Argument file parsing
6779 ;;
6780
6781 (defun verilog-getopt (arglist)
6782   "Parse -f, -v etc arguments in ARGLIST list or string."
6783   (unless (listp arglist) (setq arglist (list arglist)))
6784   (let ((space-args '())
6785         arg next-param)
6786     ;; Split on spaces, so users can pass whole command lines
6787     (while arglist
6788       (setq arg (car arglist)
6789             arglist (cdr arglist))
6790       (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
6791         (setq space-args (append space-args
6792                                  (list (match-string-no-properties 1 arg))))
6793         (setq arg (match-string 2 arg))))
6794     ;; Parse arguments
6795     (while space-args
6796       (setq arg (car space-args)
6797             space-args (cdr space-args))
6798       (cond
6799        ;; Need another arg
6800        ((equal arg "-f")
6801         (setq next-param arg))
6802        ((equal arg "-v")
6803         (setq next-param arg))
6804        ((equal arg "-y")
6805         (setq next-param arg))
6806        ;; +libext+(ext1)+(ext2)...
6807        ((string-match "^\\+libext\\+\\(.*\\)" arg)
6808         (setq arg (match-string 1 arg))
6809         (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
6810           (verilog-add-list-unique `verilog-library-extensions
6811                                    (match-string 1 arg))
6812           (setq arg (match-string 2 arg))))
6813        ;;
6814        ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg)    ;; -Ddefine=val
6815             (string-match "^-D\\([^+=]*\\)\\(\\)" arg)  ;; -Ddefine
6816             (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg)     ;; +define+val
6817             (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg))          ;; +define+define
6818         (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
6819        ;;
6820        ((or (string-match "^\\+incdir\\+\\(.*\\)" arg)  ;; +incdir+dir
6821             (string-match "^-I\\(.*\\)" arg))   ;; -Idir
6822         (verilog-add-list-unique `verilog-library-directories
6823                                  (match-string 1 arg)))
6824        ;; Ignore
6825        ((equal "+librescan" arg))
6826        ((string-match "^-U\\(.*\\)" arg))       ;; -Udefine
6827        ;; Second parameters
6828        ((equal next-param "-f")
6829         (setq next-param nil)
6830         (verilog-getopt-file arg))
6831        ((equal next-param "-v")
6832         (setq next-param nil)
6833         (verilog-add-list-unique `verilog-library-files arg))
6834        ((equal next-param "-y")
6835         (setq next-param nil)
6836         (verilog-add-list-unique `verilog-library-directories arg))
6837        ;; Filename
6838        ((string-match "^[^-+]" arg)
6839         (verilog-add-list-unique `verilog-library-files arg))
6840        ;; Default - ignore; no warning
6841        )
6842       )
6843     )
6844   )
6845 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
6846
6847 (defun verilog-getopt-file (filename)
6848   "Read verilog options from the specified FILENAME."
6849   (save-excursion
6850     (let ((fns (verilog-library-filenames filename (buffer-file-name)))
6851           (orig-buffer (current-buffer))
6852           line)
6853       (if fns
6854           (set-buffer (find-file-noselect (car fns)))
6855         (error (concat (verilog-point-text)
6856                        "Can't find verilog-getopt-file -f file: " filename)))
6857       (goto-char (point-min))
6858       (while (not (eobp))
6859         (setq line (buffer-substring (point)
6860                                      (save-excursion (end-of-line) (point))))
6861         (forward-line 1)
6862         (when (string-match "//" line)
6863           (setq line (substring line 0 (match-beginning 0))))
6864         (save-excursion
6865           (set-buffer orig-buffer)  ; Variables are buffer-local, so need right context.
6866           (verilog-getopt line))))))
6867
6868 (defun verilog-getopt-flags ()
6869   "Convert `verilog-library-flags' into standard library variables."
6870   ;; If the flags are local, then all the outputs should be local also
6871   (when (local-variable-p `verilog-library-flags (current-buffer))
6872     (make-variable-buffer-local 'verilog-library-extensions)
6873     (make-variable-buffer-local 'verilog-library-directories)
6874     (make-variable-buffer-local 'verilog-library-files)
6875     (make-variable-buffer-local 'verilog-library-flags))
6876   ;; Allow user to customize
6877   (run-hooks 'verilog-before-getopt-flags-hook)
6878   ;; Process arguments
6879   (verilog-getopt verilog-library-flags)
6880   ;; Allow user to customize
6881   (run-hooks 'verilog-getopt-flags-hook))
6882
6883 (defun verilog-add-list-unique (varref object)
6884   "Append to VARREF list the given OBJECT,
6885 unless it is already a member of the variable's list"
6886   (unless (member object (symbol-value varref))
6887     (set varref (append (symbol-value varref) (list object))))
6888   varref)
6889 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
6890
6891 \f
6892 ;;
6893 ;; Module name lookup
6894 ;;
6895
6896 (defun verilog-module-inside-filename-p (module filename)
6897   "Return point if MODULE is specified inside FILENAME, else nil.
6898 Allows version control to check out the file if need be."
6899   (and (or (file-exists-p filename)
6900            (and
6901             (condition-case nil
6902                 (fboundp 'vc-backend)
6903               (error nil))
6904             (vc-backend filename)))
6905        (let (pt)
6906          (save-excursion
6907            (set-buffer (find-file-noselect filename))
6908            (goto-char (point-min))
6909            (while (and
6910                    ;; It may be tempting to look for verilog-defun-re, don't, it slows things down a lot!
6911                    (verilog-re-search-forward-quick "\\<module\\>" nil t)
6912                    (verilog-re-search-forward-quick "[(;]" nil t))
6913              (if (equal module (verilog-read-module-name))
6914                  (setq pt (point))))
6915            pt))))
6916
6917 (defun verilog-is-number (symbol)
6918   "Return true if SYMBOL is number-like."
6919   (or (string-match "^[0-9 \t:]+$" symbol)
6920       (string-match "^[---]*[0-9]+$" symbol)
6921       (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)
6922       ))
6923
6924 (defun verilog-symbol-detick (symbol wing-it)
6925   "Return a expanded SYMBOL name without any defines.
6926 If the variable vh-{symbol} is defined, return that value.
6927 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
6928   (while (and symbol (string-match "^`" symbol))
6929     (setq symbol (substring symbol 1))
6930     (setq symbol
6931           (if (boundp (intern (concat "vh-" symbol)))
6932               ;; Emacs has a bug where boundp on a buffer-local variable in only one
6933               ;; buffer returns t in another.  This can confuse, so check for nil.
6934               (let ((val (eval (intern (concat "vh-" symbol)))))
6935                 (if (eq val nil)
6936                     (if wing-it symbol nil)
6937                   val))
6938             (if wing-it symbol nil))))
6939   symbol)
6940 ;;(verilog-symbol-detick "`mod" nil)
6941
6942 (defun verilog-symbol-detick-denumber (symbol)
6943   "Return SYMBOL with defines converted and any numbers dropped to nil."
6944   (when (string-match "^`" symbol)
6945     ;; This only will work if the define is a simple signal, not
6946     ;; something like a[b].  Sorry, it should be substituted into the parser
6947     (setq symbol
6948           (verilog-string-replace-matches
6949            "\[[^0-9: \t]+\]" "" nil nil
6950            (or (verilog-symbol-detick symbol nil)
6951                (if verilog-auto-sense-defines-constant
6952                    "0"
6953                  symbol)))))
6954   (if (verilog-is-number symbol)
6955       nil
6956     symbol))
6957
6958 (defun verilog-expand-dirnames (&optional dirnames)
6959   "Return a list of existing directories given a list of wildcarded DIRNAMES.
6960 Or, just the existing dirnames themselves if there are no wildcards."
6961   (interactive)
6962   (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
6963   (setq dirnames (reverse dirnames))    ; not nreverse
6964   (let ((dirlist nil)
6965         pattern dirfile dirfiles dirname root filename rest)
6966     (while dirnames
6967       (setq dirname (substitute-in-file-name (car dirnames))
6968             dirnames (cdr dirnames))
6969       (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)"  ;; root
6970                                    "\\([^/\\]*[*?][^/\\]*\\)"     ;; filename with *?
6971                                    "\\(.*\\)")                    ;; rest
6972                            dirname)
6973              (setq root (match-string 1 dirname)
6974                    filename (match-string 2 dirname)
6975                    rest (match-string 3 dirname)
6976                    pattern filename)
6977              ;; now replace those * and ? with .+ and .
6978              ;; use ^ and /> to get only whole file names
6979              ;;verilog-string-replace-matches
6980              (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
6981                    pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
6982
6983                    ;; Unfortunately allows abc/*/rtl to match abc/rtl
6984                    ;; because abc/.. shows up in dirfiles.  Solutions welcome.
6985                    dirfiles (if (file-directory-p root) ; Ignore version control external
6986                                 (directory-files root t pattern nil)))
6987              (while dirfiles
6988                (setq dirfile (expand-file-name (concat (car dirfiles) rest))
6989                      dirfiles (cdr dirfiles))
6990                (if (file-directory-p dirfile)
6991                    (setq dirlist (cons dirfile dirlist))))
6992              )
6993             ;; Defaults
6994             (t
6995              (if (file-directory-p dirname)
6996                  (setq dirlist (cons dirname dirlist))))
6997             ))
6998     dirlist))
6999 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
7000
7001 (defun verilog-library-filenames (filename current &optional check-ext)
7002   "Return a search path to find the given FILENAME name.
7003 Uses the CURRENT filename, `verilog-library-directories' and
7004 `verilog-library-extensions' variables to build the path.
7005 With optional CHECK-EXT also check `verilog-library-extensions'."
7006   (let ((ckdir (verilog-expand-dirnames verilog-library-directories))
7007         fn outlist)
7008     (while ckdir
7009       (let ((ckext (if check-ext verilog-library-extensions `(""))))
7010         (while ckext
7011           (setq fn (expand-file-name
7012                     (concat filename (car ckext))
7013                     (expand-file-name (car ckdir) (file-name-directory current))))
7014           (if (file-exists-p fn)
7015               (setq outlist (cons fn outlist)))
7016           (setq ckext (cdr ckext))))
7017       (setq ckdir (cdr ckdir)))
7018     (nreverse outlist)))
7019
7020 (defun verilog-module-filenames (module current)
7021   "Return a search path to find the given MODULE name.
7022 Uses the CURRENT filename, `verilog-library-extensions',
7023 `verilog-library-directories' and `verilog-library-files'
7024 variables to build the path."
7025   ;; Return search locations for it
7026   (append (list current)                ; first, current buffer
7027           (verilog-library-filenames module current t)
7028           verilog-library-files))       ; finally, any libraries
7029
7030 ;;
7031 ;; Module Information
7032 ;;
7033 ;; Many of these functions work on "modi" a module information structure
7034 ;; A modi is:  [module-name-string file-name begin-point]
7035
7036 (defvar verilog-cache-enabled t
7037   "If true, enable caching of signals, etc.  Set to nil for debugging to make things SLOW!")
7038
7039 (defvar verilog-modi-cache-list nil
7040   "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
7041 For speeding up verilog-modi-get-* commands.
7042 Buffer-local.")
7043
7044 (defvar verilog-modi-cache-preserve-tick nil
7045   "Modification tick after which the cache is still considered valid.
7046 Use verilog-preserve-cache's to set")
7047 (defvar verilog-modi-cache-preserve-buffer nil
7048   "Modification tick after which the cache is still considered valid.
7049 Use verilog-preserve-cache's to set")
7050
7051 (defun verilog-modi-current ()
7052   "Return the modi structure for the module currently at point."
7053   (let* (name pt)
7054     ;; read current module's name
7055     (save-excursion
7056       (verilog-re-search-backward-quick verilog-defun-re nil nil)
7057       (verilog-re-search-forward-quick "(" nil nil)
7058       (setq name (verilog-read-module-name))
7059       (setq pt (point)))
7060     ;; return
7061     (vector name (or (buffer-file-name) (current-buffer)) pt)))
7062
7063 (defvar verilog-modi-lookup-last-mod nil "Cache of last module looked up.")
7064 (defvar verilog-modi-lookup-last-modi nil "Cache of last modi returned.")
7065 (defvar verilog-modi-lookup-last-current nil "Cache of last `current-buffer' looked up.")
7066 (defvar verilog-modi-lookup-last-tick nil "Cache of last `buffer-modified-tick' looked up.")
7067
7068 (defun verilog-modi-lookup (module allow-cache)
7069   "Find the file and point at which MODULE is defined.
7070 If ALLOW-CACHE is set, check and remember cache of previous lookups.
7071 Return modi if successful, else print message."
7072   (let* ((current (or (buffer-file-name) (current-buffer))))
7073     (cond ((and verilog-modi-lookup-last-modi
7074                 verilog-cache-enabled
7075                 allow-cache
7076                 (equal verilog-modi-lookup-last-mod module)
7077                 (equal verilog-modi-lookup-last-current current)
7078                 (equal verilog-modi-lookup-last-tick (buffer-modified-tick)))
7079            ;; ok as is
7080            )
7081           (t (let* ((realmod (verilog-symbol-detick module t))
7082                     (orig-filenames (verilog-module-filenames realmod current))
7083                     (filenames orig-filenames)
7084                     pt)
7085                (while (and filenames (not pt))
7086                  (if (not (setq pt (verilog-module-inside-filename-p realmod (car filenames))))
7087                      (setq filenames (cdr filenames))))
7088                (cond (pt (setq verilog-modi-lookup-last-modi
7089                                (vector realmod (car filenames) pt)))
7090                      (t (setq verilog-modi-lookup-last-modi nil)
7091                         (error (concat (verilog-point-text)
7092                                        ": Can't locate " module " module definition"
7093                                        (if (not (equal module realmod))
7094                                            (concat " (Expanded macro to " realmod ")")
7095                                          "")
7096                                        "\n    Check the verilog-library-directories variable."
7097                                        "\n    I looked in (if not listed, doesn't exist):\n\t" (mapconcat 'concat orig-filenames "\n\t"))))
7098                      )
7099                (setq verilog-modi-lookup-last-mod module
7100                      verilog-modi-lookup-last-current current
7101                      verilog-modi-lookup-last-tick (buffer-modified-tick)))))
7102     verilog-modi-lookup-last-modi
7103     ))
7104
7105 (defsubst verilog-modi-name (modi)
7106   (aref modi 0))
7107 (defsubst verilog-modi-file-or-buffer (modi)
7108   (aref modi 1))
7109 (defsubst verilog-modi-point (modi)
7110   (aref modi 2))
7111
7112 (defun verilog-modi-filename (modi)
7113   "Filename of MODI, or name of buffer if its never been saved."
7114   (if (bufferp (verilog-modi-file-or-buffer modi))
7115       (or (buffer-file-name (verilog-modi-file-or-buffer modi))
7116           (buffer-name (verilog-modi-file-or-buffer modi)))
7117     (verilog-modi-file-or-buffer modi)))
7118
7119 (defun verilog-modi-goto (modi)
7120   "Move point/buffer to specified MODI."
7121   (or modi (error "Passed unfound modi to goto, check earlier"))
7122   (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
7123                   (verilog-modi-file-or-buffer modi)
7124                 (find-file-noselect (verilog-modi-file-or-buffer modi))))
7125   (or (equal major-mode `verilog-mode)  ;; Put into verilog mode to get syntax
7126       (verilog-mode))
7127   (goto-char (verilog-modi-point modi)))
7128
7129 (defun verilog-goto-defun-file (module)
7130   "Move point to the file at which a given MODULE is defined."
7131   (interactive "sGoto File for Module: ")
7132   (let* ((modi (verilog-modi-lookup module nil)))
7133     (when modi
7134       (verilog-modi-goto modi)
7135       (switch-to-buffer (current-buffer)))))
7136
7137 (defun verilog-modi-cache-results (modi function)
7138   "Run on MODI the given FUNCTION.  Locate the module in a file.
7139 Cache the output of function so next call may have faster access."
7140   (let (func-returns fass)
7141     (save-excursion
7142       (verilog-modi-goto modi)
7143       (if (and (setq fass (assoc (list (verilog-modi-name modi) function)
7144                                  verilog-modi-cache-list))
7145                ;; Destroy caching when incorrect; Modified or file changed
7146                (not (and verilog-cache-enabled
7147                          (or (equal (buffer-modified-tick) (nth 1 fass))
7148                              (and verilog-modi-cache-preserve-tick
7149                                   (<= verilog-modi-cache-preserve-tick  (nth 1 fass))
7150                                   (equal  verilog-modi-cache-preserve-buffer (current-buffer))))
7151                          (equal (visited-file-modtime) (nth 2 fass)))))
7152           (setq verilog-modi-cache-list nil
7153                 fass nil))
7154       (cond (fass
7155              ;; Found
7156              (setq func-returns (nth 3 fass)))
7157             (t
7158              ;; Read from file
7159              ;; Clear then restore any hilighting to make emacs19 happy
7160              (let ((fontlocked (when (and (memq 'v19 verilog-emacs-features)
7161                                           (boundp 'font-lock-mode)
7162                                           font-lock-mode)
7163                                  (font-lock-mode nil)
7164                                  t)))
7165                (setq func-returns (funcall function))
7166                (when fontlocked (font-lock-mode t)))
7167              ;; Cache for next time
7168              (make-variable-buffer-local 'verilog-modi-cache-list)
7169              (setq verilog-modi-cache-list
7170                    (cons (list (list (verilog-modi-name modi) function)
7171                                (buffer-modified-tick)
7172                                (visited-file-modtime)
7173                                func-returns)
7174                          verilog-modi-cache-list)))
7175             ))
7176       ;;
7177       func-returns))
7178
7179 (defun verilog-modi-cache-add (modi function element sig-list)
7180   "Add function return results to the module cache.
7181 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
7182 function now contains the additional SIG-LIST parameters."
7183   (let (fass)
7184     (save-excursion
7185       (verilog-modi-goto modi)
7186       (if (setq fass (assoc (list (verilog-modi-name modi) function)
7187                             verilog-modi-cache-list))
7188           (let ((func-returns (nth 3 fass)))
7189             (aset func-returns element
7190                   (append sig-list (aref func-returns element))))))))
7191
7192 (defmacro verilog-preserve-cache (&rest body)
7193   "Execute the BODY forms, allowing cache preservation within BODY.
7194 This means that changes to the buffer will not result in the cache being
7195 flushed.  If the changes affect the modsig state, they must call the
7196 modsig-cache-add-* function, else the results of later calls may be
7197 incorrect.  Without this, changes are assumed to be adding/removing signals
7198 and invalidating the cache."
7199   `(let ((verilog-modi-cache-preserve-tick (buffer-modified-tick))
7200          (verilog-modi-cache-preserve-buffer (current-buffer)))
7201      (progn ,@body)))
7202
7203 (defsubst verilog-modi-get-decls (modi)
7204   (verilog-modi-cache-results modi 'verilog-read-decls))
7205
7206 (defsubst verilog-modi-get-sub-decls (modi)
7207   (verilog-modi-cache-results modi 'verilog-read-sub-decls))
7208
7209 ;; Signal reading for given module
7210 ;; Note these all take modi's - as returned from the verilog-modi-current function
7211 (defsubst verilog-modi-get-outputs (modi)
7212   (aref (verilog-modi-get-decls modi) 0))
7213 (defsubst verilog-modi-get-inouts (modi)
7214   (aref (verilog-modi-get-decls modi) 1))
7215 (defsubst verilog-modi-get-inputs (modi)
7216   (aref (verilog-modi-get-decls modi) 2))
7217 (defsubst verilog-modi-get-wires (modi)
7218   (aref (verilog-modi-get-decls modi) 3))
7219 (defsubst verilog-modi-get-regs (modi)
7220   (aref (verilog-modi-get-decls modi) 4))
7221 (defsubst verilog-modi-get-assigns (modi)
7222   (aref (verilog-modi-get-decls modi) 5))
7223 (defsubst verilog-modi-get-consts (modi)
7224   (aref (verilog-modi-get-decls modi) 6))
7225 (defsubst verilog-modi-get-gparams (modi)
7226   (aref (verilog-modi-get-decls modi) 7))
7227 (defsubst verilog-modi-get-sub-outputs (modi)
7228   (aref (verilog-modi-get-sub-decls modi) 0))
7229 (defsubst verilog-modi-get-sub-inouts (modi)
7230   (aref (verilog-modi-get-sub-decls modi) 1))
7231 (defsubst verilog-modi-get-sub-inputs (modi)
7232   (aref (verilog-modi-get-sub-decls modi) 2))
7233
7234
7235 (defun verilog-signals-matching-enum (in-list enum)
7236   "Return all signals in IN-LIST matching the given ENUM."
7237   (let (out-list)
7238     (while in-list
7239       (if (equal (verilog-sig-enum (car in-list)) enum)
7240           (setq out-list (cons (car in-list) out-list)))
7241       (setq in-list (cdr in-list)))
7242     ;; New scheme
7243     (let* ((enumvar (intern (concat "venum-" enum)))
7244            (enumlist (and (boundp enumvar) (eval enumvar))))
7245       (while enumlist
7246         (add-to-list 'out-list (list (car enumlist)))
7247         (setq enumlist (cdr enumlist))))
7248     (nreverse out-list)))
7249
7250 (defun verilog-signals-not-matching-regexp (in-list regexp)
7251   "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
7252   (if (not regexp)
7253       in-list
7254     (let (out-list)
7255       (while in-list
7256         (if (not (string-match regexp (verilog-sig-name (car in-list))))
7257             (setq out-list (cons (car in-list) out-list)))
7258         (setq in-list (cdr in-list)))
7259       (nreverse out-list))))
7260
7261 ;; Combined
7262 (defun verilog-modi-get-signals (modi)
7263   (append
7264    (verilog-modi-get-outputs modi)
7265    (verilog-modi-get-inouts modi)
7266    (verilog-modi-get-inputs modi)
7267    (verilog-modi-get-wires modi)
7268    (verilog-modi-get-regs modi)
7269    (verilog-modi-get-assigns modi)
7270    (verilog-modi-get-consts modi)
7271    (verilog-modi-get-gparams modi)))
7272
7273 (defun verilog-modi-get-ports (modi)
7274   (append
7275    (verilog-modi-get-outputs modi)
7276    (verilog-modi-get-inouts modi)
7277    (verilog-modi-get-inputs modi)))
7278
7279 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
7280   (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
7281 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
7282   (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
7283 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
7284   (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
7285 (defsubst verilog-modi-cache-add-wires (modi sig-list)
7286   (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
7287 (defsubst verilog-modi-cache-add-regs (modi sig-list)
7288   (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
7289
7290 (defun verilog-signals-from-signame (signame-list)
7291   "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
7292   (mapcar (function (lambda (name) (list name nil nil)))
7293           signame-list))
7294 \f
7295 ;;
7296 ;; Auto creation utilities
7297 ;;
7298
7299 (defun verilog-auto-search-do (search-for func)
7300   "Search for the given auto text SEARCH-FOR, and perform FUNC where it occurs."
7301   (goto-char (point-min))
7302   (while (search-forward search-for nil t)
7303     (if (not (save-excursion
7304                (goto-char (match-beginning 0))
7305                (verilog-inside-comment-p)))
7306         (funcall func))))
7307
7308 (defun verilog-auto-re-search-do (search-for func)
7309   "Search for the given auto text SEARCH-FOR, and perform FUNC where it occurs."
7310   (goto-char (point-min))
7311   (while (re-search-forward search-for nil t)
7312     (if (not (save-excursion
7313                (goto-char (match-beginning 0))
7314                (verilog-inside-comment-p)))
7315         (funcall func))))
7316
7317 (defun verilog-insert-one-definition (sig type indent-pt)
7318   "Print out a definition for SIGNAL of the given TYPE,
7319 with appropriate INDENT-PT indentation."
7320   (indent-to indent-pt)
7321   (insert type)
7322   (when (verilog-sig-signed sig)
7323     (insert " " (verilog-sig-signed sig)))
7324   (when (verilog-sig-multidim sig)
7325     (insert " " (verilog-sig-multidim-string sig)))
7326   (when (verilog-sig-bits sig)
7327     (insert " " (verilog-sig-bits sig)))
7328   (indent-to (max 24 (+ indent-pt 16)))
7329   (unless (= (char-syntax (preceding-char)) ?\  )
7330     (insert " "))  ; Need space between "]name" if indent-to did nothing
7331   (insert (verilog-sig-name sig)))
7332
7333 (defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
7334   "Print out a definition for a list of SIGS of the given DIRECTION,
7335 with appropriate INDENT-PT indentation.  If V2K, use Verilog 2001 I/O
7336 format.  Sort unless DONT-SORT.  DIRECTION is normally wire/reg/output."
7337   (or dont-sort
7338       (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
7339   (while sigs
7340     (let ((sig (car sigs)))
7341       (verilog-insert-one-definition
7342        sig
7343        ;; Want "type x" or "output type x", not "wire type x"
7344        (cond ((verilog-sig-type sig)
7345               (concat
7346                (if (not (equal direction "wire"))
7347                    (concat direction " "))
7348                (verilog-sig-type sig)))
7349              (t direction))
7350        indent-pt)
7351       (insert (if v2k "," ";"))
7352       (if (or (not (verilog-sig-comment sig))
7353               (equal "" (verilog-sig-comment sig)))
7354           (insert "\n")
7355         (indent-to (max 48 (+ indent-pt 40)))
7356         (insert (concat "// " (verilog-sig-comment sig) "\n")))
7357       (setq sigs (cdr sigs)))))
7358
7359 (eval-when-compile
7360   (if (not (boundp 'indent-pt))
7361       (defvar indent-pt nil "Local used by insert-indent")))
7362
7363 (defun verilog-insert-indent (&rest stuff)
7364   "Indent to position stored in local `indent-pt' variable, then insert STUFF.
7365 Presumes that any newlines end a list element."
7366   (let ((need-indent t))
7367     (while stuff
7368       (if need-indent (indent-to indent-pt))
7369       (setq need-indent nil)
7370       (insert (car stuff))
7371       (setq need-indent (string-match "\n$" (car stuff))
7372             stuff (cdr stuff)))))
7373 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
7374
7375 (defun verilog-repair-open-comma ()
7376   "If backwards-from-point is other then a open parenthesis insert comma."
7377   (save-excursion
7378     (verilog-backward-syntactic-ws)
7379     (when (save-excursion
7380             (backward-char 1)
7381             (and (not (looking-at "[(,]"))
7382                  (progn
7383                    (verilog-re-search-backward "[(`]" nil t)
7384                    (looking-at "("))))
7385     (insert ","))))
7386
7387 (defun verilog-repair-close-comma ()
7388   "If point is at a comma followed by a close parenthesis, fix it.
7389 This repairs those mis-inserted by a AUTOARG."
7390   ;; It would be much nicer if Verilog allowed extra commas like Perl does!
7391   (save-excursion
7392     (verilog-forward-close-paren)
7393     (backward-char 1)
7394     (verilog-backward-syntactic-ws)
7395     (backward-char 1)
7396     (when (looking-at ",")
7397       (delete-char 1))))
7398
7399 (defun verilog-get-list (start end)
7400   "Return the elements of a comma separated list between START and END."
7401   (interactive)
7402   (let ((my-list (list))
7403         my-string)
7404     (save-excursion
7405       (while (< (point) end)
7406         (when (re-search-forward "\\([^,{]+\\)" end t)
7407           (setq my-string (verilog-string-remove-spaces (match-string 1)))
7408           (setq my-list (nconc my-list (list my-string) ))
7409           (goto-char (match-end 0))))
7410       my-list)))
7411
7412 (defun verilog-make-width-expression (range-exp)
7413   "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
7414   ;; strip off the []
7415   (cond ((not range-exp)
7416          "1")
7417         (t
7418          (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
7419              (setq range-exp (match-string 1 range-exp)))
7420          (cond ((not range-exp)
7421                 "1")
7422                ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$" range-exp)
7423                 (int-to-string (1+ (abs (- (string-to-int (match-string 1 range-exp))
7424                                            (string-to-int (match-string 2 range-exp)))))))
7425                ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
7426                 (concat "(1+(" (match-string 1 range-exp)
7427                         ")"
7428                         (if (equal "0" (match-string 2 range-exp))  ;; Don't bother with -(0)
7429                             ""
7430                           (concat "-(" (match-string 2 range-exp) ")"))
7431                         ")"))
7432                (t nil)))))
7433 ;;(verilog-make-width-expression "`A:`B")
7434
7435 (defun verilog-typedef-name-p (variable-name)
7436   "Return true if the VARIABLE-NAME is a type definition."
7437   (when verilog-typedef-regexp
7438     (string-match verilog-typedef-regexp variable-name)))
7439 \f
7440 ;;
7441 ;; Auto deletion
7442 ;;
7443
7444 (defun verilog-delete-autos-lined ()
7445   "Delete autos that occupy multiple lines, between begin and end comments."
7446   (let ((pt (point)))
7447     (forward-line 1)
7448     (when (and
7449            (looking-at "\\s-*// Beginning")
7450            (search-forward "// End of automatic" nil t))
7451       ;; End exists
7452       (end-of-line)
7453       (delete-region pt (point))
7454       (forward-line 1))
7455   ))
7456
7457 (defun verilog-forward-close-paren ()
7458   "Find the close parenthesis that match the current point,
7459 ignore other close parenthesis with matching open parens"
7460   (let ((parens 1))
7461     (while (> parens 0)
7462       (unless (verilog-re-search-forward-quick "[()]" nil t)
7463         (error "%s: Mismatching ()" (verilog-point-text)))
7464       (cond ((= (preceding-char) ?\( )
7465              (setq parens (1+ parens)))
7466             ((= (preceding-char) ?\) )
7467              (setq parens (1- parens)))))))
7468
7469 (defun verilog-backward-open-paren ()
7470   "Find the open parenthesis that match the current point,
7471 ignore other open parenthesis with matching close parens"
7472   (let ((parens 1))
7473     (while (> parens 0)
7474       (unless (verilog-re-search-backward-quick "[()]" nil t)
7475         (error "%s: Mismatching ()" (verilog-point-text)))
7476       (cond ((= (following-char) ?\) )
7477              (setq parens (1+ parens)))
7478             ((= (following-char) ?\( )
7479              (setq parens (1- parens)))))))
7480
7481 (defun verilog-backward-open-bracket ()
7482   "Find the open bracket that match the current point,
7483 ignore other open bracket with matching close bracket"
7484   (let ((parens 1))
7485     (while (> parens 0)
7486       (unless (verilog-re-search-backward-quick "[][]" nil t)
7487         (error "%s: Mismatching []" (verilog-point-text)))
7488       (cond ((= (following-char) ?\] )
7489              (setq parens (1+ parens)))
7490             ((= (following-char) ?\[ )
7491              (setq parens (1- parens)))))))
7492
7493 (defun verilog-delete-to-paren ()
7494   "Delete the automatic inst/sense/arg created by autos.
7495 Deletion stops at the matching end parenthesis."
7496   (delete-region (point)
7497                  (save-excursion
7498                    (verilog-backward-open-paren)
7499                    (forward-sexp 1)   ;; Moves to paren that closes argdecl's
7500                    (backward-char 1)
7501                    (point))))
7502
7503 (defun verilog-auto-star-safe ()
7504   "Return if a .* AUTOINST is safe to delete or expand.
7505 It was created by the AUTOS themselves, or by the user."
7506   (and verilog-auto-star-expand
7507        (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\)\\)")))
7508
7509 (defun verilog-delete-auto-star-all ()
7510   "Delete a .* AUTOINST, if it is safe."
7511   (when (verilog-auto-star-safe)
7512     (verilog-delete-to-paren)))
7513
7514 (defun verilog-delete-auto-star-implicit ()
7515   "Delete all .* implicit connections created by `verilog-auto-star'.
7516 This function will be called automatically at save unless
7517 `verilog-auto-star-save' is set, any non-templated expanded pins will be
7518 removed."
7519   (interactive)
7520   (let (paren-pt indent have-close-paren)
7521     (save-excursion
7522       (goto-char (point-min))
7523       ;; We need to match these even outside of comments.
7524       ;; For reasonable performance, we don't check if inside comments, sorry.
7525       (while (re-search-forward "// Implicit \\.\\*" nil t)
7526         (setq paren-pt (point))
7527         (beginning-of-line)
7528         (setq have-close-paren
7529               (save-excursion
7530                 (when (search-forward ");" paren-pt t)
7531                   (setq indent (current-indentation))
7532                   t)))
7533         (delete-region (point) (+ 1 paren-pt))  ; Nuke line incl CR
7534         (when have-close-paren
7535           ;; Delete extra commentary
7536           (save-excursion
7537             (while (progn
7538                      (forward-line -1)
7539                      (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\)\n"))
7540               (delete-region (match-beginning 0) (match-end 0))))
7541           ;; If it is simple, we can put the ); on the same line as the last text
7542           (let ((rtn-pt (point)))
7543             (save-excursion
7544               (while (progn (backward-char 1)
7545                             (looking-at "[ \t\n\f]")))
7546               (when (looking-at ",")
7547                 (delete-region (+ 1 (point)) rtn-pt))))
7548           (when (bolp)
7549             (indent-to indent))
7550           (insert ");\n")
7551           ;; Still need to kill final comma - always is one as we put one after the .*
7552           (re-search-backward ",")
7553           (delete-char 1))))))
7554
7555 (defun verilog-delete-auto ()
7556   "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
7557 Use \\[verilog-auto] to re-insert the updated AUTOs.
7558
7559 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
7560 called before and after this function, respectively."
7561   (interactive)
7562   (save-excursion
7563     (if (buffer-file-name)
7564         (find-file-noselect (buffer-file-name)))        ;; To check we have latest version
7565     ;; Allow user to customize
7566     (run-hooks 'verilog-before-delete-auto-hook)
7567
7568     ;; Remove those that have multi-line insertions
7569     (verilog-auto-re-search-do "/\\*AUTO\\(OUTPUTEVERY\\|CONCATCOMMENT\\|WIRE\\|REG\\|DEFINEVALUE\\|REGINPUT\\|INPUT\\|OUTPUT\\|INOUT\\|RESET\\|TIEOFF\\|UNUSED\\)\\*/"
7570                                'verilog-delete-autos-lined)
7571     ;; Remove those that have multi-line insertions with parameters
7572     (verilog-auto-re-search-do "/\\*AUTO\\(INOUTMODULE\\|ASCIIENUM\\)([^)]*)\\*/"
7573                                'verilog-delete-autos-lined)
7574     ;; Remove those that are in parenthesis
7575     (verilog-auto-re-search-do "/\\*\\(AS\\|AUTO\\(ARG\\|CONCATWIDTH\\|INST\\|INSTPARAM\\|SENSE\\)\\)\\*/"
7576                                'verilog-delete-to-paren)
7577     ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
7578     (verilog-auto-re-search-do "\\.\\*"
7579                                'verilog-delete-auto-star-all)
7580     ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
7581     (goto-char (point-min))
7582     (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
7583       (replace-match ""))
7584
7585     ;; Final customize
7586     (run-hooks 'verilog-delete-auto-hook)))
7587 \f
7588 ;;
7589 ;; Auto inject
7590 ;;
7591
7592 (defun verilog-inject-auto ()
7593   "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
7594
7595 Any always @ blocks with sensitivity lists that match computed lists will
7596 be replaced with /*AS*/ comments.
7597
7598 Any cells will get /*AUTOINST*/ added to the end of the pin list.  Pins with
7599 have identical names will be deleted.
7600
7601 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
7602 support adding new ports.  You may wish to delete older ports yourself.
7603
7604 For example:
7605
7606         module ex_inject (i, o);
7607           input i;
7608           input j;
7609           output o;
7610           always @ (i or j)
7611              o = i | j;
7612           cell cell (.foobar(baz),
7613                      .j(j));
7614         endmodule
7615
7616 Typing \\[verilog-inject-auto] will make this into:
7617
7618         module ex_inject (i, o/*AUTOARG*/
7619           // Inputs
7620           j);
7621           input i;
7622           output o;
7623           always @ (/*AS*/i or j)
7624              o = i | j;
7625           cell cell (.foobar(baz),
7626                      /*AUTOINST*/
7627                      // Outputs
7628                      .j(j));
7629         endmodule"
7630   (interactive)
7631   (verilog-auto t))
7632
7633 (defun verilog-inject-arg ()
7634   "Inject AUTOARG into new code.  See `verilog-inject-auto'."
7635   ;; Presume one module per file.
7636   (save-excursion
7637     (goto-char (point-min))
7638     (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
7639       (let ((endmodp (save-excursion
7640                        (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
7641                        (point))))
7642         ;; See if there's already a comment .. inside a comment so not verilog-re-search
7643         (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
7644           (verilog-re-search-forward-quick ";" nil t)
7645           (backward-char 1)
7646           (verilog-backward-syntactic-ws)
7647           (backward-char 1) ; Moves to paren that closes argdecl's
7648           (when (looking-at ")")
7649             (insert "/*AUTOARG*/")))))))
7650
7651 (defun verilog-inject-sense ()
7652   "Inject AUTOSENSE into new code.  See `verilog-inject-auto'."
7653   (save-excursion
7654     (goto-char (point-min))
7655     (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
7656       (let ((start-pt (point))
7657             (modi (verilog-modi-current))
7658             pre-sigs
7659             got-sigs)
7660         (backward-char 1)
7661         (forward-sexp 1)
7662         (backward-char 1) ;; End )
7663         (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
7664           (setq pre-sigs (verilog-signals-from-signame
7665                           (verilog-read-signals start-pt (point)))
7666                 got-sigs (verilog-auto-sense-sigs modi nil))
7667           (when (not (or (verilog-signals-not-in pre-sigs got-sigs)  ; Both are equal?
7668                          (verilog-signals-not-in got-sigs pre-sigs)))
7669             (delete-region start-pt (point))
7670             (insert "/*AS*/")))))))
7671
7672 (defun verilog-inject-inst ()
7673   "Inject AUTOINST into new code.  See `verilog-inject-auto'."
7674   (save-excursion
7675     (goto-char (point-min))
7676     ;; It's hard to distinguish modules; we'll instead search for pins.
7677     (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
7678       (verilog-backward-open-paren) ;; Inst start
7679       (cond
7680        ((= (preceding-char) ?\#)  ;; #(...) parameter section, not pin.  Skip.
7681         (forward-char 1)
7682         (verilog-forward-close-paren)) ;; Parameters done
7683        (t
7684         (forward-char 1)
7685         (let ((indent-pt (+ (current-column)))
7686               (end-pt (save-excursion (verilog-forward-close-paren) (point))))
7687           (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
7688                  (goto-char end-pt)) ;; Already there, continue search with next instance
7689                 (t
7690                  ;; Delete identical interconnect
7691                  (let ((case-fold-search nil))  ;; So we don't convert upper-to-lower, etc
7692                    (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
7693                      (delete-region (match-beginning 0) (match-end 0))
7694                      (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
7695                      (while (or (looking-at "[ \t\n\f,]+")
7696                                 (looking-at "//[^\n]*"))
7697                        (delete-region (match-beginning 0) (match-end 0))
7698                        (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
7699                  (verilog-forward-close-paren)
7700                  (backward-char 1)
7701                  ;; Not verilog-re-search, as we don't want to strip comments
7702                  (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
7703                    (delete-region (match-beginning 0) (match-end 0)))
7704                  (insert "\n")
7705                  (indent-to indent-pt)
7706                  (insert "/*AUTOINST*/")))))))))
7707 \f
7708 ;;
7709 ;; Auto save
7710 ;;
7711
7712 (defun verilog-auto-save-check ()
7713   "On saving see if we need auto update."
7714   (cond ((not verilog-auto-save-policy)) ; disabled
7715         ((not (save-excursion
7716                 (save-match-data
7717                   (let ((case-fold-search nil))
7718                     (goto-char (point-min))
7719                     (re-search-forward "AUTO" nil t))))))
7720         ((eq verilog-auto-save-policy 'force)
7721          (verilog-auto))
7722         ((not (buffer-modified-p)))
7723         ((eq verilog-auto-update-tick (buffer-modified-tick))) ; up-to-date
7724         ((eq verilog-auto-save-policy 'detect)
7725          (verilog-auto))
7726         (t
7727          (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
7728            (verilog-auto))
7729          ;; Don't ask again if didn't update
7730          (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))
7731          ))
7732   (when (not verilog-auto-star-save)
7733     (verilog-delete-auto-star-implicit))
7734   nil)  ;; Always return nil -- we don't write the file ourselves
7735
7736 (defun verilog-auto-read-locals ()
7737   "Return file local variable segment at bottom of file."
7738   (save-excursion
7739     (goto-char (point-max))
7740     (if (re-search-backward "Local Variables:" nil t)
7741         (buffer-substring-no-properties (point) (point-max))
7742       "")))
7743
7744 (defun verilog-auto-reeval-locals (&optional force)
7745   "Read file local variable segment at bottom of file if it has changed.
7746 If FORCE, always reread it."
7747   (make-variable-buffer-local 'verilog-auto-last-file-locals)
7748   (let ((curlocal (verilog-auto-read-locals)))
7749     (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
7750       (setq verilog-auto-last-file-locals curlocal)
7751       ;; Note this may cause this function to be recursively invoked.
7752       ;; The above when statement will prevent it from recursing forever.
7753       (hack-local-variables)
7754       t)))
7755 \f
7756 ;;
7757 ;; Auto creation
7758 ;;
7759
7760 (defun verilog-auto-arg-ports (sigs message indent-pt)
7761   "Print a list of ports for a AUTOINST.
7762 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
7763   (when sigs
7764     (insert "\n")
7765     (indent-to indent-pt)
7766     (insert message)
7767     (insert "\n")
7768     (let ((space ""))
7769       (indent-to indent-pt)
7770       (while sigs
7771         (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
7772                (insert "\n")
7773                (indent-to indent-pt))
7774               (t (insert space)))
7775         (insert (verilog-sig-name (car sigs)) ",")
7776         (setq sigs (cdr sigs)
7777               space " ")))))
7778
7779 (defun verilog-auto-arg ()
7780   "Expand AUTOARG statements.
7781 Replace the argument declarations at the beginning of the
7782 module with ones automatically derived from input and output
7783 statements.  This can be dangerous if the module is instantiated
7784 using position-based connections, so use only name-based when
7785 instantiating the resulting module.  Long lines are split based
7786 on the `fill-column', see \\[set-fill-column].
7787
7788 Limitations:
7789   Concatenation and outputting partial busses is not supported.
7790
7791   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
7792
7793 For example:
7794
7795         module ex_arg (/*AUTOARG*/);
7796           input i;
7797           output o;
7798         endmodule
7799
7800 Typing \\[verilog-auto] will make this into:
7801
7802         module ex_arg (/*AUTOARG*/
7803           // Outputs
7804           o,
7805           // Inputs
7806           i
7807         );
7808           input i;
7809           output o;
7810         endmodule
7811
7812 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
7813 predeclared and are not redeclared by AUTOARG.  AUTOARG will make a
7814 conservative guess on adding a comma for the first signal, if you have any
7815 ifdefs or complicated expressions before the AUTOARG you will need to
7816 choose the comma yourself.
7817
7818 Avoid declaring ports manually, as it makes code harder to maintain."
7819   (save-excursion
7820     (let ((modi (verilog-modi-current))
7821           (skip-pins (aref (verilog-read-arg-pins) 0)))
7822       (verilog-repair-open-comma)
7823       (verilog-auto-arg-ports (verilog-signals-not-in
7824                                (verilog-modi-get-outputs modi)
7825                                skip-pins)
7826                               "// Outputs"
7827                               verilog-indent-level-declaration)
7828       (verilog-auto-arg-ports (verilog-signals-not-in
7829                                (verilog-modi-get-inouts modi)
7830                                skip-pins)
7831                               "// Inouts"
7832                               verilog-indent-level-declaration)
7833       (verilog-auto-arg-ports (verilog-signals-not-in
7834                                (verilog-modi-get-inputs modi)
7835                                skip-pins)
7836                               "// Inputs"
7837                               verilog-indent-level-declaration)
7838       (verilog-repair-close-comma)
7839       (unless (eq (char-before) ?/ )
7840         (insert "\n"))
7841       (indent-to verilog-indent-level-declaration)
7842       )))
7843
7844 (defun verilog-auto-inst-port-map (port-st)
7845   nil)
7846
7847 (defvar vector-skip-list nil) ; Prevent compile warning
7848 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
7849 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
7850 (defvar vl-name  nil "See `verilog-auto-inst'.") ; Prevent compile warning
7851 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
7852 (defvar vl-dir   nil "See `verilog-auto-inst'.") ; Prevent compile warning
7853
7854 (defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star)
7855   "Print out a instantiation connection for this PORT-ST.
7856 Insert to INDENT-PT, use template TPL-LIST.
7857 @ are instantiation numbers, replaced with TPL-NUM.
7858 @\"(expression @)\" are evaluated, with @ as a variable."
7859   (let* ((port (verilog-sig-name port-st))
7860          (tpl-ass (or (assoc port (car tpl-list))
7861                       (verilog-auto-inst-port-map port-st)))
7862          ;; vl-* are documented for user use
7863          (vl-name (verilog-sig-name port-st))
7864          (vl-width (verilog-sig-width port-st))
7865          (vl-bits (if (or verilog-auto-inst-vector
7866                           (not (assoc port vector-skip-list))
7867                           (not (equal (verilog-sig-bits port-st)
7868                                       (verilog-sig-bits (assoc port vector-skip-list)))))
7869                       (or (verilog-sig-bits port-st) "")
7870                     ""))
7871          ;; Default if not found
7872          (tpl-net (if (verilog-sig-multidim port-st)
7873                       (concat port "/*" (verilog-sig-multidim-string port-st)
7874                               vl-bits "*/")
7875                     (concat port vl-bits))))
7876     ;; Find template
7877     (cond (tpl-ass          ; Template of exact port name
7878            (setq tpl-net (nth 1 tpl-ass)))
7879           ((nth 1 tpl-list) ; Wildcards in template, search them
7880            (let ((wildcards (nth 1 tpl-list)))
7881              (while wildcards
7882                (when (string-match (nth 0 (car wildcards)) port)
7883                  (setq tpl-ass (car wildcards)  ; so allow @ parsing
7884                        tpl-net (replace-match (nth 1 (car wildcards))
7885                                               t nil port)))
7886                (setq wildcards (cdr wildcards))))))
7887     ;; Parse Templated variable
7888     (when tpl-ass
7889       ;; Evaluate @"(lispcode)"
7890       (when (string-match "@\".*[^\\]\"" tpl-net)
7891         (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
7892           (setq tpl-net
7893                 (concat
7894                  (substring tpl-net 0 (match-beginning 0))
7895                  (save-match-data
7896                    (let* ((expr (match-string 1 tpl-net))
7897                           (value
7898                            (progn
7899                              (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
7900                              (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
7901                              (prin1 (eval (car (read-from-string expr)))
7902                                     (lambda (ch) ())))))
7903                      (if (numberp value) (setq value (number-to-string value)))
7904                      value
7905                      ))
7906                  (substring tpl-net (match-end 0))))))
7907       ;; Replace @ and [] magic variables in final output
7908       (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
7909       (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net))
7910       )
7911     (indent-to indent-pt)
7912     (insert "." port)
7913     (indent-to verilog-auto-inst-column)
7914     (insert "(" tpl-net "),")
7915     (cond (tpl-ass
7916            (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
7917                          verilog-auto-inst-column))
7918            (insert " // Templated")
7919            (when verilog-auto-inst-template-numbers
7920              (insert " T" (int-to-string (nth 2 tpl-ass))
7921                      " L" (int-to-string (nth 3 tpl-ass)))))
7922           (for-star
7923            (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
7924                          verilog-auto-inst-column))
7925            (insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
7926     (insert "\n")))
7927 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
7928 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
7929 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
7930
7931 (defun verilog-auto-inst-first ()
7932   "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
7933   ;; Do we need a trailing comma?
7934   ;; There maybe a ifdef or something similar before us.  What a mess.  Thus
7935   ;; to avoid trouble we only insert on preceeding ) or *.
7936   ;; Insert first port on new line
7937   (insert "\n")  ;; Must insert before search, so point will move forward if insert comma
7938   (save-excursion
7939     (verilog-re-search-backward "[^ \t\n\f]" nil nil)
7940     (when (looking-at ")\\|\\*")  ;; Generally don't insert, unless we are fairly sure
7941       (forward-char 1)
7942       (insert ","))))
7943
7944 (defun verilog-auto-star ()
7945   "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
7946
7947 If `verilog-auto-star-expand' is set, .* pins are treated if they were
7948 AUTOINST statements, otherwise they are ignored.  For safety, Verilog-Mode
7949 will also ignore any .* that are not last in your pin list (this prevents
7950 it from deleting pins following the .* when it expands the AUTOINST.)
7951
7952 On writing your file, unless `verilog-auto-star-save' is set, any
7953 non-templated expanded pins will be removed.  You may do this at any time
7954 with \\[verilog-delete-auto-star-implicit].
7955
7956 If you are converting a module to use .* for the first time, you may wish
7957 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
7958
7959 See `verilog-auto-inst' for examples, templates, and more information."
7960   (when (verilog-auto-star-safe)
7961     (verilog-auto-inst)))
7962
7963 (defun verilog-auto-inst ()
7964   "Expand AUTOINST statements, as part of \\[verilog-auto].
7965 Replace the pin connections to an instantiation with ones
7966 automatically derived from the module header of the instantiated netlist.
7967
7968 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
7969 and delete them before saving unless `verilog-auto-star-save' is set.
7970 See `verilog-auto-star' for more information.
7971
7972 Limitations:
7973   Module names must be resolvable to filenames by adding a
7974   `verilog-library-extensions', and being found in the same directory, or
7975   by changing the variable `verilog-library-flags' or
7976   `verilog-library-directories'.  Macros `modname are translated through the
7977   vh-{name} Emacs variable, if that is not found, it just ignores the `.
7978
7979   In templates you must have one signal per line, ending in a ), or ));,
7980   and have proper () nesting, including a final ); to end the template.
7981
7982   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
7983
7984   SystemVerilog multidimmensional input/output has only experimental support.
7985
7986 For example, first take the submodule inst.v:
7987
7988         module inst (o,i)
7989            output [31:0] o;
7990            input i;
7991            wire [31:0] o = {32{i}};
7992         endmodule
7993
7994 This is then used in a upper level module:
7995
7996         module ex_inst (o,i)
7997            output o;
7998            input i;
7999            inst inst (/*AUTOINST*/);
8000         endmodule
8001
8002 Typing \\[verilog-auto] will make this into:
8003
8004         module ex_inst (o,i)
8005            output o;
8006            input i;
8007            inst inst (/*AUTOINST*/
8008                       // Outputs
8009                       .ov                       (ov[31:0]),
8010                       // Inputs
8011                       .i                        (i));
8012         endmodule
8013
8014 Where the list of inputs and outputs came from the inst module.
8015 \f
8016 Exceptions:
8017
8018   Unless you are instantiating a module multiple times, or the module is
8019   something trivial like a adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
8020   It just makes for unmaintainable code.  To sanitize signal names, try
8021   vrename from http://www.veripool.com
8022
8023   When you need to violate this suggestion there are two ways to list
8024   exceptions, placing them before the AUTOINST, or using templates.
8025
8026   Any ports defined before the /*AUTOINST*/ are not included in the list of
8027   automatics.  This is similar to making a template as described below, but
8028   is restricted to simple connections just like you normally make.  Also note
8029   that any signals before the AUTOINST will only be picked up by AUTOWIRE if
8030   you have the appropriate // Input or // Output comment, and exactly the
8031   same line formatting as AUTOINST itself uses.
8032
8033         inst inst (// Inputs
8034                    .i           (my_i_dont_mess_with_it),
8035                    /*AUTOINST*/
8036                    // Outputs
8037                    .ov          (ov[31:0]));
8038
8039 \f
8040 Templates:
8041
8042   For multiple instantiations based upon a single template, create a
8043   commented out template:
8044
8045         /* instantiating_module_name AUTO_TEMPLATE (
8046                 .sig3   (sigz[]),
8047                 );
8048         */
8049
8050   Templates go ABOVE the instantiation(s).  When a instantiation is
8051   expanded `verilog-mode' simply searches up for the closest template.
8052   Thus you can have multiple templates for the same module, just alternate
8053   between the template for a instantiation and the instantiation itself.
8054
8055   The module name must be the same as the name of the module in the
8056   instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
8057   words and capitalized.  Only signals that must be different for each
8058   instantiation need to be listed.
8059
8060   Inside a template, a [] in a connection name (with nothing else inside
8061   the brackets) will be replaced by the same bus subscript as it is being
8062   connected to, or the [] will be removed if it is a single bit signal.
8063   Generally it is a good idea to do this for all connections in a template,
8064   as then they will work for any width signal, and with AUTOWIRE.  See
8065   PTL_BUS becoming PTL_BUSNEW below.
8066
8067   If you have a complicated template, set `verilog-auto-inst-template-numbers'
8068   to see which regexps are matching.  Don't leave that mode set after
8069   debugging is completed though, it will result in lots of extra differences
8070   and merge conflicts.
8071
8072   For example:
8073
8074         /* psm_mas AUTO_TEMPLATE (
8075                 .ptl_bus        (ptl_busnew[]),
8076                 );
8077         */
8078         psm_mas ms2m (/*AUTOINST*/);
8079
8080   Typing \\[verilog-auto] will make this into:
8081
8082         psm_mas ms2m (/*AUTOINST*/
8083             // Outputs
8084             .NotInTemplate      (NotInTemplate),
8085             .ptl_bus            (ptl_busnew[3:0]),  // Templated
8086             ....
8087 \f
8088 @ Templates:
8089
8090   It is common to instantiate a cell multiple times, so templates make it
8091   trivial to substitute part of the cell name into the connection name.
8092
8093         /* cell_type AUTO_TEMPLATE <optional \"REGEXP\"> (
8094                 .sig1   (sigx[@]),
8095                 .sig2   (sigy[@\"(% (+ 1 @) 4)\"]),
8096                 );
8097         */
8098
8099   If no regular expression is provided immediately after the AUTO_TEMPLATE
8100   keyword, then the @ character in any connection names will be replaced
8101   with the instantiation number; the first digits found in the cell's
8102   instantiation name.
8103
8104   If a regular expression is provided, the @ character will be replaced
8105   with the first \(\) grouping that matches against the cell name.  Using a
8106   regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
8107   regexp is provided.  If you use multiple layers of parenthesis,
8108   \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
8109   characters after test and before _, whereas
8110   \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
8111   match.
8112
8113   For example:
8114
8115         /* psm_mas AUTO_TEMPLATE (
8116                 .ptl_mapvalidx          (ptl_mapvalid[@]),
8117                 .ptl_mapvalidp1x        (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
8118                 );
8119         */
8120         psm_mas ms2m (/*AUTOINST*/);
8121
8122   Typing \\[verilog-auto] will make this into:
8123
8124         psm_mas ms2m (/*AUTOINST*/
8125             // Outputs
8126             .ptl_mapvalidx              (ptl_mapvalid[2]),
8127             .ptl_mapvalidp1x            (ptl_mapvalid[3]));
8128
8129   Note the @ character was replaced with the 2 from \"ms2m\".
8130
8131   Alternatively, using a regular expression for @:
8132
8133         /* psm_mas AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
8134                 .ptl_mapvalidx          (@_ptl_mapvalid),
8135                 .ptl_mapvalidp1x        (ptl_mapvalid_@),
8136                 );
8137         */
8138         psm_mas ms2_FOO (/*AUTOINST*/);
8139         psm_mas ms2_BAR (/*AUTOINST*/);
8140
8141   Typing \\[verilog-auto] will make this into:
8142
8143         psm_mas ms2_FOO (/*AUTOINST*/
8144             // Outputs
8145             .ptl_mapvalidx              (FOO_ptl_mapvalid),
8146             .ptl_mapvalidp1x            (ptl_mapvalid_FOO));
8147         psm_mas ms2_BAR (/*AUTOINST*/
8148             // Outputs
8149             .ptl_mapvalidx              (BAR_ptl_mapvalid),
8150             .ptl_mapvalidp1x            (ptl_mapvalid_BAR));
8151
8152 \f
8153 Regexp Templates:
8154
8155   A template entry of the form
8156
8157             .pci_req\\([0-9]+\\)_l      (pci_req_jtag_[\\1]),
8158
8159   will apply a Emacs style regular expression search for any port beginning
8160   in pci_req followed by numbers and ending in _l and connecting that to
8161   the pci_req_jtag_[] net, with the bus subscript coming from what matches
8162   inside the first set of \\( \\).  Thus pci_req2_l becomes pci_req_jtag_[2].
8163
8164   Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
8165   does the same thing. (Note a @ in the connection/replacement text is
8166   completely different -- still use \\1 there!)  Thus this is the same as
8167   the above template:
8168
8169             .pci_req@_l         (pci_req_jtag_[\\1]),
8170
8171   Here's another example to remove the _l, useful when naming conventions
8172   specify _ alone to mean active low.  Note the use of [] to keep the bus
8173   subscript:
8174
8175             .\\(.*\\)_l         (\\1_[]),
8176 \f
8177 Lisp Templates:
8178
8179   First any regular expression template is expanded.
8180
8181   If the syntax @\"( ... )\" is found in a connection, the expression in
8182   quotes will be evaluated as a Lisp expression, with @ replaced by the
8183   instantiation number.  The MAPVALIDP1X example above would put @+1 modulo
8184   4 into the brackets.  Quote all double-quotes inside the expression with
8185   a leading backslash (\\\").  There are special variables defined that are
8186   useful in these Lisp functions:
8187
8188         vl-name        Name portion of the input/output port
8189         vl-bits        Bus bits portion of the input/output port ('[2:0]')
8190         vl-width       Width of the input/output port ('3' for [2:0])
8191                        May be a (...) expression if bits isn't a constant.
8192         vl-dir         Direction of the pin input/output/inout.
8193         vl-cell-type   Module name/type of the cell ('psm_mas')
8194         vl-cell-name   Instance name of the cell ('ms2m')
8195
8196   Normal Lisp variables may be used in expressions.  See
8197   `verilog-read-defines' which can set vh-{definename} variables for use
8198   here.  Also, any comments of the form:
8199
8200         /*AUTO_LISP(setq foo 1)*/
8201
8202   will evaluate any Lisp expression inside the parenthesis between the
8203   beginning of the buffer and the point of the AUTOINST.  This allows
8204   functions to be defined or variables to be changed between instantiations.
8205
8206   Note that when using lisp expressions errors may occur when @ is not a
8207   number, you may need to use the standard Emacs Lisp functions
8208   `number-to-string' and `string-to-number'.
8209
8210   After the evaluation is completed, @ substitution and [] substitution
8211   occur."
8212   (save-excursion
8213     ;; Find beginning
8214     (let* ((pt (point))
8215            (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
8216            (indent-pt (save-excursion (verilog-backward-open-paren)
8217                                       (1+ (current-column))))
8218            (verilog-auto-inst-column (max verilog-auto-inst-column
8219                                           (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
8220            (modi (verilog-modi-current))
8221            (vector-skip-list (unless verilog-auto-inst-vector
8222                                (verilog-modi-get-signals modi)))
8223            submod submodi inst skip-pins tpl-list tpl-num did-first)
8224       ;; Find module name that is instantiated
8225       (setq submod  (verilog-read-inst-module)
8226             inst (verilog-read-inst-name)
8227             vl-cell-type submod
8228             vl-cell-name inst
8229             skip-pins (aref (verilog-read-inst-pins) 0))
8230
8231       ;; Parse any AUTO_LISP() before here
8232       (verilog-read-auto-lisp (point-min) pt)
8233
8234       ;; Lookup position, etc of submodule
8235       ;; Note this may raise an error
8236       (when (setq submodi (verilog-modi-lookup submod t))
8237         ;; If there's a number in the instantiation, it may be a argument to the
8238         ;; automatic variable instantiation program.
8239         (let* ((tpl-info (verilog-read-auto-template submod))
8240                (tpl-regexp (aref tpl-info 0)))
8241           (setq tpl-num (if (string-match tpl-regexp inst)
8242                             (match-string 1 inst)
8243                           "")
8244                 tpl-list (aref tpl-info 1)))
8245         ;; Find submodule's signals and dump
8246         (let ((sig-list (verilog-signals-not-in
8247                          (verilog-modi-get-outputs submodi)
8248                          skip-pins))
8249               (vl-dir "output"))
8250           (when sig-list
8251             (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8252             (indent-to indent-pt)
8253             (insert "// Outputs\n")     ;; Note these are searched for in verilog-read-sub-decls
8254             (mapcar (function (lambda (port)
8255                                 (verilog-auto-inst-port port indent-pt tpl-list tpl-num for-star)))
8256                     sig-list)))
8257         (let ((sig-list (verilog-signals-not-in
8258                          (verilog-modi-get-inouts submodi)
8259                          skip-pins))
8260               (vl-dir "inout"))
8261           (when sig-list
8262             (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8263             (indent-to indent-pt)
8264             (insert "// Inouts\n")
8265             (mapcar (function (lambda (port)
8266                                 (verilog-auto-inst-port port indent-pt tpl-list tpl-num for-star)))
8267                     sig-list)))
8268         (let ((sig-list (verilog-signals-not-in
8269                          (verilog-modi-get-inputs submodi)
8270                          skip-pins))
8271               (vl-dir "input"))
8272           (when sig-list
8273             (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8274             (indent-to indent-pt)
8275             (insert "// Inputs\n")
8276             (mapcar (function (lambda (port)
8277                                 (verilog-auto-inst-port port indent-pt tpl-list tpl-num for-star)))
8278                     sig-list)))
8279         ;; Kill extra semi
8280         (save-excursion
8281           (cond (did-first
8282                  (re-search-backward "," pt t)
8283                  (delete-char 1)
8284                  (insert ");")
8285                  (search-forward "\n")  ;; Added by inst-port
8286                  (delete-backward-char 1)
8287                  (if (search-forward ")" nil t) ;; From user, moved up a line
8288                      (delete-backward-char 1))
8289                  (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
8290                      (delete-backward-char 1))
8291                  )))
8292         ))))
8293
8294 (defun verilog-auto-inst-param ()
8295   "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
8296 Replace the parameter connections to an instantiation with ones
8297 automatically derived from the module header of the instantiated netlist.
8298
8299 See \\[verilog-auto-inst] for limitations, and templates to customize the
8300 output.
8301
8302 For example, first take the submodule inst.v:
8303
8304         module inst (o,i)
8305            parameter PAR;
8306         endmodule
8307
8308 This is then used in a upper level module:
8309
8310         module ex_inst (o,i)
8311            parameter PAR;
8312            inst #(/*AUTOINSTPARAM*/)
8313                 inst (/*AUTOINST*/);
8314         endmodule
8315
8316 Typing \\[verilog-auto] will make this into:
8317
8318         module ex_inst (o,i)
8319            output o;
8320            input i;
8321            inst (/*AUTOINSTPARAM*/
8322                  // Parameters
8323                  .PAR                   (PAR));
8324                 inst (/*AUTOINST*/);
8325         endmodule
8326
8327 Where the list of parameter connections come from the inst module.
8328 \f
8329 Templates:
8330
8331   You can customize the parameter connections using AUTO_TEMPLATEs,
8332   just as you would with \\[verilog-auto-inst]."
8333   (save-excursion
8334     ;; Find beginning
8335     (let* ((pt (point))
8336            (indent-pt (save-excursion (verilog-backward-open-paren)
8337                                       (1+ (current-column))))
8338            (verilog-auto-inst-column (max verilog-auto-inst-column
8339                                           (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
8340            (modi (verilog-modi-current))
8341            (vector-skip-list (unless verilog-auto-inst-vector
8342                                (verilog-modi-get-signals modi)))
8343            submod submodi inst skip-pins tpl-list tpl-num did-first)
8344       ;; Find module name that is instantiated
8345       (setq submod (save-excursion
8346                      ;; Get to the point where AUTOINST normally is to read the module
8347                      (verilog-re-search-forward-quick "[(;]" nil nil)
8348                      (verilog-read-inst-module))
8349             inst   (save-excursion
8350                      ;; Get to the point where AUTOINST normally is to read the module
8351                      (verilog-re-search-forward-quick "[(;]" nil nil)
8352                      (verilog-read-inst-name))
8353             vl-cell-type submod
8354             vl-cell-name inst
8355             skip-pins (aref (verilog-read-inst-pins) 0))
8356
8357       ;; Parse any AUTO_LISP() before here
8358       (verilog-read-auto-lisp (point-min) pt)
8359
8360       ;; Lookup position, etc of submodule
8361       ;; Note this may raise an error
8362       (when (setq submodi (verilog-modi-lookup submod t))
8363         ;; If there's a number in the instantiation, it may be a argument to the
8364         ;; automatic variable instantiation program.
8365         (let* ((tpl-info (verilog-read-auto-template submod))
8366                (tpl-regexp (aref tpl-info 0)))
8367           (setq tpl-num (if (string-match tpl-regexp inst)
8368                             (match-string 1 inst)
8369                           "")
8370                 tpl-list (aref tpl-info 1)))
8371         ;; Find submodule's signals and dump
8372         (let ((sig-list (verilog-signals-not-in
8373                          (verilog-modi-get-gparams submodi)
8374                          skip-pins))
8375               (vl-dir "parameter"))
8376           (when sig-list
8377             (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8378             (indent-to indent-pt)
8379             (insert "// Parameters\n")  ;; Note these are searched for in verilog-read-sub-decls
8380             (mapcar (function (lambda (port)
8381                                 (verilog-auto-inst-port port indent-pt tpl-list tpl-num nil)))
8382                     sig-list)))
8383         ;; Kill extra semi
8384         (save-excursion
8385           (cond (did-first
8386                  (re-search-backward "," pt t)
8387                  (delete-char 1)
8388                  (insert ")")
8389                  (search-forward "\n")  ;; Added by inst-port
8390                  (delete-backward-char 1)
8391                  (if (search-forward ")" nil t) ;; From user, moved up a line
8392                      (delete-backward-char 1))
8393                  )))
8394         ))))
8395
8396 (defun verilog-auto-reg ()
8397   "Expand AUTOREG statements, as part of \\[verilog-auto].
8398 Make reg statements for any output that isn't already declared,
8399 and isn't a wire output from a block.
8400
8401 Limitations:
8402   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8403
8404   This does NOT work on memories, declare those yourself.
8405
8406 An example:
8407
8408         module ex_reg (o,i)
8409            output o;
8410            input i;
8411            /*AUTOREG*/
8412            always o = i;
8413         endmodule
8414
8415 Typing \\[verilog-auto] will make this into:
8416
8417         module ex_reg (o,i)
8418            output o;
8419            input i;
8420            /*AUTOREG*/
8421            // Beginning of automatic regs (for this module's undeclared outputs)
8422            reg                  o;
8423            // End of automatics
8424            always o = i;
8425         endmodule"
8426   (save-excursion
8427     ;; Point must be at insertion point.
8428     (let* ((indent-pt (current-indentation))
8429            (modi (verilog-modi-current))
8430            (sig-list (verilog-signals-not-in
8431                       (verilog-modi-get-outputs modi)
8432                       (append (verilog-modi-get-wires modi)
8433                               (verilog-modi-get-regs modi)
8434                               (verilog-modi-get-assigns modi)
8435                               (verilog-modi-get-consts modi)
8436                               (verilog-modi-get-gparams modi)
8437                               (verilog-modi-get-sub-outputs modi)
8438                               (verilog-modi-get-sub-inouts modi)
8439                               ))))
8440       (forward-line 1)
8441       (when sig-list
8442         (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
8443         (verilog-insert-definition sig-list "reg" indent-pt nil)
8444         (verilog-modi-cache-add-regs modi sig-list)
8445         (verilog-insert-indent "// End of automatics\n"))
8446       )))
8447
8448 (defun verilog-auto-reg-input ()
8449   "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
8450 Make reg statements instantiation inputs that aren't already declared.
8451 This is useful for making a top level shell for testing the module that is
8452 to be instantiated.
8453
8454 Limitations:
8455   This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
8456
8457   This does NOT work on memories, declare those yourself.
8458
8459 An example (see `verilog-auto-inst' for what else is going on here):
8460
8461         module ex_reg_input (o,i)
8462            output o;
8463            input i;
8464            /*AUTOREGINPUT*/
8465            inst inst (/*AUTOINST*/);
8466         endmodule
8467
8468 Typing \\[verilog-auto] will make this into:
8469
8470         module ex_reg_input (o,i)
8471            output o;
8472            input i;
8473            /*AUTOREGINPUT*/
8474            // Beginning of automatic reg inputs (for undeclared ...
8475            reg [31:0]           iv;             // From inst of inst.v
8476            // End of automatics
8477            inst inst (/*AUTOINST*/
8478                       // Outputs
8479                       .o                        (o[31:0]),
8480                       // Inputs
8481                       .iv                       (iv));
8482         endmodule"
8483   (save-excursion
8484     ;; Point must be at insertion point.
8485     (let* ((indent-pt (current-indentation))
8486            (modi (verilog-modi-current))
8487            (sig-list (verilog-signals-combine-bus
8488                       (verilog-signals-not-in
8489                        (append (verilog-modi-get-sub-inputs modi)
8490                                (verilog-modi-get-sub-inouts modi))
8491                        (verilog-modi-get-signals modi)
8492                        ))))
8493       (forward-line 1)
8494       (when sig-list
8495         (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
8496         (verilog-insert-definition sig-list "reg" indent-pt nil)
8497         (verilog-modi-cache-add-regs modi sig-list)
8498         (verilog-insert-indent "// End of automatics\n"))
8499       )))
8500
8501 (defun verilog-auto-wire ()
8502   "Expand AUTOWIRE statements, as part of \\[verilog-auto].
8503 Make wire statements for instantiations outputs that aren't
8504 already declared.
8505
8506 Limitations:
8507   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
8508   and all busses must have widths, such as those from AUTOINST, or using []
8509   in AUTO_TEMPLATEs.
8510
8511   This does NOT work on memories or SystemVerilog .name connections,
8512   declare those yourself.
8513
8514 An example (see `verilog-auto-inst' for what else is going on here):
8515
8516         module ex_wire (o,i)
8517            output o;
8518            input i;
8519            /*AUTOWIRE*/
8520            inst inst (/*AUTOINST*/);
8521         endmodule
8522
8523 Typing \\[verilog-auto] will make this into:
8524
8525         module ex_wire (o,i)
8526            output o;
8527            input i;
8528            /*AUTOWIRE*/
8529            // Beginning of automatic wires
8530            wire [31:0]          ov;     // From inst of inst.v
8531            // End of automatics
8532            inst inst (/*AUTOINST*/
8533                       // Outputs
8534                       .ov       (ov[31:0]),
8535                       // Inputs
8536                       .i        (i));
8537            wire o = | ov;
8538         endmodule"
8539   (save-excursion
8540     ;; Point must be at insertion point.
8541     (let* ((indent-pt (current-indentation))
8542            (modi (verilog-modi-current))
8543            (sig-list (verilog-signals-combine-bus
8544                       (verilog-signals-not-in
8545                        (append (verilog-modi-get-sub-outputs modi)
8546                                (verilog-modi-get-sub-inouts modi))
8547                        (verilog-modi-get-signals modi)
8548                        ))))
8549       (forward-line 1)
8550       (when sig-list
8551         (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
8552         (verilog-insert-definition sig-list "wire" indent-pt nil)
8553         (verilog-modi-cache-add-wires modi sig-list)
8554         (verilog-insert-indent "// End of automatics\n")
8555         (when nil       ;; Too slow on huge modules, plus makes everyone's module change
8556           (beginning-of-line)
8557           (setq pnt (point))
8558           (verilog-pretty-declarations)
8559           (goto-char pnt)
8560           (verilog-pretty-expr "//")))
8561       )))
8562
8563 (defun verilog-auto-output ()
8564   "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
8565 Make output statements for any output signal from an /*AUTOINST*/ that
8566 isn't a input to another AUTOINST.  This is useful for modules which
8567 only instantiate other modules.
8568
8569 Limitations:
8570   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8571
8572   If placed inside the parenthesis of a module declaration, it creates
8573   Verilog 2001 style, else uses Verilog 1995 style.
8574
8575   If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
8576   instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
8577
8578   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8579
8580   Signals matching `verilog-auto-output-ignore-regexp' are not included.
8581
8582 An example (see `verilog-auto-inst' for what else is going on here):
8583
8584         module ex_output (ov,i)
8585            input i;
8586            /*AUTOOUTPUT*/
8587            inst inst (/*AUTOINST*/);
8588         endmodule
8589
8590 Typing \\[verilog-auto] will make this into:
8591
8592         module ex_output (ov,i)
8593            input i;
8594            /*AUTOOUTPUT*/
8595            // Beginning of automatic outputs (from unused autoinst outputs)
8596            output [31:0]        ov;                     // From inst of inst.v
8597            // End of automatics
8598            inst inst (/*AUTOINST*/
8599                       // Outputs
8600                       .ov                       (ov[31:0]),
8601                       // Inputs
8602                       .i                        (i));
8603         endmodule"
8604   (save-excursion
8605     ;; Point must be at insertion point.
8606     (let* ((indent-pt (current-indentation))
8607            (v2k  (verilog-in-paren))
8608            (modi (verilog-modi-current))
8609            (sig-list (verilog-signals-not-in
8610                       (verilog-modi-get-sub-outputs modi)
8611                       (append (verilog-modi-get-outputs modi)
8612                               (verilog-modi-get-inouts modi)
8613                               (verilog-modi-get-sub-inputs modi)
8614                               (verilog-modi-get-sub-inouts modi)
8615                               ))))
8616       (setq sig-list (verilog-signals-not-matching-regexp
8617                       sig-list verilog-auto-output-ignore-regexp))
8618       (forward-line 1)
8619       (when v2k (verilog-repair-open-comma))
8620       (when sig-list
8621         (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
8622         (verilog-insert-definition sig-list "output" indent-pt v2k)
8623         (verilog-modi-cache-add-outputs modi sig-list)
8624         (verilog-insert-indent "// End of automatics\n"))
8625       (when v2k (verilog-repair-close-comma))
8626       )))
8627
8628 (defun verilog-auto-output-every ()
8629   "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
8630 Make output statements for any signals that aren't primary inputs or
8631 outputs already.  This makes every signal in the design a output.  This is
8632 useful to get Synopsys to preserve every signal in the design, since it
8633 won't optimize away the outputs.
8634
8635 An example:
8636
8637         module ex_output_every (o,i,tempa,tempb)
8638            output o;
8639            input i;
8640            /*AUTOOUTPUTEVERY*/
8641            wire tempa = i;
8642            wire tempb = tempa;
8643            wire o = tempb;
8644         endmodule
8645
8646 Typing \\[verilog-auto] will make this into:
8647
8648         module ex_output_every (o,i,tempa,tempb)
8649            output o;
8650            input i;
8651            /*AUTOOUTPUTEVERY*/
8652            // Beginning of automatic outputs (every signal)
8653            output               tempb;
8654            output               tempa;
8655            // End of automatics
8656            wire tempa = i;
8657            wire tempb = tempa;
8658            wire o = tempb;
8659         endmodule"
8660   (save-excursion
8661     ;;Point must be at insertion point
8662     (let* ((indent-pt (current-indentation))
8663            (v2k  (verilog-in-paren))
8664            (modi (verilog-modi-current))
8665            (sig-list (verilog-signals-combine-bus
8666                       (verilog-signals-not-in
8667                        (verilog-modi-get-signals modi)
8668                        (verilog-modi-get-ports modi)
8669                        ))))
8670       (forward-line 1)
8671       (when v2k (verilog-repair-open-comma))
8672       (when sig-list
8673         (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
8674         (verilog-insert-definition sig-list "output" indent-pt v2k)
8675         (verilog-modi-cache-add-outputs modi sig-list)
8676         (verilog-insert-indent "// End of automatics\n"))
8677       (when v2k (verilog-repair-close-comma))
8678       )))
8679
8680 (defun verilog-auto-input ()
8681   "Expand AUTOINPUT statements, as part of \\[verilog-auto].
8682 Make input statements for any input signal into an /*AUTOINST*/ that
8683 isn't declared elsewhere inside the module.  This is useful for modules which
8684 only instantiate other modules.
8685
8686 Limitations:
8687   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8688
8689   If placed inside the parenthesis of a module declaration, it creates
8690   Verilog 2001 style, else uses Verilog 1995 style.
8691
8692   If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
8693   instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
8694
8695   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8696
8697   Signals matching `verilog-auto-input-ignore-regexp' are not included.
8698
8699 An example (see `verilog-auto-inst' for what else is going on here):
8700
8701         module ex_input (ov,i)
8702            output [31:0] ov;
8703            /*AUTOINPUT*/
8704            inst inst (/*AUTOINST*/);
8705         endmodule
8706
8707 Typing \\[verilog-auto] will make this into:
8708
8709         module ex_input (ov,i)
8710            output [31:0] ov;
8711            /*AUTOINPUT*/
8712            // Beginning of automatic inputs (from unused autoinst inputs)
8713            input                i;                      // From inst of inst.v
8714            // End of automatics
8715            inst inst (/*AUTOINST*/
8716                       // Outputs
8717                       .ov                       (ov[31:0]),
8718                       // Inputs
8719                       .i                        (i));
8720         endmodule"
8721   (save-excursion
8722     (let* ((indent-pt (current-indentation))
8723            (v2k  (verilog-in-paren))
8724            (modi (verilog-modi-current))
8725            (sig-list (verilog-signals-not-in
8726                       (verilog-modi-get-sub-inputs modi)
8727                       (append (verilog-modi-get-inputs modi)
8728                               (verilog-modi-get-inouts modi)
8729                               (verilog-modi-get-wires modi)
8730                               (verilog-modi-get-regs modi)
8731                               (verilog-modi-get-consts modi)
8732                               (verilog-modi-get-gparams modi)
8733                               (verilog-modi-get-sub-outputs modi)
8734                               (verilog-modi-get-sub-inouts modi)
8735                               ))))
8736       (setq sig-list (verilog-signals-not-matching-regexp
8737                       sig-list verilog-auto-input-ignore-regexp))
8738       (forward-line 1)
8739       (when v2k (verilog-repair-open-comma))
8740       (when sig-list
8741         (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
8742         (verilog-insert-definition sig-list "input" indent-pt v2k)
8743         (verilog-modi-cache-add-inputs modi sig-list)
8744         (verilog-insert-indent "// End of automatics\n"))
8745       (when v2k (verilog-repair-close-comma))
8746       )))
8747
8748 (defun verilog-auto-inout ()
8749   "Expand AUTOINOUT statements, as part of \\[verilog-auto].
8750 Make inout statements for any inout signal in an /*AUTOINST*/ that
8751 isn't declared elsewhere inside the module.
8752
8753 Limitations:
8754   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8755
8756   If placed inside the parenthesis of a module declaration, it creates
8757   Verilog 2001 style, else uses Verilog 1995 style.
8758
8759   If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
8760   instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
8761
8762   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8763
8764   Signals matching `verilog-auto-inout-ignore-regexp' are not included.
8765
8766 An example (see `verilog-auto-inst' for what else is going on here):
8767
8768         module ex_inout (ov,i)
8769            input i;
8770            /*AUTOINOUT*/
8771            inst inst (/*AUTOINST*/);
8772         endmodule
8773
8774 Typing \\[verilog-auto] will make this into:
8775
8776         module ex_inout (ov,i)
8777            input i;
8778            /*AUTOINOUT*/
8779            // Beginning of automatic inouts (from unused autoinst inouts)
8780            inout [31:0] ov;                     // From inst of inst.v
8781            // End of automatics
8782            inst inst (/*AUTOINST*/
8783                       // Inouts
8784                       .ov                       (ov[31:0]),
8785                       // Inputs
8786                       .i                        (i));
8787         endmodule"
8788   (save-excursion
8789     ;; Point must be at insertion point.
8790     (let* ((indent-pt (current-indentation))
8791            (v2k  (verilog-in-paren))
8792            (modi (verilog-modi-current))
8793            (sig-list (verilog-signals-not-in
8794                       (verilog-modi-get-sub-inouts modi)
8795                       (append (verilog-modi-get-outputs modi)
8796                               (verilog-modi-get-inouts modi)
8797                               (verilog-modi-get-inputs modi)
8798                               (verilog-modi-get-sub-inputs modi)
8799                               (verilog-modi-get-sub-outputs modi)
8800                               ))))
8801       (setq sig-list (verilog-signals-not-matching-regexp
8802                       sig-list verilog-auto-inout-ignore-regexp))
8803       (forward-line 1)
8804       (when v2k (verilog-repair-open-comma))
8805       (when sig-list
8806         (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
8807         (verilog-insert-definition sig-list "inout" indent-pt v2k)
8808         (verilog-modi-cache-add-inouts modi sig-list)
8809         (verilog-insert-indent "// End of automatics\n"))
8810       (when v2k (verilog-repair-close-comma))
8811       )))
8812
8813 (defun verilog-auto-inout-module ()
8814   "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
8815 Take input/output/inout statements from the specified module and insert
8816 into the current module.  This is useful for making null templates and
8817 shell modules which need to have identical I/O with another module.  Any
8818 I/O which are already defined in this module will not be redefined.
8819
8820 Limitations:
8821   If placed inside the parenthesis of a module declaration, it creates
8822   Verilog 2001 style, else uses Verilog 1995 style.
8823
8824   Concatenation and outputting partial busses is not supported.
8825
8826   Module names must be resolvable to filenames.  See `verilog-auto-inst'.
8827
8828   Signals are not inserted in the same order as in the original module,
8829   though they will appear to be in the same order to a AUTOINST
8830   instantiating either module.
8831
8832 An example:
8833
8834         module ex_shell (/*AUTOARG*/)
8835            /*AUTOINOUTMODULE(\"ex_main\")*/
8836         endmodule
8837
8838         module ex_main (i,o,io)
8839           input i;
8840           output o;
8841           inout io;
8842         endmodule
8843
8844 Typing \\[verilog-auto] will make this into:
8845
8846         module ex_shell (/*AUTOARG*/i,o,io)
8847            /*AUTOINOUTMODULE(\"ex_main\")*/
8848            // Beginning of automatic in/out/inouts (from specific module)
8849            input i;
8850            output o;
8851            inout io;
8852            // End of automatics
8853         endmodule"
8854   (save-excursion
8855     (let* ((submod (car (verilog-read-auto-params 1))) submodi)
8856       ;; Lookup position, etc of co-module
8857       ;; Note this may raise an error
8858       (when (setq submodi (verilog-modi-lookup submod t))
8859         (let* ((indent-pt (current-indentation))
8860                (v2k  (verilog-in-paren))
8861                (modi (verilog-modi-current))
8862                (sig-list-i  (verilog-signals-not-in
8863                              (verilog-modi-get-inputs submodi)
8864                              (append (verilog-modi-get-inputs modi))))
8865                (sig-list-o  (verilog-signals-not-in
8866                              (verilog-modi-get-outputs submodi)
8867                              (append (verilog-modi-get-outputs modi))))
8868                (sig-list-io (verilog-signals-not-in
8869                              (verilog-modi-get-inouts submodi)
8870                              (append (verilog-modi-get-inouts modi)))))
8871           (forward-line 1)
8872           (when v2k (verilog-repair-open-comma))
8873           (when (or sig-list-i sig-list-o sig-list-io)
8874             (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
8875             ;; Don't sort them so a upper AUTOINST will match the main module
8876             (verilog-insert-definition sig-list-o  "output" indent-pt v2k t)
8877             (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
8878             (verilog-insert-definition sig-list-i  "input" indent-pt v2k t)
8879             (verilog-modi-cache-add-inputs modi sig-list-i)
8880             (verilog-modi-cache-add-outputs modi sig-list-o)
8881             (verilog-modi-cache-add-inouts modi sig-list-io)
8882             (verilog-insert-indent "// End of automatics\n"))
8883           (when v2k (verilog-repair-close-comma))
8884           )))))
8885
8886 (defun verilog-auto-sense-sigs (modi presense-sigs)
8887   "Return list of signals for current AUTOSENSE block."
8888   (let* ((sigss (verilog-read-always-signals))
8889          (sig-list (verilog-signals-not-params
8890                     (verilog-signals-not-in (verilog-alw-get-inputs sigss)
8891                                             (append (and (not verilog-auto-sense-include-inputs)
8892                                                          (verilog-alw-get-outputs sigss))
8893                                                     (verilog-modi-get-consts modi)
8894                                                     (verilog-modi-get-gparams modi)
8895                                                     presense-sigs)))))
8896     sig-list))
8897
8898 (defun verilog-auto-sense ()
8899   "Expand AUTOSENSE statements, as part of \\[verilog-auto].
8900 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
8901 with one automatically derived from all inputs declared in the always
8902 statement.  Signals that are generated within the same always block are NOT
8903 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
8904 Long lines are split based on the `fill-column', see \\[set-fill-column].
8905
8906 Limitations:
8907   Verilog does not allow memories (multidimensional arrays) in sensitivity
8908   lists.  AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
8909
8910 Constant signals:
8911   AUTOSENSE cannot always determine if a `define is a constant or a signal
8912   (it could be in a include file for example).  If a `define or other signal
8913   is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
8914   declaration anywhere in the module (parenthesis are required):
8915
8916         /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
8917
8918   Better yet, use a parameter, which will be understood to be constant
8919   automatically.
8920
8921 OOps!
8922   If AUTOSENSE makes a mistake, please report it.  (First try putting
8923   a begin/end after your always!) As a workaround, if a signal that
8924   shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
8925   If a signal should be in the sensitivity list wasn't, placing it before
8926   the /*AUTOSENSE*/ comment will prevent it from being deleted when the
8927   autos are updated (or added if it occurs there already).
8928
8929 An example:
8930
8931            always @ (/*AUTOSENSE*/) begin
8932               /* AUTO_CONSTANT (`constant) */
8933               outin = ina | inb | `constant;
8934               out = outin;
8935            end
8936
8937 Typing \\[verilog-auto] will make this into:
8938
8939            always @ (/*AUTOSENSE*/ina or inb) begin
8940               /* AUTO_CONSTANT (`constant) */
8941               outin = ina | inb | `constant;
8942               out = outin;
8943            end"
8944   (save-excursion
8945     ;; Find beginning
8946     (let* ((start-pt (save-excursion
8947                        (verilog-re-search-backward "(" nil t)
8948                        (point)))
8949            (indent-pt (save-excursion
8950                         (or (and (goto-char start-pt) (1+ (current-column)))
8951                             (current-indentation))))
8952            (modi (verilog-modi-current))
8953            (sig-memories (verilog-signals-memory
8954                           (append
8955                            (verilog-modi-get-regs modi)
8956                            (verilog-modi-get-wires modi))))
8957            sig-list not-first presense-sigs)
8958       ;; Read signals in always, eliminate outputs from sense list
8959       (setq presense-sigs (verilog-signals-from-signame
8960                            (save-excursion
8961                              (verilog-read-signals start-pt (point)))))
8962       (setq sig-list (verilog-auto-sense-sigs modi presense-sigs))
8963       (when sig-memories
8964         (let ((tlen (length sig-list)))
8965           (setq sig-list (verilog-signals-not-in sig-list sig-memories))
8966           (if (not (eq tlen (length sig-list))) (insert " /*memory or*/ "))))
8967       (if (and presense-sigs  ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
8968                (save-excursion (goto-char (point))
8969                                (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
8970                                (verilog-re-search-backward "\\s-" start-pt t)
8971                                (while (looking-at "\\s-`endif")
8972                                  (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
8973                                  (verilog-re-search-backward "\\s-" start-pt t))
8974                                (not (looking-at "\\s-or\\b"))))
8975           (setq not-first t))
8976       (setq sig-list (sort sig-list `verilog-signals-sort-compare))
8977       (while sig-list
8978         (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
8979                (insert "\n")
8980                (indent-to indent-pt)
8981                (if not-first (insert "or ")))
8982               (not-first (insert " or ")))
8983         (insert (verilog-sig-name (car sig-list)))
8984         (setq sig-list (cdr sig-list)
8985               not-first t))
8986       )))
8987
8988 (defun verilog-auto-reset ()
8989   "Expand AUTORESET statements, as part of \\[verilog-auto].
8990 Replace the /*AUTORESET*/ comment with code to initialize all
8991 registers set elsewhere in the always block.
8992
8993 Limitations:
8994   AUTORESET will not clear memories.
8995
8996   AUTORESET uses <= if there are any <= in the block, else it uses =.
8997
8998 /*AUTORESET*/ presumes that any signals mentioned between the previous
8999 begin/case/if statement and the AUTORESET comment are being reset manually
9000 and should not be automatically reset.  This includes omitting any signals
9001 used on the right hand side of assignments.
9002
9003 By default, AUTORESET will include the width of the signal in the autos,
9004 this is a recent change.  To control this behavior, see
9005 `verilog-auto-reset-widths'.
9006
9007 AUTORESET ties signals to deasserted, which is presumed to be zero.
9008 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
9009 them to a one.
9010
9011 An example:
9012
9013     always @(posedge clk or negedge reset_l) begin
9014         if (!reset_l) begin
9015             c <= 1;
9016             /*AUTORESET*/
9017         end
9018         else begin
9019             a <= in_a;
9020             b <= in_b;
9021             c <= in_c;
9022         end
9023     end
9024
9025 Typing \\[verilog-auto] will make this into:
9026
9027     always @(posedge core_clk or negedge reset_l) begin
9028         if (!reset_l) begin
9029             c <= 1;
9030             /*AUTORESET*/
9031             // Beginning of autoreset for uninitialized flops
9032             a <= 0;
9033             b <= 0;
9034             // End of automatics
9035         end
9036         else begin
9037             a <= in_a;
9038             b <= in_b;
9039             c <= in_c;
9040         end
9041     end"
9042
9043   (interactive)
9044   (save-excursion
9045     ;; Find beginning
9046     (let* ((indent-pt (current-indentation))
9047            (modi (verilog-modi-current))
9048            (all-list (verilog-modi-get-signals modi))
9049            sigss sig-list prereset-sigs assignment-str)
9050       ;; Read signals in always, eliminate outputs from reset list
9051       (setq prereset-sigs (verilog-signals-from-signame
9052                            (save-excursion
9053                              (verilog-read-signals
9054                               (save-excursion
9055                                 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
9056                                 (point))
9057                               (point)))))
9058       (save-excursion
9059         (verilog-re-search-backward "@" nil t)
9060         (setq sigss (verilog-read-always-signals)))
9061       (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
9062                                (concat " <= " verilog-assignment-delay)
9063                              " = "))
9064       (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
9065                                              prereset-sigs))
9066       (setq sig-list (sort sig-list `verilog-signals-sort-compare))
9067       (when sig-list
9068         (insert "\n");
9069         (indent-to indent-pt)
9070         (insert "// Beginning of autoreset for uninitialized flops\n");
9071         (indent-to indent-pt)
9072         (while sig-list
9073           (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
9074                          (car sig-list))))
9075             (insert (verilog-sig-name sig)
9076                     assignment-str
9077                     (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
9078                     ";\n")
9079             (indent-to indent-pt)
9080             (setq sig-list (cdr sig-list))))
9081         (insert "// End of automatics"))
9082       )))
9083
9084 (defun verilog-auto-tieoff ()
9085   "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
9086 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
9087 signals to deasserted.
9088
9089 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
9090 input/output list as another module, but no internals.  Specifically, it
9091 finds all outputs in the module, and if that input is not otherwise declared
9092 as a register or wire, creates a tieoff.
9093
9094 AUTORESET ties signals to deasserted, which is presumed to be zero.
9095 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
9096 them to a one.
9097
9098 An example of making a stub for another module:
9099
9100     module FooStub (/*AUTOINST*/);
9101         /*AUTOINOUTMODULE(\"Foo\")*/
9102         /*AUTOTIEOFF*/
9103         // verilator lint_off UNUSED
9104         wire _unused_ok = &{1'b0,
9105                             /*AUTOUNUSED*/
9106                             1'b0};
9107         // verilator lint_on  UNUSED
9108     endmodule
9109
9110 Typing \\[verilog-auto] will make this into:
9111
9112     module FooStub (/*AUTOINST*/...);
9113         /*AUTOINOUTMODULE(\"Foo\")*/
9114         // Beginning of autotieoff
9115         output [2:0] foo;
9116         // End of automatics
9117
9118         /*AUTOTIEOFF*/
9119         // Beginning of autotieoff
9120         wire [2:0] foo = 3'b0;
9121         // End of automatics
9122         ...
9123     endmodule"
9124   (interactive)
9125   (save-excursion
9126     ;; Find beginning
9127     (let* ((indent-pt (current-indentation))
9128            (modi (verilog-modi-current))
9129            (sig-list (verilog-signals-not-in
9130                       (verilog-modi-get-outputs modi)
9131                       (append (verilog-modi-get-wires modi)
9132                               (verilog-modi-get-regs modi)
9133                               (verilog-modi-get-assigns modi)
9134                               (verilog-modi-get-consts modi)
9135                               (verilog-modi-get-gparams modi)
9136                               (verilog-modi-get-sub-outputs modi)
9137                               (verilog-modi-get-sub-inouts modi)
9138                               ))))
9139       (when sig-list
9140         (forward-line 1)
9141         (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
9142         (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9143         (verilog-modi-cache-add-wires modi sig-list)  ; Before we trash list
9144         (while sig-list
9145           (let ((sig (car sig-list)))
9146             (verilog-insert-one-definition sig "wire" indent-pt)
9147             (indent-to (max 48 (+ indent-pt 40)))
9148             (insert "= " (verilog-sig-tieoff sig)
9149                     ";\n")
9150             (setq sig-list (cdr sig-list))))
9151         (verilog-insert-indent "// End of automatics\n")
9152         ))))
9153
9154 (defun verilog-auto-unused ()
9155   "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
9156 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
9157 input and inout signals.
9158
9159 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
9160 input/output list as another module, but no internals.  Specifically, it
9161 finds all inputs and inouts in the module, and if that input is not otherwise
9162 used, adds it to a comma separated list.
9163
9164 The comma separated list is intended to be used to create a _unused_ok
9165 signal.  Using the exact name \"_unused_ok\" for name of the temporary
9166 signal is recommended as it will insure maximum forward compatibility, it
9167 also makes lint warnings easy to understand; ignore any unused warnings
9168 with \"unused\" in the signal name.
9169
9170 To reduce simulation time, the _unused_ok signal should be forced to a
9171 constant to prevent wiggling.  The easiest thing to do is use a
9172 reduction-and with 1'b0 as shown.
9173
9174 This way all unused signals are in one place, making it convenient to add
9175 your tool's specific pragmas around the assignment to disable any unused
9176 warnings.
9177
9178 You can add signals you do not want included in AUTOUNUSED with
9179 `verilog-auto-unused-ignore-regexp'.
9180
9181 An example of making a stub for another module:
9182
9183     module FooStub (/*AUTOINST*/);
9184         /*AUTOINOUTMODULE(\"Foo\")*/
9185         /*AUTOTIEOFF*/
9186         // verilator lint_off UNUSED
9187         wire _unused_ok = &{1'b0,
9188                             /*AUTOUNUSED*/
9189                             1'b0};
9190         // verilator lint_on  UNUSED
9191     endmodule
9192
9193 Typing \\[verilog-auto] will make this into:
9194
9195         ...
9196         // verilator lint_off UNUSED
9197         wire _unused_ok = &{1'b0,
9198                             /*AUTOUNUSED*/
9199                             // Beginning of automatics
9200                             unused_input_a,
9201                             unused_input_b,
9202                             unused_input_c,
9203                             // End of automatics
9204                             1'b0};
9205         // verilator lint_on  UNUSED
9206     endmodule"
9207   (interactive)
9208   (save-excursion
9209     ;; Find beginning
9210     (let* ((indent-pt (progn (search-backward "/*") (current-column)))
9211            (modi (verilog-modi-current))
9212            (sig-list (verilog-signals-not-in
9213                       (append (verilog-modi-get-inputs modi)
9214                               (verilog-modi-get-inouts modi))
9215                       (append (verilog-modi-get-sub-inputs modi)
9216                               (verilog-modi-get-sub-inouts modi)
9217                               ))))
9218       (setq sig-list (verilog-signals-not-matching-regexp
9219                       sig-list verilog-auto-unused-ignore-regexp))
9220       (when sig-list
9221         (forward-line 1)
9222         (verilog-insert-indent "// Beginning of automatic unused inputs\n")
9223         (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9224         (while sig-list
9225           (let ((sig (car sig-list)))
9226             (indent-to indent-pt)
9227             (insert (verilog-sig-name sig) ",\n")
9228             (setq sig-list (cdr sig-list))))
9229         (verilog-insert-indent "// End of automatics\n")
9230         ))))
9231
9232 (defun verilog-enum-ascii (signm elim-regexp)
9233   "Convert a enum name SIGNM to a ascii string for insertion.
9234 Remove user provided prefix ELIM-REGEXP."
9235   (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
9236   (let ((case-fold-search t))
9237     ;; All upper becomes all lower for readability
9238     (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
9239
9240 (defun verilog-auto-ascii-enum ()
9241   "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
9242 Create a register to contain the ASCII decode of a enumerated signal type.
9243 This will allow trace viewers to show the ASCII name of states.
9244
9245 First, parameters are built into a enumeration using the synopsys enum
9246 comment.  The comment must be between the keyword and the symbol.
9247 (Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
9248
9249 Next, registers which that enum applies to are also tagged with the same
9250 enum.  Synopsys also suggests labeling state vectors, but `verilog-mode'
9251 doesn't care.
9252
9253 Finally, a AUTOASCIIENUM command is used.
9254
9255   The first parameter is the name of the signal to be decoded.
9256
9257   The second parameter is the name to store the ASCII code into.  For the
9258   signal foo, I suggest the name _foo__ascii, where the leading _ indicates
9259   a signal that is just for simulation, and the magic characters _ascii
9260   tell viewers like Dinotrace to display in ASCII format.
9261
9262   The final optional parameter is a string which will be removed from the
9263   state names.
9264
9265 An example:
9266
9267         //== State enumeration
9268         parameter [2:0] // synopsys enum state_info
9269                            SM_IDLE =  3'b000,
9270                            SM_SEND =  3'b001,
9271                            SM_WAIT1 = 3'b010;
9272         //== State variables
9273         reg [2:0]       /* synopsys enum state_info */
9274                         state_r;                /* synopsys state_vector state_r */
9275         reg [2:0]       /* synopsys enum state_info */
9276                         state_e1;
9277
9278         //== ASCII state decoding
9279
9280         /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
9281
9282 Typing \\[verilog-auto] will make this into:
9283
9284         ... same front matter ...
9285
9286         /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
9287         // Beginning of automatic ASCII enum decoding
9288         reg [39:0]              state_ascii_r;          // Decode of state_r
9289         always @(state_r) begin
9290            case ({state_r})
9291                 SM_IDLE:  state_ascii_r = \"idle \";
9292                 SM_SEND:  state_ascii_r = \"send \";
9293                 SM_WAIT1: state_ascii_r = \"wait1\";
9294                 default:  state_ascii_r = \"%Erro\";
9295            endcase
9296         end
9297         // End of automatics"
9298   (save-excursion
9299     (let* ((params (verilog-read-auto-params 2 3))
9300            (undecode-name (nth 0 params))
9301            (ascii-name (nth 1 params))
9302            (elim-regexp (nth 2 params))
9303            ;;
9304            (indent-pt (current-indentation))
9305            (modi (verilog-modi-current))
9306            ;;
9307            (sig-list-consts (append (verilog-modi-get-consts modi)
9308                                     (verilog-modi-get-gparams modi)))
9309            (sig-list-all  (append (verilog-modi-get-regs modi)
9310                                   (verilog-modi-get-outputs modi)
9311                                   (verilog-modi-get-inouts modi)
9312                                   (verilog-modi-get-inputs modi)
9313                                   (verilog-modi-get-wires modi)))
9314            ;;
9315            (undecode-sig (or (assoc undecode-name sig-list-all)
9316                              (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
9317            (undecode-enum (or (verilog-sig-enum undecode-sig)
9318                               (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
9319            ;;
9320            (enum-sigs (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
9321                           (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum)))
9322            ;;
9323            (enum-chars 0)
9324            (ascii-chars 0))
9325       ;;
9326       ;; Find number of ascii chars needed
9327       (let ((tmp-sigs enum-sigs))
9328         (while tmp-sigs
9329           (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
9330                 ascii-chars (max ascii-chars (length (verilog-enum-ascii
9331                                                       (verilog-sig-name (car tmp-sigs))
9332                                                       elim-regexp)))
9333                 tmp-sigs (cdr tmp-sigs))))
9334       ;;
9335       (forward-line 1)
9336       (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
9337       (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
9338                                          (concat "Decode of " undecode-name) nil nil))))
9339         (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
9340         (verilog-modi-cache-add-regs modi decode-sig-list))
9341       ;;
9342       (verilog-insert-indent "always @(" undecode-name ") begin\n")
9343       (setq indent-pt (+ indent-pt verilog-indent-level))
9344       (indent-to indent-pt)
9345       (insert "case ({" undecode-name "})\n")
9346       (setq indent-pt (+ indent-pt verilog-case-indent))
9347       ;;
9348       (let ((tmp-sigs enum-sigs)
9349             (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n" (1+ (max 8 enum-chars))
9350                             ascii-name ascii-chars))
9351             (errname (substring "%Error" 0 (min 6 ascii-chars))))
9352         (while tmp-sigs
9353           (verilog-insert-indent
9354            (format chrfmt (concat (verilog-sig-name (car tmp-sigs)) ":")
9355                    (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
9356                                        elim-regexp)))
9357           (setq tmp-sigs (cdr tmp-sigs)))
9358         (verilog-insert-indent (format chrfmt "default:" errname)))
9359       ;;
9360       (setq indent-pt (- indent-pt verilog-case-indent))
9361       (verilog-insert-indent "endcase\n")
9362       (setq indent-pt (- indent-pt verilog-indent-level))
9363       (verilog-insert-indent "end\n"
9364                              "// End of automatics\n")
9365       )))
9366
9367 (defun verilog-auto-templated-rel ()
9368   "Replace Templated relative line numbers with absolute line numbers.
9369 Internal use only.  This hacks around the line numbers in AUTOINST Templates
9370 being different from the final output's line numbering."
9371   (let ((templateno 0) (template-line (list 0)))
9372     ;; Find line number each template is on
9373     (goto-char (point-min))
9374     (while (search-forward "AUTO_TEMPLATE" nil t)
9375       (setq templateno (1+ templateno))
9376       (setq template-line (cons (count-lines (point-min) (point)) template-line)))
9377     (setq template-line (nreverse template-line))
9378     ;; Replace T# L# with absolute line number
9379     (goto-char (point-min))
9380     (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
9381       (replace-match (concat " Templated "
9382                              (int-to-string (+ (nth (string-to-int (match-string 1))
9383                                                     template-line)
9384                                                (string-to-int (match-string 2)))))
9385                      t t))))
9386
9387 \f
9388 ;;
9389 ;; Auto top level
9390 ;;
9391
9392 (defun verilog-auto (&optional inject)  ; Use verilog-inject-auto instead of passing a arg
9393   "Expand AUTO statements.
9394 Look for any /*AUTO...*/ commands in the code, as used in
9395 instantiations or argument headers.  Update the list of signals
9396 following the /*AUTO...*/ command.
9397
9398 Use \\[verilog-delete-auto] to remove the AUTOs.
9399
9400 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
9401
9402 Use \\[verilog-faq] for a pointer to frequently asked questions.
9403
9404 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
9405 called before and after this function, respectively.
9406
9407 For example:
9408         module (/*AUTOARG*/)
9409         /*AUTOINPUT*/
9410         /*AUTOOUTPUT*/
9411         /*AUTOWIRE*/
9412         /*AUTOREG*/
9413         somesub sub #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
9414
9415 You can also update the AUTOs from the shell using:
9416         emacs --batch  <filenames.v>  -f verilog-batch-auto
9417 Or fix indentation with:
9418         emacs --batch  <filenames.v>  -f verilog-batch-indent
9419 Likewise, you can delete or inject AUTOs with:
9420         emacs --batch  <filenames.v>  -f verilog-batch-delete-auto
9421         emacs --batch  <filenames.v>  -f verilog-batch-inject-auto
9422
9423 Using \\[describe-function], see also:
9424     `verilog-auto-arg'          for AUTOARG module instantiations
9425     `verilog-auto-ascii-enum'   for AUTOASCIIENUM enumeration decoding
9426     `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
9427     `verilog-auto-inout'        for AUTOINOUT making hierarchy inouts
9428     `verilog-auto-input'        for AUTOINPUT making hierarchy inputs
9429     `verilog-auto-inst'         for AUTOINST instantiation pins
9430     `verilog-auto-star'         for AUTOINST .* SystemVerilog pins
9431     `verilog-auto-inst-param'   for AUTOINSTPARAM instantiation params
9432     `verilog-auto-output'       for AUTOOUTPUT making hierarchy outputs
9433     `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
9434     `verilog-auto-reg'          for AUTOREG registers
9435     `verilog-auto-reg-input'    for AUTOREGINPUT instantiation registers
9436     `verilog-auto-reset'        for AUTORESET flop resets
9437     `verilog-auto-sense'        for AUTOSENSE always sensitivity lists
9438     `verilog-auto-tieoff'       for AUTOTIEOFF output tieoffs
9439     `verilog-auto-unused'       for AUTOUNUSED unused inputs/inouts
9440     `verilog-auto-wire'         for AUTOWIRE instantiation wires
9441
9442     `verilog-read-defines'      for reading `define values
9443     `verilog-read-includes'     for reading `includes
9444
9445 If you have bugs with these autos, try contacting the AUTOAUTHOR
9446 Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
9447   (interactive)
9448   (unless noninteractive (message "Updating AUTOs..."))
9449   (if (featurep 'dinotrace)
9450       (dinotrace-unannotate-all))
9451   (let ((oldbuf (if (not (buffer-modified-p))
9452                     (buffer-string)))
9453         ;; Before version 20, match-string with font-lock returns a
9454         ;; vector that is not equal to the string.  IE if on "input"
9455         ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
9456         (fontlocked (when (and ;(memq 'v19 verilog-emacs-features)
9457                                (boundp 'font-lock-mode)
9458                                font-lock-mode)
9459                       (font-lock-mode nil)
9460                       t)))
9461     (unwind-protect
9462         (save-excursion
9463           ;; If we're not in verilog-mode, change syntax table so parsing works right
9464           (unless (eq major-mode `verilog-mode) (verilog-mode))
9465           ;; Allow user to customize
9466           (run-hooks 'verilog-before-auto-hook)
9467           ;; Try to save the user from needing to revert-file to reread file local-variables
9468           (verilog-auto-reeval-locals)
9469           (verilog-read-auto-lisp (point-min) (point-max))
9470           (verilog-getopt-flags)
9471           ;; These two may seem obvious to do always, but on large includes it can be way too slow
9472           (when verilog-auto-read-includes
9473             (verilog-read-includes)
9474             (verilog-read-defines nil nil t))
9475           ;; This particular ordering is important
9476           ;; INST: Lower modules correct, no internal dependencies, FIRST
9477           (verilog-preserve-cache
9478            ;; Clear existing autos else we'll be screwed by existing ones
9479            (verilog-delete-auto)
9480            ;; Injection if appropriate
9481            (when inject
9482              (verilog-inject-inst)
9483              (verilog-inject-sense)
9484              (verilog-inject-arg))
9485            ;;
9486            (verilog-auto-search-do "/*AUTOINSTPARAM*/" 'verilog-auto-inst-param)
9487            (verilog-auto-search-do "/*AUTOINST*/" 'verilog-auto-inst)
9488            (verilog-auto-search-do ".*" 'verilog-auto-star)
9489            ;; Doesn't matter when done, but combine it with a common changer
9490            (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
9491            (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
9492            ;; Must be done before autoin/out as creates a reg
9493            (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
9494            ;;
9495            ;; first in/outs from other files
9496            (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
9497            ;; next in/outs which need previous sucked inputs first
9498            (verilog-auto-search-do "/*AUTOOUTPUT*/" 'verilog-auto-output)
9499            (verilog-auto-search-do "/*AUTOINPUT*/" 'verilog-auto-input)
9500            (verilog-auto-search-do "/*AUTOINOUT*/" 'verilog-auto-inout)
9501            ;; Then tie off those in/outs
9502            (verilog-auto-search-do "/*AUTOTIEOFF*/" 'verilog-auto-tieoff)
9503            ;; Wires/regs must be after inputs/outputs
9504            (verilog-auto-search-do "/*AUTOWIRE*/" 'verilog-auto-wire)
9505            (verilog-auto-search-do "/*AUTOREG*/" 'verilog-auto-reg)
9506            (verilog-auto-search-do "/*AUTOREGINPUT*/" 'verilog-auto-reg-input)
9507            ;; outputevery needs AUTOOUTPUTs done first
9508            (verilog-auto-search-do "/*AUTOOUTPUTEVERY*/" 'verilog-auto-output-every)
9509            ;; After we've created all new variables
9510            (verilog-auto-search-do "/*AUTOUNUSED*/" 'verilog-auto-unused)
9511            ;; Must be after all inputs outputs are generated
9512            (verilog-auto-search-do "/*AUTOARG*/" 'verilog-auto-arg)
9513            ;; Fix line numbers (comments only)
9514            (verilog-auto-templated-rel)
9515            )
9516           ;;
9517           (run-hooks 'verilog-auto-hook)
9518           ;;
9519           (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))
9520           ;;
9521           ;; If end result is same as when started, clear modified flag
9522           (cond ((and oldbuf (equal oldbuf (buffer-string)))
9523                  (set-buffer-modified-p nil)
9524                  (unless noninteractive (message "Updating AUTOs...done (no changes)")))
9525                 (t (unless noninteractive (message "Updating AUTOs...done")))))
9526       ;; Unwind forms
9527       (progn
9528         ;; Restore font-lock
9529         (when fontlocked (font-lock-mode t)))
9530       )))
9531 \f
9532
9533 ;;
9534 ;; Skeleton based code insertion
9535 ;;
9536 (defvar verilog-template-map nil
9537   "Keymap used in Verilog mode for smart template operations.")
9538
9539 (let ((verilog-mp (make-sparse-keymap)))
9540   (define-key verilog-mp "a" 'verilog-sk-always)
9541   (define-key verilog-mp "b" 'verilog-sk-begin)
9542   (define-key verilog-mp "c" 'verilog-sk-case)
9543   (define-key verilog-mp "f" 'verilog-sk-for)
9544   (define-key verilog-mp "g" 'verilog-sk-generate)
9545   (define-key verilog-mp "h" 'verilog-sk-header)
9546   (define-key verilog-mp "i" 'verilog-sk-initial)
9547   (define-key verilog-mp "j" 'verilog-sk-fork)
9548   (define-key verilog-mp "m" 'verilog-sk-module)
9549   (define-key verilog-mp "p" 'verilog-sk-primitive)
9550   (define-key verilog-mp "r" 'verilog-sk-repeat)
9551   (define-key verilog-mp "s" 'verilog-sk-specify)
9552   (define-key verilog-mp "t" 'verilog-sk-task)
9553   (define-key verilog-mp "w" 'verilog-sk-while)
9554   (define-key verilog-mp "x" 'verilog-sk-casex)
9555   (define-key verilog-mp "z" 'verilog-sk-casez)
9556   (define-key verilog-mp "?" 'verilog-sk-if)
9557   (define-key verilog-mp ":" 'verilog-sk-else-if)
9558   (define-key verilog-mp "/" 'verilog-sk-comment)
9559   (define-key verilog-mp "A" 'verilog-sk-assign)
9560   (define-key verilog-mp "F" 'verilog-sk-function)
9561   (define-key verilog-mp "I" 'verilog-sk-input)
9562   (define-key verilog-mp "O" 'verilog-sk-output)
9563   (define-key verilog-mp "S" 'verilog-sk-state-machine)
9564   (define-key verilog-mp "=" 'verilog-sk-inout)
9565   (define-key verilog-mp "W" 'verilog-sk-wire)
9566   (define-key verilog-mp "R" 'verilog-sk-reg)
9567   (define-key verilog-mp "D" 'verilog-sk-define-signal)
9568   (setq verilog-template-map verilog-mp))
9569
9570 ;;
9571 ;; Place the templates into Verilog Mode.  They may be inserted under any key.
9572 ;; C-c C-t will be the default.  If you use templates a lot, you
9573 ;; may want to consider moving the binding to another key in your .emacs
9574 ;; file.
9575 ;;
9576 ;(define-key verilog-mode-map "\C-ct" verilog-template-map)
9577 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
9578
9579 ;;; ---- statement skeletons ------------------------------------------
9580
9581 (define-skeleton verilog-sk-prompt-condition
9582   "Prompt for the loop condition."
9583   "[condition]: " str )
9584
9585 (define-skeleton verilog-sk-prompt-init
9586   "Prompt for the loop init statement."
9587   "[initial statement]: " str )
9588
9589 (define-skeleton verilog-sk-prompt-inc
9590   "Prompt for the loop increment statement."
9591   "[increment statement]: " str )
9592
9593 (define-skeleton verilog-sk-prompt-name
9594   "Prompt for the name of something."
9595   "[name]: " str)
9596
9597 (define-skeleton verilog-sk-prompt-clock
9598   "Prompt for the name of something."
9599   "name and edge of clock(s): " str)
9600
9601 (defvar verilog-sk-reset nil)
9602 (defun verilog-sk-prompt-reset ()
9603   "Prompt for the name of a state machine reset."
9604   (setq verilog-sk-reset (read-input "name of reset: " "rst")))
9605
9606
9607 (define-skeleton verilog-sk-prompt-state-selector
9608   "Prompt for the name of a state machine selector."
9609   "name of selector (eg {a,b,c,d}): " str )
9610
9611 (define-skeleton verilog-sk-prompt-output
9612   "Prompt for the name of something."
9613   "output: " str)
9614
9615 (define-skeleton verilog-sk-prompt-msb
9616   "Prompt for least significant bit specification."
9617   "msb:" str & ?: & (verilog-sk-prompt-lsb) | -1 )
9618
9619 (define-skeleton verilog-sk-prompt-lsb
9620   "Prompt for least significant bit specification."
9621   "lsb:" str )
9622
9623 (defvar verilog-sk-p nil)
9624 (define-skeleton verilog-sk-prompt-width
9625   "Prompt for a width specification."
9626   ()
9627   (progn
9628     (setq verilog-sk-p (point))
9629     (verilog-sk-prompt-msb)
9630     (if (> (point) verilog-sk-p) "] " " ")))
9631
9632 (defun verilog-sk-header ()
9633   "Insert a descriptive header at the top of the file."
9634   (interactive "*")
9635   (save-excursion
9636     (goto-char (point-min))
9637     (verilog-sk-header-tmpl)))
9638
9639 (define-skeleton verilog-sk-header-tmpl
9640   "Insert a comment block containing the module title, author, etc."
9641   "[Description]: "
9642   "//                              -*- Mode: Verilog -*-"
9643   "\n// Filename        : " (buffer-name)
9644   "\n// Description     : " str
9645   "\n// Author          : " (user-full-name)
9646   "\n// Created On      : " (current-time-string)
9647   "\n// Last Modified By: ."
9648   "\n// Last Modified On: ."
9649   "\n// Update Count    : 0"
9650   "\n// Status          : Unknown, Use with caution!"
9651   "\n")
9652
9653 (define-skeleton verilog-sk-module
9654   "Insert a module definition."
9655   ()
9656   > "module " (verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
9657   > _ \n
9658   > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
9659
9660 (define-skeleton verilog-sk-primitive
9661   "Insert a task definition."
9662   ()
9663   > "primitive " (verilog-sk-prompt-name) " ( " (verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
9664   > _ \n
9665   > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
9666
9667 (define-skeleton verilog-sk-task
9668   "Insert a task definition."
9669   ()
9670   > "task " (verilog-sk-prompt-name) & ?; \n
9671   > _ \n
9672   > "begin" \n
9673   > \n
9674   > (- verilog-indent-level-behavioral) "end" \n
9675   > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
9676
9677 (define-skeleton verilog-sk-function
9678   "Insert a function definition."
9679   ()
9680   > "function [" (verilog-sk-prompt-width) | -1 (verilog-sk-prompt-name) ?; \n
9681   > _ \n
9682   > "begin" \n
9683   > \n
9684   > (- verilog-indent-level-behavioral) "end" \n
9685   > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
9686
9687 (define-skeleton verilog-sk-always
9688   "Insert always block.  Uses the minibuffer to prompt
9689 for sensitivity list."
9690   ()
9691   > "always @ ( /*AUTOSENSE*/ ) begin\n"
9692   > _ \n
9693   > (- verilog-indent-level-behavioral) "end" \n >
9694   )
9695
9696 (define-skeleton verilog-sk-initial
9697   "Insert an initial block."
9698   ()
9699   > "initial begin\n"
9700   > _ \n
9701   > (- verilog-indent-level-behavioral) "end" \n > )
9702
9703 (define-skeleton verilog-sk-specify
9704   "Insert specify block.  "
9705   ()
9706   > "specify\n"
9707   > _ \n
9708   > (- verilog-indent-level-behavioral) "endspecify" \n > )
9709
9710 (define-skeleton verilog-sk-generate
9711   "Insert generate block.  "
9712   ()
9713   > "generate\n"
9714   > _ \n
9715   > (- verilog-indent-level-behavioral) "endgenerate" \n > )
9716
9717 (define-skeleton verilog-sk-begin
9718   "Insert begin end block.  Uses the minibuffer to prompt for name"
9719   ()
9720   > "begin" (verilog-sk-prompt-name) \n
9721   > _ \n
9722   > (- verilog-indent-level-behavioral) "end"
9723 )
9724
9725 (define-skeleton verilog-sk-fork
9726   "Insert an fork join block."
9727   ()
9728   > "fork\n"
9729   > "begin" \n
9730   > _ \n
9731   > (- verilog-indent-level-behavioral) "end" \n
9732   > "begin" \n
9733   > \n
9734   > (- verilog-indent-level-behavioral) "end" \n
9735   > (- verilog-indent-level-behavioral) "join" \n
9736   > )
9737
9738
9739 (define-skeleton verilog-sk-case
9740   "Build skeleton case statement, prompting for the selector expression,
9741 and the case items."
9742   "[selector expression]: "
9743   > "case (" str ") " \n
9744   > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
9745   resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
9746
9747 (define-skeleton verilog-sk-casex
9748   "Build skeleton casex statement, prompting for the selector expression,
9749 and the case items."
9750   "[selector expression]: "
9751   > "casex (" str ") " \n
9752   > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
9753   resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
9754
9755 (define-skeleton verilog-sk-casez
9756   "Build skeleton casez statement, prompting for the selector expression,
9757 and the case items."
9758   "[selector expression]: "
9759   > "casez (" str ") " \n
9760   > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
9761   resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
9762
9763 (define-skeleton verilog-sk-if
9764   "Insert a skeleton if statement."
9765   > "if (" (verilog-sk-prompt-condition) & ")" " begin" \n
9766   > _ \n
9767   > (- verilog-indent-level-behavioral) "end " \n )
9768
9769 (define-skeleton verilog-sk-else-if
9770   "Insert a skeleton else if statement."
9771   > (verilog-indent-line) "else if ("
9772   (progn (setq verilog-sk-p (point)) nil) (verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
9773   > _ \n
9774   > "end" (progn (electric-verilog-terminate-line) nil))
9775
9776 (define-skeleton verilog-sk-datadef
9777   "Common routine to get data definition"
9778   ()
9779   (verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
9780
9781 (define-skeleton verilog-sk-input
9782   "Insert an input definition."
9783   ()
9784   > "input  [" (verilog-sk-datadef))
9785
9786 (define-skeleton verilog-sk-output
9787   "Insert an output definition."
9788   ()
9789   > "output [" (verilog-sk-datadef))
9790
9791 (define-skeleton verilog-sk-inout
9792   "Insert an inout definition."
9793   ()
9794   > "inout  [" (verilog-sk-datadef))
9795
9796 (defvar verilog-sk-signal nil)
9797 (define-skeleton verilog-sk-def-reg
9798   "Insert a reg definition."
9799   ()
9800   > "reg    [" (verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
9801
9802 (defun verilog-sk-define-signal ()
9803   "Insert a definition of signal under point at top of module."
9804   (interactive "*")
9805   (let* (
9806          (sig-re "[a-zA-Z0-9_]*")
9807          (v1 (buffer-substring
9808                (save-excursion
9809                  (skip-chars-backward sig-re)
9810                  (point))
9811                (save-excursion
9812                  (skip-chars-forward sig-re)
9813                  (point))))
9814          )
9815     (if (not (member v1 verilog-keywords))
9816         (save-excursion
9817           (setq verilog-sk-signal v1)
9818           (verilog-beg-of-defun)
9819           (verilog-end-of-statement)
9820           (verilog-forward-syntactic-ws)
9821           (verilog-sk-def-reg)
9822           (message "signal at point is %s" v1))
9823       (message "object at point (%s) is a keyword" v1))
9824     )
9825   )
9826
9827
9828 (define-skeleton verilog-sk-wire
9829   "Insert a wire definition."
9830   ()
9831   > "wire   [" (verilog-sk-datadef))
9832
9833 (define-skeleton verilog-sk-reg
9834   "Insert a reg definition."
9835   ()
9836   > "reg   [" (verilog-sk-datadef))
9837
9838 (define-skeleton verilog-sk-assign
9839   "Insert a skeleton assign statement."
9840   ()
9841   > "assign " (verilog-sk-prompt-name) " = " _ ";" \n)
9842
9843 (define-skeleton verilog-sk-while
9844   "Insert a skeleton while loop statement."
9845   ()
9846   > "while ("  (verilog-sk-prompt-condition)  ") begin" \n
9847   > _ \n
9848   > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
9849
9850 (define-skeleton verilog-sk-repeat
9851   "Insert a skeleton repeat loop statement."
9852   ()
9853   > "repeat ("  (verilog-sk-prompt-condition)  ") begin" \n
9854   > _ \n
9855   > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
9856
9857 (define-skeleton verilog-sk-for
9858   "Insert a skeleton while loop statement."
9859   ()
9860   > "for ("
9861   (verilog-sk-prompt-init) "; "
9862   (verilog-sk-prompt-condition) "; "
9863   (verilog-sk-prompt-inc)
9864   ") begin" \n
9865   > _ \n
9866   > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
9867
9868 (define-skeleton verilog-sk-comment
9869   "Inserts three comment lines, making a display comment."
9870   ()
9871   > "/*\n"
9872   > "* " _ \n
9873   > "*/")
9874
9875 (define-skeleton verilog-sk-state-machine
9876   "Insert a state machine definition."
9877   "Name of state variable: "
9878   '(setq input "state")
9879   > "// State registers for " str | -23 \n
9880   '(setq verilog-sk-state str)
9881   > "reg [" (verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
9882   '(setq input nil)
9883   > \n
9884   > "// State FF for " verilog-sk-state \n
9885   > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
9886   > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
9887   > verilog-sk-state " = next_" verilog-sk-state ?; \n
9888   > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
9889   > \n
9890   > "// Next State Logic for " verilog-sk-state \n
9891   > "always @ ( /*AUTOSENSE*/ ) begin\n"
9892   > "case (" (verilog-sk-prompt-state-selector) ") " \n
9893   > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
9894   resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
9895   > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
9896
9897 ;; Eliminate compile warning
9898 (eval-when-compile
9899   (if (not (boundp 'mode-popup-menu))
9900       (defvar mode-popup-menu nil "Compatibility with XEmacs.")))
9901
9902 ;; ---- add menu 'Statements' in Verilog mode (MH)
9903 (defun verilog-add-statement-menu ()
9904   "Add the menu 'Statements' to the menu bar in Verilog mode."
9905   (if verilog-running-on-xemacs
9906       (progn
9907         (easy-menu-add verilog-stmt-menu)
9908         (easy-menu-add verilog-menu)
9909         (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))))
9910
9911 (add-hook 'verilog-mode-hook 'verilog-add-statement-menu)
9912
9913 \f
9914
9915 ;;
9916 ;; Include file loading with mouse/return event
9917 ;;
9918 ;; idea & first impl.: M. Rouat (eldo-mode.el)
9919 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
9920
9921 (if verilog-running-on-xemacs
9922     (require 'overlay)
9923   (require 'lucid)) ;; what else can we do ??
9924
9925 (defconst verilog-include-file-regexp
9926   "^`include\\s-+\"\\([^\n\"]*\\)\""
9927   "Regexp that matches the include file.")
9928
9929 (defvar verilog-mode-mouse-map nil
9930   "Map containing mouse bindings for `verilog-mode'.")
9931
9932 (if verilog-mode-mouse-map
9933     ()
9934   (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
9935     (set-keymap-parent map verilog-mode-map)
9936     ;; mouse button bindings
9937     (define-key map "\r"            'verilog-load-file-at-point)
9938     (if verilog-running-on-xemacs
9939         (define-key map 'button2    'verilog-load-file-at-mouse);ffap-at-mouse ?
9940       (define-key map [mouse-2]     'verilog-load-file-at-mouse))
9941     (if verilog-running-on-xemacs
9942         (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
9943       (define-key map [S-mouse-2]   'mouse-yank-at-click))
9944     (setq verilog-mode-mouse-map map))) ;; copy complete map now
9945
9946 ;; create set-extent-keymap procedure when it does not exist
9947 (eval-and-compile
9948   (unless (fboundp 'set-extent-keymap)
9949     (defun set-extent-keymap (extent keymap)
9950       "fallback version of set-extent-keymap (for emacs 2[01])"
9951       (set-extent-property extent 'local-map keymap))))
9952
9953 (defun verilog-colorize-include-files (beg end old-len)
9954   "This function colorizes included files when the mouse passes over them.
9955 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
9956   (save-excursion
9957     (save-match-data
9958       (let (end-point)
9959         (goto-char end)
9960         (setq end-point (verilog-get-end-of-line))
9961         (goto-char beg)
9962         (beginning-of-line)  ; scan entire line !
9963         ;; delete overlays existing on this line
9964         (let ((overlays (overlays-in (point) end-point)))
9965           (while overlays
9966             (if (and
9967                  (overlay-get (car overlays) 'detachable)
9968                  (overlay-get (car overlays) 'verilog-include-file))
9969                 (delete-overlay (car overlays)))
9970             (setq overlays (cdr overlays)))) ; let
9971         ;; make new ones, could reuse deleted one ?
9972         (while (search-forward-regexp verilog-include-file-regexp end-point t)
9973           (let (extent)
9974             (goto-char (match-beginning 1))
9975             (or (extent-at (point) (buffer-name) 'mouse-face) ;; not yet extended
9976                 (progn
9977                   (setq extent (make-extent (match-beginning 1) (match-end 1)))
9978                   (set-extent-property extent 'start-closed 't)
9979                   (set-extent-property extent 'end-closed 't)
9980                   (set-extent-property extent 'detachable 't)
9981                   (set-extent-property extent 'verilog-include-file 't)
9982                   (set-extent-property extent 'mouse-face 'highlight)
9983                   (set-extent-keymap extent verilog-mode-mouse-map)))))))))
9984
9985
9986 (defun verilog-colorize-include-files-buffer ()
9987   "Colorize a include file."
9988   (interactive)
9989   ;; delete overlays
9990   (let ((overlays (overlays-in (point-min) (point-max))))
9991     (while overlays
9992       (if (and
9993            (overlay-get (car overlays) 'detachable)
9994            (overlay-get (car overlays) 'verilog-include-file))
9995           (delete-overlay (car overlays)))
9996       (setq overlays (cdr overlays)))) ; let
9997   ;; remake overlays
9998   (verilog-colorize-include-files (point-min) (point-max) nil))
9999
10000 ;; ffap-at-mouse isn't useful for verilog mode. It uses library paths.
10001 ;; so define this function to do more or less the same as ffap-at-mouse
10002 ;; but first resolve filename...
10003 (defun verilog-load-file-at-mouse (event)
10004   "Load file under button 2 click's EVENT.
10005 Files are checked based on `verilog-library-directories'."
10006   (interactive "@e")
10007   (save-excursion ;; implement a verilog specific ffap-at-mouse
10008     (mouse-set-point event)
10009     (beginning-of-line)
10010     (if (looking-at verilog-include-file-regexp)
10011         (if (and (car (verilog-library-filenames
10012                        (match-string 1) (buffer-file-name)))
10013                  (file-readable-p (car (verilog-library-filenames
10014                                         (match-string 1) (buffer-file-name)))))
10015             (find-file (car (verilog-library-filenames
10016                              (match-string 1) (buffer-file-name))))
10017           (progn
10018             (message
10019              "File '%s' isn't readable, use shift-mouse2 to paste in this field"
10020              (match-string 1))))
10021       )))
10022
10023 ;; ffap isn't useable for verilog mode. It uses library paths.
10024 ;; so define this function to do more or less the same as ffap
10025 ;; but first resolve filename...
10026 (defun verilog-load-file-at-point ()
10027   "Load file under point.
10028 Files are checked based on `verilog-library-directories'."
10029   (interactive)
10030   (save-excursion ;; implement a verilog specific ffap
10031     (beginning-of-line)
10032     (if (looking-at verilog-include-file-regexp)
10033         (if (and
10034              (car (verilog-library-filenames
10035                    (match-string 1) (buffer-file-name)))
10036              (file-readable-p (car (verilog-library-filenames
10037                                     (match-string 1) (buffer-file-name)))))
10038             (find-file (car (verilog-library-filenames
10039                              (match-string 1) (buffer-file-name))))))
10040       ))
10041
10042
10043 ;;
10044 ;; Bug reporting
10045 ;;
10046
10047 (defun verilog-faq ()
10048   "Tell the user their current version, and where to get the FAQ etc."
10049   (interactive)
10050   (with-output-to-temp-buffer "*verilog-mode help*"
10051     (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
10052     (princ "\n")
10053     (princ "For new releases, see http://www.verilog.com\n")
10054     (princ "\n")
10055     (princ "For frequently asked questions, see http://www.veripool.com/verilog-mode-faq.html\n")
10056     (princ "\n")
10057     (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
10058     (princ "\n")))
10059
10060 (defun verilog-submit-bug-report ()
10061   "Submit via mail a bug report on verilog-mode.el."
10062   (interactive)
10063   (let ((reporter-prompt-for-summary-p t))
10064     (reporter-submit-bug-report
10065      "mac@verilog.com"
10066      (concat "verilog-mode v" verilog-mode-version)
10067      '(
10068        verilog-align-ifelse
10069        verilog-auto-endcomments
10070        verilog-auto-hook
10071        verilog-auto-indent-on-newline
10072        verilog-auto-inst-vector
10073        verilog-auto-inst-template-numbers
10074        verilog-auto-lineup
10075        verilog-auto-newline
10076        verilog-auto-save-policy
10077        verilog-auto-sense-defines-constant
10078        verilog-auto-sense-include-inputs
10079        verilog-before-auto-hook
10080        verilog-case-indent
10081        verilog-cexp-indent
10082        verilog-compiler
10083        verilog-coverage
10084        verilog-highlight-translate-off
10085        verilog-indent-begin-after-if
10086        verilog-indent-declaration-macros
10087        verilog-indent-level
10088        verilog-indent-level-behavioral
10089        verilog-indent-level-declaration
10090        verilog-indent-level-directive
10091        verilog-indent-level-module
10092        verilog-indent-lists
10093        verilog-library-flags
10094        verilog-library-directories
10095        verilog-library-extensions
10096        verilog-library-files
10097        verilog-linter
10098        verilog-minimum-comment-distance
10099        verilog-mode-hook
10100        verilog-simulator
10101        verilog-tab-always-indent
10102        verilog-tab-to-comment
10103        )
10104      nil nil
10105      (concat "Hi Mac,
10106
10107 I want to report a bug.  I've read the `Bugs' section of `Info' on
10108 Emacs, so I know how to make a clear and unambiguous report.  To get
10109 to that Info section, I typed
10110
10111 M-x info RET m " invocation-name " RET m bugs RET
10112
10113 Before I go further, I want to say that Verilog mode has changed my life.
10114 I save so much time, my files are colored nicely, my co workers respect
10115 my coding ability... until now.  I'd really appreciate anything you
10116 could do to help me out with this minor deficiency in the product.
10117
10118 If you have bugs with the AUTO functions, please CC the AUTOAUTHOR Wilson
10119 Snyder (wsnyder@wsnyder.org) and/or see http://www.veripool.com.
10120 You may also want to look at the Verilog-Mode FAQ, see
10121 http://www.veripool.com/verilog-mode-faq.html.
10122
10123 To reproduce the bug, start a fresh Emacs via " invocation-name "
10124 -no-init-file -no-site-file'.  In a new buffer, in verilog mode, type
10125 the code included below.
10126
10127 Given those lines, I expected [[Fill in here]] to happen;
10128 but instead, [[Fill in here]] happens!.
10129
10130 == The code: =="))))
10131
10132 ;; Local Variables:
10133 ;; checkdoc-permit-comma-termination-flag:t
10134 ;; checkdoc-force-docstrings-flag:nil
10135 ;; End:
10136
10137 ;;; verilog-mode.el ends here