Movatterモバイル変換


[0]ホーム

URL:


Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq
Go to keyword (shortcut:k)
Site search (shortcut:s)
if_tcl.txt  ForVim version 9.2.  Last change: 2026 Feb 14VIM REFERENCE MANUAL  by Ingo WilkenTheTclInterface to VimtclTclTCL1. Commandstcl-ex-commands2.Tcl commandstcl-commands3.Tclvariablestcl-variables4.Tclwindow commandstcl-window-cmds5.Tcl buffer commandstcl-buffer-cmds6. Miscellaneous; Output fromTcltcl-misctcl-output7. Knownbugs& problemstcl-bugs8. Examplestcl-examples9. Dynamic loadingtcl-dynamic{only available when Vim was compiled with the |+tcl| feature}E280WARNING: There are probably still some bugs.  Please send bug reports,comments, ideas etc to <Ingo.Wilken@informatik.uni-oldenburg.de>==============================================================================1. Commandstcl-ex-commandsE571E572:tcl:[range]tcl{cmd}ExecuteTcl command{cmd}.A simple check if:tclis working::tcl puts "Hello":[range]tcl<<[trim] [{endmarker}]{script}{endmarker}ExecuteTclscript{script}.Note: This command doesn't work when theTcl featurewasn't compiled in.  To avoid errors, seescript-here.If[endmarker]is omitted from after the "<<",a dot '.'must be used after{script}, like for the:append and:insert commands.  Refer to:let-heredoc for more information.This form of the:tcl commandis mainly useful for includingtcl code in Vimscripts.Example:function! DefineDate()    tcl << EOF    proc date {} {return [clock format [clock seconds]]    }EOFendfunctionTo see what version ofTcl you have::tcl puts [info patchlevel]:tcldo:tcld:[range]tcld[o]{cmd}ExecuteTcl command{cmd} for each line in[range]with the variable "line" being set to the text of eachline in turn, and "lnum" to the line number.  Setting"line" will change the text, butnote thatitis notpossible to add or delete lines using this command.If{cmd} returns an error, the commandis interrupted.The default for[range]is the whole file: "1,$".Seetcl-var-line andtcl-var-lnum.:tclfile:tclf:[range]tclf[ile]{file}Execute theTclscript in{file}.  Thisis the sameas":tcl source{file}", but allows file name completion.Note thatTclobjects (like variables) persist from one command to the next,justas in theTcl shell.ExecutingTcl commandsis not possible in thesandbox.==============================================================================2.Tcl commandstcl-commandsTcl code gets all of its access to vim via commands in the "::vim" namespace.The following commands are implemented:::vim::beep# Guess.::vim::buffer {n}# Create Tcl command for one buffer.::vim::buffer list# Create Tcl commands for all buffers.::vim::command [-quiet] {cmd}# Execute an Ex command.::vim::expr {expr}# Use Vim's expression evaluator.::vim::option {opt}# Get vim option.::vim::option {opt} {val}# Set vim option.::vim::window list# Create Tcl commands for all windows.Commands:::vim::beeptcl-beepHonk.  Does not returna result.::vim::buffer{n}tcl-buffer::vim::buffer exists{n}::vim::bufferlistProvides access to vim buffers.  With an integer argument, createsabuffer command (seetcl-buffer-cmds) for the buffer with thatnumber, and returns its nameas the result.  Invalid buffer numbersresult ina standardTcl error.  To test for valid buffer numbers,vim's internalfunctions can be used:set nbufs [::vim::expr bufnr("$")]set isvalid [::vim::expr "bufexists($n)"]The "list" option createsa buffer command for each valid buffer, andreturnsalist of the command namesas the result.Example:set bufs [::vim::buffer list]foreach b $bufs { $b append end "The End!" }The "exists" option checks ifa buffer with the given number exists.Example:if { [::vim::buffer exists $n] } { ::vim::command ":e #$n" }This command might be replaced bya variable in future versions.See alsotcl-var-current for the current buffer.::vim::command{cmd}tcl-command::vim::command -quiet{cmd}Execute the vim (ex-mode) command{cmd}.  AnyEx command that affectsa buffer orwindow uses the current buffer/current window.  Does notreturna result other thana standardTcl error code.  After thiscommandis completed, the "::vim::current" variableis updated.The "-quiet" flag suppresses any errormessages from vim.Examples:::vim::command "set ts=8"::vim::command "%s/foo/bar/g"To execute normal-mode commands, use "normal" (see:normal):set cmd "jj"::vim::command "normal $cmd"See alsotcl-window-command andtcl-buffer-command.::vim::expr{expr}tcl-exprEvaluates theexpression{expr} using vim's internalexpressionevaluator (seeexpression).   Anyexpression that queriesa bufferorwindow property uses the current buffer/current window.  Returnsthe resultasa string.AListis turned intoastring by joiningthe items andinserting line breaks.Examples:set perl_available [::vim::expr has("perl")]See alsotcl-window-expr andtcl-buffer-expr.::vim::option{opt}tcl-option::vim::option{opt}{value}Without second argument, queries the value ofa vim option.  With thisargument, sets the vim option to{value}, and returns the previousvalueas the result.  Anyoptions that are markedas 'local to buffer'or 'local to window' affect the current buffer/current window.  Theglobal valueis not changed, use the ":set" command for that.  Forboolean options,{value} should be "0" or "1", or any of the keywords"on", "off" or "toggle".  Seeoption-summary foralist of options.Example:::vim::option ts 8See alsotcl-window-option andtcl-buffer-option.::vim::window{option}tcl-windowProvides access to vim windows.  Currently only the "list" optionisimplemented.  This createsawindow command (seetcl-window-cmds) foreach window, and returnsalist of the command namesas the result.Example:set wins [::vim::window list]foreach w $wins { $w height 4 }This command might be replaced bya variable in future versions.See alsotcl-var-current for the current window.==============================================================================3.Tclvariablestcl-variablesThe ::vim namespace containsa few variables.  These are created when theTclinterpreteris called from vim and set to current values.::vim::current# array containing "current" objects::vim::lbase# number of first line::vim::range# array containing current range numbersline# current line as a string (:tcldo only)lnum# current line number (:tcldo only)Variables:::vim::currenttcl-var-currentThisis an array providing access tovarious "current"objectsavailable in vim.  The contents of this array are updated after"::vim::command"is called,as this might change vim's currentsettings (e.g., bydeleting the current buffer).The "buffer" element contains the name of the buffer command for thecurrent buffer.  This can be used directly to invoke buffer commands(seetcl-buffer-cmds).  This elementis read-only.Example:$::vim::current(buffer) insert begin "Hello world"The "window" element contains the name of thewindow command for thecurrent window.  This can be used directly to invokewindow commands(seetcl-window-cmds).  This elementis read-only.Example:$::vim::current(window) height 10::vim::lbasetcl-var-lbaseThis variable controls howTcl treats line numbers.  Ifitis set to'1', then lines and columns startat 1.  This way, line numbers fromTcl commands and vim expressions are compatible.  If this variableisset to '0', then line numbers and columns startat0 in Tcl.  Thisisuseful if you want to treata bufferasaTcllist ora lineasaTclstring and use standardTcl commands that return anindex("lsort" or"string first", for example).  The default valueis '1'.  Currently,any non-zero valuesis treatedas '1', but your scripts should notrely on this.  See alsotcl-linenumbers.::vim::rangetcl-var-rangeThisis an array with three elements, "start", "begin" and "end".  Itcontains the line numbers of the start andend row of the currentrange.  "begin"is the sameas "start".  This variableis read-only.Seetcl-examples.linetcl-var-linelnumtcl-var-lnumThese globalvariables are only available if the ":tcldo"Ex commandis being executed.  They contain the text and line number of thecurrent line.  When theTcl command invoked by ":tcldo"is completed,the current lineis set to the contents of the "line" variable, unlessthe variable was unset by theTcl command.  The "lnum" variableisread-only.  Thesevariables are not in the "::vim" namespace so theycan be used in ":tcldo" without much typing (this might be changed infuture versions).  See alsotcl-linenumbers.==============================================================================4.Tclwindow commandstcl-window-cmdsWindow commands represent vim windows.  They are created by several commands:::vim::windowlisttcl-window"windows" option ofa buffer commandtcl-buffer-windowsThe ::vim::current(window) variable contains the name of thewindow commandfor the current window.Awindow commandis automatically deleted when thecorresponding vimwindowis closed.Let's assume the name of thewindow commandis stored in theTcl variable"win", i.e. "$win" calls the command.  The followingoptions are available:$win buffer# Create Tcl command for window's buffer.$win command {cmd}# Execute Ex command in windows context.$win cursor# Get current cursor position.$win cursor {var}# Set cursor position from array variable.$win cursor {row} {col}# Set cursor position.$win delcmd {cmd}# Call Tcl command when window is closed.$win expr {expr}# Evaluate vim expression in windows context.$win height# Report the window's height.$win height {n}# Set the window's height.$win option {opt} [val]# Get/Set vim option in windows context.Options:$win buffertcl-window-bufferCreatesaTcl command for the window's buffer, and returns its nameasthe result.  The name should be stored ina variable:set buf [$win buffer]$bufis nowa validTcl command.  Seetcl-buffer-cmds for theavailable options.$win cursortcl-window-cursor$win cursor{var}$win cursor{row}{col}Without argument, reports the current cursor positionasa string.This can be converted toaTcl array variable:array set here [$win cursor]"here(row)" and "here(column)" now contain the cursor position.Witha single argument, the argumentis interpretedas the name ofaTcl array variable, whichmust contain two elements "row" and"column".These are used to set the cursor to the new position:$win cursor here;# not $here !With two arguments, sets the cursor to the specified row and column:$win cursor $here(row) $here(column)Invalid positions result ina standardTcl error, which can be caughtwith "catch".  The row and column values depend on the "::vim::lbase"variable.  Seetcl-var-lbase.$win delcmd{cmd}tcl-window-delcmdRegisters theTcl command{cmd}asa deletion callback for the window.This commandis executed (in the global scope) just before thewindowis closed.  Complex commands should be built with "list":$win delcmd [list puts vimerr "window deleted"]See alsotcl-buffer-delcmd.$win heighttcl-window-height$win height{n}Without argument, reports the window's current height.  With anargument, tries to set the window's height to{n}, then reports thenew height (which might be different from{n}).$win command[-quiet]{cmd}tcl-window-command$winexpr{expr}tcl-window-expr$win option{opt}[val]tcl-window-optionThese are similar to "::vim::command" etc., except that everythingisdone in the context of thewindow represented by $win, instead of thecurrent window.  For example, setting an option thatis marked 'localto window' affects thewindow $win.  Anything that affects or queriesa buffer uses the buffer displayed in thiswindow (i.e. the bufferthatis represented by "$win buffer").  Seetcl-command,tcl-exprandtcl-option for more information.Example:$win option number on==============================================================================5.Tcl buffer commandstcl-buffer-cmdsBuffer commands represent vim buffers.  They are created by several commands:::vim::buffer{N}tcl-buffer::vim::bufferlisttcl-buffer"buffer" option ofawindow commandtcl-window-bufferThe ::vim::current(buffer) variable contains the name of the buffer commandfor the current buffer.A buffer commandis automatically deleted when thecorresponding vim bufferis destroyed.  Whenever the buffer's contents arechanged, all marks in the buffer are automatically adjusted.  Any changes tothe buffer's contents made byTcl commands can be undone with the "undo" vimcommand (seeundo).Let's assume the name of the buffer commandis stored in theTcl variable"buf", i.e. "$buf" calls the command.  The followingoptions are available:$buf append {n} {str}# Append a line to buffer, after line {n}.$buf command {cmd}# Execute Ex command in buffers context.$buf count# Report number of lines in buffer.$buf delcmd {cmd}# Call Tcl command when buffer is deleted.$buf delete {n}# Delete a single line.$buf delete {n} {m}# Delete several lines.$buf expr {expr}# Evaluate vim expression in buffers context.$buf get {n}# Get a single line as a string.$buf get {n} {m}# Get several lines as a list.$buf insert {n} {str}# Insert a line in buffer, as line {n}.$buf last# Report line number of last line in buffer.$buf mark {mark}# Report position of buffer mark.$buf name# Report name of file in buffer.$buf number# Report number of this buffer.$buf option {opt} [val]# Get/Set vim option in buffers context.$buf set {n} {text}# Replace a single line.$buf set {n} {m} {list}# Replace several lines.$buf windows# Create Tcl commands for buffer's windows.tcl-linenumbersMost buffer commands take line numbersas arguments.  HowTcl treats thesenumbers depends on the "::vim::lbase" variable (seetcl-var-lbase).  Insteadof line numbers, several keywords can be also used: "top", "start", "begin","first", "bottom", "end" and "last".Options:$buf append{n}{str}tcl-buffer-append$bufinsert{n}{str}tcl-buffer-insertAdda line to the buffer.  With the "insert" option, thestringbecomes the new line{n}, with "append"itis inserted after line{n}.Example:$buf insert top "This is the beginning."$buf append end "This is the end."To addalist of lines to the buffer, usea loop:foreach line $list { $buf append $num $line ; incr num }$bufcounttcl-buffer-countReports the total number of lines in the buffer.$buf delcmd{cmd}tcl-buffer-delcmdRegisters theTcl command{cmd}asa deletion callback for the buffer.This commandis executed (in the global scope) just before the bufferis deleted.  Complex commands should be built with "list":$buf delcmd [list puts vimerr "buffer [$buf number] gone"]See alsotcl-window-delcmd.$buf delete{n}tcl-buffer-delete$buf delete{n}{m}Deletes line{n} or lines{n} through{m} from the buffer.This example deletes everything except the last line:$buf delete first [expr [$buf last] - 1]$buf get{n}tcl-buffer-get$buf get{n}{m}Gets one or more lines from the buffer.  Fora single line, the resultisa string; for several lines,alist of strings.Example:set topline [$buf get top]$buf lasttcl-buffer-lastReports the line number of the last line.  This value depends on the"::vim::lbase" variable.  Seetcl-var-lbase.$bufmark{mark}tcl-buffer-markReports the position of the namedmarkasa string, similar to thecursor position of the "cursor" option ofawindow command (seetcl-window-cursor).  This can be converted toaTcl array variable:array set mpos [$buf mark "a"]"mpos(column)" and "mpos(row)" now contain the position of the mark.If themarkis not set,a standardTcl error results.$buf nameReports the name of the file in the buffer.  Fora buffer withoutafile, thisis an empty string.$buf numberReports the number of this buffer.  See:buffers.This example deletesa buffer fromvim:::vim::command "bdelete [$buf number]"$buf set{n}{string}tcl-buffer-set$buf set{n}{m}{list}Replace one or several lines in the buffer.  If thelist contains moreelements than there are lines to replace, they are inserted into thebuffer.  If thelist contains fewer elements, any unreplaced lineisdeleted from the buffer.$bufwindowstcl-buffer-windowsCreatesawindow command for eachwindow that displays this buffer,and returnsalist of the command namesas the result.Example:set winlist [$buf windows]foreach win $winlist { $win height 4 }Seetcl-window-cmds for the available options.$buf command[-quiet]{cmd}tcl-buffer-command$bufexpr{expr}tcl-buffer-expr$buf option{opt}[val]tcl-buffer-optionThese are similar to "::vim::command" etc., except that everythingisdone in the context of the buffer represented by $buf, instead of thecurrent buffer.  For example, setting an option thatis marked 'localto buffer' affects the buffer $buf.  Anything that affects or queriesawindow uses the firstwindow in vim'swindowlist that displays thisbuffer (i.e. the first entry in thelist returned by "$bufwindows").Seetcl-command,tcl-expr andtcl-option for more information.Example:if { [$buf option modified] } { $buf command "w" }==============================================================================6. Miscellaneous; Output fromTcltcl-misctcl-outputThe standardTcl commands "exit" and "catch" are replaced by custom versions."exit" terminates the currentTclscript and returns to vim, which deletes theTcl interpreter.  Another call to ":tcl" then createsa newTcl interpreter."exit" does NOT terminate vim!  "catch" worksas before, except thatit doesnot preventscript termination from "exit".  An exit code !=0 causes theexcommand that invoked theTclscript to return an error.Two new I/O streams are available in Tcl, "vimout" and "vimerr".  All outputdirected to themis displayed in the vim message area,as informationmessagesand error messages, respectively.  The standardTcl output streams stdout andstderr are mapped to vimout and vimerr, so thata normal "puts" command can beused to displaymessages in vim.==============================================================================7. Knownbugs& problemstcl-bugsCalling one of theTclEx commands from insideTcl (via "::vim::command") mayhave unexpected side effects.  The command createsa new interpreter, whichhas the same abilitiesas the standard interpreter- making "::vim::command"available ina safe child interpreter therefore makes the child unsafe.  (Itwould be trivial to block nested:tcl* calls or ensure that such calls fromasafe interpreter create only new safe interpreters, but quite pointless-depending on vim's configuration, "::vim::command" may execute arbitrary codein any number of other scripting languages.)A call to "exit" within this newinterpreter does not affect the old interpreter;it only terminates the newinterpreter, thenscript processing continues normally in the old interpreter.Input from stdinis currently not supported.==============================================================================8. Examples:tcl-examplesHere area few small (and maybe useful)Tcl scripts.Thisscript sorts the lines of the entire buffer (assumeit containsalistof names or something similar):set buf $::vim::current(buffer)set lines [$buf get top bottom]set lines [lsort -dictionary $lines]$buf set top bottom $linesThisscript reverses the lines in the buffer.Note the use of "::vim::lbase"and "$buf last" to work with any line number setting:set buf $::vim::current(buffer)set t $::vim::lbaseset b [$buf last]while { $t < $b } {set tl [$buf get $t]set bl [$buf get $b]$buf set $t $bl$buf set $b $tlincr tincr b -1}Thisscript addsa consecutive number to each line in the current range:set buf $::vim::current(buffer)set i $::vim::range(start)set n 1while { $i <= $::vim::range(end) } {set line [$buf get $i]$buf set $i "$n\t$line"incr i ; incr n}The same can also be done quickly with twoEx commands, using ":tcldo"::tcl set n 1:[range]tcldo set line "$n\t$line" ; incr nThis procedure runs anEx command on each buffer (idea stolen from Ron Aaron):proc eachbuf { cmd } {foreach b [::vim::buffer list] {$b command $cmd}}Useit like this::tcl eachbuf %s/foo/bar/gBe careful with Tcl'sstring andbackslash substitution, tough.  If in doubt,surround theEx command with curly braces.If you want to add someTcl procedures permanently to vim, just place them ina file (e.g. "~/.vimrc.tcl" onUnix machines), and add these lines to yourstartup file (usually "~/.vimrc" on Unix):if has("tcl")tclfile ~/.vimrc.tclendif==============================================================================9. Dynamic loadingtcl-dynamicOnMS-Windows andUnix theTcl library can be loaded dynamically.  The:version output then includes+tcl/dyn.This means that Vim will search for theTcl DLL or shared library file onlywhen needed.  When you don't use theTclinterface you don't need it, thus youcan use Vim without this file.MS-WindowsTo use theTclinterface theTcl DLLmust be in your search path.  Inaconsolewindow type "path" to see what directories are used.  The'tcldll'option can be also used to specify theTcl DLL.The name of the DLLmust match theTcl version Vim was compiled with.Currently the nameis "tcl86.dll".  Thatis forTcl 8.6.  To know for sureedit "gvim.exe" and search for "tcl\d*.dll\c".UnixThe'tcldll' option can be used to specify theTcl shared library file insteadof DYNAMIC_TCL_DLL file what was specifiedat compile time.  The version ofthe shared librarymust match theTcl version Vim was compiled with.============================================================================== vim:tw=78:ts=8:noet:ft=help:norl:

Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq


[8]ページ先頭

©2009-2026 Movatter.jp