tcl.el 53.9 KB
Newer Older
1
;;; tcl.el --- Tcl code editing commands for Emacs
Tom Tromey's avatar
Tom Tromey committed
2

Glenn Morris's avatar
Glenn Morris committed
3
;; Copyright (C) 1994, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
Glenn Morris's avatar
Glenn Morris committed
4
;;   2006, 2007, 2008, 2009, 2010  Free Software Foundation, Inc.
Tom Tromey's avatar
Tom Tromey committed
5

Stefan Monnier's avatar
Stefan Monnier committed
6
;; Maintainer: FSF
7
;; Author: Tom Tromey <tromey@redhat.com>
Tom Tromey's avatar
Tom Tromey committed
8 9
;;    Chris Lindblad <cjl@lcs.mit.edu>
;; Keywords: languages tcl modes
Tom Tromey's avatar
Tom Tromey committed
10 11 12

;; This file is part of GNU Emacs.

13
;; GNU Emacs is free software: you can redistribute it and/or modify
Tom Tromey's avatar
Tom Tromey committed
14
;; it under the terms of the GNU General Public License as published by
15 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Tom Tromey's avatar
Tom Tromey committed
17 18 19 20 21 22 23

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

;; You should have received a copy of the GNU General Public License
24
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Tom Tromey's avatar
Tom Tromey committed
25

Richard M. Stallman's avatar
Richard M. Stallman committed
26
;; BEFORE USE:
Tom Tromey's avatar
Tom Tromey committed
27 28
;;
;; If you plan to use the interface to the TclX help files, you must
Tom Tromey's avatar
Tom Tromey committed
29 30
;; set the variable tcl-help-directory-list to point to the topmost
;; directories containing the TclX help files.  Eg:
Tom Tromey's avatar
Tom Tromey committed
31
;;
Tom Tromey's avatar
Tom Tromey committed
32
;;   (setq tcl-help-directory-list '("/usr/local/lib/tclx/help"))
Tom Tromey's avatar
Tom Tromey committed
33 34 35 36 37 38 39 40 41 42
;;
;;; Commentary:

;; CUSTOMIZATION NOTES:
;; * tcl-proc-list can be used to customize a list of things that
;; "define" other things.  Eg in my project I put "defvar" in this
;; list.
;; * tcl-typeword-list is similar, but uses font-lock-type-face.
;; * tcl-keyword-list is a list of keywords.  I've generally used this
;; for flow-control words.  Eg I add "unwind_protect" to this list.
43
;; * tcl-builtin-list lists commands to be given font-lock-builtin-face.
Tom Tromey's avatar
Tom Tromey committed
44 45 46
;; * tcl-type-alist can be used to minimally customize indentation
;; according to context.

Richard M. Stallman's avatar
Richard M. Stallman committed
47
;; THANKS FOR CRITICISM AND SUGGESTIONS TO:
Tom Tromey's avatar
Tom Tromey committed
48 49 50 51 52 53 54 55
;; Guido Bosch <Guido.Bosch@loria.fr>
;; pgs1002@esc.cam.ac.uk (Dr P.G. Sjoerdsma)
;; Mike Scheidler <c23mts@kocrsv01.delcoelect.com>
;; Matt Newman <men@charney.colorado.edu>
;; rwhitby@research.canon.oz.au (Rod Whitby)
;; h9118101@hkuxa.hku.hk (Yip Chi Lap [Beta])
;; Pertti Tapio Kasanen <ptk@delta.hut.fi>
;; schmid@fb3-s7.math.TU-Berlin.DE (Gregor Schmid)
Tom Tromey's avatar
Tom Tromey committed
56 57
;; warsaw@nlm.nih.gov (Barry A. Warsaw)
;; Carl Witty <cwitty@ai.mit.edu>
58
;; T. V. Raman <raman@crl.dec.com>
Tom Tromey's avatar
Tom Tromey committed
59
;; Jesper Pedersen <blackie@imada.ou.dk>
60
;; dfarmer@evolving.com (Doug Farmer)
61
;; "Chris Alfeld" <calfeld@math.utah.edu>
Stefan Monnier's avatar
Stefan Monnier committed
62
;; Ben Wing <ben@xemacs.org>
Tom Tromey's avatar
Tom Tromey committed
63 64

;; KNOWN BUGS:
Stefan Monnier's avatar
Stefan Monnier committed
65 66 67 68 69 70 71
;; * In Tcl "#" is not always a comment character.  This can confuse tcl.el
;;   in certain circumstances.  For now the only workaround is to use
;;   font-lock which will mark the # chars accordingly or enclose offending
;;   hash characters in quotes or precede them with a backslash.  Note that
;;   using braces won't work -- quotes change the syntax class of characters
;;   between them, while braces do not.  If you don't use font-lock, the
;;   electric-# mode helps alleviate this problem somewhat.
Tom Tromey's avatar
Tom Tromey committed
72 73 74 75 76 77 78
;; * indent-tcl-exp is untested.

;; TODO:
;; * make add-log-tcl-defun smarter.  should notice if we are in the
;;   middle of a defun, or between defuns.  should notice if point is
;;   on first line of defun (or maybe even in comments before defun).
;; * Allow continuation lines to be indented under the first argument
79
;;   of the preceding line, like this:
Tom Tromey's avatar
Tom Tromey committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
;;      [list something \
;;            something-else]
;; * There is a request that indentation work like this:
;;        button .fred -label Fred \
;;                     -command {puts fred}
;; * Should have tcl-complete-symbol that queries the inferior process.
;; * Should have describe-symbol that works by sending the magic
;;   command to a tclX process.
;; * Need C-x C-e binding (tcl-eval-last-exp).
;; * Write indent-region function that is faster than indenting each
;;   line individually.
;; * tcl-figure-type should stop at "beginning of line" (only ws
;;   before point, and no "\" on previous line).  (see tcl-real-command-p).
;; * overrides some comint keybindings; fix.
;; * Trailing \ will eat blank lines.  Should deal with this.
;;   (this would help catch some potential bugs).
;; * Inferior should display in half the screen, not the whole screen.
Tom Tromey's avatar
Tom Tromey committed
97 98 99
;; * Indentation should deal with "switch".
;; * Consider writing code to find help files automatically (for
;;   common cases).
Tom Tromey's avatar
Tom Tromey committed
100
;; * `#' shouldn't insert `\#' when point is in string.
Tom Tromey's avatar
Tom Tromey committed
101 102 103 104 105



;;; Code:

106
(eval-when-compile
107
  (require 'imenu)
108 109 110 111
  (require 'outline)
  (require 'dabbrev)
  (require 'add-log))

Tom Tromey's avatar
Tom Tromey committed
112 113 114 115 116 117
(require 'comint)

;;
;; User variables.
;;

Richard M. Stallman's avatar
Richard M. Stallman committed
118
(defgroup tcl nil
119
  "Major mode for editing Tcl source in Emacs."
120
  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
Richard M. Stallman's avatar
Richard M. Stallman committed
121
  :group 'languages)
Tom Tromey's avatar
Tom Tromey committed
122

Richard M. Stallman's avatar
Richard M. Stallman committed
123 124
(defcustom tcl-indent-level 4
  "*Indentation of Tcl statements with respect to containing block."
125 126
  :type 'integer
  :group 'tcl)
127
(put 'tcl-indent-level 'safe-local-variable 'integerp)
Tom Tromey's avatar
Tom Tromey committed
128

Richard M. Stallman's avatar
Richard M. Stallman committed
129 130
(defcustom tcl-continued-indent-level 4
  "*Indentation of continuation line relative to first line of command."
131 132
  :type 'integer
  :group 'tcl)
133
(put 'tcl-continued-indent-level 'safe-local-variable 'integerp)
Tom Tromey's avatar
Tom Tromey committed
134

Richard M. Stallman's avatar
Richard M. Stallman committed
135 136
(defcustom tcl-auto-newline nil
  "*Non-nil means automatically newline before and after braces you insert."
137 138
  :type 'boolean
  :group 'tcl)
Richard M. Stallman's avatar
Richard M. Stallman committed
139

140
(defcustom tcl-tab-always-indent tab-always-indent
Tom Tromey's avatar
Tom Tromey committed
141 142 143 144 145 146 147 148 149 150 151 152
  "*Control effect of TAB key.
If t (the default), always indent current line.
If nil and point is not in the indentation area at the beginning of
the line, a TAB is inserted.
Other values cause the first possible action from the following list
to take place:

  1. Move from beginning of line to correct indentation.
  2. Delete an empty comment.
  3. Move forward to start of comment, indenting if necessary.
  4. Move forward to end of line, indenting if necessary.
  5. Create an empty comment.
Richard M. Stallman's avatar
Richard M. Stallman committed
153 154 155
  6. Move backward to start of comment, indenting if necessary."
  :type '(choice (const :tag "Always" t)
		 (const :tag "Beginning only" nil)
156 157
		 (const :tag "Maybe move or make or delete comment" 'tcl))
  :group 'tcl)
Richard M. Stallman's avatar
Richard M. Stallman committed
158

Tom Tromey's avatar
Tom Tromey committed
159

Stefan Monnier's avatar
Stefan Monnier committed
160
(defcustom tcl-electric-hash-style nil ;; 'smart
Tom Tromey's avatar
Tom Tromey committed
161
  "*Style of electric hash insertion to use.
Richard M. Stallman's avatar
Richard M. Stallman committed
162 163 164
Possible values are `backslash', meaning that `\\' quoting should be
done; `quote', meaning that `\"' quoting should be done; `smart',
meaning that the choice between `backslash' and `quote' should be
Tom Tromey's avatar
Tom Tromey committed
165 166
made depending on the number of hashes inserted; or nil, meaning that
no quoting should be done.  Any other value for this variable is
Stefan Monnier's avatar
Stefan Monnier committed
167
taken to mean `smart'.  The default is nil."
168 169
  :type '(choice (const backslash) (const quote) (const smart) (const nil))
  :group 'tcl)
Richard M. Stallman's avatar
Richard M. Stallman committed
170 171 172

(defcustom tcl-help-directory-list nil
  "*List of topmost directories containing TclX help files."
173 174
  :type '(repeat directory)
  :group 'tcl)
Richard M. Stallman's avatar
Richard M. Stallman committed
175 176 177

(defcustom tcl-use-smart-word-finder t
  "*If not nil, use smart way to find current word, for Tcl help feature."
178 179
  :type 'boolean
  :group 'tcl)
Richard M. Stallman's avatar
Richard M. Stallman committed
180 181 182

(defcustom tcl-application "wish"
  "*Name of Tcl program to run in inferior Tcl mode."
183 184
  :type 'string
  :group 'tcl)
Richard M. Stallman's avatar
Richard M. Stallman committed
185 186 187

(defcustom tcl-command-switches nil
  "*List of switches to supply to the `tcl-application' program."
188 189
  :type '(repeat string)
  :group 'tcl)
Richard M. Stallman's avatar
Richard M. Stallman committed
190 191

(defcustom tcl-prompt-regexp "^\\(% \\|\\)"
Tom Tromey's avatar
Tom Tromey committed
192 193 194 195
  "*If not nil, a regexp that will match the prompt in the inferior process.
If nil, the prompt is the name of the application with \">\" appended.

The default is \"^\\(% \\|\\)\", which will match the default primary
Richard M. Stallman's avatar
Richard M. Stallman committed
196
and secondary prompts for tclsh and wish."
197 198
  :type 'regexp
  :group 'tcl)
Tom Tromey's avatar
Tom Tromey committed
199

Richard M. Stallman's avatar
Richard M. Stallman committed
200
(defcustom inferior-tcl-source-command "source %s\n"
Tom Tromey's avatar
Tom Tromey committed
201 202 203 204
  "*Format-string for building a Tcl command to load a file.
This format string should use `%s' to substitute a file name
and should result in a Tcl expression that will command the
inferior Tcl to load that file.  The filename will be appropriately
Richard M. Stallman's avatar
Richard M. Stallman committed
205
quoted for Tcl."
206 207
  :type 'string
  :group 'tcl)
Tom Tromey's avatar
Tom Tromey committed
208

209 210 211 212 213
(defface tcl-escaped-newline '((t :inherit font-lock-string-face))
  "Face used for (non-escaped) backslash at end of a line in Tcl mode."
  :group 'tcl
  :version "22.1")

Tom Tromey's avatar
Tom Tromey committed
214 215 216 217
;;
;; Keymaps, abbrevs, syntax tables.
;;

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
(defvar tcl-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "{" 'tcl-electric-char)
    (define-key map "}" 'tcl-electric-brace)
    (define-key map "[" 'tcl-electric-char)
    (define-key map "]" 'tcl-electric-char)
    (define-key map ";" 'tcl-electric-char)
    (define-key map "#" 'tcl-electric-hash) ;Remove?  -stef
    (define-key map "\e\C-q" 'tcl-indent-exp)
    (define-key map "\177" 'backward-delete-char-untabify)
    (define-key map "\t" 'tcl-indent-command)
    (define-key map "\M-\C-x" 'tcl-eval-defun)
    (define-key map "\C-c\C-i" 'tcl-help-on-word)
    (define-key map "\C-c\C-v" 'tcl-eval-defun)
    (define-key map "\C-c\C-f" 'tcl-load-file)
    (define-key map "\C-c\C-t" 'inferior-tcl)
    (define-key map "\C-c\C-x" 'tcl-eval-region)
    (define-key map "\C-c\C-s" 'switch-to-tcl)
    map)
  "Keymap used in `tcl-mode'.")

(defvar tcl-mode-syntax-table
  (let ((st (make-syntax-table)))
    (modify-syntax-entry ?%  "_"  st)
    (modify-syntax-entry ?@  "_"  st)
    (modify-syntax-entry ?&  "_"  st)
    (modify-syntax-entry ?*  "_"  st)
    (modify-syntax-entry ?+  "_"  st)
    (modify-syntax-entry ?-  "_"  st)
    (modify-syntax-entry ?.  "_"  st)
    (modify-syntax-entry ?:  "_"  st)
    (modify-syntax-entry ?!  "_"  st)
    (modify-syntax-entry ?$  "_"  st)	; FIXME use "'"?
    (modify-syntax-entry ?/  "_"  st)
    (modify-syntax-entry ?~  "_"  st)
    (modify-syntax-entry ?<  "_"  st)
    (modify-syntax-entry ?=  "_"  st)
    (modify-syntax-entry ?>  "_"  st)
    (modify-syntax-entry ?|  "_"  st)
    (modify-syntax-entry ?\( "()" st)
    (modify-syntax-entry ?\) ")(" st)
    (modify-syntax-entry ?\; "."  st)
    (modify-syntax-entry ?\n ">"  st)
    ;; (modify-syntax-entry ?\f ">"  st)
    (modify-syntax-entry ?#  "<"  st)
    st)
  "Syntax table in use in `tcl-mode' buffers.")

(defvar inferior-tcl-mode-map
  ;; FIXME we override comint keybindings here.
  ;; Maybe someone has a better set?
  (let ((map (make-sparse-keymap)))
    ;; Will inherit from `comint-mode-map' thanks to define-derived-mode.
    (define-key map "\t" 'comint-dynamic-complete)
    (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
    (define-key map "\177" 'backward-delete-char-untabify)
    (define-key map "\M-\C-x" 'tcl-eval-defun)
    (define-key map "\C-c\C-i" 'tcl-help-on-word)
    (define-key map "\C-c\C-v" 'tcl-eval-defun)
    (define-key map "\C-c\C-f" 'tcl-load-file)
    (define-key map "\C-c\C-t" 'inferior-tcl)
    (define-key map "\C-c\C-x" 'tcl-eval-region)
    (define-key map "\C-c\C-s" 'switch-to-tcl)
    map)
  "Keymap used in `inferior-tcl-mode'.")

(easy-menu-define tcl-mode-menu tcl-mode-map "Menu used in `tcl-mode'."
  '("Tcl"
    ["Beginning of function" beginning-of-defun t]
    ["End of function" end-of-defun t]
    ["Mark function" mark-defun t]
    ["Indent region" indent-region (mark t)]
    ["Comment region" comment-region (mark t)]
    ["Uncomment region" uncomment-region (mark t)]
Tom Tromey's avatar
Tom Tromey committed
292 293
    "----"
    ["Show Tcl process buffer" inferior-tcl t]
294
    ["Send function to Tcl process" tcl-eval-defun
Tom Tromey's avatar
Tom Tromey committed
295
     (and inferior-tcl-buffer (get-buffer inferior-tcl-buffer))]
296
    ["Send region to Tcl process" tcl-eval-region
Tom Tromey's avatar
Tom Tromey committed
297
     (and inferior-tcl-buffer (get-buffer inferior-tcl-buffer))]
298
    ["Send file to Tcl process" tcl-load-file
Tom Tromey's avatar
Tom Tromey committed
299
     (and inferior-tcl-buffer (get-buffer inferior-tcl-buffer))]
Tom Tromey's avatar
Tom Tromey committed
300 301
    ["Restart Tcl process with file" tcl-restart-with-file t]
    "----"
302
    ["Tcl help" tcl-help-on-word tcl-help-directory-list]))
Tom Tromey's avatar
Tom Tromey committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

(defvar inferior-tcl-buffer nil
  "*The current inferior-tcl process buffer.

MULTIPLE PROCESS SUPPORT
===========================================================================
To run multiple Tcl processes, you start the first up with
\\[inferior-tcl].  It will be in a buffer named `*inferior-tcl*'.
Rename this buffer with \\[rename-buffer].  You may now start up a new
process with another \\[inferior-tcl].  It will be in a new buffer,
named `*inferior-tcl*'.  You can switch between the different process
buffers with \\[switch-to-buffer].

Commands that send text from source buffers to Tcl processes -- like
`tcl-eval-defun' or `tcl-load-file' -- have to choose a process to
send to, when you have more than one Tcl process around.  This is
determined by the global variable `inferior-tcl-buffer'.  Suppose you
have three inferior Lisps running:
    Buffer              Process
    foo                 inferior-tcl
    bar                 inferior-tcl<2>
    *inferior-tcl*      inferior-tcl<3>
If you do a \\[tcl-eval-defun] command on some Lisp source code, what
process do you send it to?

328
- If you're in a process buffer (foo, bar, or *inferior-tcl*),
Tom Tromey's avatar
Tom Tromey committed
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
  you send it to that process.
- If you're in some other buffer (e.g., a source file), you
  send it to the process attached to buffer `inferior-tcl-buffer'.
This process selection is performed by function `inferior-tcl-proc'.

Whenever \\[inferior-tcl] fires up a new process, it resets
`inferior-tcl-buffer' to be the new process's buffer.  If you only run
one process, this does the right thing.  If you run multiple
processes, you can change `inferior-tcl-buffer' to another process
buffer with \\[set-variable].")

;;
;; Hooks and other customization.
;;

(defvar tcl-mode-hook nil
  "Hook run on entry to Tcl mode.

Several functions exist which are useful to run from your
`tcl-mode-hook' (see each function's documentation for more
information):

351
  `tcl-guess-application'
Tom Tromey's avatar
Tom Tromey committed
352 353
    Guesses a default setting for `tcl-application' based on any
    \"#!\" line at the top of the file.
354
  `tcl-hashify-buffer'
Tom Tromey's avatar
Tom Tromey committed
355 356 357
    Quotes all \"#\" characters that don't correspond to actual
    Tcl comments.  (Useful when editing code not originally created
    with this mode).
358
  `tcl-auto-fill-mode'
Tom Tromey's avatar
Tom Tromey committed
359 360
    Auto-filling of Tcl comments.

Richard M. Stallman's avatar
Richard M. Stallman committed
361
Add functions to the hook with `add-hook':
Tom Tromey's avatar
Tom Tromey committed
362

363
   (add-hook 'tcl-mode-hook 'tcl-guess-application)")
Tom Tromey's avatar
Tom Tromey committed
364 365 366


(defvar tcl-proc-list
367
  '("proc" "method" "itcl_class" "body" "configbody" "class")
Tom Tromey's avatar
Tom Tromey committed
368
  "List of commands whose first argument defines something.
Richard M. Stallman's avatar
Richard M. Stallman committed
369
This exists because some people (eg, me) use `defvar' et al.
Tom Tromey's avatar
Tom Tromey committed
370 371 372 373 374 375 376
Call `tcl-set-proc-regexp' and `tcl-set-font-lock-keywords'
after changing this list.")

(defvar tcl-proc-regexp nil
  "Regexp to use when matching proc headers.")

(defvar tcl-typeword-list
Tom Tromey's avatar
Tom Tromey committed
377
  '("global" "upvar" "inherit" "public" "protected" "private"
378
    "common" "itk_option" "variable")
Tom Tromey's avatar
Tom Tromey committed
379
  "List of Tcl keywords denoting \"type\".  Used only for highlighting.
Tom Tromey's avatar
Tom Tromey committed
380 381 382 383 384 385
Call `tcl-set-font-lock-keywords' after changing this list.")

;; Generally I've picked control operators to be keywords.
(defvar tcl-keyword-list
  '("if" "then" "else" "elseif" "for" "foreach" "break" "continue" "while"
    "eval" "case" "in" "switch" "default" "exit" "error" "proc" "return"
386
    "uplevel" "constructor" "destructor" "itcl_class" "loop" "for_array_keys"
387 388
    "for_recursive_glob" "for_file" "method" "body" "configbody" "class"
    "chain")
Tom Tromey's avatar
Tom Tromey committed
389 390 391 392
  "List of Tcl keywords.  Used only for highlighting.
Default list includes some TclX keywords.
Call `tcl-set-font-lock-keywords' after changing this list.")

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
(defvar tcl-builtin-list
  '("after" "append" "array" "bgerror" "binary" "catch" "cd" "clock"
    "close" "concat" "console" "dde" "encoding" "eof" "exec" "expr"
    "fblocked" "fconfigure" "fcopy" "file" "fileevent" "flush"
    "format" "gets" "glob" "history" "incr" "info" "interp" "join"
    "lappend" "lindex" "linsert" "list" "llength" "load" "lrange"
    "lreplace" "lsort" "namespace" "open" "package" "pid" "puts" "pwd"
    "read" "regexp" "registry" "regsub" "rename" "scan" "seek" "set"
    "socket" "source" "split" "string" "subst" "tell" "time" "trace"
    "unknown" "unset" "vwait")
  "List of Tcl commands.  Used only for highlighting.
Call `tcl-set-font-lock-keywords' after changing this list.
This list excludes those commands already found in `tcl-proc-list' and
`tcl-keyword-list'.")

Tom Tromey's avatar
Tom Tromey committed
408 409 410 411 412 413
(defvar tcl-font-lock-keywords nil
  "Keywords to highlight for Tcl.  See variable `font-lock-keywords'.
This variable is generally set from `tcl-proc-regexp',
`tcl-typeword-list', and `tcl-keyword-list' by the function
`tcl-set-font-lock-keywords'.")

414 415 416 417 418
(defvar tcl-font-lock-syntactic-keywords
  ;; Mark the few `#' that are not comment-markers.
  '(("[^;[{ \t\n][ \t]*\\(#\\)" (1 ".")))
  "Syntactic keywords for `tcl-mode'.")

Tom Tromey's avatar
Tom Tromey committed
419 420 421
;; FIXME need some way to recognize variables because array refs look
;; like 2 sexps.
(defvar tcl-type-alist
422
  '(("proc" nil tcl-expr tcl-commands)
Tom Tromey's avatar
Tom Tromey committed
423
    ("method" nil tcl-expr tcl-commands)
424 425
    ("destructor" tcl-commands)
    ("constructor" tcl-commands)
Tom Tromey's avatar
Tom Tromey committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    ("expr" tcl-expr)
    ("catch" tcl-commands)
    ("if" tcl-expr "then" tcl-commands)
    ("elseif" tcl-expr "then" tcl-commands)
    ("elseif" tcl-expr tcl-commands)
    ("if" tcl-expr tcl-commands)
    ("while" tcl-expr tcl-commands)
    ("for" tcl-commands tcl-expr tcl-commands tcl-commands)
    ("foreach" nil nil tcl-commands)
    ("for_file" nil nil tcl-commands)
    ("for_array_keys" nil nil tcl-commands)
    ("for_recursive_glob" nil nil nil tcl-commands)
    ;; Loop handling is not perfect, because the third argument can be
    ;; either a command or an expr, and there is no real way to look
    ;; forward.
    ("loop" nil tcl-expr tcl-expr tcl-commands)
442
    ("loop" nil tcl-expr tcl-commands))
Tom Tromey's avatar
Tom Tromey committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
  "Alist that controls indentation.
\(Actually, this really only controls what happens on continuation lines).
Each entry looks like `(KEYWORD TYPE ...)'.
Each type entry describes a sexp after the keyword, and can be one of:
* nil, meaning that this sexp has no particular type.
* tcl-expr, meaning that this sexp is an arithmetic expression.
* tcl-commands, meaning that this sexp holds Tcl commands.
* a string, which must exactly match the string at the corresponding
  position for a match to be made.

For example, the entry for the \"loop\" command is:

   (\"loop\" nil tcl-expr tcl-commands)

This means that the \"loop\" command has three arguments.  The first
argument is ignored (for indentation purposes).  The second argument
is a Tcl expression, and the last argument is Tcl commands.")

(defvar tcl-explain-indentation nil
462
  "If non-nil, debugging message will be printed during indentation.")
Tom Tromey's avatar
Tom Tromey committed
463 464 465



466 467 468 469 470 471 472 473 474
;; Here's another stab.  I think this one actually works.
;; We have to be careful that the open-brace following this regexp
;; is indeed the one corresponding to the function's body so
;; that end-of-defun works correctly.  Tricky cases are:
;;    proc foo { {arg1 def} arg2 } {
;; as well as
;;    proc foo { \n {arg1 def} \n arg2 } {
;; The current setting handles the first case properly but not the second.
;; It also fails if `proc' is not in column-0 (e.g. it's in a namespace).
475
(defconst tcl-omit-ws-regexp "^[^]\" \t\n#}][^\n\"#]+[ \t]+")
Tom Tromey's avatar
Tom Tromey committed
476 477 478 479 480 481 482 483 484



;;
;; Some helper functions.
;;

(defun tcl-set-proc-regexp ()
  "Set `tcl-proc-regexp' from variable `tcl-proc-list'."
485 486
  (setq tcl-proc-regexp
	(concat "^\\s-*" (regexp-opt tcl-proc-list t) "[ \t]+")))
Tom Tromey's avatar
Tom Tromey committed
487 488 489 490 491 492 493 494 495 496 497

(defun tcl-set-font-lock-keywords ()
  "Set `tcl-font-lock-keywords'.
Uses variables `tcl-proc-regexp' and `tcl-keyword-list'."
  (setq tcl-font-lock-keywords
	(list
	 ;; Names of functions (and other "defining things").
	 (list (concat tcl-proc-regexp "\\([^ \t\n]+\\)")
	       2 'font-lock-function-name-face)

	 ;; Names of type-defining things.
498 499 500
	 (list (concat "\\(\\s-\\|^\\)"
		       (regexp-opt tcl-typeword-list t)
		       "\\(\\s-\\|$\\)")
Tom Tromey's avatar
Tom Tromey committed
501 502
	       2 'font-lock-type-face)

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
         (list (concat "\\_<" (regexp-opt tcl-builtin-list t) "\\_>")
	       1 'font-lock-builtin-face)

         ;; When variable names are enclosed in {} braces, any
         ;; character can be used. Otherwise just letters, digits,
         ;; underscores.  Variable names can be prefixed with any
         ;; number of "namespace::" qualifiers.  A leading "::" refers
         ;; to the global namespace.
         '("\\${\\([^}]+\\)}" 1 font-lock-variable-name-face)
         '("\\$\\(\\(?:::\\)?\\(?:[[:alnum:]_]+::\\)*[[:alnum:]_]+\\)"
           1 font-lock-variable-name-face)
         '("\\(?:\\s-\\|^\\|\\[\\)set\\s-+{\\([^}]+\\)}"
           1 font-lock-variable-name-face keep)
         '("\\(?:\\s-\\|^\\|\\[\\)set\\s-+\\(\\(?:::\\)?\
\\(?:[[:alnum:]_]+::\\)*[[:alnum:]_]+\\)"
           1 font-lock-variable-name-face keep)

         '("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'tcl-escaped-newline)

Tom Tromey's avatar
Tom Tromey committed
522 523 524
	 ;; Keywords.  Only recognized if surrounded by whitespace.
	 ;; FIXME consider using "not word or symbol", not
	 ;; "whitespace".
525
	 (cons (concat "\\_<" (regexp-opt tcl-keyword-list t) "\\_>")
526
	       1))))
Tom Tromey's avatar
Tom Tromey committed
527 528 529 530 531 532 533 534 535

(if tcl-proc-regexp
    ()
  (tcl-set-proc-regexp))

(if tcl-font-lock-keywords
    ()
  (tcl-set-font-lock-keywords))

536 537

(defvar tcl-imenu-generic-expression
Stefan Monnier's avatar
Stefan Monnier committed
538
  `((nil ,(concat tcl-proc-regexp "\\([-A-Za-z0-9_:+*]+\\)") 2))
539 540
  "Imenu generic expression for `tcl-mode'.  See `imenu-generic-expression'.")

Tom Tromey's avatar
Tom Tromey committed
541 542 543 544 545 546


;;
;; The mode itself.
;;

547
;;;###autoload
548
(define-derived-mode tcl-mode nil "Tcl"
Tom Tromey's avatar
Tom Tromey committed
549 550 551 552 553 554 555
  "Major mode for editing Tcl code.
Expression and list commands understand all Tcl brackets.
Tab indents for Tcl code.
Paragraphs are separated by blank lines only.
Delete converts tabs to spaces as it moves back.

Variables controlling indentation style:
556
  `tcl-indent-level'
Tom Tromey's avatar
Tom Tromey committed
557
    Indentation of Tcl statements within surrounding block.
558
  `tcl-continued-indent-level'
Tom Tromey's avatar
Tom Tromey committed
559 560 561 562
    Indentation of continuation line relative to first line of command.

Variables controlling user interaction with mode (see variable
documentation for details):
563
  `tcl-tab-always-indent'
Tom Tromey's avatar
Tom Tromey committed
564
    Controls action of TAB key.
565
  `tcl-auto-newline'
Tom Tromey's avatar
Tom Tromey committed
566 567
    Non-nil means automatically newline before and after braces, brackets,
    and semicolons inserted in Tcl code.
568
  `tcl-use-smart-word-finder'
Tom Tromey's avatar
Tom Tromey committed
569 570
    If not nil, use a smarter, Tcl-specific way to find the current
    word when looking up help on a Tcl command.
Tom Tromey's avatar
Tom Tromey committed
571

572
Turning on Tcl mode runs `tcl-mode-hook'.  Read the documentation for
Tom Tromey's avatar
Tom Tromey committed
573 574 575 576 577
`tcl-mode-hook' to see what kinds of interesting hook functions
already exist.

Commands:
\\{tcl-mode-map}"
578
  (unless (and (boundp 'filladapt-mode) filladapt-mode)
579
    (set (make-local-variable 'paragraph-ignore-fill-prefix) t))
580 581 582

  (set (make-local-variable 'indent-line-function) 'tcl-indent-line)
  (set (make-local-variable 'comment-indent-function) 'tcl-comment-indent)
Tom Tromey's avatar
Tom Tromey committed
583 584 585
  ;; Tcl doesn't require a final newline.
  ;; (make-local-variable 'require-final-newline)
  ;; (setq require-final-newline t)
Tom Tromey's avatar
Tom Tromey committed
586

587
  (set (make-local-variable 'comment-start) "# ")
588 589
  (set (make-local-variable 'comment-start-skip)
       "\\(\\(^\\|[;{[]\\)\\s-*\\)#+ *")
590
  (set (make-local-variable 'comment-end) "")
Tom Tromey's avatar
Tom Tromey committed
591

592
  (set (make-local-variable 'outline-regexp) ".")
593
  (set (make-local-variable 'outline-level) 'tcl-outline-level)
Tom Tromey's avatar
Tom Tromey committed
594

595 596
  (set (make-local-variable 'font-lock-defaults)
       '(tcl-font-lock-keywords nil nil nil beginning-of-defun
597 598
 	 (font-lock-syntactic-keywords . tcl-font-lock-syntactic-keywords)
 	 (parse-sexp-lookup-properties . t)))
Tom Tromey's avatar
Tom Tromey committed
599

600
  (set (make-local-variable 'imenu-generic-expression)
601
       tcl-imenu-generic-expression)
602

603
  ;; Settings for new dabbrev code.
604 605 606 607 608 609 610 611 612 613 614 615 616 617
  (set (make-local-variable 'dabbrev-case-fold-search) nil)
  (set (make-local-variable 'dabbrev-case-replace) nil)
  (set (make-local-variable 'dabbrev-abbrev-skip-leading-regexp) "[$!]")
  (set (make-local-variable 'dabbrev-abbrev-char-regexp) "\\sw\\|\\s_")

  (set (make-local-variable 'parse-sexp-ignore-comments) t)
  ;; XEmacs has defun-prompt-regexp, but I don't believe
  ;; that it works for end-of-defun -- only for
  ;; beginning-of-defun.
  (set (make-local-variable 'defun-prompt-regexp) tcl-omit-ws-regexp)
  (set (make-local-variable 'add-log-current-defun-function)
       'tcl-add-log-defun)

  (easy-menu-add tcl-mode-menu)
618
  ;; Append Tcl menu to popup menu for XEmacs.
619
  (if (boundp 'mode-popup-menu)
620
      (setq mode-popup-menu
621
	    (cons (concat mode-name " Mode Commands") tcl-mode-menu))))
Tom Tromey's avatar
Tom Tromey committed
622 623 624 625 626 627 628 629 630 631 632



;; This is used for braces, brackets, and semi (except for closing
;; braces, which are handled specially).
(defun tcl-electric-char (arg)
  "Insert character and correct line's indentation."
  (interactive "p")
  ;; Indent line first; this looks better if parens blink.
  (tcl-indent-line)
  (self-insert-command arg)
633
  (if (and tcl-auto-newline (= last-command-event ?\;))
Tom Tromey's avatar
Tom Tromey committed
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
      (progn
	(newline)
	(tcl-indent-line))))

;; This is used for closing braces.  If tcl-auto-newline is set, can
;; insert a newline both before and after the brace, depending on
;; context.  FIXME should this be configurable?  Does anyone use this?
(defun tcl-electric-brace (arg)
  "Insert character and correct line's indentation."
  (interactive "p")
  ;; If auto-newlining and there is stuff on the same line, insert a
  ;; newline first.
  (if tcl-auto-newline
      (progn
	(if (save-excursion
	      (skip-chars-backward " \t")
	      (bolp))
	    ()
	  (tcl-indent-line)
	  (newline))
	;; In auto-newline case, must insert a newline after each
	;; brace.  So an explicit loop is needed.
	(while (> arg 0)
657
	  (insert last-command-event)
Tom Tromey's avatar
Tom Tromey committed
658 659 660 661 662 663 664 665 666 667
	  (tcl-indent-line)
	  (newline)
	  (setq arg (1- arg))))
    (self-insert-command arg))
  (tcl-indent-line))



(defun tcl-indent-command (&optional arg)
  "Indent current line as Tcl code, or in some cases insert a tab character.
Richard M. Stallman's avatar
Richard M. Stallman committed
668 669
If `tcl-tab-always-indent' is t (the default), always indent current line.
If `tcl-tab-always-indent' is nil and point is not in the indentation
Tom Tromey's avatar
Tom Tromey committed
670
area at the beginning of the line, a TAB is inserted.
Richard M. Stallman's avatar
Richard M. Stallman committed
671
Other values of `tcl-tab-always-indent' cause the first possible action
Tom Tromey's avatar
Tom Tromey committed
672 673 674 675 676 677 678 679 680
from the following list to take place:

  1. Move from beginning of line to correct indentation.
  2. Delete an empty comment.
  3. Move forward to start of comment, indenting if necessary.
  4. Move forward to end of line, indenting if necessary.
  5. Create an empty comment.
  6. Move backward to start of comment, indenting if necessary."
  (interactive "p")
681 682 683
  (if (memq tcl-tab-always-indent '(nil t))
      (let ((tab-always-indent tcl-tab-always-indent))
        (call-interactively 'indent-for-tab-command))
Tom Tromey's avatar
Tom Tromey committed
684 685 686 687 688 689 690
    ;; "Perl-mode" style TAB command.
    (let* ((ipoint (point))
	   (eolpoint (progn
		       (end-of-line)
		       (point)))
	   (comment-p (tcl-in-comment)))
      (cond
691
       ((= ipoint (line-beginning-position))
Tom Tromey's avatar
Tom Tromey committed
692 693 694 695 696
	(beginning-of-line)
	(tcl-indent-line)
	;; If indenting didn't leave us in column 0, go to the
	;; indentation.  Otherwise leave point at end of line.  This
	;; is a hack.
697
	(if (= (point) (line-beginning-position))
Tom Tromey's avatar
Tom Tromey committed
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
	    (end-of-line)
	  (back-to-indentation)))
       ((and comment-p (looking-at "[ \t]*$"))
	;; Empty comment, so delete it.  We also delete any ";"
	;; characters at the end of the line.  I think this is
	;; friendlier, but I don't know how other people will feel.
	(backward-char)
	(skip-chars-backward " \t;")
	(delete-region (point) eolpoint))
       ((and comment-p (< ipoint (point)))
	;; Before comment, so skip to it.
	(tcl-indent-line)
	(indent-for-comment))
       ((/= ipoint eolpoint)
	;; Go to end of line (since we're not there yet).
	(goto-char eolpoint)
	(tcl-indent-line))
       ((not comment-p)
	(tcl-indent-line)
717
	(comment-indent))
Tom Tromey's avatar
Tom Tromey committed
718 719 720 721
       (t
	;; Go to start of comment.  We don't leave point where it is
	;; because we want to skip comment-start-skip.
	(tcl-indent-line)
722
	(indent-for-comment))))))
Tom Tromey's avatar
Tom Tromey committed
723 724 725 726

(defun tcl-indent-line ()
  "Indent current line as Tcl code.
Return the amount the indentation changed by."
727
  (let ((indent (tcl-calculate-indent nil))
Tom Tromey's avatar
Tom Tromey committed
728 729 730
	beg shift-amt
	(case-fold-search nil)
	(pos (- (point-max) (point))))
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
    (if (null indent)
        'noindent
      (beginning-of-line)
      (setq beg (point))
      (skip-chars-forward " \t")
      (if (listp indent) (setq indent (car indent)))
      (cond ((= (following-char) ?})
             (setq indent (- indent tcl-indent-level)))
            ((= (following-char) ?\])
             (setq indent (- indent 1))))
      (skip-chars-forward " \t")
      (setq shift-amt (- indent (current-column)))
      (if (zerop shift-amt)
          (if (> (- (point-max) pos) (point))
              (goto-char (- (point-max) pos)))
        (delete-region beg (point))
        (indent-to indent)
        ;; If initial point was within line's indentation,
        ;; position after the indentation.  Else stay at same point in text.
        (if (> (- (point-max) pos) (point))
            (goto-char (- (point-max) pos))))
      shift-amt)))
Tom Tromey's avatar
Tom Tromey committed
753 754 755

(defun tcl-figure-type ()
  "Determine type of sexp at point.
Richard M. Stallman's avatar
Richard M. Stallman committed
756
This is either `tcl-expr', `tcl-commands', or nil.  Puts point at start
Tom Tromey's avatar
Tom Tromey committed
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
of sexp that indicates types.

See documentation for variable `tcl-type-alist' for more information."
  (let ((count 0)
	result
	word-stack)
    (while (and (< count 5)
		(not result))
      (condition-case nil
	  (progn
	    ;; FIXME should use "tcl-backward-sexp", which would skip
	    ;; over entire variables, etc.
	    (backward-sexp)
	    (if (looking-at "[a-zA-Z_]+")
		(let ((list tcl-type-alist)
		      entry)
773
		  (setq word-stack (cons (tcl-word-no-props) word-stack))
Tom Tromey's avatar
Tom Tromey committed
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
		  (while (and list (not result))
		    (setq entry (car list))
		    (setq list (cdr list))
		    (let ((index 0))
		      (while (and entry (<= index count))
			;; Abort loop if string does not match word on
			;; stack.
			(and (stringp (car entry))
			     (not (string= (car entry)
					   (nth index word-stack)))
			     (setq entry nil))
			(setq entry (cdr entry))
			(setq index (1+ index)))
		      (and (> index count)
			   (not (stringp (car entry)))
			   (setq result (car entry)))
		      )))
	      (setq word-stack (cons nil word-stack))))
	(error nil))
      (setq count (1+ count)))
    (and tcl-explain-indentation
	 (message "Indentation type %s" result))
    result))

798
(defun tcl-calculate-indent (&optional parse-start)
Tom Tromey's avatar
Tom Tromey committed
799 800 801 802 803 804 805
  "Return appropriate indentation for current line as Tcl code.
In usual case returns an integer: the column to indent to.
Returns nil if line starts inside a string, t if in a comment."
  (save-excursion
    (beginning-of-line)
    (let* ((indent-point (point))
	   (case-fold-search nil)
806
	   (continued-line
Tom Tromey's avatar
Tom Tromey committed
807 808 809 810 811 812 813 814 815 816 817 818 819
	    (save-excursion
	      (if (bobp)
		  nil
		(backward-char)
		(= ?\\ (preceding-char)))))
	   (continued-indent-value (if continued-line
				       tcl-continued-indent-level
				     0))
	   state
	   containing-sexp
	   found-next-line)
      (if parse-start
	  (goto-char parse-start)
820
	(beginning-of-defun))
Tom Tromey's avatar
Tom Tromey committed
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
      (while (< (point) indent-point)
	(setq parse-start (point))
	(setq state (parse-partial-sexp (point) indent-point 0))
	(setq containing-sexp (car (cdr state))))
      (cond ((or (nth 3 state) (nth 4 state))
	     ;; Inside comment or string.  Return nil or t if should
	     ;; not change this line
	     (nth 4 state))
	    ((null containing-sexp)
	     ;; Line is at top level.
	     continued-indent-value)
	    (t
	     ;; Set expr-p if we are looking at the expression part of
	     ;; an "if", "expr", etc statement.  Set commands-p if we
	     ;; are looking at the body part of an if, while, etc
	     ;; statement.  FIXME Should check for "for" loops here.
	     (goto-char containing-sexp)
	     (let* ((sexpr-type (tcl-figure-type))
		    (expr-p (eq sexpr-type 'tcl-expr))
		    (commands-p (eq sexpr-type 'tcl-commands))
		    (expr-start (point)))
	       ;; Find the first statement in the block and indent
	       ;; like it.  The first statement in the block might be
	       ;; on the same line, so what we do is skip all
	       ;; "virtually blank" lines, looking for a non-blank
	       ;; one.  A line is virtually blank if it only contains
	       ;; a comment and whitespace.  FIXME continued comments
	       ;; aren't supported.  They are a wart on Tcl anyway.
	       ;; We do it this funky way because we want to know if
	       ;; we've found a statement on some line _after_ the
	       ;; line holding the sexp opener.
	       (goto-char containing-sexp)
	       (forward-char)
	       (if (and (< (point) indent-point)
			(looking-at "[ \t]*\\(#.*\\)?$"))
		   (progn
		     (forward-line)
		     (while (and (< (point) indent-point)
				 (looking-at "[ \t]*\\(#.*\\)?$"))
		       (setq found-next-line t)
		       (forward-line))))
	       (if (or continued-line
		       (/= (char-after containing-sexp) ?{)
		       expr-p)
		   (progn
		     ;; Line is continuation line, or the sexp opener
		     ;; is not a curly brace, or we are are looking at
		     ;; an `expr' expression (which must be split
		     ;; specially).  So indentation is column of first
		     ;; good spot after sexp opener (with some added
		     ;; in the continued-line case).  If there is no
		     ;; nonempty line before the indentation point, we
		     ;; use the column of the character after the sexp
		     ;; opener.
		     (if (>= (point) indent-point)
			 (progn
			   (goto-char containing-sexp)
			   (forward-char))
		       (skip-chars-forward " \t"))
		     (+ (current-column) continued-indent-value))
		 ;; After a curly brace, and not a continuation line.
		 ;; So take indentation from first good line after
		 ;; start of block, unless that line is on the same
		 ;; line as the opening brace.  In this case use the
		 ;; indentation of the opening brace's line, plus
		 ;; another indent step.  If we are in the body part
		 ;; of an "if" or "while" then the indentation is
		 ;; taken from the line holding the start of the
		 ;; statement.
		 (if (and (< (point) indent-point)
			  found-next-line)
		     (current-indentation)
		   (if commands-p
		       (goto-char expr-start)
		     (goto-char containing-sexp))
		   (+ (current-indentation) tcl-indent-level)))))))))



900
(defun tcl-indent-exp ()
Tom Tromey's avatar
Tom Tromey committed
901 902 903 904 905 906
  "Indent each line of the Tcl grouping following point."
  (interactive)
  (let ((indent-stack (list nil))
	(contain-stack (list (point)))
	(case-fold-search nil)
	outer-loop-done inner-loop-done state ostate
907
	this-indent continued-line
Tom Tromey's avatar
Tom Tromey committed
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
	(next-depth 0)
	last-depth)
    (save-excursion
      (forward-sexp 1))
    (save-excursion
      (setq outer-loop-done nil)
      (while (and (not (eobp)) (not outer-loop-done))
	(setq last-depth next-depth)
	;; Compute how depth changes over this line
	;; plus enough other lines to get to one that
	;; does not end inside a comment or string.
	;; Meanwhile, do appropriate indentation on comment lines.
	(setq inner-loop-done nil)
	(while (and (not inner-loop-done)
		    (not (and (eobp) (setq outer-loop-done t))))
	  (setq ostate state)
	  (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
					  nil nil state))
	  (setq next-depth (car state))
	  (if (or (nth 4 ostate))
	      (tcl-indent-line))
	  (if (or (nth 3 state))
	      (forward-line 1)
	    (setq inner-loop-done t)))
	(if (<= next-depth 0)
	    (setq outer-loop-done t))
	(if outer-loop-done
	    nil
	  ;; If this line had ..))) (((.. in it, pop out of the levels
	  ;; that ended anywhere in this line, even if the final depth
	  ;; doesn't indicate that they ended.
	  (while (> last-depth (nth 6 state))
	    (setq indent-stack (cdr indent-stack)
		  contain-stack (cdr contain-stack)
		  last-depth (1- last-depth)))
	  ;; Add levels for any parens that were started in this line.
	  (while (< last-depth next-depth)
	    (setq indent-stack (cons nil indent-stack)
		  contain-stack (cons nil contain-stack)
		  last-depth (1+ last-depth)))
	  (if (null (car contain-stack))
949
	      (setcar contain-stack
Tom Tromey's avatar
Tom Tromey committed
950 951 952 953 954
		      (or (car (cdr state))
			  (save-excursion
			    (forward-sexp -1)
			    (point)))))
	  (forward-line 1)
955
	  (setq continued-line
Tom Tromey's avatar
Tom Tromey committed
956 957 958 959 960 961 962 963 964 965 966 967
		(save-excursion
		  (backward-char)
		  (= (preceding-char) ?\\)))
	  (skip-chars-forward " \t")
	  (if (eolp)
	      nil
	    (if (and (car indent-stack)
		     (>= (car indent-stack) 0))
		;; Line is on an existing nesting level.
		(setq this-indent (car indent-stack))
	      ;; Just started a new nesting level.
	      ;; Compute the standard indent for this level.
968
	      (let ((val (tcl-calculate-indent
Tom Tromey's avatar
Tom Tromey committed
969 970 971 972 973 974 975 976 977 978 979 980
			  (if (car indent-stack)
			      (- (car indent-stack))))))
		(setcar indent-stack
			(setq this-indent val))
		(setq continued-line nil)))
	    (cond ((not (numberp this-indent)))
		  ((= (following-char) ?})
		   (setq this-indent (- this-indent tcl-indent-level)))
		  ((= (following-char) ?\])
		   (setq this-indent (- this-indent 1))))
	    ;; Put chosen indentation into effect.
	    (or (null this-indent)
981 982
		(= (current-column)
		   (if continued-line
Tom Tromey's avatar
Tom Tromey committed
983 984 985 986
		       (+ this-indent tcl-indent-level)
		     this-indent))
		(progn
		  (delete-region (point) (progn (beginning-of-line) (point)))
987 988
		  (indent-to
		   (if continued-line
Tom Tromey's avatar
Tom Tromey committed
989 990 991 992 993 994 995 996 997 998 999
		       (+ this-indent tcl-indent-level)
		     this-indent)))))))))
  )



;;
;; Interfaces to other packages.
;;

;; FIXME Definition of function is very ad-hoc.  Should use
1000
;; beginning-of-defun.  Also has incestuous knowledge about the
Tom Tromey's avatar
Tom Tromey committed
1001
;; format of tcl-proc-regexp.
1002
(defun tcl-add-log-defun ()
Tom Tromey's avatar
Tom Tromey committed
1003 1004
  "Return name of Tcl function point is in, or nil."
  (save-excursion
1005 1006
    (end-of-line)
    (if (re-search-backward (concat tcl-proc-regexp "\\([^ \t\n{]+\\)") nil t)
1007
	(match-string 2))))
Tom Tromey's avatar
Tom Tromey committed
1008

Tom Tromey's avatar
Tom Tromey committed
1009 1010 1011 1012 1013
(defun tcl-outline-level ()
  (save-excursion
    (skip-chars-forward " \t")
    (current-column)))

Tom Tromey's avatar
Tom Tromey committed
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027


;;
;; Helper functions for inferior Tcl mode.
;;

;; This exists to let us delete the prompt when commands are sent
;; directly to the inferior Tcl.  See gud.el for an explanation of how
;; it all works (I took it from there).  This stuff doesn't really
;; work as well as I'd like it to.  But I don't believe there is
;; anything useful that can be done.
(defvar inferior-tcl-delete-prompt-marker nil)

(defun tcl-filter (proc string)
1028
  (let ((inhibit-quit t))               ;FIXME: Isn't that redundant?
1029
    (with-current-buffer (process-buffer proc)
Tom Tromey's avatar
Tom Tromey committed
1030
      ;; Delete prompt if requested.
1031 1032 1033
      (when (marker-buffer inferior-tcl-delete-prompt-marker)
        (delete-region (process-mark proc) inferior-tcl-delete-prompt-marker)
        (set-marker inferior-tcl-delete-prompt-marker nil))))
1034
  (comint-output-filter proc string))
Tom Tromey's avatar
Tom Tromey committed
1035 1036

(defun tcl-send-string (proc string)
1037
  (with-current-buffer (process-buffer proc)
Tom Tromey's avatar
Tom Tromey committed
1038
    (goto-char (process-mark proc))
1039
    (forward-line 0)             ;Not (beginning-of-line) because of fields.
Tom Tromey's avatar
Tom Tromey committed
1040 1041 1042 1043 1044
    (if (looking-at comint-prompt-regexp)
	(set-marker inferior-tcl-delete-prompt-marker (point))))
  (comint-send-string proc string))

(defun tcl-send-region (proc start end)
1045
  (with-current-buffer (process-buffer proc)
Tom Tromey's avatar
Tom Tromey committed
1046
    (goto-char (process-mark proc))
1047
    (forward-line 0)             ;Not (beginning-of-line) because of fields.
Tom Tromey's avatar
Tom Tromey committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    (if (looking-at comint-prompt-regexp)
	(set-marker inferior-tcl-delete-prompt-marker (point))))
  (comint-send-region proc start end))

(defun switch-to-tcl (eob-p)
  "Switch to inferior Tcl process buffer.
With argument, positions cursor at end of buffer."
  (interactive "P")
  (if (get-buffer inferior-tcl-buffer)
      (pop-to-buffer inferior-tcl-buffer)
    (error "No current inferior Tcl buffer"))
  (cond (eob-p
	 (push-mark)
	 (goto-char (point-max)))))

(defun inferior-tcl-proc ()
  "Return current inferior Tcl process.
See variable `inferior-tcl-buffer'."
  (let ((proc (get-buffer-process (if (eq major-mode 'inferior-tcl-mode)
				      (current-buffer)
				    inferior-tcl-buffer))))
    (or proc
	(error "No Tcl process; see variable `inferior-tcl-buffer'"))))

(defun tcl-eval-region (start end &optional and-go)
  "Send the current region to the inferior Tcl process.
Prefix argument means switch to the Tcl buffer afterwards."
  (interactive "r\nP")
  (let ((proc (inferior-tcl-proc)))
1077 1078 1079 1080 1081
    (tcl-send-region
     proc
     ;; Strip leading and trailing whitespace.
     (save-excursion (goto-char start) (skip-chars-forward " \t\n") (point))
     (save-excursion (goto-char end) (skip-chars-backward " \t\n") (point)))
Tom Tromey's avatar
Tom Tromey committed
1082 1083 1084 1085 1086 1087 1088 1089
    (tcl-send-string proc "\n")
    (if and-go (switch-to-tcl t))))

(defun tcl-eval-defun (&optional and-go)
  "Send the current defun to the inferior Tcl process.
Prefix argument means switch to the Tcl buffer afterwards."
  (interactive "P")
  (save-excursion
1090
    (end-of-defun)
Tom Tromey's avatar
Tom Tromey committed
1091
    (let ((end (point)))
1092
      (beginning-of-defun)
Tom Tromey's avatar
Tom Tromey committed
1093 1094 1095 1096 1097 1098 1099 1100 1101
      (tcl-eval-region (point) end)))
  (if and-go (switch-to-tcl t)))



;;
;; Inferior Tcl mode itself.
;;

1102
(define-derived-mode inferior-tcl-mode comint-mode "Inferior Tcl"
Tom Tromey's avatar
Tom Tromey committed
1103 1104
  "Major mode for interacting with Tcl interpreter.

1105
You can start a Tcl process with \\[inferior-tcl].
Tom Tromey's avatar
Tom Tromey committed
1106

Richard M. Stallman's avatar
Richard M. Stallman committed
1107 1108
Entry to this mode runs the normal hooks `comint-mode-hook' and
`inferior-tcl-mode-hook', in that order.
Tom Tromey's avatar
Tom Tromey committed
1109 1110 1111 1112 1113

You can send text to the inferior Tcl process from other buffers
containing Tcl source.

Variables controlling Inferior Tcl mode:
1114
  `tcl-application'
Tom Tromey's avatar
Tom Tromey committed
1115
    Name of program to run.
1116
  `tcl-command-switches'
Tom Tromey's avatar
Tom Tromey committed
1117
    Command line arguments to `tcl-application'.
1118
  `tcl-prompt-regexp'
Tom Tromey's avatar
Tom Tromey committed
1119
    Matches prompt.
1120
  `inferior-tcl-source-command'
Tom Tromey's avatar
Tom Tromey committed
1121
    Command to use to read Tcl file in running application.
1122
  `inferior-tcl-buffer'
Tom Tromey's avatar
Tom Tromey committed
1123 1124 1125 1126 1127
    The current inferior Tcl process buffer.  See variable
    documentation for details on multiple-process support.

The following commands are available:
\\{inferior-tcl-mode-map}"
1128 1129 1130 1131
  (set (make-local-variable 'comint-prompt-regexp)
       (or tcl-prompt-regexp
	   (concat "^" (regexp-quote tcl-application) ">")))
  (setq mode-line-process '(": %s"))
Tom Tromey's avatar
Tom Tromey committed
1132 1133
  (setq local-abbrev-table tcl-mode-abbrev-table)
  (set-syntax-table tcl-mode-syntax-table)
1134 1135 1136
  (set (make-local-variable 'defun-prompt-regexp) tcl-omit-ws-regexp)
  (set (make-local-variable 'inferior-tcl-delete-prompt-marker) (make-marker))
  (set-process-filter (get-buffer-process (current-buffer)) 'tcl-filter))
Tom Tromey's avatar
Tom Tromey committed
1137

1138
;;;###autoload
Tom Tromey's avatar
Tom Tromey committed
1139 1140 1141 1142 1143 1144 1145 1146
(defun inferior-tcl (cmd)
  "Run inferior Tcl process.
Prefix arg means enter program name interactively.
See documentation for function `inferior-tcl-mode' for more information."
  (interactive
   (list (if current-prefix-arg
	     (read-string "Run Tcl: " tcl-application)
	   tcl-application)))
1147 1148 1149
  (unless (comint-check-proc "*inferior-tcl*")
    (set-buffer (apply (function make-comint) "inferior-tcl" cmd nil
		       tcl-command-switches))
1150 1151 1152 1153 1154 1155
    (inferior-tcl-mode)
    ;; Make tclsh display a prompt on ms-windows (or under Unix, when a tty
    ;; wasn't used).  Doesn't affect wish, unfortunately.
    (unless (process-tty-name (inferior-tcl-proc))
      (tcl-send-string (inferior-tcl-proc)
                       "set ::tcl_interactive 1; concat\n")))
1156
  (set (make-local-variable 'tcl-application) cmd)
Tom Tromey's avatar
Tom Tromey committed
1157
  (setq inferior-tcl-buffer "*inferior-tcl*")
1158
  (pop-to-buffer "*inferior-tcl*"))
Tom Tromey's avatar
Tom Tromey committed
1159

1160
(defalias 'run-tcl 'inferior-tcl)
Tom Tromey's avatar
Tom Tromey committed
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188



;;
;; Auto-fill support.
;;

(defun tcl-real-command-p ()
  "Return nil if point is not at the beginning of a command.
A command is the first word on an otherwise empty line, or the
first word following a semicolon, opening brace, or opening bracket."
  (save-excursion
    (skip-chars-backward " \t")
    (cond
     ((bobp) t)
     ((bolp)
      (backward-char)
      ;; Note -- continued comments are not supported here.  I
      ;; consider those to be a wart on the language.
      (not (eq ?\\ (preceding-char))))
     (t
      (memq (preceding-char) '(?\; ?{ ?\[))))))

;; FIXME doesn't actually return t.  See last case.
(defun tcl-real-comment-p ()
  "Return t if point is just after the `#' beginning a real comment.
Does not check to see if previous char is actually `#'.
A real comment is either at the beginning of the buffer,
1189
preceded only by whitespace on the line, or has a preceding
Tom Tromey's avatar
Tom Tromey committed
1190 1191 1192 1193 1194 1195 1196 1197 1198
semicolon, opening brace, or opening bracket on the same line."
  (save-excursion
    (backward-char)
    (tcl-real-command-p)))

(defun tcl-hairy-scan-for-comment (state end always-stop)
  "Determine if point is in a comment.
Returns a list of the form `(FLAG . STATE)'.  STATE can be used
as input to future invocations.  FLAG is nil if not in comment,
1199
t otherwise.  If in comment, leaves point at beginning of comment."
Tom Tromey's avatar
Tom Tromey committed
1200 1201 1202 1203 1204 1205 1206
  (let ((bol (save-excursion
	       (goto-char end)
	       (beginning-of-line)
	       (point)))
	real-comment
	last-cstart)
    (while (and (not last-cstart) (< (point) end))
1207
      (setq real-comment nil)	 ;In case we've looped around and it is set.
Tom Tromey's avatar
Tom Tromey committed
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231