Updated 2014-08-02 01:25:07 by SMSM

What: Vim
 Where: http://www.vim.org/
        http://vim.sf.net/
        http://vimdoc.sf.net/
 Description: The Vim editor - "Vi-IMproved".
        Currently at version 7.2 .
 Updated: 11/2009
 Contact: See web site

See vi for predecessor to vim.


MC 16 Jul 2003: This is probably old news to many, but I finally stumbled upon this little gem only this evening:

vim already does syntax highlighting for *.tcl files. For files without an extension, however, adding a comment in your code that says:
 # vim: syntax=tcl

causes vim to do the highlighting properly.

glennj This magic depends on two settings: (default values)
 set modeline modelines=5

vim will then look at the top 5 lines and the bottom 5 lines for these special comments. See
 :help modeline

Modelines are handy for "forcing" people to conform to particular vim settings. For example, if you like a 8 space indent using tabs, but you're editing someone else's code who likes 4 space indent and no tabs, then in order not to mess up that person's code, you'll want a modeline like (demonstrating the alternate modeline syntax)
 # vim: set shiftwidth=4 smarttab expandtab:

Configuring Vim to conform to the Tcl Style Guide

indenting
    set autoindent           " keep the previous line's indentation
    set cindent              " indent after line ending in {, and use 'cinwords'
                             " see also ':help c-indent'
    set shiftwidth=4

do not inadvertantly break a line
    set textwidth=0

comments
    set comments=:#
    set formatoptions+=r      " Automatically insert the current comment leader
    set formatoptions+=q      " Allow formatting of comments with 'gq'

prevent the comment character from forcibly being inserted in column 1
    set cpoptions-=<          " allow '<keycode>' forms in mappings, e.g. <CR>
    inoremap # X<BS>#
    set cinkeys-=0#           " # in column 1 does not prevent >> from indenting
    set indentkeys-=0#

Version 6 of vim has a wonderful feature called folding, where blocks of text can be hidden as a single line until you have to enter them. However, I can't seem to get syntax-based automatic folding of procs. The obvious
    set foldmethod=syntax
    syntax region tclFunc start="^proc.*{$" end="^}" transparent fold

does nothing. Folding blocks works fine with
    syntax region tclBlock  start="{" end="}" transparent fold

but I don't really want to fold every block, I'd rather do it on the proc level. Any suggestions?

US The start regex interferes with "syntax keyword" in the tcl syntax file. Change the line
    syn keyword tclStatement        proc global return lindex

into
    syn keyword tclStatement        global return lindex
    syn match   tclStatement        "proc" contained

and add the (slightly extended) region rule
    syntax region tclFunc start="^\z(\s*\)proc.*{$" end="^\z1}$" transparent fold contains=ALL

Now it should (mostly) work. The "z" part of the start and end regex allows for arbitrary indentation of your proc definition.

There is (at least) one pathological file: I reaped the bitmap editor http://wiki.tcl.tk/6298 and tried the above folding rules on it. It works quite nice, but not for the procedure definitions of ClearBMP, NewBMP, NewDlg and BitFunc. I have no idea, why. Maybe someone else knows better.

NEM I just tried this out, and it doesn't seem to work very well at all. It seems to get the start of procs ok, but the end of the proc seems to be somewhat arbitrary. A couple of procs seem to be closed by a } but not the correct one (like the end of an if statement). One proc was actually closed after a button command, which was quite strange as it didn't contain any braces at all... I don't know Vim re syntax but (\s*\) looks suspicious to me (is the end paren escaped? if so, why?), and what does \z1 do? Presumably, it means the same amount of indenting as at the start of the proc?

AMucha vim folding with marker Use foldmethod marker:

First include in .vimrc:
   filetype plugin on

in $VIMRUNTIME/ftplugin/ (in my linux box this is usr/share/vim/current/ftplugin/) edit file tcl.vim to look like:
 " This is file $VIMRUNTIME/ftplugin/tcl.vim
 " Vim FileType plugin for Tcl/Tk-Files adding folding
 "
 source $VIMRUNTIME/ftplugin/vim.vim
 :setlocal fmr=<-<,>-> fdm=marker cms=#%s
 " this sets the folding marks to <-< and >->
 function! MyFoldText()
    let line = getline(v:foldstart+1)
    let sub = substitute(line, '/\*\|\*/\|{{{\d\=', '', 'g')
    return v:folddashes . sub
 endfunction
 set foldtext=MyFoldText()
 " this shows the line after the foldmark as text
 map <F5> :call append(line(".")-1, "\# <-<" . (foldlevel(line(".")) + 1))
 map <F6> :call append(line("."), "\# >->")
 " maps to help insert foldmarks. Use: go to end of proc on } and press F6 % F5
 " ############################################
 " end of tcl.vim

If you are daring enough to use a proc with german comments you can add in the same file :
 function! Foldproc()
    :normal 1g
    let s:anz=0
    let W = "W"
    while search("proc\\>",W) > 0
        let s:startpos = line(".") - 1
        let s:anz = s:anz + 1
        "auf das zweite wort gehen (Argumente)
      " go to 2nd word (args)
        :normal WW
        "testen, ob das erste Zeichen der Argumente eine ist
      " test if the first char is a brace
        let startofargument =strpart(getline(line(".")), col(".") - 1 , 10)
        if  match(startofargument,"{") == 0
            "eine Argumentenliste
            if searchpair("{","","}",W,'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"') <= 0
                " keine schließende klammer gefunden
                " die nächste proc probieren
                continue
            endif
        else
            "ein einzelnes wort ; no ist a single word
        endif
        " wir stehen jetzt entweder am beginn eines wortes oder auf der
        " schließenden klammer
      " we are at the beginning of a single word argument
      " or at the closing brace of an argumentlist
        :normal W
        " Jetzt stehen wir auf der öffnenden Klammer
      " this is the opening brace of the proc
        let startofargument =strpart(getline(line(".")), col(".") - 1 , 10)
        if  match(startofargument,"{") == 0
            " if searchpair("{","","}",W,'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"') <= 0
            if searchpair("{","","}",W,'') <= 0
                " das ende der Proc ist nicht gefunden
            " didn't find end of proc
                continue
            endif
        else
            continue
        endif
      "insert foldmarks
        call append(s:startpos , "\# <-<1")
        call append(line("."), "\# >->1")
    endwhile
 endfunction

To call this proc to place foldmarks around all your procs type
 :call Foldproc()

 What: Vim
 Where: http://www.vim.org/
        http://www.bodenstab.org/#VIMCONSOLE
 Description: Vi clone which provides language syntax colorization (including
        Tcl), command line edit and recall, filename completion,
        split windows, mouse control, drag and drop, and other features.
        The vimconsole is a Tclsh shell that interacts with the
         Tcl support one can build into vim.
        Currently at version 6.0 .
 Updated: 09/2001
 Contact: mailto:vim@vim.org

dgonyier Can anybody say why VIM has a seperate syntax file for Expect and TCL? I would think it would make more sense for the latter to be a superset of the former...

AMG Although I love my vim to pieces, I am really disappointed in its Tcl highlighting (look in $VIMRUNTIME/syntax/tcl.vim if you want to read along or fix stuff). The problem is that vim's syntax system highlights based soley on keywords, regexp matchs, and regexp start-end regions. I've tried and failed to describe the Tcl language using these primitives, which work soooo well for languages like C but maybe don't apply wholly to Tcl. Maybe someone can give me a hand...?

For this vim misbehaves in four degrees [5].

For first: proc, global, return, lindex, set, and so on are mostly "tclStatement" keywords. But we all know they're not really keywords, since they only have meaning when they appear as the first word of a line of Tcl script. So when I type "set set set" I wind up with all three instances of the word colored yellow, which is exceedingly ugly to me. This is why I don't name my variables "list".

For secondly: expr, namespace, string, array, etc., that is, many things with special syntax (use of math functions), subcommands (like "namespace children"), and/or or common switches ("pack -in"), are match regions beginning with the command name and ending with ] or end-of-line (regardless of \, due to a bug) or [...] (but not semicolon). The function names and subcommands and switches (sans -) are all considered keywords contained in the appropriate match region. But I find that mostly this screws up everything else I try to type on the line, and it's really annoying to have switches colored brown on the first line and white on the remaining because the match region ended prematurely.

For thirdly: text, message, entry, and other Tk commands are match regions containing keywords, like above, but they have names I very often want to use for variables. Since the match region starts anywhere "text" or whatever appears, I get a lot of mangled highlighting. (Thankfully "$text" doesn't trigger, but "set text" still does.) These match regions do appear to correctly span multiple lines. I wonder why that doesn't work for the non-Tk highlights.

For fourthly: There are many miscellaneous problems. \newline doesn't work for comments. $ expansion doesn't recognize :: or variables starting with underscore or numerals, even when ${...} is used. Unlike decimal highlighting, hexadecimal highlighting starts even when the number doesn't begin the word. (And besides, numbers shouldn't be highlighted anyway.)

I don't know how to adequately express the Tcl language using only regexps. I'm not even sure it's possible. So I find myself adjusting my code to avoid for the more gratuitous highlighting bugs, and that's a pretty sad situation.

RLH - Is anyone working on a comprehensive Vim script? Perl has one called perl-support that does a whole lot of nifty things. I was wondering if there was a Tcl one out there somewhere.

Vim Folding That Just Works (for me)

Put this in $HOME/.vim/ftplugins/tcl.vim and enjoy! Hopefully this works for you. This only seems to work for me on Vim 6.3.46.
 function! MyFoldLevel(lnum)

     let l:line = getline(a:lnum)
     let l:nextline = getline(a:lnum+1)
     let l:previous = foldlevel(a:lnum-1)

     if (l:line =~ "^::proc" || l:line =~ "^proc") && l:previous != 1
         return ">1"
     elseif l:line =~ "^proc" || l:line =~ "^::proc"
         return "="
     elseif l:line =~ "^################" && l:previous != 1
         return ">1"
     elseif l:line =~ "^ý" && l:previous != 1
         return ">1"
     elseif l:line =~ "^#%PS%" && l:previous != 1
         return ">1"
     elseif l:line =~ "^#{{{" && l:previous != 1
         return ">1"
     elseif l:line =~ "^}$" && (l:previous == 1 && match(nextline, "#}}}") == -1)
         return "<1"
     elseif l:line =~ "#}}}"
         return "<1"
     elseif l:line =~ "^$" && (l:previous == 0 || l:previous == "<1")
         return "<1"
     endif

     return "="

 endfunction

 function MyFoldText()
     let line = getline(v:foldstart)

     let n = v:foldstart
     while match(line, "proc.*\{$") == -1
         let line = getline(n)
         let n = n + 1
     endwhile

     let sub = substitute(line, 'rpc::rproc', '', 'g')
     let sub = substitute(sub, 'proc', '', 'g')
     let sub = substitute(sub, '::proc', '', 'g')
     let sub = substitute(sub, '^::', '', 'g')
     let sub = substitute(sub, '{$', '', 'g')
     let sub = substitute(sub, '{.*}', '', 'g')

     return v:folddashes . " (" . (v:foldend - v:foldstart) . ")" . sub
 endfunction

 set foldtext=MyFoldText()
 set foldexpr=MyFoldLevel(v:lnum)
 set foldmethod=expr

male (2006-01-12): fantastic, your tcl folding mechanism works quiet well in Vim 6.4! Except of one line size foldings, that fold the level higher instead of itself. But I'm not firm enough with Vim script, so I'm not sure about how to change. Thanks for this helper!

2006-03-31, SB: How do I make vim run the current script on the command line and capture the output into a new buffer? I would like to bind this behaviour to a keystroke in order to avoid having to switch to a command line to run the script.

AMG I do most of my work on computers in a network not attached to the Internet, so downloading is a rather involved process involving having designated personnel burn CDs. So I tend to rely on modifying the tools I already have. In the case of Vim's Tcl highlighting, I copied tcl.vim from /usr/share/vim/... to ~/.vim/syntax/ and edited out all the tclKeyword lines (except for TODO, to which I added FIXME, XXX, and NOTE). This made highlighting much nicer and more accurate (everything's a string; highlight accordingly!). I corrected the variable match pattern (a variable name is just \$[a-zA-Z0-9_:]* or \${[^}]*}; leave out all that C trash about not starting with a digit). I made other functionality reductions too.

When finished, I had a syntax highlighter that recognizes only real numbers, "quoted strings", [command substitution], $normal::variables, ${braced variables}, \backslashed characters and newlines, and #comments. From memory, since I can't access my tcl.vim and this website on the same computer, highlighting works a bit like the following:

  • Numbers and quoted strings are highlighted in purple
  • Square brackets for command substitution are highlighted in yellow
  • Comments are highlighted in cyan
  • TODO, etc. inside comments are black-on-brown
  • Variable expansions are highlighted in green
  • Array notation is not highlighted specially
  • Backslashed characters are highlighted in red

Most interestingly, variables and command substitutions are highlighted even when inside quoted strings. In the following two examples, w is silvery white, p is magenta/purple, g is green, y is yellow, b is brown highlight, and c is cyan:
 set answer answer ;# TODO: comment
 www wwwwww wwwwww wc bbbbc ccccccc

 puts "the $::answer is [expr {34 + [string length "x ${answer}"]}]."
 wwww pppp ggggggggg pp ywwww wpp w ywwwwww wwwwww pppgggggggggpywypp

This really aids readability. Strings and brackets nest properly, amazing!

Someday I will put my tcl.vim up on my website, and I'll post a link to it.

Improvements to the Distributed Syntax File

2009-02-09 TCV I recently became the maintainer of the Tcl syntax highlighting support which is distributed with the Vim release. Noticing that there are a couple of alternative approaches to solving common shortcomings with the current Tcl syntax support, I'm looking for a way forward to unite these methods and bring them into the support which is shipped with Vim itself. I feel like this would provide a lot of benefit to both casual and hardcore Tclers since everything could potentially be available in one place, and without having to fetch external files. Anyone who has comments on features they would like added or changed please add them here. I'm open to both replacing existing functionality and to adding options for things which are sometimes touchy. (For example, it would be possible to provide an option to disable highlighting of Tcl core commands.)

You can get the current "stable" version of the syntax file on the Vim FTP site [6]. Or watch the development that I conduct from my CVS repository [7]. I'm tracking bugs and features with code samples and expected formatting on a page on my site [8].

Here are my ideas so far of things that could use some work:

  • highlighting of commands not intelligent based on placement - the "set set set" problem
  • Tk commands are highlighted in a fairly complicated way which is difficult to maintain
  • possibly look into selectively highlighting code between braces; if and for would get highlighting, but arguments to puts would not

I'm sure there are plenty of others; let me know what you want to see. Also, I know that because of the simple nature of Vim's syntax highlighting system (which also makes it quite fast and easy to use for most languages) some of these things could be quite challenging to implement. So when you have ideas to refine the existing code or implement a new feature, leave a note for that too! Bug reports are of course always valuable, but are probably most usefully directed to my email. Throw the words "Vim" and "Tcl" into the subject so I'll be sure not to miss it.

RLH Should the ttk and OO namespace stuff go in there as well?

2009-04-01 TCV Yes I think so but I also want to avoid some of the crazy magic that's in there right now around the Tk commands (and clean up the existing stuff). New 8.6 commands like coroutine and tailcall need to be added as well, of course that's relatively simple. I'm trying to work out a way to tell for common commands (e.g. subst and if) when stuff in braces is interpreted as a string literal or a script, and to do highlighting appropriately; it is annoying to use a word like "default" in an argument to puts and have it get highlighted.

Lorance - 2011-09-21 18:12:30 - Updates 2011-09-22

I have create a plugin to utilize Nagelfar for syntax checking in Vim via the compiler facility. I also have a heavily customized Tcl Syntax file that others might find interesting. Just click my name... Adding to my list a TclShell for Vim using the builtin Tcl interpreter.

2013-11-28 Lorry

To ensure that Vim recognizes Tcl Modules (*.tm) as Tcl files for syntax highlighting, add the following line to your .vimrc:
au BufNewFile,BufRead *.tm set filetype=tcl

juef (2014-07-02): set correct section for the "K" command
autocmd FileType tcl set keywordprg=man\ n