Version 93 of Vim

Updated 2013-11-28 07:07:10 by Lorry

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:[email protected] 

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 [L5 ].

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.

SMSM Below, on this page, I have linked replacements for tcl-syntax and tcl-indent scripts for vim 6.0 and up. The syntax script address each of the issues you describe and a few more besides. You can [set set set] with gleeful abandon and it will look right. You can have multi-lined comments with line continues, and you can use if {0} {} to brace comments. And, for those who like more austere coloring, you can turn off the highlighting for various categories of tcl words, for example "only highlight braces, brackets & quotes" or "only variables".

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.


Updated Vim Scripts for Tcl

2007-02-01 SMSM: Here are a set of vimscripts that provide better indentation, updated (current with 8.5) syntax coloring, and a way to extend the tcl syntax to include additional packages and even other languages. The basic syntax file also provide you with the option to use :se foldmethod=syntax, to take care of folding expressions. It only folds proc's and namespaces, and only at the outer level of braces.

  • tcl-indent [L6 ]
  • tcl-syntax [L7 ]

extended syntax files:

  • tcl-itcl-syntax [L8 ]
  • tcl-snit-syntax [L9 ]
  • tcl-sqlite-syntax [L10 ] includes sql highlighting inside [$db eval {...}]
  • tcl-togl-syntax [L11 ]
  • tcl-critcl-syntax [L12 ] includes c highlighting

RT, 2Feb07 installed both of above on WinXP, Vim6.3 - when I start editing with 'o'pen the vim session hangs with 100% cpu. Suggestions or further info I can provide?

SMSM 2Feb07 Good to know. I'll get to the bottom of this within the day. The indent file is the villain.

SMSM 2Feb07 Fixed. And posted to the vim.org site. RT Yes the bad behavior is gone with vim6.3 - thanks.

male - 2007-02-02:

Installed the "new" syntax file and now I have problems with the coloring of texts between quotes.

This case is working:

 A b \
     "c" \
     d;

This case won't recognize the first quote and suddenly with/after the second quote everything is a quoted text:

 A create \
     "c" \
     d; # " needed to stop the quoted text colouring

But ... thanks for your work! I tried sometimes to extend the tcl syntax file, but I failed with this wonderful vim syntax description syntax!

Martin

RT, 6Feb07: perhaps related to Martin's case:

   proc bad {} {
    # puts "grid $b -row $r -column $c -padx $px -pady [list $pytop 2] \
                -sticky $st -columnspan $cs"
    set a 100
   }

Syntax parsing extends the quoted section to the set command. vim6.3 using 0.4.5 syntax file from above.

SMSM Need a little more input. Could you contact me at m_smithfield AT yahoo DOT com?

SMSM This issue is resolved.

RLH I believe that this should become the default script that is distributed with Vim. They are very nice.


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.

SMSM Just to get the word out... The tcl.vim syntax file at [L13 ] is setup to do all this and other variations as well. At the top of the file are a list of switch variables that name highlighting groups. 'Let' them into existance, and the group lights. Otherwise, no. The default is 'ALL', so you will have to comment that one. Restart vim to see changes.

Small note. 'Bookends' is the name for quotes, braces and brackets collectively.

It has a few odd spots because it hasn't been through very many hands. If these trouble anyone, do let me know.

There are a lot of odd cases in tcl syntax coloring, even when you want a simpler scheme. These cases are handled by the overall coloring and then certain groups are not lit. It's not something that you are going to notice in a small sample, but you will notice it if you look at some complex source file, like tkcon.tcl.

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 [L14 ]. Or watch the development that I conduct from my CVS repository [L15 ]. I'm tracking bugs and features with code samples and expected formatting on a page on my site [L16 ].

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