Professional Documents
Culture Documents
Vim Editor Documentation
Vim Editor Documentation
*index*
This file contains a list of all commands for each mode, with a tag and a
short description. The lists are sorted on ASCII value.
Tip: When looking for certain functionality, use a search command. E.g.,
to look for deleting something, use: "/delete".
1. Insert mode |insert-index|
2. Normal mode |normal-index|
2.1. Text objects |objects|
2.2. Window commands |CTRL-W|
2.3. Square bracket commands |[|
2.4. Commands starting with 'g' |g|
2.5. Commands starting with 'z' |z|
3. Visual mode |visual-index|
4. Command-line editing |ex-edit-index|
5. EX commands |ex-cmd-index|
For an overview of options see help.txt |option-list|.
For an overview of built-in functions see |functions|.
For a list of Vim variables see |vim-variable|.
For a complete listing of all help items see |help-tags|.
==============================================================================
1. Insert mode *insert-index*
tag char action in Insert mode
|i_CTRL-@| CTRL-@ insert previously inserted text and stop
insert
|i_CTRL-A| CTRL-A insert previously inserted text
CTRL-B not used |i_CTRL-B-gone|
|i_CTRL-C| CTRL-C quit insert mode, without checking for
abbreviation, unless 'insertmode' set.
|i_CTRL-D| CTRL-D delete one shiftwidth of indent in the current
line
|i_CTRL-E| CTRL-E insert the character which is below the cursor
CTRL-F not used (but by default it's in 'cinkeys' to
re-indent the current line)
|i_CTRL-G_j| CTRL-G CTRL-J line down, to column where inserting started
|i_CTRL-G_j| CTRL-G j line down, to column where inserting started
|i_CTRL-G_j| CTRL-G <Down> line down, to column where inserting started
|i_CTRL-G_k| CTRL-G CTRL-K line up, to column where inserting started
|i_CTRL-G_k| CTRL-G k line up, to column where inserting started
|i_CTRL-G_k| CTRL-G <Up> line up, to column where inserting started
|i_CTRL-G_u| CTRL-G u start new undoable edit
|i_<BS>| <BS> delete character before the cursor
|i_digraph| {char1}<BS>{char2}
enter digraph (only when 'digraph' option set)
|i_CTRL-H| CTRL-H same as <BS>
|i_<Tab>| <Tab> insert a <Tab> character
|i_CTRL-I| CTRL-I same as <Tab>
|i_<NL>| <NL> same as <CR>
|i_CTRL-J| CTRL-J same as <CR>
|i_CTRL-K| CTRL-K {char1} {char2}
enter digraph
|i_CTRL-L| CTRL-L when 'insertmode' set: Leave Insert mode
|k| k 1
cursor N lines upward
|l| l 1
cursor N chars to the right
|m| m{A-Za-z} set mark {A-Za-z} at cursor position
|n| n 1 repeat the latest '/' or '?' N times
|o| o 2 begin a new line below the cursor and
insert text, repeat N times
|p| ["x]p 2 put the text [from register x] after the
cursor N times
|q| q{0-9a-zA-Z"} record typed characters into named register
{0-9a-zA-Z"} (uppercase to append)
|q| q (while recording) stops recording
|q:| q: edit : command-line in command-line window
|q/| q/ edit / command-line in command-line window
|q?| q? edit ? command-line in command-line window
|r| r{char} 2 replace N chars with {char}
|s| ["x]s 2 (substitute) delete N characters [into
buffer x] and start insert
|t| t{char} 1 cursor till before Nth occurrence of {char}
to the right
|u| u 2 undo changes
|v| v start characterwise Visual mode
|w| w 1 cursor N words forward
|x| ["x]x 2 delete N characters under and after the
cursor [into buffer x]
|y| ["x]y{motion} yank Nmove text [into buffer x]
|yy| ["x]yy yank N lines [into buffer x]
|z| z{char} commands starting with 'z', see |z| below
|{| { 1 cursor N paragraphs backward
|bar| | 1 cursor to column N
|}| } 1 cursor N paragraphs forward
|~| ~ 2 'tildeop' off: switch case of N characters
under cursor and move the cursor N
characters to the right
|~| ~{motion} 'tildeop' on: switch case of Nmove text
|<C-End>| <C-End> 1 same as "G"
|<C-Home>| <C-Home> 1 same as "gg"
|<C-Left>| <C-Left> 1 same as "b"
|<C-LeftMouse>| <C-LeftMouse> ":ta" to the keyword at the mouse click
|<C-Right>| <C-Right> 1 same as "w"
|<C-RightMouse>| <C-RightMouse> same as "CTRL-T"
|<Del>| ["x]<Del> 2 same as "x"
|N<Del>| {count}<Del> remove the last digit from {count}
|<Down>| <Down> 1 same as "j"
|<End>| <End> 1 same as "$"
|<F1>| <F1> same as <Help>
|<Help>| <Help> open a help window
|<Home>| <Home> 1 same as "0"
|<Insert>| <Insert> 2 same as "i"
|<Left>| <Left> 1 same as "h"
|<LeftMouse>| <LeftMouse> 1 move cursor to the mouse click position
|<MiddleMouse>| <MiddleMouse> 2 same as "gP" at the mouse click position
|<PageDown>| <PageDown> same as CTRL-F
|<PageUp>| <PageUp> same as CTRL-B
|<Right>| <Right> 1 same as "l"
|<RightMouse>| <RightMouse> start Visual mode, move cursor to the mouse
click position
|<S-Down>| <S-Down> 1 same as CTRL-F
|<S-Left>| <S-Left> 1 same as "b"
|<S-LeftMouse>| <S-LeftMouse> same as "*" at the mouse click position
|<S-Right>| <S-Right> 1 same as "w"
|<S-RightMouse>| <S-RightMouse> same as "#" at the mouse click position
|<S-Up>| <S-Up> 1 same as CTRL-B
|<Undo>| <Undo> 2 same as "u"
|<Up>| <Up> 1 same as "k"
|<ScrollWheelDown>| <ScrollWheelDown> move window three lines down
|<S-ScrollWheelDown>| <S-ScrollWheelDown> move window one page down
|<ScrollWheelUp>| <ScrollWheelUp> move window three lines up
|<S-ScrollWheelUp>| <S-ScrollWheelUp> move window one page up
|<ScrollWheelLeft>| <ScrollWheelLeft> move window six columns left
|<S-ScrollWheelLeft>| <S-ScrollWheelLeft> move window one page left
|<ScrollWheelRight>| <ScrollWheelRight> move window six columns right
|<S-ScrollWheelRight>| <S-ScrollWheelRight> move window one page right
==============================================================================
2.1 Text objects *objects*
These can be used after an operator or in Visual mode to select an object.
tag command action in op-pending and Visual mode
------------------------------------------------------------------------------
|v_aquote| a" double quoted string
|v_a'| a' single quoted string
|v_a(| a( same as ab
|v_a)| a) same as ab
|v_a<| a< "a <>" from '<' to the matching '>'
|v_a>| a> same as a<
|v_aB| aB "a Block" from "[{" to "]}" (with brackets)
|v_aW| aW "a WORD" (with white space)
|v_a[| a[ "a []" from '[' to the matching ']'
|v_a]| a] same as a[
|v_a`| a` string in backticks
|v_ab| ab "a block" from "[(" to "])" (with braces)
|v_ap| ap "a paragraph" (with white space)
|v_as| as "a sentence" (with white space)
|v_at| at "a tag block" (with white space)
|v_aw| aw "a word" (with white space)
|v_a{| a{ same as aB
|v_a}| a} same as aB
|v_iquote| i" double quoted string without the quotes
|v_i'| i' single quoted string without the quotes
|v_i(| i( same as ib
|v_i)| i) same as ib
|v_i<| i< "inner <>" from '<' to the matching '>'
|v_i>| i> same as i<
|v_iB| iB "inner Block" from "[{" and "]}"
|v_iW| iW "inner WORD"
|v_i[| i[ "inner []" from '[' to the matching ']'
|v_i]| i] same as i[
|v_i`| i` string in backticks without the backticks
|v_ib| ib "inner block" from "[(" to "])"
|v_ip| ip "inner paragraph"
|v_is| is "inner sentence"
|v_it| it "inner tag block"
|v_iw| iw "inner word"
|v_i{| i{ same as iB
|v_i}| i} same as iB
==============================================================================
2.2 Window commands *CTRL-W*
tag command action in Normal mode
------------------------------------------------------------------------------
|CTRL-W_CTRL-B| CTRL-W CTRL-B same as "CTRL-W b"
|CTRL-W_CTRL-C| CTRL-W CTRL-C same as "CTRL-W c"
|CTRL-W_CTRL-D| CTRL-W CTRL-D same as "CTRL-W d"
|CTRL-W_CTRL-F| CTRL-W CTRL-F same as "CTRL-W f"
CTRL-W CTRL-G same as "CTRL-W g .."
|CTRL-W_CTRL-H| CTRL-W CTRL-H same as "CTRL-W h"
|CTRL-W_CTRL-I| CTRL-W CTRL-I same as "CTRL-W i"
|CTRL-W_CTRL-J| CTRL-W CTRL-J same as "CTRL-W j"
|CTRL-W_CTRL-K| CTRL-W CTRL-K same as "CTRL-W k"
|CTRL-W_CTRL-L| CTRL-W CTRL-L same as "CTRL-W l"
|CTRL-W_CTRL-N| CTRL-W CTRL-N same as "CTRL-W n"
|CTRL-W_CTRL-O| CTRL-W CTRL-O same as "CTRL-W o"
|CTRL-W_CTRL-P| CTRL-W CTRL-P same as "CTRL-W p"
|CTRL-W_CTRL-Q| CTRL-W CTRL-Q same as "CTRL-W q"
|CTRL-W_CTRL-R| CTRL-W CTRL-R same as "CTRL-W r"
|CTRL-W_CTRL-S| CTRL-W CTRL-S same as "CTRL-W s"
|CTRL-W_CTRL-T| CTRL-W CTRL-T same as "CTRL-W t"
|CTRL-W_CTRL-V| CTRL-W CTRL-V same as "CTRL-W v"
|CTRL-W_CTRL-W| CTRL-W CTRL-W same as "CTRL-W w"
|CTRL-W_CTRL-X| CTRL-W CTRL-X same as "CTRL-W x"
|CTRL-W_CTRL-Z| CTRL-W CTRL-Z same as "CTRL-W z"
|CTRL-W_CTRL-]| CTRL-W CTRL-] same as "CTRL-W ]"
|CTRL-W_CTRL-^| CTRL-W CTRL-^ same as "CTRL-W ^"
|CTRL-W_CTRL-_| CTRL-W CTRL-_ same as "CTRL-W _"
|CTRL-W_+| CTRL-W + increase current window height N lines
|CTRL-W_-| CTRL-W - decrease current window height N lines
|CTRL-W_<| CTRL-W < decrease current window width N columns
|CTRL-W_=| CTRL-W = make all windows the same height & width
|CTRL-W_>| CTRL-W > increase current window width N columns
|CTRL-W_H| CTRL-W H move current window to the far left
|CTRL-W_J| CTRL-W J move current window to the very bottom
|CTRL-W_K| CTRL-W K move current window to the very top
|CTRL-W_L| CTRL-W L move current window to the far right
|CTRL-W_P| CTRL-W P go to preview window
|CTRL-W_R| CTRL-W R rotate windows upwards N times
|CTRL-W_S| CTRL-W S same as "CTRL-W s"
|CTRL-W_T| CTRL-W T
move current window to a new tab page
|CTRL-W_W| CTRL-W W
go to N previous window (wrap around)
|CTRL-W_]| CTRL-W ]
split window and jump to tag under cursor
|CTRL-W_^| CTRL-W ^
split current window and edit alternate
file N
|CTRL-W__| CTRL-W _ set current window height to N (default:
very high)
|CTRL-W_b| CTRL-W b go to bottom window
|CTRL-W_c| CTRL-W c close current window (like |:close|)
|CTRL-W_d| CTRL-W d split window and jump to definition under
the cursor
|CTRL-W_f| CTRL-W f split window and edit file name under the
cursor
|CTRL-W_F| CTRL-W F split window and edit file name under the
cursor and jump to the line number
following the file name.
|CTRL-W_g_CTRL-]| CTRL-W g CTRL-] split window and do |:tjump| to tag under
cursor
|CTRL-W_g]| CTRL-W g ] split window and do |:tselect| for tag
under cursor
|CTRL-W_g}| CTRL-W g } do a |:ptjump| to the tag under the cursor
|CTRL-W_gf| CTRL-W g f edit file name under the cursor in a new
tab page
|CTRL-W_gF| CTRL-W g F edit file name under the cursor in a new
tab page and jump to the line number
following the file name.
|CTRL-W_h| CTRL-W h go to Nth left window (stop at first window)
|CTRL-W_i| CTRL-W i split window and jump to declaration of
identifier under the cursor
|CTRL-W_j| CTRL-W j go N windows down (stop at last window)
|CTRL-W_k| CTRL-W k go N windows up (stop at first window)
|CTRL-W_l| CTRL-W l go to Nth right window (stop at last window)
|CTRL-W_n| CTRL-W n open new window, N lines high
|CTRL-W_o| CTRL-W o close all but current window (like |:only|)
|CTRL-W_p| CTRL-W p go to previous (last accessed) window
|CTRL-W_q| CTRL-W q quit current window (like |:quit|)
|CTRL-W_r| CTRL-W r rotate windows downwards N times
|CTRL-W_s| CTRL-W s split current window in two parts, new
window N lines high
|CTRL-W_t| CTRL-W t go to top window
|CTRL-W_v| CTRL-W v split current window vertically, new window
N columns wide
|CTRL-W_w| CTRL-W w go to N next window (wrap around)
|CTRL-W_x| CTRL-W x exchange current window with window N
(default: next window)
|CTRL-W_z| CTRL-W z close preview window
|CTRL-W_bar| CTRL-W | set window width to N columns
|CTRL-W_}| CTRL-W } show tag under cursor in preview window
|CTRL-W_<Down>| CTRL-W <Down> same as "CTRL-W j"
|CTRL-W_<Up>| CTRL-W <Up> same as "CTRL-W k"
|CTRL-W_<Left>| CTRL-W <Left> same as "CTRL-W h"
|CTRL-W_<Right>| CTRL-W <Right> same as "CTRL-W l"
==============================================================================
2.3 Square bracket commands *[* *]*
tag char note action in Normal mode
------------------------------------------------------------------------------
|[_CTRL-D| [ CTRL-D jump to first #define found in current and
included files matching the word under the
cursor, start searching at beginning of
current file
|[_CTRL-I| [ CTRL-I jump to first line in current and included
files that contains the word under the
cursor, start searching at beginning of
current file
|[#| [# 1 cursor to N previous unmatched #if, #else
or #ifdef
|['| [' 1 cursor to previous lowercase mark, on first
non-blank
|[(| [( 1 cursor N times back to unmatched '('
|[star| [* 1 same as "[/"
|[`| [` 1 cursor to previous lowercase mark
|[/| [/ 1 cursor to N previous start of a C comment
|[D| [D list all defines found in current and
included files matching the word under the
cursor, start searching at beginning of
current file
|[I| [I list all lines found in current and
of
the current screen line
|g&| g& 2
repeat last ":s" on all lines
|g'| g'{mark} 1
like |'| but without changing the jumplist
|g`| g`{mark} 1
like |`| but without changing the jumplist
|gstar| g* 1 like "*", but without using "\<" and "\>"
|g0| g0 1 when 'wrap' off go to leftmost character of
the current line that is on the screen;
when 'wrap' on go to the leftmost character
of the current screen line
|g8| g8 print hex value of bytes used in UTF-8
character under the cursor
|g<| g< display previous command output
|g?| g? 2 Rot13 encoding operator
|g?g?| g?? 2 Rot13 encode current line
|g?g?| g?g? 2 Rot13 encode current line
|gD| gD 1 go to definition of word under the cursor
in current file
|gE| gE 1 go backwards to the end of the previous
WORD
|gH| gH start Select line mode
|gI| gI 2 like "I", but always start in column 1
|gJ| gJ 2 join lines without inserting space
|gP| ["x]gP 2 put the text [from register x] before the
cursor N times, leave the cursor after it
|gQ| gQ switch to "Ex" mode with Vim editing
|gR| gR 2 enter Virtual Replace mode
|gU| gU{motion} 2 make Nmove text uppercase
|gV| gV don't reselect the previous Visual area
when executing a mapping or menu in Select
mode
|g]| g] :tselect on the tag under the cursor
|g^| g^ 1 when 'wrap' off go to leftmost non-white
character of the current line that is on
the screen; when 'wrap' on go to the
leftmost non-white character of the current
screen line
|ga| ga print ascii value of character under the
cursor
|gd| gd 1 go to definition of word under the cursor
in current function
|ge| ge 1 go backwards to the end of the previous
word
|gf| gf start editing the file whose name is under
the cursor
|gF| gF start editing the file whose name is under
the cursor and jump to the line number
following the filename.
|gg| gg 1 cursor to line N, default first line
|gh| gh start Select mode
|gi| gi 2 like "i", but first move to the |'^| mark
|gj| gj 1 like "j", but when 'wrap' on go N screen
lines down
|gk| gk 1 like "k", but when 'wrap' on go N screen
lines up
|gm| gm 1 go to character at middle of the screenline
|go| go 1 cursor to byte N in the buffer
|gp| ["x]gp 2 put the text [from register x] after the
cursor N times, leave the cursor after it
|gq| gq{motion} 2 format Nmove text
|gr| gr{char} 2 virtual replace N chars with {char}
|gs| gs go to sleep for N seconds (default 1)
|gu| gu{motion} 2 make Nmove text lowercase
|gv| gv reselect the previous Visual area
|gw| gw{motion} 2 format Nmove text and keep cursor
|netrw-gx| gx execute application for file name under the
cursor (only with |netrw| plugin)
|g@| g@{motion} call 'operatorfunc'
|g~| g~{motion} 2 swap case for Nmove text
|g<Down>| g<Down> 1 same as "gj"
|g<End>| g<End> 1 same as "g$"
|g<Home>| g<Home> 1 same as "g0"
|g<LeftMouse>| g<LeftMouse> same as <C-LeftMouse>
g<MiddleMouse> same as <C-MiddleMouse>
|g<RightMouse>| g<RightMouse> same as <C-RightMouse>
|g<Up>| g<Up> 1 same as "gk"
==============================================================================
2.5 Commands starting with 'z' *z*
argument list
|:wprevious| :wp[revious] write to a file and go to previous file in
argument list
|:wq| :wq write to a file and quit window or Vim
|:wqall| :wqa[ll] write all changed buffers and quit Vim
|:wsverb| :ws[verb] pass the verb to workshop over IPC
|:wundo| :wu[ndo] write undo information to a file
|:wviminfo| :wv[iminfo] write to viminfo file
|:xit| :x[it] write if buffer changed and quit window or Vim
|:xall| :xa[ll] same as ":wqall"
|:xmapclear| :xmapc[lear] remove all mappings for Visual mode
|:xmap| :xm[ap] like ":map" but for Visual mode
|:xmenu| :xme[nu] add menu for Visual mode
|:xnoremap| :xn[oremap] like ":noremap" but for Visual mode
|:xnoremenu| :xnoreme[nu] like ":noremenu" but for Visual mode
|:xunmap| :xu[nmap] like ":unmap" but for Visual mode
|:xunmenu| :xunme[nu] remove menu for Visual mode
|:yank| :y[ank] yank lines into a register
|:z| :z print some lines
|:~| :~ repeat last ":substitute"
'compatible'.
------------------------------------------------------------------------------
top
*pronounce*
Vim is pronounced as one word, like Jim, not vi-ai-em. It's written with a
capital, since it's a name, again like Jim.
This manual is a reference for all the Vim commands and options. This is not
an introduction to the use of Vi or Vim, it gets a bit complicated here and
there. For beginners, there is a hands-on |tutor|. To learn using Vim, read
the user manual |usr_toc.txt|.
*book*
There are many books on Vi that contain a section for beginners. There are
two books I can recommend:
"Vim - Vi Improved" by Steve Oualline
This is the very first book completely dedicated to Vim. It is very good for
beginners. The most often used commands are explained with pictures and
examples. The less often used commands are also explained, the more advanced
features are summarized. There is a comprehensive index and a quick
reference. Parts of this book have been included in the user manual
|frombook|.
Published by New Riders Publishing. ISBN: 0735710015
For more information try one of these:
http://iccf-holland.org/click5.html
http://www.vim.org/iccf/click5.html
"Learning the Vi editor" by Linda Lamb and Arnold Robbins
This is a book about Vi that includes a chapter on Vim (in the sixth edition).
The first steps in Vi are explained very well. The commands that Vim adds are
only briefly mentioned. There is also a German translation.
Published by O'Reilly. ISBN: 1-56592-426-6.
==============================================================================
2. Vim on the internet *internet*
*mail-list* *maillist*
There are several mailing lists for Vim:
<vim@vim.org>
For discussions about using existing versions of Vim: Useful mappings,
questions, answers, where to get a specific version, etc. There are
quite a few people watching this list and answering questions, also
for beginners. Don't hesitate to ask your question here.
<vim-dev@vim.org> *vim-dev* *vimdev*
For discussions about changing Vim: New features, porting, patches,
beta-test versions, etc.
<vim-announce@vim.org> *vim-announce*
Announcements about new versions of Vim; also for beta-test versions
and ports to different systems. This is a read-only list.
<vim-multibyte@vim.org> *vim-multibyte*
For discussions about using and improving the multi-byte aspects of
Vim.
<vim-mac@vim.org> *vim-mac*
For discussions about using and improving the Macintosh version of
Vim.
See http://www.vim.org/maillist.php for the latest information.
NOTE:
- You can only send messages to these lists if you have subscribed!
- You need to send the messages from the same location as where you subscribed
from (to avoid spam mail).
- Maximum message size is 40000 characters.
*subscribe-maillist*
If you want to join, send a message to
<vim-subscribe@vim.org>
Make sure that your "From:" address is correct. Then the list server will
give you help on how to subscribe.
*maillist-archive*
For more information and archives look on the Vim maillist page:
http://www.vim.org/maillist.php
*year-2000* *Y2K*
Since Vim internally doesn't use dates for editing, there is no year 2000
problem to worry about. Vim does use the time in the form of seconds since
January 1st 1970. It is used for a time-stamp check of the edited file and
the swap file, which is not critical and should only cause warning messages.
There might be a year 2038 problem, when the seconds don't fit in a 32 bit int
anymore. This depends on the compiler, libraries and operating system.
Specifically, time_t and the ctime() function are used. And the time_t is
stored in four bytes in the swap file. But that's only used for printing a
file date/time for recovery, it will never affect normal editing.
The Vim strftime() function directly uses the strftime() system function.
localtime() uses the time() system function. getftime() uses the time
returned by the stat() system function. If your system libraries are year
2000 compliant, Vim is too.
The user may create scripts for Vim that use external commands. These might
introduce Y2K problems, but those are not really part of Vim itself.
==============================================================================
3. Credits *credits* *author* *Bram* *Moolenaar*
Most of Vim was written by Bram Moolenaar <Bram@vim.org>.
Parts of the documentation come from several Vi manuals, written by:
W.N. Joy
Alan P.W. Hewett
Mark Horton
The Vim editor is based on Stevie and includes (ideas from) other software,
worked on by the people mentioned here. Other people helped by sending me
patches, suggestions and giving feedback about what is good and bad in Vim.
Vim would never have become what it is now, without the help of these people!
Ron Aaron Win32 GUI changes
Mohsin Ahmed encryption
Zoltan Arpadffy work on VMS port
Tony Andrews Stevie
Gert van Antwerpen changes for DJGPP on MS-DOS
Berkeley DB(3) ideas for swap file implementation
Keith Bostic Nvi
Walter Briscoe Makefile updates, various patches
Ralf Brown SPAWNO library for MS-DOS
Robert Colon many useful remarks
Marcin Dalecki GTK+ GUI port, toolbar icons, gettext()
*Elvis*
Elvis Another Vi clone, made by Steve Kirkendall. Very compact but isn't
as flexible as Vim.
The version used is 2.1. It is still being developed. Source code is
freely available.
==============================================================================
4. Notation *notation*
When syntax highlighting is used to read this, text that is not typed
literally is often highlighted with the Special group. These are items in [],
{} and <>, and CTRL-X.
Note that Vim uses all possible characters in commands. Sometimes the [], {}
and <> are part of what you type, the context should make this clear.
*count* *[count]*
[count] An optional number that may precede the command to multiply
or iterate the command. If no number is given, a count of one
is used, unless otherwise noted. Note that in this manual the
[count] is not mentioned in the description of the command,
but only in the explanation. This was done to make the
commands easier to look up. If the 'showcmd' option is on,
the (partially) entered count is shown at the bottom of the
window. You can use <Del> to erase the last digit (|N<Del>|).
*[quotex]*
["x] An optional register designation where text can be stored.
See |registers|. The x is a single character between 'a' and
'z' or 'A' and 'Z' or '"'', and in some cases (with the put
command) between '0' and '9', '%', '#', or others. The
uppercase and lowercase letter designate the same register,
but the lowercase letter is used to overwrite the previous
register contents, while the uppercase letter is used to
append to the previous register contents. Without the ""x" or
with """" the stored text is put into the unnamed register.
*{}*
{} Curly braces denote parts of the command which must appear,
but which can take a number of different values. The
differences between Vim and Vi are also given in curly braces
(this will be clear from the context).
*{char1-char2}*
{char1-char2} A single character from the range char1 to char2. For
example: {a-z} is a lowercase letter. Multiple ranges may be
concatenated. For example, {a-zA-Z0-9} is any alphanumeric
character.
*{motion}* *movement*
{motion} A command that moves the cursor. These are explained in
|motion.txt|. Examples:
w to start of next word
b to begin of current word
4j four lines down
/The<CR> to next occurrence of "The"
This is used after an |operator| command to move over the text
that is to be operated upon.
- If the motion includes a count and the operator also has a
count, the two counts are multiplied. For example: "2d3w"
deletes six words.
- The motion can be backwards, e.g. "db" to delete to the
start of the word.
- The motion can also be a mouse click. The mouse is not
supported in every terminal though.
- The ":omap" command can be used to map characters while an
operator is pending.
- Ex commands can be used to move the cursor. This can be
used to call a function that does some complicated motion.
The motion is always characterwise exclusive, no matter
*{Visual}*
{Visual} A selected text area. It is started with the "v", "V", or
CTRL-V command, then any cursor movement command can be used
to change the end of the selected text.
This is used before an |operator| command to highlight the
text that is to be operated upon.
See |Visual-mode|.
*<character>*
<character> A special character from the table below, optionally with
modifiers, or a single ASCII character with modifiers.
*'character'*
'c' A single ASCII character.
*CTRL-{char}*
CTRL-{char} {char} typed as a control character; that is, typing {char}
while holding the CTRL key down. The case of {char} does not
matter; thus CTRL-A and CTRL-a are equivalent. But on some
terminals, using the SHIFT key will produce another code,
don't use it then.
*'option'*
'option' An option, or parameter, that can be set to a value, is
enclosed in single quotes. See |options|.
*quotecommandquote*
"command" A reference to a command that you can type is enclosed in
double quotes.
Note: There are two codes for the delete key. 127 is the decimal ASCII value
for the delete key, which is always recognized. Some delete keys send another
value, in which case this value is obtained from the termcap entry "kD". Both
values have the same effect. Also see |:fixdel|.
Note: The keypad keys are used in the same way as the corresponding "normal"
keys. For example, <kHome> has the same effect as <Home>. If a keypad key
sends the same raw key code as its non-keypad equivalent, it will be
recognized as the non-keypad code. For example, when <kHome> sends the same
code as <Home>, when pressing <kHome> Vim will think <Home> was pressed.
Mapping <kHome> will not work then.
*<>*
Examples are often given in the <> notation. Sometimes this is just to make
clear what you need to type, but often it can be typed literally, e.g., with
the ":map" command. The rules are:
1. Any printable characters are typed directly, except backslash and '<'
2. A backslash is represented with "\\", double backslash, or "<Bslash>".
3. A real '<' is represented with "\<" or "<lt>". When there is no
confusion possible, a '<' can be used directly.
4. "<key>" means the special key typed. This is the notation explained in
the table above. A few examples:
<Esc> Escape key
<C-G> CTRL-G
<Up> cursor up key
<C-LeftMouse> Control- left mouse click
<S-F11> Shifted function key 11
<M-a> Meta- a ('a' with bit 8 set)
<M-A> Meta- A ('A' with bit 8 set)
<t_kd> "kd" termcap entry (cursor down key)
If you want to use the full <> notation in Vim, you have to make sure the '<'
flag is excluded from 'cpoptions' (when 'compatible' is not set, it already is
by default).
:set cpo-=<
The <> notation uses <lt> to escape the special meaning of key names. Using a
backslash also works, but only when 'cpoptions' does not include the 'B' flag.
Examples for mapping CTRL-H to the six characters "<Home>":
:imap <C-H> \<Home>
:imap <C-H> <lt>Home>
The first one only works when the 'B' flag is not in 'cpoptions'. The second
one always works.
To get a literal "<lt>" in a mapping:
:map <C-L> <lt>lt>
For mapping, abbreviation and menu commands you can then copy-paste the
examples and use them directly. Or type them literally, including the '<' and
'>' characters. This does NOT work for other commands, like ":set" and
":autocmd"!
==============================================================================
5. Modes, introduction *vim-modes-intro* *vim-modes*
Vim has six BASIC modes:
*Operator-pending* *Operator-pending-mode*
Operator-pending mode This is like Normal mode, but after an operator
command has started, and Vim is waiting for a {motion}
to specify the text that the operator will work on.
Replace mode Replace mode is a special case of Insert mode. You
can do the same things as in Insert mode, but for
each character you enter, one character of the existing
text is deleted. See |Replace-mode|.
If the 'showmode' option is on "-- REPLACE --" is
shown at the bottom of the window.
Virtual Replace mode Virtual Replace mode is similar to Replace mode, but
instead of file characters you are replacing screen
real estate. See |Virtual-Replace-mode|.
If the 'showmode' option is on "-- VREPLACE --" is
shown at the bottom of the window.
Insert Normal mode Entered when CTRL-O given in Insert mode. This is
like Normal mode, but after executing one command Vim
returns to Insert mode.
If the 'showmode' option is on "-- (insert) --" is
shown at the bottom of the window.
Insert Visual mode Entered when starting a Visual selection from Insert
mode, e.g., by using CTRL-O and then "v", "V" or
CTRL-V. When the Visual selection ends, Vim returns
to Insert mode.
If the 'showmode' option is on "-- (insert) VISUAL --"
is shown at the bottom of the window.
Insert Select mode Entered when starting Select mode from Insert mode.
E.g., by dragging the mouse or <S-Right>.
When the Select mode ends, Vim returns to Insert mode.
If the 'showmode' option is on "-- (insert) SELECT --"
is shown at the bottom of the window.
==============================================================================
6. Switching from mode to mode *mode-switching*
If for any reason you do not know which mode you are in, you can always get
back to Normal mode by typing <Esc> twice. This doesn't work for Ex mode
though, use ":visual".
You will know you are back in Normal mode when you see the screen flash or
hear the bell after you type <Esc>. However, when pressing <Esc> after using
CTRL-O in Insert mode you get a beep but you are still in Insert mode, type
<Esc> again.
*i_esc*
TO mode
Normal Visual Select Insert Replace Cmd-line Ex
FROM mode
Normal v V ^V *4 *1 R gR : / ? ! Q
Visual *2 ^G c C -- : --
Select *5 ^O ^G *6 -- -- --
Insert <Esc> -- -- <Insert> -- --
Replace <Esc> -- -- <Insert> -- --
Command-line *3 -- -- :start -- -
-
Ex :vi -- -- -- -- --
-- not possible
*1 Go from Normal mode to Insert mode by giving the command "i", "I", "a",
"A", "o", "O", "c", "C", "s" or S".
*2 Go from Visual mode to Normal mode by giving a non-movement command, which
causes the command to be executed, or by hitting <Esc> "v", "V" or "CTRL-V"
(see |v_v|), which just stops Visual mode without side effects.
*3 Go from Command-line mode to Normal mode by:
- Hitting <CR> or <NL>, which causes the entered command to be executed.
- Deleting the complete line (e.g., with CTRL-U) and giving a final <BS>.
- Hitting CTRL-C or <Esc>, which quits the command-line without executing
the command.
In the last case <Esc> may be the character defined with the 'wildchar'
option, in which case it will start command-line completion. You can
ignore that and type <Esc> again. {Vi: when hitting <Esc> the command-line
is executed. This is unexpected for most people; therefore it was changed
in Vim. But when the <Esc> is part of a mapping, the command-line is
executed. If you want the Vi behaviour also when typing <Esc>, use ":cmap
^V<Esc> ^V^M"}
*4 Go from Normal to Select mode by:
- use the mouse to select text while 'selectmode' contains "mouse"
- use a non-printable command to move the cursor while keeping the Shift
key pressed, and the 'selectmode' option contains "key"
- use "v", "V" or "CTRL-V" while 'selectmode' contains "cmd"
- use "gh", "gH" or "g CTRL-H" |g_CTRL-H|
*5 Go from Select mode to Normal mode by using a non-printable command to move
the cursor, without keeping the Shift key pressed.
*6 Go from Select mode to Insert mode by typing a printable character. The
selection is deleted and the character is inserted.
If the 'insertmode' option is on, editing a file will start in Insert mode.
*gQ*
gQ Switch to "Ex" mode like with "Q", but really behave
like typing ":" commands after another. All command
line editing, completion etc. is available.
Use the ":vi" command |:visual| to exit "Ex" mode.
{not in Vi}
==============================================================================
7. The window contents *window-contents*
In Normal mode and Insert/Replace mode the screen window will show the current
contents of the buffer: What You See Is What You Get. There are two
exceptions:
- When the 'cpoptions' option contains '$', and the change is within one line,
the text is not directly deleted, but a '$' is put at the last deleted
character.
- When inserting text in one window, other windows on the same text are not
updated until the insert is finished.
{Vi: The screen is not always updated on slow terminals}
Lines longer than the window width will wrap, unless the 'wrap' option is off
(see below). The 'linebreak' option can be set to wrap at a blank character.
If the window has room after the last line of the buffer, Vim will show '~' in
the first column of the last lines in the window, like this:
+-----------------------+
|some line |
|last line |
|~ |
|~ |
+-----------------------+
Thus the '~' lines indicate that the end of the buffer was reached.
If the last line in a window doesn't fit, Vim will indicate this with a '@' in
the first column of the last lines in the window, like this:
+-----------------------+
|first line |
|second line |
|@ |
|@ |
+-----------------------+
Thus the '@' lines indicate that there is a line that doesn't fit in the
window.
When the "lastline" flag is present in the 'display' option, you will not see
'@' characters at the left side of window. If the last line doesn't fit
completely, only the part that fits is shown, and the last three characters of
the last line are replaced with "@@@", like this:
+-----------------------+
|first line |
|second line |
|a very long line that d|
|oesn't fit in the wi@@@|
+-----------------------+
If there is a single line that is too long to fit in the window, this is a
special situation. Vim will show only part of the line, around where the
cursor is. There are no special characters shown, so that you can edit all
parts of this line.
{Vi: gives an "internal error" on lines that do not fit in the window}
The '@' occasion in the 'highlight' option can be used to set special
highlighting for the '@' and '~' characters. This makes it possible to
distinguish them from real characters in the buffer.
The 'showbreak' option contains the string to put in front of wrapped lines.
*wrap-off*
If the 'wrap' option is off, long lines will not wrap. Only the part that
fits on the screen is shown. If the cursor is moved to a part of the line
that is not shown, the screen is scrolled horizontally. The advantage of
this method is that columns are shown as they are and lines that cannot fit
on the screen can be edited. The disadvantage is that you cannot see all the
characters of a line at once. The 'sidescroll' option can be set to the
minimal number of columns to scroll. {Vi: has no 'wrap' option}
All normal ASCII characters are displayed directly on the screen. The <Tab>
is replaced with the number of spaces that it represents. Other non-printing
characters are replaced with "^{char}", where {char} is the non-printing
character with 64 added. Thus character 7 (bell) will be shown as "^G".
Characters between 127 and 160 are replaced with "~{char}", where {char} is
the character with 64 subtracted. These characters occupy more than one
position on the screen. The cursor can only be positioned on the first one.
If you set the 'number' option, all lines will be preceded with their
number. Tip: If you don't like wrapping lines to mix with the line numbers,
set the 'showbreak' option to eight spaces:
":set showbreak=\ \ \ \ \ \ \ \ "
If you set the 'list' option, <Tab> characters will not be shown as several
spaces, but as "^I". A '$' will be placed at the end of the line, so you can
find trailing blanks.
In Command-line mode only the command-line itself is shown correctly. The
display of the buffer contents is updated as soon as you go back to Command
mode.
The last line of the window is used for status and other messages. The
status messages will only be used if an option is on:
status message option default Unix default
current mode 'showmode' on on
command characters 'showcmd' on off
cursor position 'ruler' off off
The current mode is "-- INSERT --" or "-- REPLACE --", see |'showmode'|. The
command characters are those that you typed but were not used yet. {Vi: does
not show the characters you typed or the cursor position}
If you have a slow terminal you can switch off the status messages to speed
up editing:
:set nosc noru nosm
If there is an error, an error message will be shown for at least one second
(in reverse video). {Vi: error messages may be overwritten with other
messages before you have a chance to read them}
Some commands show how many lines were affected. Above which threshold this
happens can be controlled with the 'report' option (default 2).
On the Amiga Vim will run in a CLI window. The name Vim and the full name of
the current file name will be shown in the title bar. When the window is
resized, Vim will automatically redraw the window. You may make the window as
small as you like, but if it gets too small not a single line will fit in it.
Make it at least 40 characters wide to be able to read most messages on the
last line.
On most Unix systems, resizing the window is recognized and handled correctly
by Vim. {Vi: not ok}
==============================================================================
8. Definitions *definitions*
screen The whole area that Vim uses to work in. This can be
a terminal emulator window. Also called "the Vim
window".
window A view on a buffer.
A screen contains one or more windows, separated by status lines and with the
command line at the bottom.
+-------------------------------+
screen | window 1 | window 2 |
| | |
| | |
|= status line =|= status line =|
| window 3 |
| |
| |
|==== status line ==============|
|command line |
+-------------------------------+
The command line is also used for messages. It scrolls up the screen when
there is not enough room in the command line.
A difference is made between four types of lines:
buffer lines The lines in the buffer. This is the same as the
lines as they are read from/written to a file. They
can be thousands of characters long.
logical lines The buffer lines with folding applied. Buffer lines
in a closed fold are changed to a single logical line:
"+-- 99 lines folded". They can be thousands of
characters long.
window lines The lines displayed in a window: A range of logical
lines with wrapping, line breaks, etc. applied. They
*tag* *tags*
A tag is an identifier that appears in a "tags" file. It is a sort of label
that can be jumped to. For example: In C programs each function name can be
used as a tag. The "tags" file has to be generated by a program like ctags,
before the tag commands can be used.
With the ":tag" command the cursor will be positioned on the tag. With the
CTRL-] command, the keyword on which the cursor is standing is used as the
tag. If the cursor is not on a keyword, the first keyword to the right of the
cursor is used.
The ":tag" command works very well for C programs. If you see a call to a
function and wonder what that function does, position the cursor inside of the
function name and hit CTRL-]. This will bring you to the function definition.
An easy way back is with the CTRL-T command. Also read about the tag stack
below.
g<LeftMouse> *g<LeftMouse>*
<C-LeftMouse> *<C-LeftMouse>* *CTRL-]*
CTRL-] Jump to the definition of the keyword under the
cursor. Same as ":tag {ident}", where {ident} is the
keyword under or after cursor.
When there are several matching tags for {ident}, jump
to the [count] one. When no [count] is given the
first one is jumped to. See |tag-matchlist| for
jumping to other matching tags.
*v_CTRL-]*
{Visual}CTRL-] Same as ":tag {ident}", where {ident} is the text that
is highlighted. {not in Vi}
*telnet-CTRL-]*
CTRL-] is the default telnet escape key. When you type CTRL-] to jump to a
tag, you will get the telnet prompt instead. Most versions of telnet allow
changing or disabling the default escape key. See the telnet man page. You
can 'telnet -E {Hostname}' to disable the escape character, or 'telnet -e
{EscapeCharacter} {Hostname}' to specify another escape character. If
possible, try to use "ssh" instead of "telnet" to avoid this problem.
*tag-priority*
When there are multiple matches for a tag, this priority is used:
1. "FSC" A full matching static tag for the current file.
2. "F C" A full matching global tag for the current file.
3. "F " A full matching global tag for another file.
4. "FS " A full matching static tag for another file.
5. " SC" An ignore-case matching static tag for the current file.
6. " C" An ignore-case matching global tag for the current file.
7. " " An ignore-case matching global tag for another file.
8. " S " An ignore-case matching static tag for another file.
Note that when the current file changes, the priority list is mostly not
changed, to avoid confusion when using ":tnext". It is changed when using
":tag {ident}".
The ignore-case matches are not found for a ":tag" command when the
'ignorecase' option is off. They are found when a pattern is used (starting
with a "/") and for ":tselect", also when 'ignorecase' is off. Note that
using ignore-case tag searching disables binary searching in the tags file,
which causes a slowdown. This can be avoided by fold-case sorting the tag
file. See the 'tagbsearch' option for an explanation.
==============================================================================
2. Tag stack *tag-stack* *tagstack* *E425*
On the tag stack is remembered which tags you jumped to, and from where.
Tags are only pushed onto the stack when the 'tagstack' option is set.
g<RightMouse> *g<RightMouse>*
<C-RightMouse> *<C-RightMouse>* *CTRL-T*
CTRL-T Jump to [count] older entry in the tag stack
(default 1). {not in Vi}
*:tags*
:tags Show the contents of the tag stack. The active
entry is marked with a '>'. {not in Vi}
The output of ":tags" looks like this:
# TO tag FROM line in file/text
1 1 main 1 harddisk2:text/vim/test
> 2 2 FuncA 58 i = FuncA(10);
3 1 FuncC 357 harddisk2:text/vim/src/amiga.c
This list shows the tags that you jumped to and the cursor position before
that jump. The older tags are at the top, the newer at the bottom.
The '>' points to the active entry. This is the tag that will be used by the
next ":tag" command. The CTRL-T and ":pop" command will use the position
above the active entry.
Below the "TO" is the number of the current match in the match list. Note
that this doesn't change when using ":pop" or ":tag".
The line number and file name are remembered to be able to get back to where
you were before the tag command. The line number will be correct, also when
deleting/inserting lines, unless this was done by another program (e.g.
another instance of Vim).
For the current file, the "file/text" column shows the text at the position.
An indent is removed and a long line is truncated to fit in the window.
You can jump to previously used tags with several commands. Some examples:
":pop" or CTRL-T to position before previous tag
{count}CTRL-T to position before {count} older tag
":tag" to newer tag
":0tag" to last used tag
The most obvious way to use this is while browsing through the call graph of
a program. Consider the following call graph:
main ---> FuncA ---> FuncC
---> FuncB
(Explanation: main calls FuncA and FuncB; FuncA calls FuncC).
You can get from main to FuncA by using CTRL-] on the call to FuncA. Then
you can CTRL-] to get to FuncC. If you now want to go back to main you can
use CTRL-T twice. Then you can CTRL-] to FuncB.
If you issue a ":ta {ident}" or CTRL-] command, this tag is inserted at the
current position in the stack. If the stack was full (it can hold up to 20
entries), the oldest entry is deleted and the older entries shift one
position up (their index number is decremented by one). If the last used
entry was not at the bottom, the entries below the last used one are
deleted. This means that an old branch in the call graph is lost. After the
commands explained above the tag stack will look like this:
# TO tag FROM line in file/text
1 1 main 1 harddisk2:text/vim/test
2 1 FuncB 59 harddisk2:text/vim/src/main.c
*E73*
When you try to use the tag stack while it doesn't contain anything you will
get an error message.
==============================================================================
3. Tag match list *tag-matchlist* *E427* *E428*
When there are several matching tags, these commands can be used to jump
between them. Note that these commands don't change the tag stack, they keep
the same entry.
*:ts* *:tselect*
:ts[elect][!] [ident] List the tags that match [ident], using the
information in the tags file(s).
When [ident] is not given, the last tag name from the
tag stack is used.
With a '>' in the first column is indicated which is
the current position in the list (if there is one).
[ident] can be a regexp pattern, see |tag-regexp|.
See |tag-priority| for the priorities used in the
listing. {not in Vi}
Example output:
*:sts* *:stselect*
:sts[elect][!] [ident] Does ":tselect[!] [ident]" and splits the window for
the selected tag. {not in Vi}
*g]*
g] Like CTRL-], but use ":tselect" instead of ":tag".
{not in Vi}
*v_g]*
{Visual}g] Same as "g]", but use the highlighted text as the
identifier. {not in Vi}
*:tj* *:tjump*
:tj[ump][!] [ident] Like ":tselect", but jump to the tag directly when
there is only one match. {not in Vi}
*:stj* *:stjump*
:stj[ump][!] [ident] Does ":tjump[!] [ident]" and splits the window for the
selected tag. {not in Vi}
*g_CTRL-]*
g CTRL-] Like CTRL-], but use ":tjump" instead of ":tag".
{not in Vi}
*v_g_CTRL-]*
{Visual}g CTRL-] Same as "g CTRL-]", but use the highlighted text as
the identifier. {not in Vi}
*:tn* *:tnext*
:[count]tn[ext][!] Jump to [count] next matching tag (default 1). See
|tag-!| for [!]. {not in Vi}
*:tp* *:tprevious*
:[count]tp[revious][!] Jump to [count] previous matching tag (default 1).
See |tag-!| for [!]. {not in Vi}
*:tN* *:tNext*
:[count]tN[ext][!] Same as ":tprevious". {not in Vi}
*:tr* *:trewind*
:[count]tr[ewind][!] Jump to first matching tag. If [count] is given, jump
to [count]th matching tag. See |tag-!| for [!]. {not
in Vi}
*:tf* *:tfirst*
:[count]tf[irst][!] Same as ":trewind". {not in Vi}
*:tl* *:tlast*
:tl[ast][!] Jump to last matching tag. See |tag-!| for [!]. {not
in Vi}
*:lt* *:ltag*
:lt[ag][!] [ident] Jump to tag [ident] and add the matching tags to a new
location list for the current window. [ident] can be
a regexp pattern, see |tag-regexp|. When [ident] is
not given, the last tag name from the tag stack is
*tag-skip-file*
When a matching tag is found for which the file doesn't exist, this match is
skipped and the next matching tag is used. Vim reports this, to notify you of
missing files. When the end of the list of matches has been reached, an error
message is given.
*tag-preview*
The tag match list can also be used in the preview window. The commands are
the same as above, with a "p" prepended.
{not available when compiled without the |+quickfix| feature}
*:pts* *:ptselect*
:pts[elect][!] [ident] Does ":tselect[!] [ident]" and shows the new tag in a
"Preview" window. See |:ptag| for more info.
{not in Vi}
*:ptj* *:ptjump*
:ptj[ump][!] [ident] Does ":tjump[!] [ident]" and shows the new tag in a
"Preview" window. See |:ptag| for more info.
{not in Vi}
*:ptn* *:ptnext*
:[count]ptn[ext][!] ":tnext" in the preview window. See |:ptag|.
{not in Vi}
*:ptp* *:ptprevious*
:[count]ptp[revious][!] ":tprevious" in the preview window. See |:ptag|.
{not in Vi}
*:ptN* *:ptNext*
:[count]ptN[ext][!] Same as ":ptprevious". {not in Vi}
*:ptr* *:ptrewind*
:[count]ptr[ewind][!] ":trewind" in the preview window. See |:ptag|.
{not in Vi}
*:ptf* *:ptfirst*
:[count]ptf[irst][!] Same as ":ptrewind". {not in Vi}
*:ptl* *:ptlast*
:ptl[ast][!] ":tlast" in the preview window. See |:ptag|.
{not in Vi}
==============================================================================
4. Tags details *tag-details*
*static-tag*
A static tag is a tag that is defined for a specific file. In a C program
this could be a static function.
In Vi jumping to a tag sets the current search pattern. This means that
the "n" command after jumping to a tag does not search for the same pattern
that it did before jumping to the tag. Vim does not do this as we consider it
to be a bug. You can still find the tag search pattern in the search history.
If you really want the old Vi behavior, set the 't' flag in 'cpoptions'.
*tag-binary-search*
Vim uses binary searching in the tags file to find the desired tag quickly
(when enabled at compile time |+tag_binary|). But this only works if the
tags file was sorted on ASCII byte value. Therefore, if no match was found,
another try is done with a linear search. If you only want the linear search,
reset the 'tagbsearch' option. Or better: Sort the tags file!
Note that the binary searching is disabled when not looking for a tag with a
specific name. This happens when ignoring case and when a regular expression
is used that doesn't start with a fixed string. Tag searching can be a lot
slower then. The former can be avoided by case-fold sorting the tags file.
See 'tagbsearch' for details.
*tag-regexp*
The ":tag" and "tselect" commands accept a regular expression argument. See
|pattern| for the special characters that can be used.
When the argument starts with '/', it is used as a pattern. If the argument
does not start with '/', it is taken literally, as a full tag name.
Examples:
:tag main
jumps to the tag "main" that has the highest priority.
:tag /^get
jumps to the tag that starts with "get" and has the highest priority.
:tag /norm
lists all the tags that contain "norm", including "id_norm".
When the argument both exists literally, and match when used as a regexp, a
literal match has a higher priority. For example, ":tag /open" matches "open"
before "open_file" and "file_open".
When using a pattern case is ignored. If you want to match case use "\C" in
the pattern.
*tag-!*
If the tag is in the current file this will always work. Otherwise the
performed actions depend on whether the current file was changed, whether a !
is added to the command and on the 'autowrite' option:
tag in file autowrite
current file changed ! option action
-----------------------------------------------------------------------------
yes x x x goto tag
no no x x read other file, goto tag
no yes yes x abandon current file, read other file, goto
tag
no yes no on write current file, read other file, goto
tag
no yes no off fail
-----------------------------------------------------------------------------
- If the tag is in the current file, the command will always work.
- If the tag is in another file and the current file was not changed, the
other file will be made the current file and read into the buffer.
- If the tag is in another file, the current file was changed and a ! is
added to the command, the changes to the current file are lost, the other
file will be made the current file and read into the buffer.
- If the tag is in another file, the current file was changed and the
'autowrite' option is on, the current file will be written, the other
file will be made the current file and read into the buffer.
- If the tag is in another file, the current file was changed and the
'autowrite' option is off, the command will fail. If you want to save
the changes, use the ":w" command and then use ":tag" without an argument.
This works because the tag is put on the stack anyway. If you want to lose
the changes you can use the ":tag!" command.
*tag-security*
Note that Vim forbids some commands, for security reasons. This works like
using the 'secure' option for exrc/vimrc files in the current directory. See
|trojan-horse| and |sandbox|.
When the {tagaddress} changes a buffer, you will get a warning message:
"WARNING: tag command changed a buffer!!!"
In a future version changing the buffer will be impossible. All this for
security reasons: Somebody might hide a nasty command in the tags file, which
would otherwise go unnoticed. Example:
:$d|/tag-function-name/
{this security prevention is not present in Vi}
In Vi the ":tag" command sets the last search pattern when the tag is searched
for. In Vim this is not done, the previous search pattern is still remembered,
unless the 't' flag is present in 'cpoptions'. The search pattern is always
put in the search history, so you can modify it if searching fails.
*tags-option*
The 'tags' option is a list of file names. Each of these files is searched
for the tag. This can be used to use a different tags file than the default
file "tags". It can also be used to access a common tags file.
The next file in the list is not used when:
- A matching static tag for the current buffer has been found.
- A matching global tag has been found.
This also depends on the 'ignorecase' option. If it is off, and the tags file
only has a match without matching case, the next tags file is searched for a
match with matching case. If no tag with matching case is found, the first
match without matching case is used. If 'ignorecase' is on, and a matching
global tag with or without matching case is found, this one is used, no
further tags files are searched.
When a tag file name starts with "./", the '.' is replaced with the path of
the current file. This makes it possible to use a tags file in the directory
where the current file is (no matter what the current directory is). The idea
of using "./" is that you can define which tag file is searched first: In the
current directory ("tags,./tags") or in the directory of the current file
("./tags,tags").
For example:
:set tags=./tags,tags,/home/user/commontags
In this example the tag will first be searched for in the file "tags" in the
directory where the current file is. Next the "tags" file in the current
directory. If it is not found there, then the file "/home/user/commontags"
will be searched for the tag.
This can be switched off by including the 'd' flag in 'cpoptions', to make
it Vi compatible. "./tags" will then be the tags file in the current
directory, instead of the tags file in the directory where the current file
is.
Instead of the comma a space may be used. Then a backslash is required for
the space to be included in the string option:
:set tags=tags\ /home/user/commontags
To include a space in a file name use three backslashes. To include a comma
in a file name use two backslashes. For example, use:
:set tags=tag\\\ file,/home/user/common\\,tags
for the files "tag file" and "/home/user/common,tags". The 'tags' option will
have the value "tag\ file,/home/user/common\,tags".
If the 'tagrelative' option is on (which is the default) and using a tag file
in another directory, file names in that tag file are relative to the
directory where the tag file is.
==============================================================================
5. Tags file format *tags-file-format* *E431*
*ctags* *jtags*
A tags file can be created with an external command, for example "ctags". It
will contain a tag for each function. Some versions of "ctags" will also make
The lines in the tags file must have one of these three formats:
1. {tagname} {TAB} {tagfile} {TAB} {tagaddress}
2. {tagfile}:{tagname} {TAB} {tagfile} {TAB} {tagaddress}
3. {tagname} {TAB} {tagfile} {TAB} {tagaddress} {term} {field} ..
The first is a normal tag, which is completely compatible with Vi. It is the
only format produced by traditional ctags implementations. This is often used
for functions that are global, also referenced in other files.
The lines in the tags file can end in <LF> or <CR><LF>. On the Macintosh <CR>
also works. The <CR> and <NL> characters can never appear inside a line.
*tag-old-static*
The second format is for a static tag only. It is obsolete now, replaced by
the third format. It is only supported by Elvis 1.x and Vim and a few
versions of ctags. A static tag is often used for functions that are local,
only referenced in the file {tagfile}. Note that for the static tag, the two
occurrences of {tagfile} must be exactly the same. Also see |tags-option|
below, for how static tags are used.
The third format is new. It includes additional information in optional
fields at the end of each line. It is backwards compatible with Vi. It is
only supported by new versions of ctags (such as Exuberant ctags).
{tagname} The identifier. Normally the name of a function, but it can
be any identifier. It cannot contain a <Tab>.
{TAB} One <Tab> character. Note: previous versions allowed any
white space here. This has been abandoned to allow spaces in
{tagfile}. It can be re-enabled by including the
|+tag_any_white| feature at compile time. *tag-any-white*
{tagfile} The file that contains the definition of {tagname}. It can
have an absolute or relative path. It may contain environment
variables and wildcards (although the use of wildcards is
doubtful). It cannot contain a <Tab>.
{tagaddress} The Ex command that positions the cursor on the tag. It can
be any Ex command, although restrictions apply (see
|tag-security|). Posix only allows line numbers and search
commands, which are mostly used.
{term} ;" The two characters semicolon and double quote. This is
interpreted by Vi as the start of a comment, which makes the
following be ignored. This is for backwards compatibility
with Vi, it ignores the following fields.
{field} .. A list of optional fields. Each field has the form:
<Tab>{fieldname}:{value}
The {fieldname} identifies the field, and can only contain
alphabetical characters [a-zA-Z].
The {value} is any string, but cannot contain a <Tab>.
These characters are special:
"\t" stands for a <Tab>
"\r" stands for a <CR>
"\n" stands for a <NL>
"\\" stands for a single '\' character
There is one field that doesn't have a ':'. This is the kind
*tag-search*
The command can be any Ex command, but often it is a search command.
Examples:
tag1 file1 /^main(argc, argv)/
tag2 file2 108
The command is always executed with 'magic' not set. The only special
characters in a search pattern are "^" (begin-of-line) and "$" (<EOL>).
See |pattern|. Note that you must put a backslash before each backslash in
the search text. This is for backwards compatibility with Vi.
*E434* *E435*
If the command is a normal search command (it starts and ends with "/" or
"?"), some special handling is done:
- Searching starts on line 1 of the file.
The direction of the search is forward for "/", backward for "?".
Note that 'wrapscan' does not matter, the whole file is always searched. (Vi
does use 'wrapscan', which caused tags sometimes not be found.) {Vi starts
searching in line 2 of another file. It does not find a tag in line 1 of
another file when 'wrapscan' is not set}
- If the search fails, another try is done ignoring case. If that fails too,
a search is done for:
"^tagname[ \t]*("
(the tag with '^' prepended and "[ \t]*(" appended). When using function
names, this will find the function name when it is in column 0. This will
help when the arguments to the function have changed since the tags file was
made. If this search also fails another search is done with:
"^[#a-zA-Z_].*\<tagname[ \t]*("
This means: A line starting with '#' or an identifier and containing the tag
followed by white space and a '('. This will find macro names and function
names with a type prepended. {the extra searches are not in Vi}
==============================================================================
6. Include file searches *include-search* *definition-search*
*E387* *E388* *E389*
These commands look for a string in the current file and in all encountered
included files (recursively). This can be used to find the definition of a
variable, function or macro. If you only want to search in the current
buffer, use the commands listed at |pattern-searches|.
These commands are not available when the |+find_in_path| feature was disabled
at compile time.
When a line is encountered that includes another file, that file is searched
before continuing in the current buffer. Files included by included files are
also searched. When an include file could not be found it is silently
ignored. Use the |:checkpath| command to discover which files could not be
found, possibly your 'path' option is not set up correctly. Note: the
included file is searched, not a buffer that may be editing that file. Only
for the current file the lines in the buffer are used.
The string can be any keyword or a defined macro. For the keyword any match
will be found. For defined macros only lines that match with the 'define'
option will be found. The default is "^#\s*define", which is for C programs.
For other languages you probably want to change this. See 'define' for an
example for C++. The string cannot contain an end-of-line, only matches
within a line are found.
When a match is found for a defined macro, the displaying of lines continues
with the next line when a line ends in a backslash.
The commands that start with "[" start searching from the start of the current
file. The commands that start with "]" start at the current cursor position.
The 'include' option is used to define a line that includes another file. The
default is "\^#\s*include", which is for C programs. Note: Vim does not
recognize C syntax, if the 'include' option matches a line inside
"#ifdef/#endif" or inside a comment, it is searched anyway. The 'isfname'
option is used to recognize the file name that comes after the matched
pattern.
The 'path' option is used to find the directory for the include files that
do not have an absolute path.
The 'comments' option is used for the commands that display a single line or
jump to a line. It defines patterns that may start a comment. Those lines
are ignored for the search, unless [!] is used. One exception: When the line
matches the pattern "^# *define" it is not considered to be a comment.
If you want to list matches, and then select one to jump to, you could use a
mapping to do that for you. Here is an example:
:map <F4> [I:let nr = input("Which one: ")<Bar>exe "normal " . nr ."[\t"<CR>
*[i*
[i Display the first line that contains the keyword
under the cursor. The search starts at the beginning
of the file. Lines that look like a comment are
ignored (see 'comments' option). If a count is given,
the count'th matching line is displayed, and comment
lines are not ignored. {not in Vi}
*]i*
]i like "[i", but start at the current cursor position.
{not in Vi}
*:is* *:isearch*
:[range]is[earch][!] [count] [/]pattern[/]
Like "[i" and "]i", but search in [range] lines
(default: whole file).
See |:search-args| for [/] and [!]. {not in Vi}
*[I*
[I Display all lines that contain the keyword under the
cursor. Filenames and line numbers are displayed
for the found lines. The search starts at the
beginning of the file. {not in Vi}
*]I*
]I like "[I", but start at the current cursor position.
{not in Vi}
*:il* *:ilist*
:[range]il[ist][!] [/]pattern[/]
Like "[I" and "]I", but search in [range] lines
(default: whole file).
See |:search-args| for [/] and [!]. {not in Vi}
*[_CTRL-I*
[ CTRL-I Jump to the first line that contains the keyword
under the cursor. The search starts at the beginning
of the file. Lines that look like a comment are
*]_CTRL-I*
] CTRL-I like "[ CTRL-I", but start at the current cursor
position. {not in Vi}
*:ij* *:ijump*
:[range]ij[ump][!] [count] [/]pattern[/]
Like "[ CTRL-I" and "] CTRL-I", but search in
[range] lines (default: whole file).
See |:search-args| for [/] and [!]. {not in Vi}
*:isp* *:isplit*
:[range]isp[lit][!] [count] [/]pattern[/]
Like "CTRL-W i" and "CTRL-W i", but search in
[range] lines (default: whole file).
See |:search-args| for [/] and [!]. {not in Vi}
*[d*
[d Display the first macro definition that contains the
macro under the cursor. The search starts from the
beginning of the file. If a count is given, the
count'th matching line is displayed. {not in Vi}
*]d*
]d like "[d", but start at the current cursor position.
{not in Vi}
*:ds* *:dsearch*
:[range]ds[earch][!] [count] [/]string[/]
Like "[d" and "]d", but search in [range] lines
(default: whole file).
See |:search-args| for [/] and [!]. {not in Vi}
*[D*
[D Display all macro definitions that contain the macro
under the cursor. Filenames and line numbers are
displayed for the found lines. The search starts
from the beginning of the file. {not in Vi}
*]D*
]D like "[D", but start at the current cursor position.
{not in Vi}
*:dli* *:dlist*
:[range]dl[ist][!] [/]string[/]
Like "[D" and "]D", but search in [range] lines
(default: whole file).
See |:search-args| for [/] and [!]. {not in Vi}
Note that ":dl" works like ":delete" with the "l"
flag.
*[_CTRL-D*
[ CTRL-D Jump to the first macro definition that contains the
keyword under the cursor. The search starts from
the beginning of the file. If a count is given, the
count'th matching line is jumped to. {not in Vi}
*]_CTRL-D*
] CTRL-D like "[ CTRL-D", but start at the current cursor
position. {not in Vi}
*:dj* *:djump*
:[range]dj[ump][!] [count] [/]string[/]
Like "[ CTRL-D" and "] CTRL-D", but search in
[range] lines (default: whole file).
See |:search-args| for [/] and [!]. {not in Vi}
*:dsp* *:dsplit*
:[range]dsp[lit][!] [count] [/]string[/]
Like "CTRL-W d", but search in [range] lines
(default: whole file).
See |:search-args| for [/] and [!]. {not in Vi}
*:che* *:checkpath*
:che[ckpath] List all the included files that could not be found.
{not in Vi}
:che[ckpath]! List all the included files. {not in Vi}
*:search-args*
Common arguments for the commands above:
[!] When included, find matches in lines that are recognized as comments.
When excluded, a match is ignored when the line is recognized as a
comment (according to 'comments'), or the match is in a C comment (after
"//" or inside /* */). Note that a match may be missed if a line is
recognized as a comment, but the comment ends halfway the line.
And if the line is a comment, but it is not recognized (according to
'comments') a match may be found in it anyway. Example:
/* comment
foobar */
A match for "foobar" is found, because this line is not recognized as a
comment (even though syntax highlighting does recognize it).
Note: Since a macro definition mostly doesn't look like a comment, the
[!] makes no difference for ":dlist", ":dsearch" and ":djump".
[/] A pattern can be surrounded by '/'. Without '/' only whole words are
matched, using the pattern "\<pattern\>". Only after the second '/' a
next command can be appended with '|'. Example:
:isearch /string/ | echo "the last one"
For a ":djump", ":dsplit", ":dlist" and ":dsearch" command the pattern
is used as a literal string, not as a search pattern.
top - main help file
This file describes commands that delete or change text. In this context,
changing text means deleting the text and replacing it with other text using
one command. You can undo all of these commands. You can repeat the non-Ex
commands with the "." command.
1. Deleting text |deleting|
2. Delete and insert |delete-insert|
3. Simple changes |simple-change| *changing*
4. Complex changes |complex-change|
4.1 Filter commands |filter|
4.2 Substitute |:substitute|
4.3 Search and replace |search-replace|
4.4 Changing tabs |change-tabs|
5. Copying and moving text |copy-move|
6. Formatting text |formatting|
7. Sorting text |sorting|
For inserting text see |insert.txt|.
==============================================================================
1. Deleting text *deleting* *E470*
*X* *dh*
["x]X Delete [count] characters before the cursor [into
register x] (not |linewise|). Does the same as "dh".
Also see |'whichwrap'|.
*d*
["x]d{motion} Delete text that {motion} moves over [into register
x]. See below for exceptions.
*dd*
["x]dd Delete [count] lines [into register x] |linewise|.
*D*
["x]D Delete the characters under the cursor until the end
of the line and [count]-1 more lines [into register
x]; synonym for "d$".
(not |linewise|)
When the '#' flag is in 'cpoptions' the count is
ignored.
*J*
J Join [count] lines, with a minimum of two lines.
Remove the indent and insert up to two spaces (see
below).
*v_J*
{Visual}J Join the highlighted lines, with a minimum of two
lines. Remove the indent and insert up to two spaces
(see below). {not in Vi}
*gJ*
gJ Join [count] lines, with a minimum of two lines.
Don't insert or remove any spaces. {not in Vi}
*v_gJ*
{Visual}gJ Join the highlighted lines, with a minimum of two
lines. Don't insert or remove any spaces. {not in
Vi}
*:j* *:join*
:[range]j[oin][!] [flags]
Join [range] lines. Same as "J", except with [!]
the join does not insert or delete any spaces.
If a [range] has equal start and end values, this
command does nothing. The default behavior is to
join the current line with the line below it.
{not in Vi: !}
See |ex-flags| for [flags].
:[range]j[oin][!] {count} [flags]
Join {count} lines, starting with [range] (default:
current line |cmdline-ranges|). Same as "J", except
==============================================================================
2. Delete and insert *delete-insert* *replacing*
*R*
R Enter Replace mode: Each character you type replaces
an existing character, starting with the character
under the cursor. Repeat the entered text [count]-1
times. See |Replace-mode| for more details.
*gR*
gR Enter Virtual Replace mode: Each character you type
replaces existing characters in screen space. So a
<Tab> may replace several characters at once.
Repeat the entered text [count]-1 times. See
|Virtual-Replace-mode| for more details.
{not available when compiled without the |+vreplace|
feature}
*c*
["x]c{motion} Delete {motion} text [into register x] and start
insert. When 'cpoptions' includes the 'E' flag and
there is no text to delete (e.g., with "cTx" when the
cursor is just after an 'x'), an error occurs and
insert mode does not start (this is Vi compatible).
When 'cpoptions' does not include the 'E' flag, the
"c" command always starts insert mode, even if there
is no text to delete.
*cc*
["x]cc Delete [count] lines [into register x] and start
insert |linewise|. If 'autoindent' is on, preserve
the indent of the first line.
*C*
["x]C Delete from the cursor position to the end of the
line and [count]-1 more lines [into register x], and
start insert. Synonym for c$ (not |linewise|).
*s*
["x]s Delete [count] characters [into register x] and start
insert (s stands for Substitute). Synonym for "cl"
(not |linewise|).
*S*
["x]S Delete [count] lines [into register x] and start
insert. Synonym for "cc" |linewise|.
*v_r*
{Visual}["x]r{char} Replace all selected characters by {char}.
*v_C*
{Visual}["x]C Delete the highlighted lines [into register x] and
start insert. In Visual block mode it works
differently |v_b_C|. {not in Vi}
*v_S*
{Visual}["x]S Delete the highlighted lines [into register x] and
start insert (for {Visual} see |Visual-mode|). {not
in Vi}
*v_R*
{Visual}["x]R Currently just like {Visual}["x]S. In a next version
it might work differently. {not in Vi}
Notes:
- You can end Insert and Replace mode with <Esc>.
- See the section "Insert and Replace mode" |mode-ins-repl| for the other
special characters in these modes.
- The effect of [count] takes place after Vim exits Insert or Replace mode.
- When the 'cpoptions' option contains '$' and the change is within one line,
Vim continues to show the text to be deleted and puts a '$' at the last
deleted character.
See |registers| for an explanation of registers.
Replace mode is just like Insert mode, except that every character you enter
deletes one character. If you reach the end of a line, Vim appends any
further characters (just like Insert mode). In Replace mode, the backspace
key restores the original text (if there was any). (See section "Insert and
Replace mode" |mode-ins-repl|).
*cw* *cW*
Special case: When the cursor is in a word, "cw" and "cW" do not include the
white space after a word, they only change up to the end of the word. This is
because Vim interprets "cw" as change-word, and a word does not include the
following white space.
{Vi: "cw" when on a blank followed by other blanks changes only the first
blank; this is probably a bug, because "dw" deletes all the blanks; use the
'w' flag in 'cpoptions' to make it work like Vi anyway}
If you prefer "cw" to include the space after a word, use this mapping:
:map cw dwi
Or use "caw" (see |aw|).
*r*
r{char} Replace the character under the cursor with {char}.
If {char} is a <CR> or <NL>, a line break replaces the
character. To replace with a real <CR>, use CTRL-V
<CR>. CTRL-V <NL> replaces with a <Nul>.
{Vi: CTRL-V <CR> still replaces with a line break,
cannot replace something with a <CR>}
If you give a [count], Vim replaces [count] characters
with [count] {char}s. When {char} is a <CR> or <NL>,
however, Vim inserts only one <CR>: "5r<CR>" replaces
five characters with a single line break.
When {char} is a <CR> or <NL>, Vim performs
autoindenting. This works just like deleting the
characters that are replaced and then doing
"i<CR><Esc>".
{char} can be entered as a digraph |digraph-arg|.
*gr*
gr{char} Replace the virtual characters under the cursor with
{char}. This replaces in screen space, not file
space. See |gR| and |Virtual-Replace-mode| for more
details. As with |r| a count may be given.
{char} can be entered like with |r|.
{not available when compiled without the |+vreplace|
feature}
*digraph-arg*
The argument for Normal mode commands like |r| and |t| is a single character.
When 'cpo' doesn't contain the 'D' flag, this character can also be entered
like |digraphs|. First type CTRL-K and then the two digraph characters.
{not available when compiled without the |+digraphs| feature}
*case*
The following commands change the case of letters. The currently active
|locale| is used. See |:language|. The LC_CTYPE value matters here.
*~*
~ 'notildeop' option: Switch case of the character
under the cursor and move the cursor to the right.
If a [count] is given, do that many characters. {Vi:
no count}
~{motion} 'tildeop' option: switch case of {motion} text. {Vi:
tilde cannot be used as an operator}
*g~*
g~{motion} Switch case of {motion} text. {not in Vi}
*v_~*
{Visual}~ Switch case of highlighted text (for {Visual} see
|Visual-mode|). {not in Vi}
*v_U*
{Visual}U Make highlighted text uppercase (for {Visual} see
|Visual-mode|). {not in Vi}
*gU* *uppercase*
gU{motion} Make {motion} text uppercase. {not in Vi}
Example:
:map! <C-F> <Esc>gUiw`]a
This works in Insert mode: press CTRL-F to make the
word before the cursor uppercase. Handy to type
words in lowercase and then make them uppercase.
*v_u*
{Visual}u Make highlighted text lowercase (for {Visual} see
|Visual-mode|). {not in Vi}
*gu* *lowercase*
gu{motion} Make {motion} text lowercase. {not in Vi}
*g?* *rot13*
g?{motion} Rot13 encode {motion} text. {not in Vi}
*v_g?*
{Visual}g? Rot13 encode the highlighted text (for {Visual} see
|Visual-mode|). {not in Vi}
*CTRL-X*
CTRL-X Subtract [count] from the number or alphabetic
character at or after the cursor. {not in Vi}
The CTRL-A and CTRL-X commands work for (signed) decimal numbers, unsigned
octal and hexadecimal numbers and alphabetic characters. This depends on the
'nrformats' option.
- When 'nrformats' includes "octal", Vim considers numbers starting with a '0'
to be octal, unless the number includes a '8' or '9'. Other numbers are
decimal and may have a preceding minus sign.
If the cursor is on a number, the commands apply to that number; otherwise
Vim uses the number to the right of the cursor.
- When 'nrformats' includes "hex", Vim assumes numbers starting with '0x' or
'0X' are hexadecimal. The case of the rightmost letter in the number
determines the case of the resulting hexadecimal number. If there is no
letter in the current number, Vim uses the previously detected case.
- When 'nrformats' includes "alpha", Vim will change the alphabetic character
under or after the cursor. This is useful to make lists with an alphabetic
index.
For numbers with leading zeros (including all octal and hexadecimal numbers),
Vim preserves the number of characters in the number when possible. CTRL-A on
"0077" results in "0100", CTRL-X on "0x100" results in "0x0ff".
There is one exception: When a number that starts with a zero is found not to
be octal (it contains a '8' or '9'), but 'nrformats' does include "octal",
leading zeros are removed to avoid that the result may be recognized as an
octal number.
Note that when 'nrformats' includes "octal", decimal numbers with leading
zeros cause mistakes, because they can be confused with octal numbers.
The CTRL-A command is very useful in a macro. Example: Use the following
steps to make a numbered list.
1. Create the first list entry, make sure it starts with a number.
2. qa - start recording into register 'a'
3. Y - yank the entry
4. p - put a copy of the entry below the first one
5. CTRL-A - increment the number
6. q - stop recording
7. <count>@a - repeat the yank, put and increment <count> times
*<*
<{motion} Shift {motion} lines one 'shiftwidth' leftwards.
*<<*
*v_<*
{Visual}[count]< Shift the highlighted lines [count] 'shiftwidth'
leftwards (for {Visual} see |Visual-mode|). {not in
Vi}
*>*
>{motion} Shift {motion} lines one 'shiftwidth' rightwards.
*>>*
>> Shift [count] lines one 'shiftwidth' rightwards.
*v_>*
{Visual}[count]> Shift the highlighted lines [count] 'shiftwidth'
rightwards (for {Visual} see |Visual-mode|). {not in
Vi}
*:<*
:[range]< Shift [range] lines one 'shiftwidth' left. Repeat '<'
for shifting multiple 'shiftwidth's.
:[range]< {count} Shift {count} lines one 'shiftwidth' left, starting
with [range] (default current line |cmdline-ranges|).
Repeat '<' for shifting multiple 'shiftwidth's.
:[range]le[ft] [indent] left align lines in [range]. Sets the indent in the
lines to [indent] (default 0). {not in Vi}
*:>*
:[range]> [flags] Shift {count} [range] lines one 'shiftwidth' right.
Repeat '>' for shifting multiple 'shiftwidth's.
See |ex-flags| for [flags].
:[range]> {count} [flags]
Shift {count} lines one 'shiftwidth' right, starting
with [range] (default current line |cmdline-ranges|).
Repeat '>' for shifting multiple 'shiftwidth's.
See |ex-flags| for [flags].
The ">" and "<" commands are handy for changing the indentation within
programs. Use the 'shiftwidth' option to set the size of the white space
which these commands insert or delete. Normally the 'shiftwidth' option is 8,
but you can set it to, say, 3 to make smaller indents. The shift leftwards
stops when there is no indent. The shift right does not affect empty lines.
If the 'shiftround' option is on, the indent is rounded to a multiple of
'shiftwidth'.
If the 'smartindent' option is on, or 'cindent' is on and 'cinkeys' contains
'#', shift right does not affect lines starting with '#' (these are supposed
to be C preprocessor lines that must stay in column 1).
When the 'expandtab' option is off (this is the default) Vim uses <Tab>s as
much as possible to make the indent. You can use ">><<" to replace an indent
made out of spaces with the same indent made out of <Tab>s (and a few spaces
if necessary). If the 'expandtab' option is on, Vim uses only spaces. Then
you can use ">><<" to replace <Tab>s in the indent by spaces (or use
":retab!").
To move a line several 'shiftwidth's, use Visual mode or the ":" commands.
For example:
Vjj4> move three lines 4 indents to the right
:<<< move current line 3 indents to the left
:>> 5 move 5 lines 2 indents to the right
:5>> move line 5 2 indents to the right
==============================================================================
4. Complex changes *complex-change*
*!*
!{motion}{filter} Filter {motion} text lines through the external
program {filter}.
*!!*
!!{filter} Filter [count] lines through the external program
{filter}.
*v_!*
{Visual}!{filter} Filter the highlighted lines through the external
program {filter} (for {Visual} see |Visual-mode|).
{not in Vi}
*=*
={motion} Filter {motion} lines through the external program
given with the 'equalprg' option. When the 'equalprg'
option is empty (this is the default), use the
internal formatting function |C-indenting|. But when
'indentexpr' is not empty, it will be used instead
|indent-expression|. When Vim was compiled without
internal formatting then the "indent" program is used
as a last resort.
*==*
== Filter [count] lines like with ={motion}.
*v_=*
{Visual}= Filter the highlighted lines like with ={motion}.
{not in Vi}
*tempfile* *setuid*
Vim uses temporary files for filtering, generating diffs and also for
tempname(). For Unix, the file will be in a private directory (only
accessible by the current user) to avoid security problems (e.g., a symlink
attack or other people reading your file). When Vim exits the directory and
all files in it are deleted. When Vim has the setuid bit set this may cause
problems, the temp file is owned by the setuid user but the filter command
probably runs as the original user.
On MS-DOS and OS/2 the first of these directories that works is used: $TMP,
$TEMP, c:\TMP, c:\TEMP.
For Unix the list of directories is: $TMPDIR, /tmp, current-dir, $HOME.
For MS-Windows the GetTempFileName() system function is used.
For other systems the tmpnam() library function is used.
*&*
& Synonym for ":s" (repeat last substitute). Note
that the flags are not remembered, thus it might
actually work differently. You can use ":&&" to keep
the flags.
*g&*
g& Synonym for ":%s//~/&" (repeat last substitute on all
lines with the same flags).
Mnemonic: global substitute. {not in Vi}
*:snomagic* *:sno*
:[range]sno[magic] ... Same as ":substitute", but always use 'nomagic'.
{not in Vi}
*:smagic* *:sm*
:[range]sm[agic] ... Same as ":substitute", but always use 'magic'.
{not in Vi}
*:s_flags*
The flags that you can use for the substitute commands:
[&] Must be the first one: Keep the flags from the previous substitute
command. Examples:
:&&
:s/this/that/&
Note that ":s" and ":&" don't keep the flags.
{not in Vi}
[c] Confirm each substitution. Vim highlights the matching string (with
|hl-IncSearch|). You can type: *:s_c*
'y' to substitute this match
'l' to substitute this match and then quit ("last")
'n' to skip this match
<Esc> to quit substituting
'a' to substitute this and all remaining matches {not in Vi}
*sub-replace-special* *:s\=*
When the {string} starts with "\=" it is evaluated as an expression, see
|sub-replace-expression|. You can use that for any special characters.
Otherwise these characters in {string} have a special meaning:
*:s%*
When {string} is equal to "%" and '/' is included with the 'cpoptions' option,
then the {string} of the previous substitute command is used. |cpo-/|
magic nomagic action
& \& replaced with the whole matched pattern *s/\&*
\& & replaced with &
\0 replaced with the whole matched pattern *\0* *s/\0*
\1 replaced with the matched pattern in the first
pair of () *s/\1*
\2 replaced with the matched pattern in the second
pair of () *s/\2*
.. .. *s/\3*
\9 replaced with the matched pattern in the ninth
pair of () *s/\9*
~ \~ replaced with the {string} of the previous
substitute *s~*
\~ ~ replaced with ~ *s/\~*
\u next character made uppercase *s/\u*
\U following characters made uppercase, until \E *s/\U*
\l next character made lowercase *s/\l*
\L following characters made lowercase, until \E *s/\L*
\e end of \u, \U, \l and \L (NOTE: not <Esc>!) *s/\e*
\E end of \u, \U, \l and \L *s/\E*
<CR> split line in two at this point
(Type the <CR> as CTRL-V <Enter>) *s<CR>*
\r idem *s/\r*
\<CR> insert a carriage-return (CTRL-M)
(Type the <CR> as CTRL-V <Enter>) *s/\<CR>*
\n insert a <NL> (<NUL> in the file)
(does NOT break the line) *s/\n*
\b insert a <BS> *s/\b*
\t insert a <Tab> *s/\t*
\\ insert a single backslash *s/\\*
\x where x is any character not mentioned above:
*:pro* *:promptfind*
:promptf[ind] [string]
Put up a Search dialog. When [string] is given, it is
used as the initial search string.
{only for Win32, Motif and GTK GUI}
*:promptr* *:promptrepl*
:promptr[epl] [string]
Put up a Search/Replace dialog. When [string] is
given, it is used as the initial search string.
{only for Win32, Motif and GTK GUI}
*retab-example*
Example for using autocommands and ":retab" to edit a file which is stored
with tabstops at 8 but edited with tabstops set at 4. Warning: white space
inside of strings can change! Also see 'softtabstop' option.
:auto BufReadPost *.xx retab! 4
:auto BufWritePre *.xx retab! 8
:auto BufWritePost *.xx retab! 4
:auto BufNewFile *.xx set ts=4
==============================================================================
5. Copying and moving text *copy-move*
*quote*
"{a-zA-Z0-9.%#:-"} Use register {a-zA-Z0-9.%#:-"} for next delete, yank
or put (use uppercase character to append with
delete and yank) ({.%#:} only work with put).
*:reg* *:registers*
:reg[isters] Display the contents of all numbered and named
registers. If a register is written to for |:redir|
it will not be listed.
{not in Vi}
*:di* *:display*
:di[splay] [arg] Same as :registers. {not in Vi}
*y* *yank*
["x]y{motion} Yank {motion} text [into register x]. When no
characters are to be yanked (e.g., "y0" in column 1),
this is an error when 'cpoptions' includes the 'E'
flag.
*yy*
["x]yy Yank [count] lines [into register x] |linewise|.
*Y*
["x]Y yank [count] lines [into register x] (synonym for
yy, |linewise|). If you like "Y" to work from the
cursor to the end of line (which is more logical,
but not Vi-compatible) use ":map Y y$".
*v_y*
{Visual}["x]y Yank the highlighted text [into register x] (for
{Visual} see |Visual-mode|). {not in Vi}
*v_Y*
{Visual}["x]Y Yank the highlighted lines [into register x] (for
{Visual} see |Visual-mode|). {not in Vi}
*:y* *:yank*
:[range]y[ank] [x] Yank [range] lines [into register x].
:[range]y[ank] [x] {count}
Yank {count} lines, starting with last line number
in [range] (default: current line |cmdline-ranges|),
[into register x].
*P*
["x]P Put the text [from register x] before the cursor
[count] times. {Vi: no count}
*<MiddleMouse>*
["x]<MiddleMouse> Put the text from a register before the cursor [count]
times. Uses the "* register, unless another is
specified.
Leaves the cursor at the end of the new text.
Using the mouse only works when 'mouse' contains 'n'
or 'a'.
{not in Vi}
If you have a scrollwheel and often accidentally paste
text, you can use these mappings to disable the
pasting with the middle mouse button:
:map <MiddleMouse> <Nop>
:imap <MiddleMouse> <Nop>
You might want to disable the multi-click versions
too, see |double-click|.
*gp*
["x]gp Just like "p", but leave the cursor just after the new
text. {not in Vi}
*gP*
["x]gP Just like "P", but leave the cursor just after the new
text. {not in Vi}
*:pu* *:put*
:[line]pu[t] [x] Put the text [from register x] after [line] (default
current line). This always works |linewise|, thus
this command can be used to put a yanked block as new
lines.
The cursor is left on the first non-blank in the last
new line.
The register can also be '=' followed by an optional
expression. The expression continues until the end of
the command. You need to escape the '|' and '"''
["x][P or *[P*
["x]]P or *]P*
["x][p or *[p* *[<MiddleMouse>*
["x][<MiddleMouse> Like "P", but adjust the indent to the current line.
Using the mouse only works when 'mouse' contains 'n'
or 'a'. {not in Vi}
You can use these commands to copy text from one place to another. Do this
by first getting the text into a register with a yank, delete or change
command, then inserting the register contents with a put command. You can
also use these commands to move text from one file to another, because Vim
preserves all registers when changing buffers (the CTRL-^ command is a quick
way to toggle between two files).
*linewise-register* *characterwise-register*
You can repeat the put commands with "." (except for :put) and undo them. If
the command that was used to get the text into the register was |linewise|,
Vim inserts the text below ("p") or above ("P") the line where the cursor is.
Otherwise Vim inserts the text after ("p") or before ("P") the cursor. With
the ":put" command, Vim always inserts the text in the next line. You can
exchange two characters with the command sequence "xp". You can exchange two
lines with the command sequence "ddp". You can exchange two words with the
command sequence "deep" (start with the cursor in the blank space before the
first word). You can use the "']" or "`]" command after the put command to
move the cursor to the end of the inserted text, or use "'[" or "`[" to move
the cursor to the start.
*blockwise-register*
If you use a blockwise Visual mode command to get the text into the register,
the block of text will be inserted before ("P") or after ("p") the cursor
column in the current and next lines. Vim makes the whole block of text start
in the same column. Thus the inserted text looks the same as when it was
yanked or deleted. Vim may replace some <Tab> characters with spaces to make
this happen. However, if the width of the block is not a multiple of a <Tab>
width and the text after the inserted block contains <Tab>s, that text may be
misaligned.
Note that after a characterwise yank command, Vim leaves the cursor on the
first yanked character that is closest to the start of the buffer. This means
that "yl" doesn't move the cursor, but "yh" moves the cursor one character
left.
Rationale: In Vi the "y" command followed by a backwards motion would
sometimes not move the cursor to the first yanked character,
because redisplaying was skipped. In Vim it always moves to
the first character, as specified by Posix.
With a linewise yank command the cursor is put in the first line, but the
column is unmodified, thus it may not be on the first yanked character.
*@/*
You can write to a register with a ":let" command |:let-@|. Example:
:let @/ = "the"
If you use a put command without specifying a register, Vim uses the register
that was last filled (this is also the contents of the unnamed register). If
you are confused, use the ":dis" command to find out what Vim will put (this
command displays all named and numbered registers; the unnamed register is
labelled '"'').
The next three commands always work on whole lines.
*:t*
:t Synonym for copy.
*:le* *:left*
:[range]le[ft] [indent]
Left-align lines in [range]. Sets the indent in the
lines to [indent] (default 0). {not in Vi}
Not available when |+ex_extra| feature was disabled at
compile time.
*gq*
gq{motion} Format the lines that {motion} moves over.
Formatting is done with one of three methods:
1. If 'formatexpr' is not empty the expression is
evaluated. This can differ for each buffer.
2. If 'formatprg' is not empty an external program
is used.
3. Otherwise formatting is done internally.
In the third case the 'textwidth' option controls the
length of each formatted line (see below).
If the 'textwidth' option is 0, the formatted line
length is the screen width (with a maximum width of
79).
The 'formatoptions' option controls the type of
formatting |fo-table|.
The cursor is left on the first non-blank of the last
formatted line.
NOTE: The "Q" command formerly performed this
function. If you still want to use "Q" for
formatting, use this mapping:
:nnoremap Q gq
*v_gq*
{Visual}gq Format the highlighted text. (for {Visual} see
|Visual-mode|). {not in Vi}
*gw*
gw{motion} Format the lines that {motion} moves over. Similar to
*v_gw*
{Visual}gw Format the highlighted text as with "gw". (for
{Visual} see |Visual-mode|). {not in Vi}
*right-justify*
There is no command in Vim to right justify text. You can do it with
an external command, like "par" (e.g.: "!}par" to format until the end of the
paragraph) or set 'formatprg' to "par".
*format-comments*
An overview of comment formatting is in section |30.6| of the user manual.
Vim can automatically insert and format comments in a special way. Vim
recognizes a comment by a specific string at the start of the line (ignoring
white space). Three types of comments can be used:
- A comment string that repeats at the start of each line. An example is the
type of comment used in shell scripts, starting with "#".
- A comment string that occurs only in the first line, not in the following
lines. An example is this list with dashes.
- Three-piece comments that have a start string, an end string, and optional
lines in between. The strings for the start, middle and end are different.
An example is the C style comment:
/*
* this is a C comment
*/
The 'comments' option is a comma-separated list of parts. Each part defines a
type of comment string. A part consists of:
{flags}:{string}
{string} is the literal text that must appear.
{flags}:
n Nested comment. Nesting with mixed parts is allowed. If 'comments'
is "n:),n:>" a line starting with "> ) >" is a comment.
b Blank (<Space>, <Tab> or <EOL>) required after {string}.
f Only the first line has the comment string. Do not repeat comment on
the next line, but preserve indentation (e.g., a bullet-list).
*fo-table*
You can use the 'formatoptions' option to influence how Vim formats text.
'formatoptions' is a string that can contain any of the letters below. The
default setting is "tcq". You can separate the option letters with commas for
readability.
letter meaning when present in 'formatoptions'
t Auto-wrap text using textwidth
c Auto-wrap comments using textwidth, inserting the current comment
leader automatically.
r Automatically insert the current comment leader after hitting
<Enter> in Insert mode.
o Automatically insert the current comment leader after hitting 'o' or
'O' in Normal mode.
q Allow formatting of comments with "gq".
Note that formatting will not change blank lines or lines containing
only the comment leader. A new paragraph starts after such a line,
or when the comment leader changes.
w Trailing white space indicates a paragraph continues in the next line.
A line that ends in a non-white character ends a paragraph.
a Automatic formatting of paragraphs. Every time text is inserted or
deleted the paragraph will be reformatted. See |auto-format|.
When the 'c' flag is present this only happens for recognized
comments.
n When formatting text, recognize numbered lists. This actually uses
the 'formatlistpat' option, thus any kind of list can be used. The
indent of the text after the number is used for the next line. The
default is to find a number, optionally followed by '.', ':', ')',
']' or '}'. Note that 'autoindent' must be set too. Doesn't work
well together with "2".
Example:
1. the first item
wraps
2. the second item
2 When formatting text, use the indent of the second line of a paragraph
for the rest of the paragraph, instead of the indent of the first
line. This supports paragraphs in which the first line has a
different indent than the rest. Note that 'autoindent' must be set
too. Example:
first line of a paragraph
second line of the same paragraph
third line.
v Vi-compatible auto-wrapping in insert mode: Only break a line at a
blank that you have entered during the current insert command. (Note:
this is not 100% Vi compatible. Vi has some "unexpected features" or
bugs in this area. It uses the screen column instead of the line
column.)
b Like 'v', but only auto-wrap if you enter a blank at or before
the wrap margin. If the line was longer than 'textwidth' when you
started the insert, or you do not enter a blank in the insert before
reaching 'textwidth', Vim does not perform auto-wrapping.
l Long lines are not broken in insert mode: When a line was longer than
'textwidth' when the insert command started, Vim does not
automatically format it.
m Also break at a multi-byte character above 255. This is useful for
Asian text where every character is a word on its own.
With 't' and 'c' you can specify when Vim performs auto-wrapping:
value action
"" no automatic formatting (you can use "gq" for manual formatting)
"t" automatic formatting of text, but not comments
"c" automatic formatting for comments, but not text (good for C code)
"tc" automatic formatting for text and comments
Note that when 'textwidth' is 0, Vim does no automatic formatting anyway (but
does insert comment leaders according to the 'comments' option). An exception
is when the 'a' flag is present. |auto-format|
Note that when 'paste' is on, Vim does no formatting at all.
Note that 'textwidth' can be non-zero even if Vim never performs auto-wrapping;
'textwidth' is still useful for formatting with "gq".
If the 'comments' option includes "/*", "*" and/or "*/", then Vim has some
built in stuff to treat these types of comments a bit more cleverly.
Opening a new line before or after "/*" or "*/" (with 'r' or 'o' present in
'formatoptions') gives the correct start of the line automatically. The same
happens with formatting and auto-wrapping. Opening a line after a line
starting with "/*" or "*" and containing "*/", will cause no comment leader to
be inserted, and the indent of the new line is taken from the line containing
the start of the comment.
E.g.:
/*
* Your typical comment.
*/
The indent on this line is the same as the start of the above
comment.
All of this should be really cool, especially in conjunction with the new
:autocmd command to prepare different settings for different types of file.
Some examples:
for C code (only format comments):
:set fo=croq
for Mail/news (format all, don't start comment with "o" command):
:set fo=tcrq
:set fo-=a
- When using the 'w' flag (trailing space means paragraph continues) and
deleting the last line of a paragraph with |dd|, the paragraph will be
joined with the next one.
- Changed text is saved for undo. Formatting is also a change. Thus each
format action saves text for undo. This may consume quite a lot of memory.
- Formatting a long paragraph and/or with complicated indenting may be slow.
==============================================================================
7. Sorting text *sorting*
Vim has a sorting function and a sorting command. The sorting function can be
found here: |sort()|.
*:sor* *:sort*
:[range]sor[t][!] [i][u][r][n][x][o] [/{pattern}/]
Sort lines in [range]. When no range is given all
lines are sorted.
With [!] the order is reversed.
With [i] case is ignored.
With [n] sorting is done on the first decimal number
in the line (after or inside a {pattern} match).
One leading '-' is included in the number.
With [x] sorting is done on the first hexadecimal
number in the line (after or inside a {pattern}
match). A leading "0x" or "0X" is ignored.
One leading '-' is included in the number.
With [o] sorting is done on the first octal number in
the line (after or inside a {pattern} match).
With [u] only keep the first of a sequence of
identical lines (ignoring case when [i] is used).
Without this flag, a sequence of identical lines
will be kept in their original order.
Note that leading and trailing white space may cause
lines to be different.
When /{pattern}/ is specified and there is no [r] flag
the text matched with {pattern} is skipped, so that
you sort on what comes after the match.
Instead of the slash any non-letter can be used.
For example, to sort on the second comma-separated
field:
:sort /[^,]*,/
To sort on the text at virtual column 10 (thus
ignoring the difference between tabs and spaces):
:sort /.*\%10v/
To sort on the first number in the line, no matter
what is in front of it:
:sort /.\{-}\ze\d/
(Explanation: ".\{-}" matches any text, "\ze" sets the
end of the match and \d matches a digit.)
With [r] sorting is done on the matching {pattern}
instead of skipping past it as described above.
For example, to sort on only the first three letters
of each line:
:sort /\a\a\a/ r
If a {pattern} is used, any lines which don't have a
match for {pattern} are kept in their current order,
but separate from the lines which do match {pattern}.
If you sorted in reverse, they will be in reverse
order after the sorted lines, otherwise they will be
in their original order, right before the sorted
lines.
If {pattern} is empty (e.g. // is specified), the
last search pattern is used. This allows trying out
a pattern first.
Note that using ":sort" with ":global" doesn't sort the matching lines, it's
quite useless.
The details about sorting depend on the library function used. There is no
guarantee that sorting is "stable" or obeys the current locale. You will have
to try it out.
The sorting can be interrupted, but if you interrupt it too late in the
process you may end up with duplicated lines. This also depends on the system
library function used.
top - main help file
*Insert* *Insert-mode*
Inserting and replacing text *mode-ins-repl*
Most of this file is about Insert and Replace mode. At the end are a few
commands for inserting text in other ways.
An overview of the most often used commands can be found in chapter 24 of the
user manual |usr_24.txt|.
1. Special keys |ins-special-keys|
2. Special special keys |ins-special-special|
3. 'textwidth' and 'wrapmargin' options |ins-textwidth|
4. 'expandtab', 'smarttab' and 'softtabstop' options |ins-expandtab|
5. Replace mode |Replace-mode|
6. Virtual Replace mode |Virtual-Replace-mode|
7. Insert mode completion |ins-completion|
8. Insert mode commands |inserting|
9. Ex insert commands |inserting-ex|
10. Inserting a file |inserting-file|
Also see 'virtualedit', for moving the cursor to positions where there is no
character. Useful for editing a table.
==============================================================================
1. Special keys *ins-special-keys*
In Insert and Replace mode, the following characters have a special meaning;
other characters are inserted directly. To insert one of these special
characters into the buffer, precede it with CTRL-V. To insert a <Nul>
character use "CTRL-V CTRL-@" or "CTRL-V 000". On some systems, you have to
use "CTRL-V 003" to insert a CTRL-C. Note: When CTRL-V is mapped you can
often use CTRL-Q instead |i_CTRL-Q|.
If you are working in a special language mode when inserting text, see the
'langmap' option, |'langmap'|, on how to avoid switching this mode on and off
all the time.
If you have 'insertmode' set, <Esc> and a few other keys get another meaning.
See |'insertmode'|.
char action
*i_CTRL-[* *i_<Esc>*
<Esc> or CTRL-[ End insert or Replace mode, go back to Normal mode. Finish
abbreviation.
Note: If your <Esc> key is hard to hit on your keyboard, train
yourself to use CTRL-[.
*i_CTRL-C*
CTRL-C Quit insert mode, go back to Normal mode. Do not check for
abbreviations. Does not trigger the |InsertLeave| autocommand
event.
*i_CTRL-@*
CTRL-@ Insert previously inserted text and stop insert. {Vi: only
when typed as first char, only up to 128 chars}
*i_CTRL-A*
CTRL-A Insert previously inserted text. {not in Vi}
*i_CTRL-T*
CTRL-T Insert one shiftwidth of indent at the start of the current
line. The indent is always rounded to a 'shiftwidth' (this is
vi compatible). {Vi: only when in indent}
*i_CTRL-D*
CTRL-D Delete one shiftwidth of indent at the start of the current
line. The indent is always rounded to a 'shiftwidth' (this is
vi compatible). {Vi: CTRL-D works only when used after
autoindent}
*i_0_CTRL-D*
0 CTRL-D Delete all indent in the current line. {Vi: CTRL-D works
only when used after autoindent}
*i_^_CTRL-D*
^ CTRL-D Delete all indent in the current line. The indent is
restored in the next line. This is useful when inserting a
label. {Vi: CTRL-D works only when used after autoindent}
*i_CTRL-V*
CTRL-V Insert next non-digit literally. For special keys, the
terminal code is inserted. It's also possible to enter the
decimal, octal or hexadecimal value of a character
|i_CTRL-V_digit|.
The characters typed right after CTRL-V are not considered for
mapping. {Vi: no decimal byte entry}
Note: When CTRL-V is mapped (e.g., to paste text) you can
often use CTRL-Q instead |i_CTRL-Q|.
*i_CTRL-Q*
CTRL-Q Same as CTRL-V.
Note: Some terminal connections may eat CTRL-Q, it doesn't
work then. It does work in the GUI.
*i_CTRL-E*
CTRL-E Insert the character which is below the cursor. {not in Vi}
*i_CTRL-Y*
CTRL-Y Insert the character which is above the cursor. {not in Vi}
Note that for CTRL-E and CTRL-Y 'textwidth' is not used, to be
able to copy characters from a long line.
*i_CTRL-_*
CTRL-_ Switch between languages, as follows:
- When in a rightleft window, revins and nohkmap are toggled,
since English will likely be inserted in this case.
- When in a norightleft window, revins and hkmap are toggled,
since Hebrew will likely be inserted in this case.
CTRL-_ moves the cursor to the end of the typed text.
This command is only available when the 'allowrevins' option
is set.
Please refer to |rileft.txt| for more information about
right-to-left mode.
{not in Vi}
Only if compiled with the |+rightleft| feature.
*i_CTRL-^*
CTRL-^ Toggle the use of typing language characters.
When language |:lmap| mappings are defined:
- If 'iminsert' is 1 (langmap mappings used) it becomes 0 (no
langmap mappings used).
- If 'iminsert' has another value it becomes 1, thus langmap
mappings are enabled.
When no language mappings are defined:
- If 'iminsert' is 2 (Input Method used) it becomes 0 (no
Input Method used).
- If 'iminsert' has another value it becomes 2, thus the Input
Method is enabled.
When set to 1, the value of the "b:keymap_name" variable, the
'keymap' option or "<lang>" appears in the status line.
The language mappings are normally used to type characters
that are different from what the keyboard produces. The
'keymap' option can be used to install a whole number of them.
{not in Vi}
*i_CTRL-]*
CTRL-] Trigger abbreviation, without inserting a character. {not in
Vi}
*i_<Insert>*
<Insert> Toggle between Insert and Replace mode. {not in Vi}
*i_backspacing*
The effect of the <BS>, CTRL-W, and CTRL-U depend on the 'backspace' option
(unless 'revins' is set). This is a comma separated list of items:
item action
indent allow backspacing over autoindent
eol allow backspacing over end-of-line (join lines)
start allow backspacing over the start position of insert; CTRL-W and
CTRL-U stop once at the start position
When 'backspace' is empty, Vi compatible backspacing is used. You cannot
backspace over autoindent, before column 1 or before where insert started.
For backwards compatibility the values "0", "1" and "2" are also allowed, see
|'backspace'|.
If the 'backspace' option does contain "eol" and the cursor is in column 1
when one of the three keys is used, the current line is joined with the
previous line. This effectively deletes the <EOL> in front of the cursor.
{Vi: does not cross lines, does not delete past start position of insert}
*i_CTRL-V_digit*
With CTRL-V the decimal, octal or hexadecimal value of a character can be
entered directly. This way you can enter any character, except a line break
(<NL>, value 10). There are five ways to enter the character value:
first char mode max nr of chars max value
(none) decimal 3 255
o or O octal 3 377 (255)
x or X hexadecimal 2 ff (255)
u hexadecimal 4 ffff (65535)
U hexadecimal 8 7fffffff (2147483647)
Normally you would type the maximum number of characters. Thus to enter a
space (value 32) you would type <C-V>032. You can omit the leading zero, in
which case the character typed after the number must be a non-digit. This
happens for the other modes as well: As soon as you type a character that is
invalid for the mode, the value before it will be used and the "invalid"
character is dealt with in the normal way.
If you enter a value of 10, it will end up in the file as a 0. The 10 is a
<NL>, which is used internally to represent the <Nul> character. When writing
the buffer to a file, the <NL> character is translated into <Nul>. The <NL>
character is written at the end of each line. Thus if you want to insert a
<NL> character in a file you will have to make a line break.
*i_CTRL-X* *insert_expand*
CTRL-X enters a sub-mode where several commands can be used. Most of these
commands do keyword completion; see |ins-completion|. These are not available
when Vim was compiled without the |+insert_expand| feature.
Two commands can be used to scroll the window up or down, without exiting
insert mode:
*i_CTRL-X_CTRL-E*
CTRL-X CTRL-E scroll window one line up.
When doing completion look here: |complete_CTRL-E|
*i_CTRL-X_CTRL-Y*
CTRL-X CTRL-Y scroll window one line down.
When doing completion look here: |complete_CTRL-Y|
After CTRL-X is pressed, each CTRL-E (CTRL-Y) scrolls the window up (down) by
one line unless that would cause the cursor to move from its current position
in the file. As soon as another key is pressed, CTRL-X mode is exited and
that key is interpreted as in Insert mode.
==============================================================================
2. Special special keys *ins-special-special*
The following keys are special. They stop the current insert, do something,
and then restart insertion. This means you can do something without getting
out of Insert mode. This is very handy if you prefer to use the Insert mode
all the time, just like editors that don't have a separate Normal mode. You
may also want to set the 'backspace' option to "indent,eol,start" and set the
'insertmode' option. You can use CTRL-O if you want to map a function key to
a command.
The changes (inserted or deleted characters) before and after these keys can
be undone separately. Only the last change can be redone and always behaves
like an "i" command.
char action
<Up> cursor one line up *i_<Up>*
<Down> cursor one line down *i_<Down>*
CTRL-G <Up> cursor one line up, insert start column *i_CTRL-G_<Up>*
CTRL-G k cursor one line up, insert start column *i_CTRL-G_k*
CTRL-G CTRL-K cursor one line up, insert start column *i_CTRL-G_CTRL-K*
CTRL-G <Down> cursor one line down, insert start column *i_CTRL-G_<Down>*
CTRL-G j cursor one line down, insert start column *i_CTRL-G_j*
CTRL-G CTRL-J cursor one line down, insert start column *i_CTRL-G_CTRL-J*
<Left> cursor one character left *i_<Left>*
<Right> cursor one character right *i_<Right>*
<S-Left> cursor one word back (like "b" command) *i_<S-Left>*
<C-Left> cursor one word back (like "b" command) *i_<C-Left>*
<S-Right> cursor one word forward (like "w" command) *i_<S-Right>*
<C-Right> cursor one word forward (like "w" command) *i_<C-Right>*
<Home> cursor to first char in the line *i_<Home>*
<End> cursor to after last char in the line *i_<End>*
<C-Home> cursor to first char in the file *i_<C-Home>*
<C-End> cursor to after last char in the file *i_<C-End>*
<LeftMouse> cursor to position of mouse click *i_<LeftMouse>*
<S-Up> move window one page up *i_<S-Up>*
<PageUp> move window one page up *i_<PageUp>*
<S-Down> move window one page down *i_<S-Down>*
<PageDown> move window one page down *i_<PageDown>*
<ScrollWheelDown> move window three lines down *i_<ScrollWheelDown>*
<S-ScrollWheelDown> move window one page down *i_<S-ScrollWheelDown>*
<ScrollWheelUp> move window three lines up *i_<ScrollWheelUp>*
<S-ScrollWheelUp> move window one page up *i_<S-ScrollWheelUp>*
<ScrollWheelLeft> move window six columns left *i_<ScrollWheelLeft>*
<S-ScrollWheelLeft> move window one page left *i_<S-ScrollWheelLeft>*
<ScrollWheelRight> move window six columns right *i_<ScrollWheelRight>*
<S-ScrollWheelRight> move window one page right *i_<S-ScrollWheelRight>*
CTRL-O execute one command, return to Insert mode *i_CTRL-O*
CTRL-\ CTRL-O like CTRL-O but don't move the cursor *i_CTRL-\_CTRL-O*
CTRL-L when 'insertmode' is set: go to Normal mode *i_CTRL-L*
CTRL-G u break undo sequence, start new change *i_CTRL-G_u*
Note: If the cursor keys take you out of Insert mode, check the 'noesckeys'
option.
The CTRL-O command sometimes has a side effect: If the cursor was beyond the
end of the line, it will be put on the last character in the line. In
mappings it's often better to use <Esc> (first put an "x" in the text, <Esc>
will then always put the cursor on it). Or use CTRL-\ CTRL-O, but then
beware of the cursor possibly being beyond the end of the line.
The CTRL-O command takes you to Normal mode. If you then use a command enter
Insert mode again it doesn't nest. Thus when typing "a<C-O>a" and then <Esc>
takes you back to Normal mode, you do not need to type <Esc> twice.
The shifted cursor keys are not available on all terminals.
Another side effect is that a count specified before the "i" or "a" command is
ignored. That is because repeating the effect of the command after CTRL-O is
too complicated.
An example for using CTRL-G u:
:inoremap <C-H> <C-G>u<C-H>
This redefines the backspace key to start a new undo sequence. You can now
undo the effect of the backspace key, without changing what you typed before
that, with CTRL-O u.
Using CTRL-O splits undo: the text typed before and after it is undone
separately. If you want to avoid this (e.g., in a mapping) you might be able
to use CTRL-R = |i_CTRL-R|. E.g., to call a function:
:imap <F2> <C-R>=MyFunc()<CR>
When the 'whichwrap' option is set appropriately, the <Left> and <Right>
keys on the first/last character in the line make the cursor wrap to the
previous/next line.
The CTRL-G j and CTRL-G k commands can be used to insert text in front of a
column. Example:
int i;
int j;
Position the cursor on the first "int", type "istatic <C-G>j ". The
result is:
static int i;
int j;
When inserting the same text in front of the column in every line, use the
Visual blockwise command "I" |v_b_I|.
==============================================================================
3. 'textwidth' and 'wrapmargin' options *ins-textwidth*
The 'textwidth' option can be used to automatically break a line before it
gets too long. Set the 'textwidth' option to the desired maximum line
length. If you then type more characters (not spaces or tabs), the
last word will be put on a new line (unless it is the only word on the
line). If you set 'textwidth' to 0, this feature is disabled.
The 'wrapmargin' option does almost the same. The difference is that
'textwidth' has a fixed width while 'wrapmargin' depends on the width of the
screen. When using 'wrapmargin' this is equal to using 'textwidth' with a
value equal to (columns - 'wrapmargin'), where columns is the width of the
screen.
When 'textwidth' and 'wrapmargin' are both set, 'textwidth' is used.
If you don't really want to break the line, but view the line wrapped at a
convenient place, see the 'linebreak' option.
The line is only broken automatically when using Insert mode, or when
appending to a line. When in replace mode and the line length is not
changed, the line will not be broken.
Long lines are broken if you enter a non-white character after the margin.
The situations where a line will be broken can be restricted by adding
characters to the 'formatoptions' option:
"l" Only break a line if it was not longer than 'textwidth' when the insert
started.
"v" Only break at a white character that has been entered during the
current insert command. This is mostly Vi-compatible.
"lv" Only break if the line was not longer than 'textwidth' when the insert
started and only at a white character that has been entered during the
current insert command. Only differs from "l" when entering non-white
characters while crossing the 'textwidth' boundary.
Normally an internal function will be used to decide where to break the line.
If you want to do it in a different way set the 'formatexpr' option to an
expression that will take care of the line break.
If you want to format a block of text, you can use the "gq" operator. Type
"gq" and a movement command to move the cursor to the end of the block. In
many cases, the command "gq}" will do what you want (format until the end of
paragraph). Alternatively, you can use "gqap", which will format the whole
paragraph, no matter where the cursor currently is. Or you can use Visual
mode: hit "v", move to the end of the block, and type "gq". See also |gq|.
==============================================================================
*ins-smarttab*
When the 'smarttab' option is on, a <Tab> inserts 'shiftwidth' positions at
the beginning of a line and 'tabstop' positions in other places. This means
that often spaces instead of a <Tab> character are inserted. When 'smarttab
is off, a <Tab> always inserts 'tabstop' positions, and 'shiftwidth' is only
used for ">>" and the like. {not in Vi}
*ins-softtabstop*
When the 'softtabstop' option is non-zero, a <Tab> inserts 'softtabstop'
positions, and a <BS> used to delete white space, will delete 'softtabstop'
positions. This feels like 'tabstop' was set to 'softtabstop', but a real
<Tab> character still takes 'tabstop' positions, so your file will still look
correct when used by other applications.
If 'softtabstop' is non-zero, a <BS> will try to delete as much white space to
move to the previous 'softtabstop' position, except when the previously
inserted character is a space, then it will only delete the character before
the cursor. Otherwise you cannot always delete a single character before the
cursor. You will have to delete 'softtabstop' characters first, and then type
extra spaces to get where you want to be.
==============================================================================
5. Replace mode *Replace* *Replace-mode* *mode-replace*
Enter Replace mode with the "R" command in normal mode.
In Replace mode, one character in the line is deleted for every character you
type. If there is no character to delete (at the end of the line), the
typed character is appended (as in Insert mode). Thus the number of
characters in a line stays the same until you get to the end of the line.
If a <NL> is typed, a line break is inserted and no character is deleted.
Be careful with <Tab> characters. If you type a normal printing character in
its place, the number of characters is still the same, but the number of
columns will become smaller.
If you delete characters in Replace mode (with <BS>, CTRL-W, or CTRL-U), what
happens is that you delete the changes. The characters that were replaced
are restored. If you had typed past the existing text, the characters you
added are deleted. This is effectively a character-at-a-time undo.
If the 'expandtab' option is on, a <Tab> will replace one character with
several spaces. The result of this is that the number of characters in the
line increases. Backspacing will delete one space at a time. The original
character will be put back for only one space that you backspace over (the
last one). {Vi does not have the 'expandtab' option}
==============================================================================
6. Virtual Replace mode *vreplace-mode* *Virtual-Replace-mode*
Enter Virtual Replace mode with the "gR" command in normal mode.
{not available when compiled without the |+vreplace| feature}
{Vi does not have Virtual Replace mode}
Virtual Replace mode is similar to Replace mode, but instead of replacing
actual characters in the file, you are replacing screen real estate, so that
characters further on in the file never appear to move.
So if you type a <Tab> it may replace several normal characters, and if you
type a letter on top of a <Tab> it may not replace anything at all, since the
<Tab> will still line up to the same place as before.
Typing a <NL> still doesn't cause characters later in the file to appear to
move. The rest of the current line will be replaced by the <NL> (that is,
they are deleted), and replacing continues on the next line. A new line is
NOT inserted unless you go past the end of the file.
Interesting effects are seen when using CTRL-T and CTRL-D. The characters
before the cursor are shifted sideways as normal, but characters later in the
line still remain still. CTRL-T will hide some of the old line under the
shifted characters, but CTRL-D will reveal them again.
As with Replace mode, using <BS> etc will bring back the characters that were
replaced. This still works in conjunction with 'smartindent', CTRL-T and
CTRL-D, 'expandtab', 'smarttab', 'softtabstop', etc.
In 'list' mode, Virtual Replace mode acts as if it was not in 'list' mode,
unless "L" is in 'cpoptions'.
Note that the only situations for which characters beyond the cursor should
appear to move are in List mode |'list'|, and occasionally when 'wrap' is set
(and the line changes length to become shorter or wider than the width of the
screen). In other cases spaces may be inserted to avoid following characters
to move.
This mode is very useful for editing <Tab> separated columns in tables, for
entering new data while keeping all the columns aligned.
==============================================================================
7. Insert mode completion *ins-completion*
In Insert and Replace mode, there are several commands to complete part of a
keyword or line that has been typed. This is useful if you are using
complicated keywords (e.g., function names with capitals and underscores).
These commands are not available when the |+insert_expand| feature was
disabled at compile time.
Completion can be done for:
1. Whole lines |i_CTRL-X_CTRL-L|
2. keywords in the current file |i_CTRL-X_CTRL-N|
3. keywords in 'dictionary' |i_CTRL-X_CTRL-K|
4. keywords in 'thesaurus', thesaurus-style |i_CTRL-X_CTRL-T|
5. keywords in the current and included files |i_CTRL-X_CTRL-I|
6. tags |i_CTRL-X_CTRL-]|
7. file names |i_CTRL-X_CTRL-F|
8. definitions or macros |i_CTRL-X_CTRL-D|
9. Vim command-line |i_CTRL-X_CTRL-V|
10. User defined completion |i_CTRL-X_CTRL-U|
11. omni completion |i_CTRL-X_CTRL-O|
12. Spelling suggestions |i_CTRL-X_s|
13. keywords in 'complete' |i_CTRL-N|
All these (except 2) are done in CTRL-X mode. This is a sub-mode of Insert
and Replace modes. You enter CTRL-X mode by typing CTRL-X and one of the
CTRL-X commands. You exit CTRL-X mode by typing a key that is not a valid
CTRL-X mode command. Valid keys are the CTRL-X command itself, CTRL-N (next),
and CTRL-P (previous).
Also see the 'infercase' option if you want to adjust the case of the match.
*complete_CTRL-E*
When completion is active you can use CTRL-E to stop it and go back to the
originally typed text. The CTRL-E will not be inserted.
*complete_CTRL-Y*
When the popup menu is displayed you can use CTRL-Y to stop completion and
accept the currently selected entry. The CTRL-Y is not inserted. Typing a
space, Enter, or some other unprintable character will leave completion mode
and insert that typed character.
When the popup menu is displayed there are a few more special keys, see
|popupmenu-keys|.
Note: The keys that are valid in CTRL-X mode are not mapped. This allows for
":map ^F ^X^F" to work (where ^F is CTRL-F and ^X is CTRL-X). The key that
ends CTRL-X mode (any key that is not a valid CTRL-X mode command) is mapped.
Also, when doing completion with 'complete' mappings apply as usual.
Note: While completion is active Insert mode can't be used recursively.
Mappings that somehow invoke ":normal i.." will generate an E523 error.
The following mappings are suggested to make typing the completion commands
a bit easier (although they will hide other commands):
:inoremap ^] ^X^]
:inoremap ^F ^X^F
:inoremap ^D ^X^D
:inoremap ^L ^X^L
As a special case, typing CTRL-R to perform register insertion (see
|i_CTRL-R|) will not exit CTRL-X mode. This is primarily to allow the use of
the '=' register to call some function to determine the next operation. If
the contents of the register (or result of the '=' register evaluation) are
not valid CTRL-X mode keys, then CTRL-X mode will be exited as if those keys
had been typed.
For example, the following will map <Tab> to either actually insert a <Tab> if
the current line is currently only whitespace, or start/continue a CTRL-N
completion operation:
function! CleverTab()
if strpart( getline('.'), 0, col('.')-1 ) =~ '^\s*$'
return "\<Tab>"
else
return "\<C-N>"
endif
endfunction
inoremap <Tab> <C-R>=CleverTab()<CR>
*i_CTRL-X_CTRL-L*
CTRL-X CTRL-L Search backwards for a line that starts with the
same characters as those in the current line before
the cursor. Indent is ignored. The matching line is
inserted in front of the cursor.
The 'complete' option is used to decide which buffers
are searched for a match. Both loaded and unloaded
buffers are used.
CTRL-L or
CTRL-P Search backwards for next matching line. This line
replaces the previous matching line.
CTRL-N Search forward for next matching line. This line
replaces the previous matching line.
CTRL-X CTRL-L After expanding a line you can additionally get the
line next to it by typing CTRL-X CTRL-L again, unless
a double CTRL-X is used. Only works for loaded
buffers.
*i_CTRL-X_CTRL-P*
*i_CTRL-X_CTRL-N*
CTRL-X CTRL-N Search forwards for words that start with the keyword
in front of the cursor. The found keyword is inserted
in front of the cursor.
CTRL-X CTRL-P Search backwards for words that start with the keyword
in front of the cursor. The found keyword is inserted
in front of the cursor.
CTRL-N Search forward for next matching keyword. This
keyword replaces the previous matching keyword.
CTRL-P Search backwards for next matching keyword. This
keyword replaces the previous matching keyword.
CTRL-X CTRL-N or
CTRL-X CTRL-P Further use of CTRL-X CTRL-N or CTRL-X CTRL-P will
copy the words following the previous expansion in
*i_CTRL-X_CTRL-K*
CTRL-X CTRL-K Search the files given with the 'dictionary' option
for words that start with the keyword in front of the
cursor. This is like CTRL-N, but only the dictionary
files are searched, not the current file. The found
keyword is inserted in front of the cursor. This
could potentially be pretty slow, since all matches
are found before the first match is used. By default,
the 'dictionary' option is empty.
For suggestions where to find a list of words, see the
'dictionary' option.
CTRL-K or
CTRL-N Search forward for next matching keyword. This
keyword replaces the previous matching keyword.
CTRL-P Search backwards for next matching keyword. This
keyword replaces the previous matching keyword.
*i_CTRL-X_CTRL-T*
CTRL-X CTRL-T Works as CTRL-X CTRL-K, but in a special way. It uses
the 'thesaurus' option instead of 'dictionary'. If a
match is found in the thesaurus file, all the
remaining words on the same line are included as
matches, even though they don't complete the word.
Thus a word can be completely replaced.
For an example, imagine the 'thesaurus' file has a
line like this:
angry furious mad enraged
Placing the cursor after the letters "ang" and typing
CTRL-X CTRL-T would complete the word "angry";
subsequent presses would change the word to "furious",
"mad" etc.
Other uses include translation between two languages,
or grouping API functions by keyword.
CTRL-T or
CTRL-N Search forward for next matching keyword. This
keyword replaces the previous matching keyword.
CTRL-P Search backwards for next matching keyword. This
keyword replaces the previous matching keyword.
*i_CTRL-X_CTRL-I*
CTRL-X CTRL-I Search for the first keyword in the current and
included files that starts with the same characters
as those before the cursor. The matched keyword is
inserted in front of the cursor.
CTRL-N Search forwards for next matching keyword. This
keyword replaces the previous matching keyword.
Note: CTRL-I is the same as <Tab>, which is likely to
be typed after a successful completion, therefore
CTRL-I is not used for searching for the next match.
CTRL-P Search backward for previous matching keyword. This
keyword replaces the previous matching keyword.
CTRL-X CTRL-I Further use of CTRL-X CTRL-I will copy the words
following the previous expansion in other contexts
unless a double CTRL-X is used.
*i_CTRL-X_CTRL-D*
CTRL-X CTRL-D Search in the current and included files for the
first definition (or macro) name that starts with
the same characters as before the cursor. The found
definition name is inserted in front of the cursor.
CTRL-D or
CTRL-N Search forwards for next matching macro name. This
macro name replaces the previous matching macro
name.
CTRL-P Search backward for previous matching macro name.
This macro name replaces the previous matching macro
name.
CTRL-X CTRL-D Further use of CTRL-X CTRL-D will copy the words
following the previous expansion in other contexts
unless a double CTRL-X is used.
*i_CTRL-X_CTRL-V*
CTRL-X CTRL-V Guess what kind of item is in front of the cursor and
find the first match for it.
Note: When CTRL-V is mapped you can often use CTRL-Q
instead of |i_CTRL-Q|.
CTRL-V or
CTRL-N Search forwards for next match. This match replaces
the previous one.
CTRL-P Search backwards for previous match. This match
replaces the previous one.
CTRL-X CTRL-V Further use of CTRL-X CTRL-V will do the same as
CTRL-V. This allows mapping a key to do Vim command
completion, for example:
:imap <Tab> <C-X><C-V>
*i_CTRL-X_CTRL-U*
CTRL-X CTRL-U Guess what kind of item is in front of the cursor and
find the first match for it.
CTRL-U or
CTRL-N Use the next match. This match replaces the previous
one.
*i_CTRL-X_CTRL-O*
CTRL-X CTRL-O Guess what kind of item is in front of the cursor and
find the first match for it.
CTRL-O or
CTRL-N Use the next match. This match replaces the previous
one.
CTRL-P Use the previous match. This match replaces the
previous one.
*i_CTRL-X_CTRL-S* *i_CTRL-X_s*
CTRL-X CTRL-S or
CTRL-X s Locate the word in front of the cursor and find the
first spell suggestion for it.
CTRL-S or
CTRL-N Use the next suggestion. This replaces the previous
one. Note that you can't use 's' here.
CTRL-P Use the previous suggestion. This replaces the
previous one.
*i_CTRL-N*
CTRL-N Find next match for words that start with the
keyword in front of the cursor, looking in places
specified with the 'complete' option. The found
keyword is inserted in front of the cursor.
*i_CTRL-P*
CTRL-P Find previous match for words that start with the
keyword in front of the cursor, looking in places
specified with the 'complete' option. The found
keyword is inserted in front of the cursor.
CTRL-N Search forward for next matching keyword. This
keyword replaces the previous matching keyword.
CTRL-P Search backwards for next matching keyword. This
keyword replaces the previous matching keyword.
CTRL-X CTRL-N or
CTRL-X CTRL-P Further use of CTRL-X CTRL-N or CTRL-X CTRL-P will
copy the words following the previous expansion in
other contexts unless a double CTRL-X is used.
*E839* *E840*
The function is allowed to move the cursor, it is restored afterwards.
The function is not allowed to move to another window or delete text.
*popupmenu-keys*
In the first state these keys have a special meaning:
<BS> and CTRL-H Delete one character, find the matches for the word before
the cursor. This reduces the list of matches, often to one
entry, and switches to the second state.
Any non-special character:
Stop completion without changing the match and insert the
typed character.
In the second and third state these keys have a special meaning:
<BS> and CTRL-H Delete one character, find the matches for the shorter word
before the cursor. This may find more matches.
CTRL-L Add one character from the current match, may reduce the
number of matches.
any printable, non-white character:
Add this character and reduce the number of matches.
In all three states these can be used:
CTRL-Y Yes: Accept the currently selected match and stop completion.
CTRL-E End completion, go back to what was there before selecting a
match (what was typed or longest common string).
<PageUp> Select a match several entries back, but don't insert it.
<PageDown> Select a match several entries further, but don't insert it.
<Up> Select the previous match, as if CTRL-P was used, but don't
insert it.
<Down> Select the next match, as if CTRL-N was used, but don't
insert it.
<Space> or <Tab> Stop completion without changing the match and insert the
typed character.
The behavior of the <Enter> key depends on the state you are in:
first state: Use the text as it is and insert a line break.
second state: Insert the currently selected match.
third state: Use the text as it is and insert a line break.
In other words: If you used the cursor keys to select another entry in the
list of matches then the <Enter> key inserts that match. If you typed
something else then <Enter> inserts a line break.
The colors of the menu can be changed with these highlight groups:
Pmenu normal item |hl-Pmenu|
PmenuSel selected item |hl-PmenuSel|
PmenuSbar scrollbar |hl-PmenuSbar|
PmenuThumb thumb of the scrollbar |hl-PmenuThumb|
There are no special mappings for when the popup menu is visible. However,
you can use an Insert mode mapping that checks the |pumvisible()| function to
do something different. Example:
:inoremap <Down> <C-R>=pumvisible() ? "\<lt>C-N>" : "\<lt>Down>"<CR>
You can use of <expr> in mapping to have the popup menu used when typing a
character and some condition is met. For example, for typing a dot:
inoremap <expr> . MayComplete()
func MayComplete()
if (can complete)
return ".\<C-X>\<C-O>"
endif
return '.'
endfunc
See |:map-<expr>| for more info.
C *ft-c-omni*
Completion of C code requires a tags file. You should use Exuberant ctags,
because it adds extra information that is needed for completion. You can find
it here: http://ctags.sourceforge.net/ Version 5.6 or later is recommended.
For version 5.5.4 you should add a patch that adds the "typename:" field:
ftp://ftp.vim.org/pub/vim/unstable/patches/ctags-5.5.4.patch
A compiled .exe for MS-Windows can be found at:
http://georgevreilly.com/vim/ctags.html
If you want to complete system functions you can do something like this. Use
ctags to generate a tags file for all the system header files:
% ctags -R -f ~/.vim/systags /usr/include /usr/local/include
In your vimrc file add this tags file to the 'tags' option:
set tags+=~/.vim/systags
When using CTRL-X CTRL-O after a name without any "." or "->" it is completed
from the tags file directly. This works for any identifier, also function
names. If you want to complete a local variable name, which does not appear
in the tags file, use CTRL-P instead.
When using CTRL-X CTRL-O after something that has "." or "->" Vim will attempt
to recognize the type of the variable and figure out what members it has.
This means only members valid for the variable will be listed.
When a member name already was complete, CTRL-X CTRL-O will add a "." or
"->" for composite types.
Vim doesn't include a C compiler, only the most obviously formatted
declarations are recognized. Preprocessor stuff may cause confusion.
When the same structure name appears in multiple places all possible members
are included.
CSS *ft-css-omni*
Complete properties and their appropriate values according to CSS 2.1
specification.
HTML *ft-html-omni*
XHTML *ft-xhtml-omni*
CTRL-X CTRL-O provides completion of various elements of (X)HTML files. It is
designed to support writing of XHTML 1.0 Strict files but will also works for
other versions of HTML. Features:
- after "<" complete tag name depending on context (no div suggestion inside
of an a tag); '/>' indicates empty tags
- inside of tag complete proper attributes (no width attribute for an a tag);
show also type of attribute; '*' indicates required attributes
- when attribute has limited number of possible values help to complete them
- complete names of entities
- complete values of "class" and "id" attributes with data obtained from
<style> tag and included CSS files
- when completing value of "style" attribute or working inside of "style" tag
switch to |ft-css-omni| completion
- when completing values of events attributes or working inside of "script"
tag switch to |ft-javascript-omni| completion
- when used after "</" CTRL-X CTRL-O will close the last opened tag
Note: When used first time completion menu will be shown with little delay
- this is time needed for loading of data file.
Note: Completion may fail in badly formatted documents. In such case try to
run |:make| command to detect formatting problems.
next completions.
More about format of data file in |xml-omni-datafile|. Some of the data files
may be found on the Vim website (|www|).
Note that b:html_omni_flavor may point to a file with any XML data. This
makes possible to mix PHP (|ft-php-omni|) completion with any XML dialect
(assuming you have data file for it). Without setting that variable XHTML 1.0
Strict will be used.
JAVASCRIPT *ft-javascript-omni*
Completion of most elements of JavaScript language and DOM elements.
Complete:
- variables
- function name; show function arguments
- function arguments
- properties of variables trying to detect type of variable
- complete DOM objects and properties depending on context
- keywords of language
Completion works in separate JavaScript files (&ft==javascript), inside of
<script> tag of (X)HTML and in values of event attributes (including scanning
of external files.
DOM compatibility
At the moment (beginning of 2006) there are two main browsers - MS Internet
Explorer and Mozilla Firefox. These two applications are covering over 90% of
market. Theoretically standards are created by W3C organisation
http://www.w3c.org but they are not always followed/implemented.
IE FF W3C Omni completion
+/- +/- + +
+ + - +
+ - - -
- + - -
Regardless from state of implementation in browsers but if element is defined
in standards, completion plugin will place element in suggestion list. When
both major engines implemented element, even if this is not in standards it
will be suggested. All other elements are not placed in suggestion list.
PHP *ft-php-omni*
Completion of PHP code requires a tags file for completion of data from
external files and for class aware completion. You should use Exuberant ctags
version 5.5.4 or newer. You can find it here: http://ctags.sourceforge.net/
Script completes:
- after $ variables name
- if variable was declared as object add "->", if tags file is available show
name of class
- after "->" complete only function and variable names specific for given
class. To find class location and contents tags file is required. Because
PHP isn't strongly typed language user can use @var tag to declare class:
/* @var $myVar myClass */
$myVar->
Still, to find myClass contents tags file is required.
- function names with additional info:
- in case of built-in functions list of possible arguments and after | type
data returned by function
- in case of user function arguments and name of file where function was
defined (if it is not current file)
- constants names
- class names after "new" declaration
Note: when doing completion first time Vim will load all necessary data into
memory. It may take several seconds. After next use of completion delay
should not be noticeable.
Script detects if cursor is inside <?php ?> tags. If it is outside it will
automatically switch to HTML/CSS/JavaScript completion. Note: contrary to
original HTML files completion of tags (and only tags) isn't context aware.
RUBY *ft-ruby-omni*
Completion of Ruby code requires that vim be built with |+ruby|.
Ruby completion will parse your buffer on demand in order to provide a list of
completions. These completions will be drawn from modules loaded by 'require'
and modules defined in the current buffer.
The completions provided by CTRL-X CTRL-O are sensitive to the context:
CONTEXT COMPLETIONS PROVIDED
1. Not inside a class definition Classes, constants and globals
2. Inside a class definition Methods or constants defined in the class
3. After '.', '::' or ':' Methods applicable to the object being
dereferenced
4. After ':' or ':foo' Symbol name (beginning with 'foo')
Notes:
- Vim will load/evaluate code in order to provide completions. This may
cause some code execution, which may be a concern. This is no longer
enabled by default, to enable this feature add
let g:rubycomplete_buffer_loading = 1
- In context 1 above, Vim can parse the entire buffer to add a list of
classes to the completion results. This feature is turned off by default,
to enable it add
let g:rubycomplete_classes_in_global = 1
to your vimrc
- In context 2 above, anonymous classes are not supported.
- In context 3 above, Vim will attempt to determine the methods supported by
the object.
- Vim can detect and load the Rails environment for files within a rails
project. The feature is disabled by default, to enable it add
let g:rubycomplete_rails = 1
to your vimrc
SYNTAX *ft-syntax-omni*
Vim has the ability to color syntax highlight nearly 500 languages. Part of
this highlighting includes knowing what keywords are part of a language. Many
filetypes already have custom completion scripts written for them, the
syntaxcomplete plugin provides basic completion for all other filetypes. It
does this by populating the omni completion list with the text Vim already
knows how to color highlight. It can be used for any filetype and provides a
minimal language-sensitive completion.
To enable syntax code completion you can run:
setlocal omnifunc=syntaxcomplete#Complete
You can automate this by placing the following in your vimrc (after any
":filetype" command):
if has("autocmd") && exists("+omnifunc")
autocmd Filetype *
\ if &omnifunc == "" |
\ setlocal omnifunc=syntaxcomplete#Complete |
\ endif
endif
The above will set completion to this script only if a specific plugin does
not already exist for that filetype.
Each filetype can have a wide range of syntax items. The plugin allows you to
customize which syntax groups to include or exclude from the list. Let's have
a look at the PHP filetype to see how this works.
SQL *ft-sql-omni*
Completion for the SQL language includes statements, functions, keywords.
It will also dynamically complete tables, procedures, views and column lists
with data pulled directly from within a database. For detailed instructions
and a tutorial see |omni-sql-completion|.
The SQL completion plugin can be used in conjunction with other completion
plugins. For example, the PHP filetype has its own completion plugin.
Since PHP is often used to generate dynamic website by accessing a database,
the SQL completion plugin can also be enabled. This allows you to complete
PHP code and SQL code at the same time.
XML *ft-xml-omni*
Vim 7 provides a mechanism for context aware completion of XML files. It
depends on a special |xml-omni-datafile| and two commands: |:XMLns| and
|:XMLent|. Features are:
- after "<" complete the tag name, depending on context
- inside of a tag complete proper attributes
- when an attribute has a limited number of possible values help to complete
them
- complete names of entities (defined in |xml-omni-datafile| and in the
current file with "<!ENTITY" declarations)
- when used after "</" CTRL-X CTRL-O will close the last opened tag
Commands
==============================================================================
8. Insert mode commands *inserting*
The following commands can be used to insert new text into the buffer. They
can all be undone and repeated with the "." command.
*a*
a Append text after the cursor [count] times. If the
cursor is in the first column of an empty line Insert
starts there. But not when 'virtualedit' is set!
*A*
A Append text at the end of the line [count] times.
*I*
I Insert text before the first non-blank in the line
[count] times.
When the 'H' flag is present in 'cpoptions' and the
line only contains blanks, insert start just before
the last blank.
*gI*
gI Insert text in column 1 [count] times. {not in Vi}
*gi*
gi Insert text in the same position as where Insert mode
was stopped last time in the current buffer.
This uses the |'^| mark. It's different from "`^i"
when the mark is past the end of the line.
The position is corrected for inserted/deleted lines,
but NOT for inserted/deleted characters.
When the |:keepjumps| command modifier is used the |'^|
mark won't be changed.
{not in Vi}
*o*
o Begin a new line below the cursor and insert text,
repeat [count] times. {Vi: blank [count] screen
lines}
When the '#' flag is in 'cpoptions' the count is
ignored.
*O*
O Begin a new line above the cursor and insert text,
repeat [count] times. {Vi: blank [count] screen
lines}
When the '#' flag is in 'cpoptions' the count is
ignored.
These commands are used to start inserting text. You can end insert mode with
<Esc>. See |mode-ins-repl| for the other special characters in Insert mode.
The effect of [count] takes place after Insert mode is exited.
When 'autoindent' is on, the indent for a new line is obtained from the
previous line. When 'smartindent' or 'cindent' is on, the indent for a line
is automatically adjusted for C programs.
'textwidth' can be set to the maximum width for a line. When a line becomes
too long when appending characters a line break is automatically inserted.
==============================================================================
9. Ex insert commands *inserting-ex*
*:a* *:append*
:{range}a[ppend][!] Insert several lines of text below the specified
line. If the {range} is missing, the text will be
inserted after the current line.
Adding [!] toggles 'autoindent' for the time this
command is executed.
*:start* *:startinsert*
:star[tinsert][!] Start Insert mode just after executing this command.
Works like typing "i" in Normal mode. When the ! is
included it works like "A", append to the line.
Otherwise insertion starts at the cursor position.
Note that when using this command in a function or
script, the insertion only starts after the function
or script is finished.
This command does not work from |:normal|.
{not in Vi}
{not available when compiled without the |+ex_extra|
feature}
*:stopi* *:stopinsert*
:stopi[nsert] Stop Insert mode as soon as possible. Works like
typing <Esc> in Insert mode.
Can be used in an autocommand, example:
:au BufEnter scratch stopinsert
*replacing-ex* *:startreplace*
:startr[eplace][!] Start Replace mode just after executing this command.
Works just like typing "R" in Normal mode. When the
! is included it acts just like "$R" had been typed
(ie. begin replace mode at the end-of-line). Other-
wise replacement begins at the cursor position.
Note that when using this command in a function or
script that the replacement will only start after
the function or script is finished.
{not in Vi}
{not available when compiled without the |+ex_extra|
feature}
*:startgreplace*
:startg[replace][!] Just like |:startreplace|, but use Virtual Replace
mode, like with |gR|.
{not in Vi}
{not available when compiled without the |+ex_extra|
feature}
==============================================================================
10. Inserting a file *inserting-file*
*:r!* *:read!*
:[range]r[ead] !{cmd} Execute {cmd} and insert its standard output below
the cursor or the specified line. A temporary file is
used to store the output of the command which is then
read into the buffer. 'shellredir' is used to save
the output of the command, which can be set to include
stderr or not. {cmd} is executed like with ":!{cmd}",
any '!' is replaced with the previous command |:!|.
These commands insert the contents of a file, or the output of a command,
into the buffer. They can be undone. They cannot be repeated with the "."
command. They work on a line basis, insertion starts below the line in which
the cursor is, or below the specified line. To insert text above the first
line use the command ":0r {name}".
After the ":read" command, the cursor is left on the first non-blank in the
first new line. Unless in Ex mode, then the cursor is left on the last new
line (sorry, this is Vi compatible).
If a file name is given with ":r", it becomes the alternate file. This can be
used, for example, when you want to edit that file instead: ":e! #". This can
be switched off by removing the 'a' flag from the 'cpoptions' option.
Of the [++opt] arguments one is specifically for ":read", the ++edit argument.
This is useful when the ":read" command is actually used to read a file into
the buffer as if editing that file. Use this command in an empty buffer:
:read ++edit filename
The effect is that the 'fileformat', 'fileencoding', 'bomb', etc. options are
set to what has been detected for "filename". Note that a single empty line
remains, you may want to delete it.
*file-read*
The 'fileformat' option sets the <EOL> style for a file:
'fileformat' characters name
"dos" <CR><NL> or <NL> DOS format
"unix" <NL> Unix format
"mac" <CR> Mac format
Previously 'textmode' was used. It is obsolete now.
If 'fileformat' is "dos", a <CR> in front of an <NL> is ignored and a CTRL-Z
at the end of the file is ignored.
If 'fileformat' is "mac", a <NL> in the file is internally represented by a
<CR>. This is to avoid confusion with a <NL> which is used to represent a
<NUL>. See |CR-used-for-NL|.
If the 'fileformats' option is not empty Vim tries to recognize the type of
<EOL> (see |file-formats|). However, the 'fileformat' option will not be
changed, the detected format is only used while reading the file.
A similar thing happens with 'fileencodings'.
On non-MS-DOS, Win32, and OS/2 systems the message "[dos format]" is shown if
a file is read in DOS format, to remind you that something unusual is done.
On Macintosh, MS-DOS, Win32, and OS/2 the message "[unix format]" is shown if
a file is read in Unix format.
On non-Macintosh systems, the message "[Mac format]" is shown if a file is
read in Mac format.
An example on how to use ":r !":
:r !uuencode binfile binfile
This command reads "binfile", uuencodes it and reads it into the current
buffer. Useful when you are editing e-mail and want to include a binary
file.
*read-messages*
When reading a file Vim will display a message with information about the read
file. In the table is an explanation for some of the items. The others are
self explanatory. Using the long or the short version depends on the
'shortmess' option.
long short meaning
[readonly] {RO} the file is write protected
[fifo/socket] using a stream
[fifo] using a fifo stream
[socket] using a socket stream
[CR missing] reading with "dos" 'fileformat' and a
NL without a preceding CR was found.
[NL found] reading with "mac" 'fileformat' and a
NL was found (could be "unix" format)
[long lines split] at least one line was split in two
[NOT converted] conversion from 'fileencoding' to
'encoding' was desired but not
possible
[converted] conversion from 'fileencoding' to
'encoding' done
[crypted] file was decrypted
[READ ERRORS] not all of the file could be read
*visual-block*
With CTRL-V (blockwise Visual mode) the highlighted text will be a rectangle
between start position and the cursor. However, some operators work on whole
lines anyway (see the list below). The change and substitute operators will
delete the highlighted text and then start insertion at the top left
position.
==============================================================================
*v* *characterwise-visual*
v start Visual mode per character.
*V* *linewise-visual*
V start Visual mode linewise.
*CTRL-V* *blockwise-visual*
CTRL-V start Visual mode blockwise. Note: Under Windows
CTRL-V could be mapped to paste text, it doesn't work
to start Visual mode then, see |CTRL-V-alternative|.
If you use <Esc>, click the left mouse button or use any command that
does a jump to another buffer while in Visual mode, the highlighting stops
and no text is affected. Also when you hit "v" in characterwise Visual mode,
"CTRL-V" in blockwise Visual mode or "V" in linewise Visual mode. If you hit
CTRL-Z the highlighting stops and the editor is suspended or a new shell is
started |CTRL-Z|.
*<LeftMouse>*
<LeftMouse> Set the current cursor position. If Visual mode is
active it is stopped. Only when 'mouse' option is
contains 'n' or 'a'. If the position is within 'so'
lines from the last line on the screen the text is
scrolled up. If the position is within 'so' lines from
the first line on the screen the text is scrolled
down.
*<RightMouse>*
<RightMouse> Start Visual mode if it is not active. The text from
the cursor position to the position of the click is
highlighted. If Visual mode was already active move
the start or end of the highlighted text, which ever
is closest, to the position of the click. Only when
'mouse' option contains 'n' or 'a'.
Note: when 'mousemodel' is set to "popup",
<S-LeftMouse> has to be used instead of <RightMouse>.
*<LeftRelease>*
<LeftRelease> This works like a <LeftMouse>, if it is not at
the same position as <LeftMouse>. In an older version
of xterm you won't see the selected area until the
button is released, unless there is access to the
display where the xterm is running (via the DISPLAY
environment variable or the -display argument). Only
when 'mouse' option contains 'n' or 'a'.
If Visual mode is not active and the "v", "V" or CTRL-V is preceded with a
count, the size of the previously highlighted area is used for a start. You
can then move the end of the highlighted area and give an operator. The type
of the old area is used (character, line or blockwise).
- Linewise Visual mode: The number of lines is multiplied with the count.
- Blockwise Visual mode: The number of lines and columns is multiplied with
the count.
- Normal Visual mode within one line: The number of characters is multiplied
with the count.
- Normal Visual mode with several lines: The number of lines is multiplied
with the count, in the last line the same number of characters is used as
in the last line in the previously highlighted area.
The start of the text is the Cursor position. If the "$" command was used as
one of the last commands to extend the highlighted text, the area will be
extended to the rightmost column of the longest line.
If you want to highlight exactly the same area as the last time, you can use
"gv" |gv| |v_gv|.
*v_<Esc>*
<Esc> In Visual mode: Stop Visual mode.
*v_CTRL-C*
CTRL-C In Visual mode: Stop Visual mode. When insert mode is
pending (the mode message shows
"-- (insert) VISUAL --"), it is also stopped.
==============================================================================
3. Changing the Visual area *visual-change*
*v_o*
o Go to Other end of highlighted text: The current
cursor position becomes the start of the highlighted
text and the cursor is moved to the other end of the
highlighted text. The highlighted area remains the
same.
*v_O*
O Go to Other end of highlighted text. This is like
"o", but in Visual block mode the cursor moves to the
other corner in the same line. When the corner is at
a character that occupies more than one position on
the screen (e.g., a <Tab>), the highlighted text may
change.
*v_$*
When the "$" command is used with blockwise Visual mode, the right end of the
highlighted text will be determined by the longest highlighted line. This
stops when a motion command is used that does not move straight up or down.
For moving the end of the block many commands can be used, but you cannot
use Ex commands, commands that make changes or abandon the file. Commands
(starting with) ".", "&", CTRL-^, "Z", CTRL-], CTRL-T, CTRL-R, CTRL-I
and CTRL-O cause a beep and Visual mode continues.
When switching to another window on the same buffer, the cursor position in
that window is adjusted, so that the same Visual area is still selected. This
is especially useful to view the start of the Visual area in one window, and
the end in another. You can then use <RightMouse> (or <S-LeftMouse> when
'mousemodel' is "popup") to drag either end of the Visual area.
==============================================================================
4. Operating on the Visual area *visual-operators*
The operators that can be used are:
~ switch case |v_~|
d delete |v_d|
c change (4) |v_c|
y yank |v_y|
> shift right (4) |v_>|
< shift left (4) |v_<|
! filter through external command (1) |v_!|
= filter through 'equalprg' option command (1) |v_=|
gq format lines to 'textwidth' length (1) |v_gq|
The objects that can be used are:
aw a word (with white space) |v_aw|
iw inner word |v_iw|
aW a WORD (with white space) |v_aW|
*{move-around}*
The {move-around} is any sequence of movement commands. Note the difference
with {motion}, which is only ONE movement command.
Another way to operate on the Visual area is using the |/\%V| item in a
pattern. For example, to replace all '(' in the Visual area with '#':
:%s/\%V(/X/g
==============================================================================
5. Blockwise operators *blockwise-operators*
{not available when compiled without the |+visualextra| feature}
Reminder: Use 'virtualedit' to be able to select blocks that start or end
after the end of a line or halfway a tab.
*v_b_<*
Visual-block Shift *v_b_>*
The block is shifted by 'shiftwidth'. The RHS of the block is irrelevant. The
LHS of the block determines the point from which to apply a right shift, and
padding includes TABs optimally according to 'ts' and 'et'. The LHS of the
block determines the point upto which to shift left.
See |v_b_>_example|.
See |v_b_<_example|.
==============================================================================
6. Repeating *visual-repeat*
When repeating a Visual mode operator, the operator will be applied to the
same amount of text as the last time:
- Linewise Visual mode: The same number of lines.
- Blockwise Visual mode: The same number of lines and columns.
- Normal Visual mode within one line: The same number of characters.
- Normal Visual mode with several lines: The same number of lines, in the
last line the same number of characters as in the last line the last time.
The start of the text is the Cursor position. If the "$" command was used as
one of the last commands to extend the highlighted text, the repeating will
be applied up to the rightmost column of the longest line.
==============================================================================
7. Examples *visual-examples*
*:visual_example*
Currently the ":" command works on whole lines only. When you select part of
a line, doing something like ":!date" will replace the whole line. If you
want only part of the line to be replaced you will have to make a mapping for
it. In a future release ":" may work on partial lines.
Here is an example, to replace the selected text with the output of "date":
:vmap _a <Esc>`>a<CR><Esc>`<i<CR><Esc>!!date<CR>kJJ
(In the <> notation |<>|, when typing it you should type it literally; you
need to remove the 'B' and '<' flags from 'cpoptions')
What this does is:
<Esc> stop Visual mode
`> go to the end of the Visual area
a<CR><Esc> break the line after the Visual area
`< jump to the start of the Visual area
i<CR><Esc> break the line before the Visual area
!!date<CR> filter the Visual text through date
kJJ Join the lines back together
*visual-search*
Here is an idea for a mapping that makes it possible to do a search for the
selected text:
:vmap X y/<C-R>"<CR>
(In the <> notation |<>|, when typing it you should type it literally; you
need to remove the 'B' and '<' flags from 'cpoptions')
Note that special characters (like '.' and '*') will cause problems.
1. fo<C-v>3jISTRING<ESC> *v_b_I_example*
abcdefghijklmnSTRINGopqrstuvwxyz
abc STRING defghijklmnopqrstuvwxyz
abcdef ghi STRING jklmnopqrstuvwxyz
abcdefghijklmnSTRINGopqrstuvwxyz
2. fo<C-v>3j$ASTRING<ESC> *v_b_A_example*
abcdefghijklmnopqrstuvwxyzSTRING
abc defghijklmnopqrstuvwxyzSTRING
abcdef ghi jklmnopqrstuvwxyzSTRING
abcdefghijklmnopqrstuvwxyzSTRING
3. fo<C-v>3j3l<.. *v_b_<_example*
abcdefghijklmnopqrstuvwxyz
abc defghijklmnopqrstuvwxyz
abcdef ghi jklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
4. fo<C-v>3j>.. *v_b_>_example*
abcdefghijklmn opqrstuvwxyz
abc defghijklmnopqrstuvwxyz
abcdef ghi jklmnopqrstuvwxyz
abcdefghijklmn opqrstuvwxyz
5. fo<C-v>5l3jrX *v_b_r_example*
abcdefghijklmnXXXXXXuvwxyz
abc XXXXXXhijklmnopqrstuvwxyz
abcdef ghi XXXXXX jklmnopqrstuvwxyz
abcdefghijklmnXXXXXXuvwxyz
==============================================================================
8. Select mode *Select* *Select-mode*
Select mode looks like Visual mode, but the commands accepted are quite
different. This resembles the selection mode in Microsoft Windows.
When the 'showmode' option is set, "-- SELECT --" is shown in the last line.
Entering Select mode:
- Using the mouse to select an area, and 'selectmode' contains "mouse".
'mouse' must also contain a flag for the current mode.
- Using a non-printable movement command, with the Shift key pressed, and
'selectmode' contains "key". For example: <S-Left> and <S-End>. 'keymodel'
must also contain "startsel".
- Using "v", "V" or CTRL-V command, and 'selectmode' contains "cmd".
- Using "gh", "gH" or "g_CTRL-H" command in Normal mode.
- From Visual mode, press CTRL-G. *v_CTRL-G*
Commands in Select mode:
- Printable characters, <NL> and <CR> cause the selection to be deleted, and
Vim enters Insert mode. The typed character is inserted.
- Non-printable movement commands, with the Shift key pressed, extend the
selection. 'keymodel' must include "startsel".
- Non-printable movement commands, with the Shift key NOT pressed, stop Select
mode. 'keymodel' must include "stopsel".
- ESC stops Select mode.
- CTRL-O switches to Visual mode for the duration of one command. *v_CTRL-O*
- CTRL-G switches to Visual mode.
Otherwise, typed characters are handled as in Visual mode.
When using an operator in Select mode, and the selection is linewise, the
selected lines are operated upon, but like in characterwise selection. For
example, when a whole line is deleted, it can later be pasted halfway a line.
*gV* *v_gV*
gV Avoid the automatic reselection of the Visual area
after a Select mode mapping or menu has finished.
Put this just before the end of the mapping or menu.
At least it should be after any operations on the
selection.
*gh*
gh Start Select mode, characterwise. This is like "v",
but starts Select mode instead of Visual mode.
Mnemonic: "get highlighted".
*gH*
gH Start Select mode, linewise. This is like "V",
but starts Select mode instead of Visual mode.
Mnemonic: "get Highlighted".
*g_CTRL-H*
g CTRL-H Start Select mode, blockwise. This is like CTRL-V,
but starts Select mode instead of Visual mode.
Mnemonic: "get Highlighted".
top - main help file
*Cmdline-mode* *Command-line-mode*
Command-line mode *Cmdline* *Command-line* *mode-cmdline* *:*
Command-line mode is used to enter Ex commands (":"), search patterns
("/" and "?"), and filter commands ("!").
Basic command line editing is explained in chapter 20 of the user manual
|usr_20.txt|.
1. Command-line editing |cmdline-editing|
2. Command-line completion |cmdline-completion|
3. Ex command-lines |cmdline-lines|
4. Ex command-line ranges |cmdline-ranges|
5. Ex command-line flags |ex-flags|
6. Ex special characters |cmdline-special|
7. Command-line window |cmdline-window|
==============================================================================
1. Command-line editing *cmdline-editing*
Normally characters are inserted in front of the cursor position. You can
move around in the command-line with the left and right cursor keys. With the
<Insert> key, you can toggle between inserting and overstriking characters.
{Vi: can only alter the last character in the line}
Note that if your keyboard does not have working cursor keys or any of the
other special keys, you can use ":cnoremap" to define another key for them.
For example, to define tcsh style editing keys: *tcsh-style*
:cnoremap <C-A> <Home>
:cnoremap <C-F> <Right>
:cnoremap <C-B> <Left>
:cnoremap <Esc>b <S-Left>
:cnoremap <Esc>f <S-Right>
(<> notation |<>|; type all this literally)
*cmdline-too-long*
When the command line is getting longer than what fits on the screen, only the
part that fits will be shown. The cursor can only move in this visible part,
thus you cannot edit beyond that.
*cmdline-history* *history*
The command-lines that you enter are remembered in a history table. You can
recall them with the up and down cursor keys. There are actually five
history tables:
- one for ':' commands
- one for search strings
- one for expressions
- one for input lines, typed for the |input()| function.
- one for debug mode commands
These are completely separate. Each history can only be accessed when
*c_CTRL-V*
CTRL-V Insert next non-digit literally. Up to three digits form the
decimal value of a single byte. The non-digit and the three
digits are not considered for mapping. This works the same
way as in Insert mode (see above, |i_CTRL-V|).
Note: Under Windows CTRL-V is often mapped to paste text.
Use CTRL-Q instead then.
*c_CTRL-Q*
CTRL-Q Same as CTRL-V. But with some terminals it is used for
control flow, it doesn't work then.
*c_<Left>* *c_Left*
<Left> cursor left
*c_<Right>* *c_Right*
<Right> cursor right
*c_<S-Left>*
<S-Left> or <C-Left> *c_<C-Left>*
cursor one WORD left
*c_<S-Right>*
<S-Right> or <C-Right> *c_<C-Right>*
cursor one WORD right
CTRL-B or <Home> *c_CTRL-B* *c_<Home>* *c_Home*
cursor to beginning of command-line
CTRL-E or <End> *c_CTRL-E* *c_<End>* *c_End*
cursor to end of command-line
*c_<LeftMouse>*
<LeftMouse> Move the cursor to the position of the mouse click.
*c_<Insert>* *c_Insert*
<Insert> Toggle between insert and overstrike. {not in Vi}
*c_CTRL-R_CTRL-R* *c_<C-R>_<C-R>*
*c_CTRL-R_CTRL-O* *c_<C-R>_<C-O>*
*c_CTRL-Y*
CTRL-Y When there is a modeless selection, copy the selection into
the clipboard. |modeless-selection|
If there is no selection CTRL-Y is inserted as a character.
*c_<Up>* *c_Up*
<Up> recall older command-line from history, whose beginning
matches the current command-line (see below).
{not available when compiled without the |+cmdline_hist|
feature}
*c_<Down>* *c_Down*
<Down> recall more recent command-line from history, whose beginning
matches the current command-line (see below).
{not available when compiled without the |+cmdline_hist|
feature}
*c_<S-Up>* *c_<PageUp>*
<S-Up> or <PageUp>
recall older command-line from history
{not available when compiled without the |+cmdline_hist|
feature}
*c_<S-Down>* *c_<PageDown>*
<S-Down> or <PageDown>
recall more recent command-line from history
{not available when compiled without the |+cmdline_hist|
feature}
*c_CTRL-_*
CTRL-_ a - switch between Hebrew and English keyboard mode, which is
private to the command-line and not related to hkmap.
This is useful when Hebrew text entry is required in the
command-line, searches, abbreviations, etc. Applies only if
Vim is compiled with the |+rightleft| feature and the
'allowrevins' option is set.
See |rileft.txt|.
b - switch between Farsi and English keyboard mode, which is
private to the command-line and not related to fkmap. In
Farsi keyboard mode the characters are inserted in reverse
insert manner. This is useful when Farsi text entry is
required in the command-line, searches, abbreviations, etc.
Applies only if Vim is compiled with the |+farsi| feature.
See |farsi.txt|.
*c_CTRL-^*
CTRL-^ Toggle the use of language |:lmap| mappings and/or Input
Method.
When typing a pattern for a search command and 'imsearch' is
not -1, VAL is the value of 'imsearch', otherwise VAL is the
value of 'iminsert'.
When language mappings are defined:
- If VAL is 1 (langmap mappings used) it becomes 0 (no langmap
mappings used).
- If VAL was not 1 it becomes 1, thus langmap mappings are
enabled.
When no language mappings are defined:
- If VAL is 2 (Input Method is used) it becomes 0 (no input
method used)
- If VAL has another value it becomes 2, thus the Input Method
is enabled.
These language mappings are normally used to type characters
that are different from what the keyboard produces. The
'keymap' option can be used to install a whole number of them.
When entering a command line, langmap mappings are switched
off, since you are expected to type a command. After
switching it on with CTRL-^, the new state is not used again
for the next command or Search pattern.
{not in Vi}
*c_CTRL-]*
CTRL-] Trigger abbreviation, without inserting a character. {not in
Vi}
For Emacs-style editing on the command-line see |emacs-keys|.
The <Up> and <Down> keys take the current command-line as a search string.
The beginning of the next/previous command-lines are compared with this
string. The first line that matches is the new command-line. When typing
these two keys repeatedly, the same string is used again. For example, this
can be used to find the previous substitute command: Type ":s" and then <Up>.
The same could be done by typing <S-Up> a number of times until the desired
command-line is shown. (Note: the shifted arrow keys do not work on all
terminals)
*:his* *:history*
:his[tory] Print the history of last entered commands.
{not in Vi}
{not available when compiled without the |+cmdline_hist|
feature}
:his[tory] [{name}] [{first}][, [{last}]]
List the contents of history {name} which can be:
c[md] or : command-line history
s[earch] or / search string history
e[xpr] or = expression register history
*c_CTRL-D*
CTRL-D List names that match the pattern in front of the cursor.
When showing file names, directories are highlighted (see
'highlight' option). Names where 'suffixes' matches are moved
to the end.
The 'wildoptions' option can be set to "tagfile" to list the
file of matching tags.
*c_CTRL-I* *c_wildchar* *c_<Tab>*
'wildchar' option
A match is done on the pattern in front of the cursor. The
match (if there are several, the first match) is inserted
in place of the pattern. (Note: does not work inside a
macro, because <Tab> or <Esc> are mostly used as 'wildchar',
and these have a special meaning in some macros.) When typed
again and there were multiple matches, the next
match is inserted. After the last match, the first is used
again (wrap around).
The behavior can be changed with the 'wildmode' option.
*c_CTRL-N*
CTRL-N After using 'wildchar' which got multiple matches, go to next
match. Otherwise recall more recent command-line from history.
<S-Tab> *c_CTRL-P* *c_<S-Tab>*
CTRL-P After using 'wildchar' which got multiple matches, go to
previous match. Otherwise recall older command-line from
history. <S-Tab> only works with the GUI, on the Amiga and
with MS-DOS.
*c_CTRL-A*
CTRL-A All names that match the pattern in front of the cursor are
inserted.
*c_CTRL-L*
CTRL-L A match is done on the pattern in front of the cursor. If
there is one match, it is inserted in place of the pattern.
If there are multiple matches the longest common part is
inserted in place of the pattern. If the result is shorter
than the pattern, no completion is done.
When 'incsearch' is set, entering a search pattern for "/" or
"?" and the current match is displayed then CTRL-L will add
one character from the end of the current match. If
'ignorecase' and 'smartcase' are set and the command line has
no uppercase characters, the added character is converted to
lowercase.
The 'wildchar' option defaults to <Tab> (CTRL-E when in Vi compatible mode; in
a previous version <Esc> was used). In the pattern standard wildcards '*' and
'?' are accepted when matching file names. '*' matches any string, '?'
matches exactly one character.
If you like tcsh's autolist completion, you can use this mapping:
:cnoremap X <C-L><C-D>
(Where X is the command key to use, <C-L> is CTRL-L and <C-D> is CTRL-D)
This will find the longest match and then list all matching files.
If you like tcsh's autolist completion, you can use the 'wildmode' option to
emulate it. For example, this mimics autolist=ambiguous:
:set wildmode=longest,list
This will find the longest match with the first 'wildchar', then list all
matching files with the next.
*suffixes*
For file name completion you can use the 'suffixes' option to set a priority
between files with almost the same name. If there are multiple matches,
those files with an extension that is in the 'suffixes' option are ignored.
The default is ".bak,~,.o,.h,.info,.swp,.obj", which means that files ending
in ".bak", "~", ".o", ".h", ".info", ".swp" and ".obj" are sometimes ignored.
An empty entry, two consecutive commas, match a file name that does not
contain a ".", thus has no suffix. This is useful to ignore "prog" and prefer
"prog.c".
Examples:
pattern: files: match:
test* test.c test.h test.o test.c
test* test.h test.o test.h and test.o
test* test.i test.h test.c test.i and test.c
It is impossible to ignore suffixes with two dots.
If there is more than one matching file (after ignoring the ones matching
the 'suffixes' option) the first file name is inserted. You can see that
there is only one match when you type 'wildchar' twice and the completed
match stays the same. You can get to the other matches by entering
'wildchar', CTRL-N or CTRL-P. All files are included, also the ones with
extensions matching the 'suffixes' option.
To completely ignore files with some extension use 'wildignore'.
To match only files that end at the end of the typed text append a "$". For
example, to match only files that end in ".c":
:e *.c$
This will not match a file ending in ".cpp". Without the "$" it does match.
The old value of an option can be obtained by hitting 'wildchar' just after
the '='. For example, typing 'wildchar' after ":set dir=" will insert the
current value of 'dir'. This overrules file name completion for the options
that take a file name.
If you would like using <S-Tab> for CTRL-P in an xterm, put this command in
your .cshrc:
xmodmap -e "keysym Tab = Tab Find"
And this in your .vimrc:
:cmap <Esc>[1~ <C-P>
==============================================================================
3. Ex command-lines *cmdline-lines*
The Ex commands have a few specialties:
*:quote* *:comment*
'"'' at the start of a line causes the whole line to be ignored. '"''
after a command causes the rest of the line to be ignored. This can be used
to add comments. Example:
:set ai "set 'autoindent' option
It is not possible to add a comment to a shell command ":!cmd" or to the
":map" command and a few others, because they see the '"'' as part of their
argument. This is mentioned where the command is explained.
*:bar* *:\bar*
'|' can be used to separate commands, so you can give multiple commands in one
line. If you want to use '|' in an argument, precede it with '\'.
These commands see the '|' as their argument, and can therefore not be
followed by another Vim command:
:argdo
:autocmd
:bufdo
:command
:cscope
:debug
:folddoopen
:folddoclosed
:function
:global
:help
:helpfind
:lcscope
:make
:normal
:perl
:perldo
:promptfind
:promptrepl
:pyfile
:python
:registers
:read !
:scscope
:sign
:tcl
:tcldo
:tclfile
:vglobal
:windo
:write !
:[range]!
a user defined command without the "-bar" argument |:command|
Note that this is confusing (inherited from Vi): With ":g" the '|' is included
in the command, with ":s" it is not.
To be able to use another command anyway, use the ":execute" command.
Example (append the output of "ls" and jump to the first line):
:execute 'r !ls' | '[
There is one exception: When the 'b' flag is present in 'cpoptions', with the
":map" and ":abbr" commands and friends CTRL-V needs to be used instead of
'\'. You can also use "<Bar>" instead. See also |map_bar|.
Examples:
:!ls | wc view the output of two commands
:r !ls | wc insert the same output in the text
:%g/foo/p|> moves all matching lines one shiftwidth
:%s/foo/bar/|> moves one line one shiftwidth
:map q 10^V| map "q" to "10|"
:map q 10\| map \ l map "q" to "10\" and map "\" to "l"
(when 'b' is present in 'cpoptions')
You can also use <NL> to separate commands in the same way as with '|'. To
insert a <NL> use CTRL-V CTRL-J. "^@" will be shown. Using '|' is the
preferred method. But for external commands a <NL> must be used, because a
'|' is included in the external command. To avoid the special meaning of <NL>
it must be preceded with a backslash. Example:
:r !date<NL>-join
This reads the current date into the file and joins it with the previous line.
Note that when the command before the '|' generates an error, the following
commands will not be executed.
*:_!*
The '!' (bang) character after an Ex command makes the command behave in a
different way. The '!' should be placed immediately after the command, without
any blanks in between. If you insert blanks the '!' will be seen as an
argument for the command, which has a different meaning. For example:
:w! name write the current buffer to file "name", overwriting
any existing file
:w !name send the current buffer as standard input to command
"name"
==============================================================================
4. Ex command-line ranges *cmdline-ranges* *[range]* *E16*
Some Ex commands accept a line range in front of them. This is noted as
[range]. It consists of one or more line specifiers, separated with ',' or
';'.
The basics are explained in section |10.3| of the user manual.
*:,* *:;*
When separated with ';' the cursor position will be set to that line
before interpreting the next line specifier. This doesn't happen for ','.
Examples:
4,/this line/
from line 4 till match with "this line" after the cursor line.
5;/that line/
from line 5 till match with "that line" after line 5.
The default line specifier for most commands is the cursor position, but the
commands ":write" and ":global" have the whole file (1,$) as default.
If more line specifiers are given than required for the command, the first
one(s) will be ignored.
\# #
\\# \#
*filename-modifiers*
*:_%:* *::8* *::p* *::.* *::~* *::h* *::t* *::r* *::e* *::s* *::gs*
*%:8* *%:p* *%:.* *%:~* *%:h* *%:t* *%:r* *%:e* *%:s* *%:gs*
The file name modifiers can be used after "%", "#", "#n", "<cfile>", "<sfile>",
"<afile>" or "<abuf>". They are also used with the |fnamemodify()| function.
These are not available when Vim has been compiled without the |+modify_fname|
feature.
These modifiers can be given, in this order:
:p Make file name a full path. Must be the first modifier. Also
changes "~/" (and "~user/" for Unix and VMS) to the path for
the home directory. If the name is a directory a path
separator is added at the end. For a file name that does not
exist and does not have an absolute path the result is
unpredictable.
:8 Converts the path to 8.3 short format (currently only on
win32). Will act on as much of a path that is an existing
path.
:~ Reduce file name to be relative to the home directory, if
possible. File name is unmodified if it is not below the home
directory.
:. Reduce file name to be relative to current directory, if
possible. File name is unmodified if it is not below the
current directory.
For maximum shortness, use ":~:.".
:h Head of the file name (the last component and any separators
removed). Cannot be used with :e, :r or :t.
Can be repeated to remove several components at the end.
When the file name ends in a path separator, only the path
separator is removed. Thus ":p:h" on a directory name results
on the directory name itself (without trailing slash).
When the file name is an absolute path (starts with "/" for
Unix; "x:\" for MS-DOS, WIN32, OS/2; "drive:" for Amiga), that
part is not removed. When there is no head (path is relative
to current directory) the result is empty.
:t Tail of the file name (last component of the name). Must
precede any :r or :e.
*extension-removal* *:_%<*
If a "<" is appended to "%", "#", "#n" or "CTRL-V p" the extension of the file
name is removed (everything after and including the last '.' in the file
name). This is included for backwards compatibility with version 3.0, the
":r" form is preferred. Examples:
% current file name
%< current file name without extension
# alternate file name for current window
#< idem, without extension
#31 alternate file number 31
#31< idem, without extension
<cword> word under the cursor
<cWORD> WORD under the cursor (see |WORD|)
<cfile> path name under the cursor
<cfile>< idem, without extension
Note: Where a file name is expected wildcards expansion is done. On Unix the
shell is used for this, unless it can be done internally (for speed).
Backticks also work, like in
:n `echo *.c`
(backtick expansion is not possible in |restricted-mode|)
But expansion is only done if there are any wildcards before expanding the
'%', '#', etc.. This avoids expanding wildcards inside a file name. If you
want to expand the result of <cfile>, add a wildcard character to it.
Examples: (alternate file name is "?readme?")
command expands to
:e # :e ?readme?
:e `ls #` :e {files matching "?readme?"}
:e #.* :e {files matching "?readme?.*"}
:cd <cfile> :cd {file name under cursor}
:cd <cfile>* :cd {file name under cursor plus "*" and then expanded}
When the expanded argument contains a "!" and it is used for a shell command
(":!cmd", ":r !cmd" or ":w !cmd"), the "!" is escaped with a backslash to
avoid it being expanded into a previously used command. When the 'shell'
option contains "sh", this is done twice, to avoid the shell trying to expand
the "!".
*filename-backslash*
For filesystems that use a backslash as directory separator (MS-DOS, Windows,
OS/2), it's a bit difficult to recognize a backslash that is used to escape
the special meaning of the next character. The general rule is: If the
backslash is followed by a normal file name character, it does not have a
special meaning. Therefore "\file\foo" is a valid file name, you don't have
to type the backslash twice.
An exception is the '$' sign. It is a valid character in a file name. But
to avoid a file name like "$home" to be interpreted as an environment variable,
it needs to be preceded by a backslash. Therefore you need to use "/\$home"
for the file "$home" in the root directory. A few examples:
FILE NAME INTERPRETED AS
$home expanded to value of environment var $home
\$home file "$home" in current directory
/\$home file "$home" in root directory
\\$home file "\\", followed by expanded $home
==============================================================================
6. Command-line window *cmdline-window* *cmdwin*
*command-line-window*
In the command-line window the command line can be edited just like editing
text in any window. It is a special kind of window, because you cannot leave
it in a normal way.
{not available when compiled without the |+cmdline_hist| or |+vertsplit|
feature}
EDIT
You can now use commands to move around and edit the text in the window. Both
in Normal mode and Insert mode.
It is possible to use ":", "/" and other commands that use the command-line,
but it's not possible to open another command-line window then. There is no
nesting.
*E11*
The command-line window is not a normal window. It is not possible to move to
another window or edit another buffer. All commands that would do this are
disabled in the command-line window. Of course it _is_ possible to execute
any command that you entered in the command-line window. Other text edits are
discarded when closing the window.
CLOSE *E199*
There are several ways to leave the command-line window:
<CR> Execute the command-line under the cursor. Works both in
Insert and in Normal mode.
CTRL-C Continue in Command-line mode. The command-line under the
cursor is used as the command-line. Works both in Insert and
in Normal mode. ":close" also works. There is no redraw,
thus the window will remain visible.
:quit Discard the command line and go back to Normal mode.
":exit", ":xit" and CTRL-\ CTRL-N also work.
:qall Quit Vim, unless there are changes in some buffer.
:qall! Quit Vim, discarding changes to any buffer.
Once the command-line window is closed the old window sizes are restored. The
executed command applies to the window and buffer where the command-line was
started from. This works as if the command-line window was not there, except
that there will be an extra screen redraw.
The buffer used for the command-line window is deleted. Any changes to lines
other than the one that is executed with <CR> are lost.
If you would like to execute the command under the cursor and then have the
command-line window open again, you may find this mapping useful:
:autocmd CmdwinEnter * map <buffer> <F5> <CR>q:
VARIOUS
The command-line window cannot be used:
- when there already is a command-line window (no nesting)
- for entering an encryption key or when using inputsecret()
- when Vim was not compiled with the |+vertsplit| feature
Some options are set when the command-line window is opened:
'filetype' "vim", when editing an Ex command-line; this starts Vim syntax
highlighting if it was enabled
'rightleft' off
'modifiable' on
'buftype' "nofile"
'swapfile' off
It is allowed to write the buffer contents to a file. This is an easy way to
save the command-line history and read it back later.
If the 'wildchar' option is set to <Tab>, and the command-line window is used
for an Ex command, then two mappings will be added to use <Tab> for completion
in the command-line window, like this:
:imap <buffer> <Tab> <C-X><C-V>
:nmap <buffer> <Tab> a<C-X><C-V>
Note that hitting <Tab> in Normal mode will do completion on the next
character. That way it works at the end of the line.
If you don't want these mappings, disable them with:
au CmdwinEnter [:>] iunmap <Tab>
au CmdwinEnter [:>] nunmap <Tab>
You could put these lines in your vimrc file.
While in the command-line window you cannot use the mouse to put the cursor in
another window, or drag statuslines of other windows. You can drag the
statusline of the command-line window itself and the statusline above it.
Thus you can resize the command-line window, but not others.
AUTOCOMMANDS
Two autocommand events are used: |CmdwinEnter| and |CmdwinLeave|. Since this
window is of a special type, the WinEnter, WinLeave, BufEnter and BufLeave
events are not triggered. You can use the Cmdwin events to do settings
specifically for the command-line window. Be careful not to cause side
effects!
Example:
:au CmdwinEnter : let b:cpt_save = &cpt | set cpt=.
*cmdwin-char*
The character used for the pattern indicates the type of command-line:
: normal Ex command
> debug mode command |debug-mode|
/ forward search string
? backward search string
= expression for "= |expr-register|
@ string for |input()|
- text for |:insert| or |:append|
top - main help file
Options *options*
1. Setting options |set-option|
2. Automatically setting options |auto-setting|
3. Options summary |option-summary|
For an overview of options see help.txt |option-list|.
Vim has a number of internal variables and switches which can be set to
achieve special effects. These options come in three forms:
boolean can only be on or off *boolean* *toggle*
number has a numeric value
string has a string value
==============================================================================
1. Setting options *set-option* *E764*
*:se* *:set*
:se[t] Show all options that differ from their default value.
:se[t] all Show all but terminal options.
:se[t] termcap Show all terminal options. Note that in the GUI the
key codes are not shown, because they are generated
internally and can't be changed. Changing the terminal
codes in the GUI is not useful either...
*E518* *E519*
:se[t] {option}? Show value of {option}.
:se[t] {option} Toggle option: set, switch it on.
Number option: show value.
String option: show value.
:se[t] no{option} Toggle option: Reset, switch it off.
*:set-!* *:set-inv*
:se[t] {option}! or
:se[t] inv{option} Toggle option: Invert value. {not in Vi}
*:set-verbose*
When 'verbose' is non-zero, displaying an option value will also tell where it
was last set. Example:
:verbose set shiftwidth cindent?
shiftwidth=4
Last set from modeline
cindent
Last set from /usr/local/share/vim/vim60/ftplugin/c.vim
This is only done when specific option values are requested, not for ":verbose
set all" or ":verbose set" without an argument.
When the option was set by hand there is no "Last set" message.
When the option was set while executing a function, user command or
autocommand, the script in which it was defined is reported.
Note that an option may also have been set as a side effect of setting
'compatible'.
A few special texts:
Last set from modeline
Option was set in a |modeline|.
Last set from --cmd argument
Option was set with command line argument |--cmd| or +.
*:set-termcap* *E522*
For {option} the form "t_xx" may be used to set a terminal option. This will
override the value from the termcap. You can then use it in a mapping. If
the "xx" part contains special characters, use the <t_xx> form:
:set <t_#4>=^[Ot
This can also be used to translate a special code for a normal key. For
example, if Alt-b produces <Esc>b, use this:
:set <M-b>=^[b
(the ^[ is a real <Esc> here, use CTRL-V <Esc> to enter it)
The advantage over a mapping is that it works in all situations.
You can define any key codes, e.g.:
:set t_xy=^[foo;
There is no warning for using a name that isn't recognized. You can map these
codes as you like:
:map <t_xy> something
*E846*
When a key code is not set, it's like it does not exist. Trying to get its
value will result in an error:
:set t_kb=
:set t_kb
E846: Key code not set: t_kb
The t_xx options cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
The listing from ":set" looks different from Vi. Long string options are put
at the end of the list. The number of options is quite large. The output of
"set all" probably does not fit on the screen, causing Vim to give the
|more-prompt|.
*option-backslash*
To include white space in a string option value it has to be preceded with a
backslash. To include a backslash you have to use two. Effectively this
means that the number of backslashes in an option value is halved (rounded
down).
A few examples:
:set tags=tags\ /usr/tags results in "tags /usr/tags"
:set tags=tags\\,file results in "tags\,file"
:set tags=tags\\\ file results in "tags\ file"
The "|" character separates a ":set" command from a following command. To
include the "|" in the option value, use "\|" instead. This example sets the
'titlestring' option to "hi|there":
:set titlestring=hi\|there
This sets the 'titlestring' option to "hi" and 'iconstring' to "there":
:set titlestring=hi|set iconstring=there
Similarly, the double quote character starts a comment. To include the '"'' in
the option value, use '\"' instead. This example sets the 'titlestring'
option to 'hi "there"':
:set titlestring=hi\ \"there\"
For MS-DOS and WIN32 backslashes in file names are mostly not removed. More
precise: For options that expect a file name (those where environment
variables are expanded) a backslash before a normal file name character is not
removed. But a backslash before a special character (space, backslash, comma,
etc.) is used like explained above.
There is one special situation, when the value starts with "\\":
:set dir=\\machine\path results in "\\machine\path"
:set dir=\\\\machine\\path results in "\\machine\path"
:set dir=\\path\\file results in "\\path\file" (wrong!)
For the first one the start is kept, but for the second one the backslashes
are halved. This makes sure it works both when you expect backslashes to be
halved and when you expect the backslashes to be kept. The third gives a
*add-option-flags* *remove-option-flags*
*E539* *E550* *E551* *E552*
Some options are a list of flags. When you want to add a flag to such an
option, without changing the existing ones, you can do it like this:
:set guioptions+=a
Remove a flag from an option like this:
:set guioptions-=a
This removes the 'a' flag from 'guioptions'.
Note that you should add or remove one flag at a time. If 'guioptions' has
the value "ab", using "set guioptions-=ba" won't work, because the string "ba"
doesn't appear.
*:setl* *:setlocal*
:setl[ocal] ... Like ":set" but set only the value local to the
current buffer or window. Not all options have a
local value. If the option does not have a local
value the global value is set.
With the "all" argument: display local values for all
local options.
Without argument: Display local values for all local
options which are different from the default.
When displaying a specific local option, show the
local value. For a global/local boolean option, when
the global value is being used, "--" is displayed
before the option name.
For a global option the global value is
shown (but that might change in the future).
{not in Vi}
:setl[ocal] {option}< Set the local value of {option} to its global value by
copying the value.
{not in Vi}
:se[t] {option}< Set the local value of {option} to its global value by
making it empty. Only makes sense for |global-local|
options.
{not in Vi}
*:setg* *:setglobal*
:setg[lobal] ... Like ":set" but set only the global value for a local
option without changing the local value.
When displaying an option, the global value is shown.
With the "all" argument: display global values for all
local options.
Without argument: display global values for all local
options which are different from the default.
{not in Vi}
For buffer-local and window-local options:
Command global value local value
:set option=value set set
:setlocal option=value - set
:setglobal option=value set -
:set option? - display
:setlocal option? - display
:setglobal option? display -
*option-window* *optwin*
:bro[wse] se[t] *:set-browse* *:browse-set* *:opt* *:options*
:opt[ions] Open a window for viewing and setting all options.
Options are grouped by function.
Offers short help for each option. Hit <CR> on the
short help to open a help window with more help for
the option.
Modify the value of the option and hit <CR> on the
"set" line to set the new value. For window and
buffer specific options, the last accessed window is
used to set the option value in, unless this is a help
window, in which case the window below help window is
used (skipping the option-window).
{not available when compiled without the |+eval| or
|+autocmd| features}
*$HOME*
Using "~" is like using "$HOME", but it is only recognized at the start of an
option and after a space or comma.
On Unix systems "~user" can be used too. It is replaced by the home directory
of user "user". Example:
:set path=~mool/include,/usr/include,.
On Unix systems the form "${HOME}" can be used too. The name between {} can
contain non-id characters then. Note that if you want to use this for the
"gf" command, you need to add the '{' and '}' characters to 'isfname'.
NOTE: expanding environment variables and "~/" is only done with the ":set"
command, not when assigning a value to an option with ":let".
Note the maximum length of an expanded option is limited. How much depends on
the system, mostly it is something like 256 or 1024 characters.
*:fix* *:fixdel*
:fix[del] Set the value of 't_kD':
't_kb' is 't_kD' becomes
CTRL-? CTRL-H
not CTRL-? CTRL-?
(CTRL-? is 0177 octal, 0x7f hex) {not in Vi}
If your delete key terminal code is wrong, but the
code for backspace is alright, you can put this in
your .vimrc:
:fixdel
This works no matter what the actual code for
backspace is.
If the backspace key terminal code is wrong you can
use this:
:if &term == "termname"
: set t_kb=^V<BS>
: fixdel
:endif
Where "^V" is CTRL-V and "<BS>" is the backspace key
*Linux-backspace*
Note about Linux: By default the backspace key
produces CTRL-?, which is wrong. You can fix it by
putting this line in your rc.local:
echo "keycode 14 = BackSpace" | loadkeys
*NetBSD-backspace*
Note about NetBSD: If your backspace doesn't produce
the right code, try this:
xmodmap -e "keycode 22 = BackSpace"
If this works, add this in your .Xmodmap file:
keysym 22 = BackSpace
You need to restart for this to take effect.
==============================================================================
2. Automatically setting options *auto-setting*
Besides changing options with the ":set" command, there are three alternatives
to set options automatically for one or more files:
1. When starting Vim initializations are read from various places. See
|initialization|. Most of them are performed for all editing sessions,
and some of them depend on the directory where Vim is started.
You can create an initialization file with |:mkvimrc|, |:mkview| and
|:mksession|.
2. If you start editing a new file, the automatic commands are executed.
This can be used to set options for files matching a particular pattern and
many other things. See |autocommand|.
3. If you start editing a new file, and the 'modeline' option is on, a
number of lines at the beginning and end of the file are checked for
modelines. This is explained here.
The white space before {vi:|vim:|ex:} is required. This minimizes the chance
that a normal word like "lex:" is caught. There is one exception: "vi:" and
"vim:" can also be at the start of the line (for compatibility with version
3.0). Using "ex:" at the start of the line will be ignored (this could be
short for "example:").
*modeline-local*
The options are set like with ":setlocal": The new value only applies to the
buffer and window that contain the file. Although it's possible to set global
options from a modeline, this is unusual. If you have two windows open and
the files in it set the same global option to a different value, the result
depends on which one was opened last.
When editing a file that was already loaded, only the window-local options
from the modeline are used. Thus if you manually changed a buffer-local
option after opening the file, it won't be changed if you edit the same buffer
in another window. But window-local options will be set.
*modeline-version*
If the modeline is only to be used for some versions of Vim, the version
number can be specified where "vim:" is used:
vim{vers}: version {vers} or later
vim<{vers}: version before {vers}
vim={vers}: version {vers}
vim>{vers}: version after {vers}
{vers} is 600 for Vim 6.0 (hundred times the major version plus minor).
For example, to use a modeline only for Vim 6.0 and later:
/* vim600: set foldmethod=marker: */
To use a modeline for Vim before version 5.7:
/* vim<570: set sw=4: */
There can be no blanks between "vim" and the ":".
The number of lines that are checked can be set with the 'modelines' option.
If 'modeline' is off or 'modelines' is 0 no lines are checked.
Note that for the first form all of the rest of the line is used, thus a line
like:
/* vi:ts=4: */
will give an error message for the trailing "*/". This line is OK:
/* vi:set ts=4: */
If an error is detected the rest of the line is skipped.
If you want to include a ':' in a set command precede it with a '\'. The
backslash in front of the ':' will be removed. Example:
/* vi:set dir=c\:\tmp: */
This sets the 'dir' option to "c:\tmp". Only a single backslash before the
':' is removed. Thus to include "\:" you have to specify "\\:".
No other commands than "set" are supported, for security reasons (somebody
might create a Trojan horse text file with modelines). And not all options
can be set. For some options a flag is set, so that when it's used the
|sandbox| is effective. Still, there is always a small risk that a modeline
causes trouble. E.g., when some joker sets 'textwidth' to 5 all your lines
are wrapped unexpectedly. So disable modelines before editing untrusted text.
The mail ftplugin does this, for example.
Hint: If you would like to do something else than setting an option, you could
define an autocommand that checks the file for a specific string. For
example:
au BufReadPost * if getline(1) =~ "VAR" | call SetVar() | endif
And define a function SetVar() that does something with the line containing
"VAR".
==============================================================================
3. Options summary *option-summary*
In the list below all the options are mentioned with their full name and with
an abbreviation if there is one. Both forms may be used.
In this document when a boolean option is "set" that means that ":set option"
is entered. When an option is "reset", ":set nooption" is used.
For some options there are two default values: The "Vim default", which is
used when 'compatible' is not set, and the "Vi default", which is used when
'compatible' is set.
Most options are the same in all windows and buffers. There are a few that
are specific to how the text is presented in a window. These can be set to a
different value in each window. For example the 'list' option can be set in
one window and reset in another for the same text, giving both types of view
at the same time. There are a few options that are specific to a certain
file. These can have a different value for each file or buffer. For example
the 'textwidth' option can be 78 for a normal text file and 0 for a C
program.
global one option for all buffers and windows
local to window each window has its own copy of this option
local to buffer each buffer has its own copy of this option
When creating a new window the option values from the currently active window
are used as a default value for the window-specific options. For the
buffer-specific options this depends on the 's' and 'S' flags in the
'cpoptions' option. If 's' is included (which is the default) the values for
buffer options are copied from the currently active buffer when a buffer is
first entered. If 'S' is present the options are copied each time the buffer
is entered, this is almost like having global options. If 's' and 'S' are not
present, the options are copied from the currently active buffer when the
buffer is created.
*E355*
A jump table for the options with a short description can be found at |Q_op|.
When off, the keyboard map toggles between Hebrew and English. This
is useful to start the Vim in native mode i.e. English (left-to-right
mode) and have default second language Farsi or Hebrew (right-to-left
mode). See |farsi.txt|.
*'ambiwidth'* *'ambw'*
'ambiwidth' 'ambw' string (default: "single")
global
{not in Vi}
{only available when compiled with the |+multi_byte|
feature}
Only effective when 'encoding' is "utf-8" or another Unicode encoding.
Tells Vim what to do with characters with East Asian Width Class
Ambiguous (such as Euro, Registered Sign, Copyright Sign, Greek
letters, Cyrillic letters).
There are currently two possible values:
"single": Use the same width as characters in US-ASCII. This is
expected by most users.
"double": Use twice the width of ASCII characters.
*E834* *E835*
The value "double" cannot be used if 'listchars' or 'fillchars'
contains a character that would be double width.
There are a number of CJK fonts for which the width of glyphs for
those characters are solely based on how many octets they take in
legacy/traditional CJK encodings. In those encodings, Euro,
Registered sign, Greek/Cyrillic letters are represented by two octets,
therefore those fonts have "wide" glyphs for them. This is also
true of some line drawing characters used to make tables in text
file. Therefore, when a CJK font is used for GUI Vim or
Vim is running inside a terminal (emulators) that uses a CJK font
(or Vim is run inside an xterm invoked with "-cjkwidth" option.),
this option should be set to "double" to match the width perceived
by Vim with the width of glyphs in the font. Perhaps it also has
to be set to "double" under CJK Windows 9x/ME or Windows 2k/XP
when the system locale is set to one of CJK locales. See Unicode
Standard Annex #11 http://www.unicode.org/reports/tr11.
*'arabicshape'* *'arshape'*
*'noarabicshape'* *'noarshape'*
'arabicshape' 'arshape' boolean (default on)
global
{not in Vi}
{only available when compiled with the |+arabic|
feature}
When on and 'termbidi' is off, the required visual character
corrections that need to take place for displaying the Arabic language
take affect. Shaping, in essence, gets enabled; the term is a broad
one which encompasses:
a) the changing/morphing of characters based on their location
within a word (initial, medial, final and stand-alone).
b) the enabling of the ability to compose characters
c) the enabling of the required combining of some characters
When disabled the display shows each character's true stand-alone
form.
Arabic is a complex language which requires other settings, for
further details see |arabic.txt|.
global
{not in Vi}
Like 'autowrite', but also used for commands ":edit", ":enew", ":quit",
":qall", ":exit", ":xit", ":recover" and closing the Vim window.
Setting this option also implies that Vim behaves like 'autowrite' has
been set.
*'background'* *'bg'*
'background' 'bg' string (default "dark" or "light")
global
{not in Vi}
When set to "dark", Vim will try to use colors that look good on a
dark background. When set to "light", Vim will try to use colors that
look good on a light background. Any other value is illegal.
Vim tries to set the default value according to the terminal used.
This will not always be correct.
Setting this option does not change the background color, it tells Vim
what the background color looks like. For changing the background
color, see |:hi-normal|.
When 'background' is set Vim will adjust the default color groups for
the new value. But the colors used for syntax highlighting will not
change. *g:colors_name*
When a color scheme is loaded (the "g:colors_name" variable is set)
setting 'background' will cause the color scheme to be reloaded. If
the color scheme adjusts to the value of 'background' this will work.
However, if the color scheme sets 'background' itself the effect may
be undone. First delete the "g:colors_name" variable when needed.
When setting 'background' to the default value with:
:set background&
Vim will guess the value. In the GUI this should work correctly,
in other cases Vim might not be able to guess the right value.
When starting the GUI, the default value for 'background' will be
"light". When the value is not set in the .gvimrc, and Vim detects
that the background is actually quite dark, 'background' is set to
"dark". But this happens only AFTER the .gvimrc file has been read
(because the window needs to be opened to find the actual background
color). To get around this, force the GUI window to be opened by
putting a ":gui" command in the .gvimrc file, before where the value
of 'background' is used (e.g., before ":syntax on").
Normally this option would be set in the .vimrc file. Possibly
depending on the terminal name. Example:
:if &term == "pcterm"
: set background=dark
:endif
When this option is set, the default settings for the highlight groups
will change. To use other settings, place ":highlight" commands AFTER
the setting of the 'background' option.
This option is also used in the "$VIMRUNTIME/syntax/syntax.vim" file
to select the colors for syntax highlighting. After changing this
option, you must load syntax.vim again to see the result. This can be
done with ":syntax on".
*'backspace'* *'bs'*
'backspace' 'bs' string (default "")
global
{not in Vi}
Influences the working of <BS>, <Del>, CTRL-W and CTRL-U in Insert
mode. This is a list of items, separated by commas. Each item allows
a way to backspace over something:
value effect
indent allow backspacing over autoindent
eol allow backspacing over line breaks (join lines)
start allow backspacing over the start of insert; CTRL-W and CTRL-U
stop once at the start of insert.
When the value is empty, Vi compatible backspacing is used.
For backwards compatibility with version 5.4 and earlier:
value effect
0 same as ":set backspace=" (Vi compatible)
1 same as ":set backspace=indent,eol"
2 same as ":set backspace=indent,eol,start"
See |:fixdel| if your <BS> or <Del> key does not do what you want.
*'backupcopy'* *'bkc'*
'backupcopy' 'bkc' string (Vi default for Unix: "yes", otherwise: "auto")
global
{not in Vi}
When writing a file and a backup is made, this option tells how it's
done. This is a comma separated list of words.
The main values are:
"yes" make a copy of the file and overwrite the original one
"no" rename the file and write a new one
"auto" one of the previous, what works best
Extra values that can be combined with the ones above are:
"breaksymlink" always break symlinks when writing
"breakhardlink" always break hardlinks when writing
Making a copy and overwriting the original file:
- Takes extra time to copy the file.
+ When the file has special attributes, is a (hard/symbolic) link or
has a resource fork, all this is preserved.
- When the file is a link the backup will have the name of the link,
not of the real file.
Renaming the file and writing a new one:
+ It's fast.
- Sometimes not all attributes of the file can be copied to the new
file.
- When the file is a link the new file will not be a link.
The "auto" value is the middle way: When Vim sees that renaming file
is possible without side effects (the attributes can be passed on and
the file is not a link) that is used. When problems are expected, a
copy will be made.
The "breaksymlink" and "breakhardlink" values can be used in
combination with any of "yes", "no" and "auto". When included, they
force Vim to always break either symbolic or hard links by doing
exactly what the "no" option does, renaming the original file to
become the backup and writing a new file in its place. This can be
useful for example in source trees where all the files are symbolic or
hard links and any changes should stay in the local source tree, not
be propagated back to the original source.
*crontab*
One situation where "no" and "auto" will cause problems: A program
that opens a file, invokes Vim to edit that file, and then tests if
the open file was changed (through the file descriptor) will check the
backup file instead of the newly created file. "crontab -e" is an
example.
When a copy is made, the original file is truncated and then filled
with the new text. This means that protection bits, owner and
symbolic links of the original file are unmodified. The backup file
however, is a new file, owned by the user who edited the file. The
group of the backup is set to the group of the original file. If this
fails, the protection bits for the group are made the same as for
others.
When the file is renamed this is the other way around: The backup has
the same attributes of the original file, and the newly written file
*'backupdir'* *'bdir'*
'backupdir' 'bdir' string (default for Amiga: ".,t:",
for MS-DOS and Win32: ".,c:/tmp,c:/temp"
for Unix: ".,~/tmp,~/")
global
{not in Vi}
List of directories for the backup file, separated with commas.
- The backup file will be created in the first directory in the list
where this is possible. The directory must exist, Vim will not
create it for you.
- Empty means that no backup file will be created ('patchmode' is
impossible!). Writing may fail because of this.
- A directory "." means to put the backup file in the same directory
as the edited file.
- A directory starting with "./" (or ".\" for MS-DOS et al.) means to
put the backup file relative to where the edited file is. The
leading "." is replaced with the path name of the edited file.
("." inside a directory name has no special meaning).
- Spaces after the comma are ignored, other spaces are considered part
of the directory name. To have a space at the start of a directory
name, precede it with a backslash.
- To include a comma in a directory name precede it with a backslash.
- A directory name may end in an '/'.
- Environment variables are expanded |:set_env|.
- Careful with '\' characters, type one before a space, type two to
get one in the option (see |option-backslash|), for example:
:set bdir=c:\\tmp,\ dir\\,with\\,commas,\\\ dir\ with\ spaces
- For backwards compatibility with Vim version 3.0 a '>' at the start
of the option is removed.
See also 'backup' and 'writebackup' options.
If you want to hide your backup files on Unix, consider this value:
:set backupdir=./.backup,~/.backup,.,/tmp
You must create a ".backup" directory in each directory and in your
home directory for this to work properly.
The use of |:set+=| and |:set-=| is preferred when adding or removing
directories from the list. This avoids problems when a future version
uses another default.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'backupskip'* *'bsk'*
'backupskip' 'bsk' string (default: "/tmp/*,$TMPDIR/*,$TMP/*,$TEMP/*")
global
{not in Vi}
{not available when compiled without the |+wildignore|
feature}
A list of file patterns. When one of the patterns matches with the
name of the file which is written, no backup file is created. Both
the specified file name and the full path name of the file are used.
The pattern is used like with |:autocmd|, see |autocmd-patterns|.
Watch out for special characters, see |option-backslash|.
When $TMPDIR, $TMP or $TEMP is not defined, it is not used for the
default value. "/tmp/*" is only used for Unix.
Note that environment variables are not expanded. If you want to use
$HOME you must expand it explicitly, e.g.:
:let backupskip = escape(expand('$HOME'), '\') . '/tmp/*'
Note that the default also makes sure that "crontab -e" works (when a
backup would be made by renaming the original file crontab won't see
the newly created file). Also see 'backupcopy' and |crontab|.
*'balloondelay'* *'bdlay'*
'balloondelay' 'bdlay' number (default: 600)
global
{not in Vi}
{only available when compiled with the |+balloon_eval|
feature}
Delay in milliseconds before a balloon may pop up. See |balloon-eval|.
*'balloonexpr'* *'bexpr'*
'balloonexpr' 'bexpr' string (default "")
global or local to buffer |global-local|
{not in Vi}
{only available when compiled with the |+balloon_eval|
feature}
Expression for text to show in evaluation balloon. It is only used
when 'ballooneval' is on. These variables can be used:
v:beval_bufnr number of the buffer in which balloon is going to show
v:beval_winnr number of the window
v:beval_lnum line number
v:beval_col column number (byte index)
v:beval_text word under or after the mouse pointer
The evaluation of the expression must not have side effects!
Example:
function! MyBalloonExpr()
return 'Cursor is at line ' . v:beval_lnum .
\', column ' . v:beval_col .
\ ' of file ' . bufname(v:beval_bufnr) .
\ ' on word "' . v:beval_text . '"'
endfunction
set bexpr=MyBalloonExpr()
set ballooneval
NOTE: The balloon is displayed only if the cursor is on a text
character. If the result of evaluating 'balloonexpr' is not empty,
Vim does not try to send a message to an external debugger (Netbeans
or Sun Workshop).
The expression may be evaluated in the |sandbox|, see
|sandbox-option|.
It is not allowed to change text or jump to another window while
evaluating 'balloonexpr' |textlock|.
To check whether line breaks in the balloon text work use this check:
if has("balloon_multiline")
When they are supported "\n" characters will start a new line. If the
expression evaluates to a |List| this is equal to using each List item
as a string and putting "\n" in between them.
*'bomb'* *'nobomb'*
'bomb' boolean (default off)
local to buffer
{not in Vi}
{only available when compiled with the |+multi_byte|
feature}
When writing a file and the following conditions are met, a BOM (Byte
Order Mark) is prepended to the file:
- this option is on
- the 'binary' option is off
- 'fileencoding' is "utf-8", "ucs-2", "ucs-4" or one of the little/big
endian variants.
Some applications use the BOM to recognize the encoding of the file.
Often used for UCS-2 files on MS-Windows. For other applications it
causes trouble, for example: "cat file1 file2" makes the BOM of file2
appear halfway the resulting file. Gcc doesn't accept a BOM.
When Vim reads a file and 'fileencodings' starts with "ucs-bom", a
check for the presence of the BOM is done and 'bomb' set accordingly.
Unless 'binary' is set, it is removed from the first line, so that you
don't see it when editing. When you don't change the options, the BOM
will be restored when writing the file.
*'breakat'* *'brk'*
'breakat' 'brk' string (default " ^I!@*-+;:,./?")
global
{not in Vi}
{not available when compiled without the |+linebreak|
feature}
This option lets you choose which characters might cause a line
break if 'linebreak' is on. Only works for ASCII and also for 8-bit
characters when 'encoding' is an 8-bit encoding.
*'browsedir'* *'bsdir'*
'browsedir' 'bsdir' string (default: "last")
global
{not in Vi} {only for Motif, Athena, GTK, Mac and
Win32 GUI}
Which directory to use for the file browser:
last Use same directory as with last file browser, where a
file was opened or saved.
buffer Use the directory of the related buffer.
current Use the current directory.
{path} Use the specified directory
*'bufhidden'* *'bh'*
'bufhidden' 'bh' string (default: "")
local to buffer
{not in Vi}
{not available when compiled without the |+quickfix|
feature}
This option specifies what happens when a buffer is no longer
displayed in a window:
<empty> follow the global 'hidden' option
hide hide the buffer (don't unload it), also when 'hidden'
is not set
unload unload the buffer, also when 'hidden' is set or using
|:hide|
delete delete the buffer from the buffer list, also when
'hidden' is set or using |:hide|, like using
|:bdelete|
wipe wipe out the buffer from the buffer list, also when
'hidden' is set or using |:hide|, like using
|:bwipeout|
CAREFUL: when "unload", "delete" or "wipe" is used changes in a buffer
are lost without a warning.
This option is used together with 'buftype' and 'swapfile' to specify
special kinds of buffers. See |special-buffers|.
*E676*
"acwrite" implies that the buffer name is not related to a file, like
"nofile", but it will be written. Thus, in contrast to "nofile" and
"nowrite", ":w" does work and a modified buffer can't be abandoned
without saving. For writing there must be matching |BufWriteCmd|,
|FileWriteCmd| or |FileAppendCmd| autocommands.
*'casemap'* *'cmp'*
'casemap' 'cmp' string (default: "internal,keepascii")
global
{not in Vi}
{only available when compiled with the |+multi_byte|
feature}
Specifies details about changing the case of letters. It may contain
these words, separated by a comma:
internal Use internal case mapping functions, the current
locale does not change the case mapping. This only
matters when 'encoding' is a Unicode encoding,
"latin1" or "iso-8859-15". When "internal" is
omitted, the towupper() and towlower() system library
functions are used when available.
keepascii For the ASCII characters (0x00 to 0x7f) use the US
case mapping, the current locale is not effective.
This probably only matters for Turkish.
*'cedit'*
'cedit' string (Vi default: "", Vim default: CTRL-F)
global
{not in Vi}
{not available when compiled without the |+vertsplit|
feature}
The key used in Command-line Mode to open the command-line window.
The default is CTRL-F when 'compatible' is off.
Only non-printable keys are allowed.
The key can be specified as a single character, but it is difficult to
type. The preferred way is to use the <> notation. Examples:
:set cedit=<C-Y>
:set cedit=<Esc>
|Nvi| also has this option, but it only uses the first character.
See |cmdwin|.
*'cinkeys'* *'cink'*
'cinkeys' 'cink' string (default "0{,0},0),:,0#,!^F,o,O,e")
local to buffer
{not in Vi}
{not available when compiled without the |+cindent|
feature}
A list of keys that, when typed in Insert mode, cause reindenting of
the current line. Only used if 'cindent' is on and 'indentexpr' is
empty.
For the format of this option see |cinkeys-format|.
See |C-indenting|.
*'cinoptions'* *'cino'*
'cinoptions' 'cino' string (default "")
local to buffer
{not in Vi}
{not available when compiled without the |+cindent|
feature}
The 'cinoptions' affect the way 'cindent' reindents lines in a C
program. See |cinoptions-values| for the values of this option, and
|C-indenting| for info on C indenting in general.
*'cinwords'* *'cinw'*
*'clipboard'* *'cb'*
'clipboard' 'cb' string (default "autoselect,exclude:cons\|linux"
for X-windows, "" otherwise)
global
{not in Vi}
{only in GUI versions or when the |+xterm_clipboard|
feature is included}
This option is a list of comma separated names.
These names are recognized:
unnamed When included, Vim will use the clipboard register '*'
for all yank, delete, change and put operations which
would normally go to the unnamed register. When a
register is explicitly specified, it will always be
used regardless of whether "unnamed" is in 'clipboard'
or not. The clipboard register can always be
explicitly accessed using the "* notation. Also see
|gui-clipboard|.
unnamedplus A variant of "unnamed" flag which uses the clipboard
register '+' (|quoteplus|) instead of register '*' for
all operations except yank. Yank shall copy the text
into register '+' and also into '*' when "unnamed" is
included.
Only available with the |+X11| feature.
Availability can be checked with:
if has('unnamedplus')
autoselect Works like the 'a' flag in 'guioptions': If present,
then whenever Visual mode is started, or the Visual
area extended, Vim tries to become the owner of the
windowing system's global selection or put the
selected text on the clipboard used by the selection
register "*. See |guioptions_a| and |quotestar| for
details. When the GUI is active, the 'a' flag in
'guioptions' is used, when the GUI is not active, this
"autoselect" flag is used.
Also applies to the modeless selection.
autoselectml Like "autoselect", but for the modeless selection
only. Compare to the 'A' flag in 'guioptions'.
html When the clipboard contains HTML, use this when
pasting. When putting text on the clipboard, mark it
as HTML. This works to copy rendered HTML from
Firefox, paste it as raw HTML in Vim, select the HTML
in Vim and paste it in a rich edit box in Firefox.
You probably want to add this only temporarily,
possibly use BufEnter autocommands.
Only supported for GTK version 2 and later.
Only available with the |+multi_byte| feature.
exclude:{pattern}
Defines a pattern that is matched against the name of
the terminal 'term'. If there is a match, no
connection will be made to the X server. This is
useful in this situation:
- Running Vim in a console.
- $DISPLAY is set to start applications on another
display.
- You do not want to connect to the X server in the
console, but do want this in a terminal emulator.
To never connect to the X server use:
exclude:.*
This has the same effect as using the |-X| argument.
Note that when there is no connection to the X server
the window title won't be restored and the clipboard
cannot be accessed.
The value of 'magic' is ignored, {pattern} is
interpreted as if 'magic' was on.
The rest of the option value will be used for
{pattern}, this must be the last entry.
*'cmdheight'* *'ch'*
'cmdheight' 'ch' number (default 1)
global
{not in Vi}
Number of screen lines to use for the command-line. Helps avoiding
|hit-enter| prompts.
The value of this option is stored with the tab page, so that each tab
page can have a different value.
*'cmdwinheight'* *'cwh'*
'cmdwinheight' 'cwh' number (default 7)
global
{not in Vi}
{not available when compiled without the |+vertsplit|
feature}
Number of screen lines to use for the command-line window. |cmdwin|
*'colorcolumn'* *'cc'*
'colorcolumn' 'cc' string (default "")
local to window
{not in Vi}
{not available when compiled without the |+syntax|
feature}
'colorcolumn' is a comma separated list of screen columns that are
highlighted with ColorColumn |hl-ColorColumn|. Useful to align
text. Will make screen redrawing slower.
The screen column can be an absolute number, or a number preceded with
'+' or '-', which is added to or subtracted from 'textwidth'.
:set cc=+1 " highlight column after 'textwidth'
:set cc=+1,+2,+3 " highlight three columns after 'textwidth'
:hi ColorColumn ctermbg=lightgrey guibg=lightgrey
When 'textwidth' is zero then the items with '-' and '+' are not used.
A maximum of 256 columns are highlighted.
{not in Vi}
{not available when compiled without the |+folding|
feature}
A template for a comment. The "%s" in the value is replaced with the
comment text. Currently only used to add markers for folding, see
|fold-marker|.
*'completefunc'* *'cfu'*
'completefunc' 'cfu' string (default: empty)
local to buffer
{not in Vi}
{not available when compiled without the |+eval|
or |+insert_expand| features}
This option specifies a function to be used for Insert mode completion
with CTRL-X CTRL-U. |i_CTRL-X_CTRL-U|
See |complete-functions| for an explanation of how the function is
invoked and what it should return.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'completeopt'* *'cot'*
*'concealcursor'* *'cocu'*
'concealcursor' 'cocu' string (default: "")
local to window
{not in Vi}
{not available when compiled without the |+conceal|
feature}
Sets the modes in which text in the cursor line can also be concealed.
When the current mode is listed then concealing happens just like in
other lines.
n Normal mode
v Visual mode
i Insert mode
c Command line editing, for 'incsearch'
'v' applies to all lines in the Visual area, not only the cursor.
A useful value is "nc". This is used in help files. So long as you
are moving around text is concealed, but when starting to insert text
or selecting a Visual area the concealed text is displayed, so that
you can see what you are doing.
Keep in mind that the cursor position is not always where it's
displayed. E.g., when moving vertically it may change column.
*'cpoptions'* *'cpo'*
'cpoptions' 'cpo' string (Vim default: "aABceFs",
Vi default: all flags)
global
{not in Vi}
A sequence of single character flags. When a character is present
this indicates vi-compatible behavior. This is used for things where
not being vi-compatible is mostly or sometimes preferred.
'cpoptions' stands for "compatible-options".
Commas can be added for readability.
To avoid problems with flags that are added in the future, use the
"+=" and "-=" feature of ":set" |add-option-flags|.
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
NOTE: This option is set to the POSIX default value at startup when
the Vi default value would be used and the $VIM_POSIX environment
variable exists |posix|. This means Vim tries to behave like the
POSIX specification.
contains behavior
*cpo-a*
a When included, a ":read" command with a file name
argument will set the alternate file name for the
current window.
*cpo-A*
A When included, a ":write" command with a file name
argument will set the alternate file name for the
current window.
*cpo-b*
b "\|" in a ":map" command is recognized as the end of
the map command. The '\' is included in the mapping,
the text after the '|' is interpreted as the next
command. Use a CTRL-V instead of a backslash to
include the '|' in the mapping. Applies to all
mapping, abbreviation, menu and autocmd commands.
*cpo-J*
J A |sentence| has to be followed by two spaces after
the '.', '!' or '?'. A <Tab> is not recognized as
white space.
*cpo-k*
k Disable the recognition of raw key codes in
mappings, abbreviations, and the "to" part of menu
commands. For example, if <Key> sends ^[OA (where ^[
is <Esc>), the command ":map X ^[OA" results in X
being mapped to:
'k' included: "^[OA" (3 characters)
'k' excluded: "<Key>" (one key code)
Also see the '<' flag below.
*cpo-K*
K Don't wait for a key code to complete when it is
halfway a mapping. This breaks mapping <F1><F1> when
only part of the second <F1> has been read. It
enables cancelling the mapping by typing <F1><Esc>.
*cpo-l*
l Backslash in a [] range in a search pattern is taken
literally, only "\]", "\^", "\-" and "\\" are special.
See |/[]|
'l' included: "/[ \t]" finds <Space>, '\' and 't'
'l' excluded: "/[ \t]" finds <Space> and <Tab>
Also see |cpo-\|.
*cpo-L*
L When the 'list' option is set, 'wrapmargin',
'textwidth', 'softtabstop' and Virtual Replace mode
(see |gR|) count a <Tab> as two characters, instead of
the normal behavior of a <Tab>.
*cpo-m*
m When included, a showmatch will always wait half a
second. When not included, a showmatch will wait half
a second or until a character is typed. |'showmatch'|
*cpo-M*
M When excluded, "%" matching will take backslashes into
account. Thus in "( \( )" and "\( ( \)" the outer
parenthesis match. When included "%" ignores
backslashes, which is Vi compatible.
*cpo-n*
n When included, the column used for 'number' and
'relativenumber' will also be used for text of wrapped
lines.
*cpo-o*
o Line offset to search command is not remembered for
next search.
*cpo-O*
O Don't complain if a file is being overwritten, even
when it didn't exist when editing it. This is a
protection against a file unexpectedly created by
someone else. Vi didn't complain about this.
*cpo-p*
p Vi compatible Lisp indenting. When not present, a
slightly better algorithm is used.
*cpo-P*
P When included, a ":write" command that appends to a
file will set the file name for the current buffer, if
the current buffer doesn't have a file name yet and
the 'F' flag is also included |cpo-F|.
*cpo-q*
q When joining multiple lines leave the cursor at the
position where it would be when joining two lines.
*cpo-r*
r Redo ("." command) uses "/" to repeat a search
command, instead of the actually used search string.
*cpo-R*
R Remove marks from filtered lines. Without this flag
marks are kept like |:keepmarks| was used.
*cpo-s*
s Set buffer options when entering the buffer for the
first time. This is like it is in Vim version 3.0.
And it is the default. If not present the options are
set when the buffer is created.
*cpo-S*
S Set buffer options always when entering a buffer
(except 'readonly', 'fileformat', 'filetype' and
'syntax'). This is the (most) Vi compatible setting.
The options are set to the values in the current
buffer. When you change an option and go to another
buffer, the value is copied. Effectively makes the
buffer options global to all buffers.
's' 'S' copy buffer options
no no when buffer created
yes no when buffer first entered (default)
X yes each time when buffer entered (vi comp.)
*cpo-t*
t Search pattern for the tag command is remembered for
"n" command. Otherwise Vim only puts the pattern in
the history for search pattern, but doesn't change the
last used search pattern.
*cpo-u*
u Undo is Vi compatible. See |undo-two-ways|.
*cpo-v*
v Backspaced characters remain visible on the screen in
Insert mode. Without this flag the characters are
erased from the screen right away. With this flag the
screen newly typed text overwrites backspaced
characters.
*cpo-w*
w When using "cw" on a blank character, only change one
character and not all blanks until the start of the
next word.
*cpo-W*
W Don't overwrite a readonly file. When omitted, ":w!"
overwrites a readonly file, if possible.
*cpo-x*
x <Esc> on the command-line executes the command-line.
The default in Vim is to abandon the command-line,
because <Esc> normally aborts a command. |c_<Esc>|
*cpo-X*
X When using a count with "R" the replaced text is
deleted only once. Also when repeating "R" with "."
and a count.
*cpo-y*
y A yank command can be redone with ".".
*cpo-Z*
Z When using "w!" while the 'readonly' option is set,
don't reset 'readonly'.
*cpo-!*
! When redoing a filter command, use the last used
external command, whatever it was. Otherwise the last
used -filter- command is used.
*cpo-$*
$ When making a change to one line, don't redisplay the
line, but put a '$' at the end of the changed text.
The changed text will be overwritten when you type the
new text. The line is redisplayed if you type any
command that moves the cursor from the insertion
point.
*cpo-%*
% Vi-compatible matching is done for the "%" command.
Does not recognize "#if", "#endif", etc.
Does not recognize "/*" and "*/".
Parens inside single and double quotes are also
counted, causing a string that contains a paren to
disturb the matching. For example, in a line like
"if (strcmp("foo(", s))" the first paren does not
match the last one. When this flag is not included,
parens inside single and double quotes are treated
specially. When matching a paren outside of quotes,
everything inside quotes is ignored. When matching a
paren inside quotes, it will find the matching one (if
there is one). This works very well for C programs.
This flag is also used for other features, such as
C-indenting.
*cpo--*
- When included, a vertical movement command fails when
it would go above the first line or below the last
line. Without it the cursor moves to the first or
last line, unless it already was in that line.
Applies to the commands "-", "k", CTRL-P, "+", "j",
CTRL-N, CTRL-J and ":1234".
*cpo-+*
+ When included, a ":write file" command will reset the
'modified' flag of the buffer, even though the buffer
itself may still be different from its file.
*cpo-star*
* Use ":*" in the same way as ":@". When not included,
":*" is an alias for ":'<,'>", select the Visual area.
*cpo-<*
< Disable the recognition of special key codes in |<>|
form in mappings, abbreviations, and the "to" part of
menu commands. For example, the command
":map X <Tab>" results in X being mapped to:
'<' included: "<Tab>" (5 characters)
'<' excluded: "^I" (^I is a real <Tab>)
Also see the 'k' flag above.
*cpo->*
> When appending to a register, put a line break before
the appended text.
POSIX flags. These are not included in the Vi default value, except
when $VIM_POSIX was set on startup. |posix|
contains behavior
*cpo-#*
# A count before "D", "o" and "O" has no effect.
*cpo-&*
& When ":preserve" was used keep the swap file when
exiting normally while this buffer is still loaded.
This flag is tested when exiting.
*cpo-\*
\ Backslash in a [] range in a search pattern is taken
literally, only "\]" is special See |/[]|
'\' included: "/[ \-]" finds <Space>, '\' and '-'
'\' excluded: "/[ \-]" finds <Space> and '-'
Also see |cpo-l|.
*cpo-/*
/ When "%" is used as the replacement string in a |:s|
command, use the previous replacement string. |:s%|
*cpo-{*
{ The |{| and |}| commands also stop at a "{" character
at the start of a line.
*cpo-.*
. The ":chdir" and ":cd" commands fail if the current
buffer is modified, unless ! is used. Vim doesn't
need this, since it remembers the full path of an
opened file.
*cpo-bar*
| The value of the $LINES and $COLUMNS environment
variables overrule the terminal size values obtained
with system specific functions.
*'cryptmethod'* *'cm'*
'cryptmethod' string (default "zip")
global or local to buffer |global-local|
{not in Vi}
Method used for encryption when the buffer is written to a file:
*pkzip*
zip PkZip compatible method. A weak kind of encryption.
Backwards compatible with Vim 7.2 and older.
*blowfish*
blowfish Blowfish method. Strong encryption. Requires Vim 7.3
or later, files can NOT be read by Vim 7.2 and older.
This adds a "seed" to the file, every time you write
the file the encrypted bytes will be different.
When reading an encrypted file 'cryptmethod' will be set automatically
to the detected method of the file being read. Thus if you write it
without changing 'cryptmethod' the same method will be used.
Changing 'cryptmethod' does not mark the file as modified, you have to
explicitly write it, you don't get a warning unless there are other
modifications. Also see |:X|.
When setting the global value to an empty string, it will end up with
the value "zip". When setting the local value to an empty string the
buffer will use the global value.
When a new encryption method is added in a later version of Vim, and
the current version does not recognize it, you will get *E821* .
You need to edit this file with the later version of Vim.
*'cscopepathcomp'* *'cspc'*
'cscopepathcomp' 'cspc' number (default 0)
global
{not available when compiled without the |+cscope|
feature}
{not in Vi}
Determines how many components of the path to show in a list of tags.
See |cscopepathcomp|.
*'cscopeprg'* *'csprg'*
'cscopeprg' 'csprg' string (default "cscope")
global
{not available when compiled without the |+cscope|
feature}
{not in Vi}
Specifies the command to execute cscope. See |cscopeprg|.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'cscopequickfix'* *'csqf'*
'cscopequickfix' 'csqf' string (default "")
global
{not available when compiled without the |+cscope|
or |+quickfix| features}
{not in Vi}
Specifies whether to use quickfix window to show cscope results.
See |cscopequickfix|.
*'cscopetagorder'* *'csto'*
'cscopetagorder' 'csto' number (default 0)
global
{not available when compiled without the |+cscope|
feature}
{not in Vi}
Determines the order in which ":cstag" performs a search. See
|cscopetagorder|.
NOTE: This option is set to 0 when 'compatible' is set.
*'cscopeverbose'* *'csverb'*
*'nocscopeverbose'* *'nocsverb'*
'cscopeverbose' 'csverb' boolean (default off)
global
{not available when compiled without the |+cscope|
feature}
{not in Vi}
Give messages when adding a cscope database. See |cscopeverbose|.
NOTE: This option is reset when 'compatible' is set.
*'debug'*
'debug' string (default "")
global
{not in Vi}
These values can be used:
msg Error messages that would otherwise be omitted will be given
anyway.
*'define'* *'def'*
'define' 'def' string (default "^\s*#\s*define")
global or local to buffer |global-local|
{not in Vi}
Pattern to be used to find a macro definition. It is a search
pattern, just like for the "/" command. This option is used for the
commands like "[i" and "[d" |include-search|. The 'isident' option is
used to recognize the defined name after the match:
{match with 'define'}{non-ID chars}{defined name}{non-ID char}
See |option-backslash| about inserting backslashes to include a space
or backslash.
The default value is for C programs. For C++ this value would be
useful, to include const type declarations:
^\(#\s*define\|[a-z]*\s*const\s*[a-z]*\)
When using the ":set" command, you need to double the backslashes!
*'dictionary'* *'dict'*
'dictionary' 'dict' string (default "")
global or local to buffer |global-local|
{not in Vi}
List of file names, separated by commas, that are used to lookup words
for keyword completion commands |i_CTRL-X_CTRL-K|. Each file should
contain a list of words. This can be one word per line, or several
words per line, separated by non-keyword characters (white space is
preferred). Maximum line length is 510 bytes.
When this option is empty, or an entry "spell" is present, spell
checking is enabled the currently active spelling is used. |spell|
To include a comma in a file name precede it with a backslash. Spaces
after a comma are ignored, otherwise spaces are included in the file
name. See |option-backslash| about using backslashes.
This has nothing to do with the |Dictionary| variable type.
Where to find a list of words?
- On FreeBSD, there is the file "/usr/share/dict/words".
- In the Simtel archive, look in the "msdos/linguist" directory.
- In "miscfiles" of the GNU collection.
The use of |:set+=| and |:set-=| is preferred when adding or removing
directories from the list. This avoids problems when a future version
uses another default.
Backticks cannot be used in this option for security reasons.
*'diff'* *'nodiff'*
'diff' boolean (default off)
local to window
{not in Vi}
{not available when compiled without the |+diff|
feature}
Join the current window in the group of windows that shows differences
between files. See |vimdiff|.
*'dex'* *'diffexpr'*
'diffexpr' 'dex' string (default "")
global
{not in Vi}
{not available when compiled without the |+diff|
feature}
Expression which is evaluated to obtain an ed-style diff file from two
versions of a file. See |diff-diffexpr|.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'dip'* *'diffopt'*
'diffopt' 'dip' string (default "filler")
global
{not in Vi}
{not available when compiled without the |+diff|
feature}
Option settings for diff mode. It can consist of the following items.
All are optional. Items must be separated by a comma.
filler Show filler lines, to keep the text
synchronized with a window that has inserted
lines at the same position. Mostly useful
when windows are side-by-side and 'scrollbind'
is set.
context:{n} Use a context of {n} lines between a change
and a fold that contains unchanged lines.
When omitted a context of six lines is used.
See |fold-diff|.
icase Ignore changes in case of text. "a" and "A"
are considered the same. Adds the "-i" flag
to the "diff" command if 'diffexpr' is empty.
iwhite Ignore changes in amount of white space. Adds
the "-b" flag to the "diff" command if
'diffexpr' is empty. Check the documentation
of the "diff" command for what this does
exactly. It should ignore adding trailing
white space, but not leading white space.
horizontal Start diff mode with horizontal splits (unless
explicitly specified otherwise).
vertical Start diff mode with vertical splits (unless
explicitly specified otherwise).
foldcolumn:{n} Set the 'foldcolumn' option to {n} when
starting diff mode. Without this 2 is used.
Examples:
:set diffopt=filler,context:4
:set diffopt=
:set diffopt=filler,foldcolumn:3
*'directory'* *'dir'*
'directory' 'dir' string (default for Amiga: ".,t:",
for MS-DOS and Win32: ".,c:\tmp,c:\temp"
for Unix: ".,~/tmp,/var/tmp,/tmp")
global
List of directory names for the swap file, separated with commas.
- The swap file will be created in the first directory where this is
possible.
- Empty means that no swap file will be used (recovery is
impossible!).
- A directory "." means to put the swap file in the same directory as
the edited file. On Unix, a dot is prepended to the file name, so
*'display'* *'dy'*
'display' 'dy' string (default "")
global
{not in Vi}
Change the way text is displayed. This is comma separated list of
flags:
lastline When included, as much as possible of the last line
in a window will be displayed. When not included, a
last line that doesn't fit is replaced with "@" lines.
uhex Show unprintable characters hexadecimal as <xx>
instead of using ^C and ~C.
*'eadirection'* *'ead'*
'eadirection' 'ead' string (default "both")
global
{not in Vi}
{not available when compiled without the |+vertsplit|
feature}
Tells when the 'equalalways' option applies:
ver vertically, width of windows is not affected
hor horizontally, height of windows is not affected
both width and height of windows is affected
size of the current window and leave the other windows the same. When
closing a window the extra lines are given to the window next to it
(depending on 'splitbelow' and 'splitright').
When mixing vertically and horizontally split windows, a minimal size
is computed and some windows may be larger if there is room. The
'eadirection' option tells in which direction the size is affected.
Changing the height and width of a window can be avoided by setting
'winfixheight' and 'winfixwidth', respectively.
If a window size is specified when creating a new window sizes are
currently not equalized (it's complicated, but may be implemented in
the future).
*'equalprg'* *'ep'*
'equalprg' 'ep' string (default "")
global or local to buffer |global-local|
{not in Vi}
External program to use for "=" command. When this option is empty
the internal formatting functions are used; either 'lisp', 'cindent'
or 'indentexpr'. When Vim was compiled without internal formatting,
the "indent" program is used.
Environment variables are expanded |:set_env|. See |option-backslash|
about including spaces and backslashes.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'errorfile'* *'ef'*
'errorfile' 'ef' string (Amiga default: "AztecC.Err",
others: "errors.err")
global
{not in Vi}
{not available when compiled without the |+quickfix|
feature}
Name of the errorfile for the QuickFix mode (see |:cf|).
When the "-q" command-line argument is used, 'errorfile' is set to the
following argument. See |-q|.
NOT used for the ":make" command. See 'makeef' for that.
Environment variables are expanded |:set_env|.
See |option-backslash| about including spaces and backslashes.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'errorformat'* *'efm'*
'errorformat' 'efm' string (default is very long)
global or local to buffer |global-local|
{not in Vi}
{not available when compiled without the |+quickfix|
feature}
Scanf-like description of the format for the lines in the error file
(see |errorformat|).
*'eventignore'* *'ei'*
'eventignore' 'ei' string (default "")
global
{not in Vi}
{not available when compiled without the |+autocmd|
feature}
A list of autocommand event names, which are to be ignored.
When set to "all" or when "all" is one of the items, all autocommand
events are ignored, autocommands will not be executed.
Otherwise this is a comma separated list of event names. Example:
:set ei=WinEnter,WinLeave
*'fe'*
NOTE: Before version 6.0 this option specified the encoding for the
whole of Vim, this was a mistake. Now use 'encoding' instead. The
old short name was 'fe', which is no longer used.
*'fileencodings'* *'fencs'*
'fileencodings' 'fencs' string (default: "ucs-bom",
"ucs-bom,utf-8,default,latin1" when
'encoding' is set to a Unicode value)
global
{only available when compiled with the |+multi_byte|
feature}
{not in Vi}
This is a list of character encodings considered when starting to edit
an existing file. When a file is read, Vim tries to use the first
mentioned character encoding. If an error is detected, the next one
in the list is tried. When an encoding is found that works,
'fileencoding' is set to it. If all fail, 'fileencoding' is set to
an empty string, which means the value of 'encoding' is used.
WARNING: Conversion can cause loss of information! When
'encoding' is "utf-8" (or one of the other Unicode variants)
conversion is most likely done in a way that the reverse
conversion results in the same text. When 'encoding' is not
"utf-8" some non-ASCII characters may be lost! You can use
the |++bad| argument to specify what is done with characters
that can't be converted.
For an empty file or a file with only ASCII characters most encodings
will work and the first entry of 'fileencodings' will be used (except
"ucs-bom", which requires the BOM to be present). If you prefer
another encoding use an BufReadPost autocommand event to test if your
preferred encoding is to be used. Example:
au BufReadPost * if search('\S', 'w') == 0 |
\ set fenc=iso-2022-jp | endif
This sets 'fileencoding' to "iso-2022-jp" if the file does not contain
non-blank characters.
When the |++enc| argument is used then the value of 'fileencodings' is
not used.
Note that 'fileencodings' is not used for a new file, the global value
of 'fileencoding' is used instead. You can set it with:
:setglobal fenc=iso-8859-2
This means that a non-existing file may get a different encoding than
an empty file.
The special value "ucs-bom" can be used to check for a Unicode BOM
(Byte Order Mark) at the start of the file. It must not be preceded
by "utf-8" or another Unicode encoding for this to work properly.
An entry for an 8-bit encoding (e.g., "latin1") should be the last,
because Vim cannot detect an error, thus the encoding is always
accepted.
The special value "default" can be used for the encoding from the
environment. This is the default value for 'encoding'. It is useful
when 'encoding' is set to "utf-8" and your environment uses a
non-latin1 encoding, such as Russian.
When 'encoding' is "utf-8" and a file contains an illegal byte
sequence it won't be recognized as UTF-8. You can use the |8g8|
command to find the illegal byte sequence.
WRONG VALUES: WHAT'S WRONG:
latin1,utf-8 "latin1" will always be used
utf-8,ucs-bom,latin1 BOM won't be recognized in an utf-8
file
cp1250,latin1 "cp1250" will always be used
If 'fileencodings' is empty, 'fileencoding' is not modified.
See 'fileencoding' for the possible values.
Setting this option does not have an effect until the next time a file
is read.
*'fileformat'* *'ff'*
'fileformat' 'ff' string (MS-DOS, MS-Windows, OS/2 default: "dos",
Unix default: "unix",
Macintosh default: "mac")
local to buffer
{not in Vi}
This gives the <EOL> of the current buffer, which is used for
*'fileformats'* *'ffs'*
'fileformats' 'ffs' string (default:
Vim+Vi MS-DOS, MS-Windows OS/2: "dos,unix",
Vim Unix: "unix,dos",
Vim Mac: "mac,unix,dos",
Vi Cygwin: "unix,dos",
Vi others: "")
global
{not in Vi}
This gives the end-of-line (<EOL>) formats that will be tried when
starting to edit a new buffer and when reading a file into an existing
buffer:
- When empty, the format defined with 'fileformat' will be used
always. It is not set automatically.
- When set to one name, that format will be used whenever a new buffer
is opened. 'fileformat' is set accordingly for that buffer. The
'fileformats' name will be used when a file is read into an existing
buffer, no matter what 'fileformat' for that buffer is set to.
- When more than one name is present, separated by commas, automatic
<EOL> detection will be done when reading a file. When starting to
edit a file, a check is done for the <EOL>:
1. If all lines end in <CR><NL>, and 'fileformats' includes "dos",
'fileformat' is set to "dos".
2. If a <NL> is found and 'fileformats' includes "unix", 'fileformat'
is set to "unix". Note that when a <NL> is found without a
preceding <CR>, "unix" is preferred over "dos".
3. If 'fileformat' has not yet been set, and if 'fileformats'
includes "mac", 'fileformat' is set to "mac".
This means that "mac" is only chosen when:
"unix" is not present or no <NL> is found in the file, and
"dos" is not present or no <CR><NL> is found in the file.
Except: if "unix" was chosen, but there is a <CR> before
the first <NL>, and there appear to be more <CR>s than <NL>s in
the first few lines, "mac" is used.
4. If 'fileformat' is still not set, the first name from
'fileformats' is used.
When reading a file into an existing buffer, the same is done, but
this happens like 'fileformat' has been set appropriately for that
file only, the option is not changed.
When 'binary' is set, the value of 'fileformats' is not used.
Note that when Vim starts up with an empty buffer this option is not
used. Set 'fileformat' in your .vimrc instead.
For systems with a Dos-like <EOL> (<CR><NL>), when reading files that
are ":source"ed and for vimrc files, automatic <EOL> detection may be
done:
- When 'fileformats' is empty, there is no automatic detection. Dos
format will be used.
- When 'fileformats' is set to one or more names, automatic detection
is done. This is based on the first <NL> in the file: If there is a
<CR> in front of it, Dos format is used, otherwise Unix format is
used.
Also see |file-formats|.
For backwards compatibility: When this option is set to an empty
string or one format (no comma is included), 'textauto' is reset,
otherwise 'textauto' is set.
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
*'filetype'* *'ft'*
*'fillchars'* *'fcs'*
'fillchars' 'fcs' string (default "vert:YXXY,fold:-")
global
{not in Vi}
{not available when compiled without the |+windows|
and |+folding| features}
Characters to fill the statuslines and vertical separators.
It is a comma separated list of items:
item default Used for
stl:c '' '' or '^' statusline of the current window
stlnc:c '' '' or '-' statusline of the non-current windows
vert:c '|' vertical separators |:vsplit|
fold:c '-' filling 'foldtext'
diff:c '-' deleted lines of the 'diff' option
Any one that is omitted will fall back to the default. For "stl" and
"stlnc" the space will be used when there is highlighting, '^' or '-'
otherwise.
Example:
:set fillchars=stl:^,stlnc:-,vert:\|,fold:-,diff:-
This is similar to the default, except that these characters will also
be used when there is highlighting.
for "stl" and "stlnc" only single-byte values are supported.
The highlighting used for these items:
item highlight group
stl:c StatusLine |hl-StatusLine|
stlnc:c StatusLineNC |hl-StatusLineNC|
vert:c VertSplit |hl-VertSplit|
fold:c Folded |hl-Folded|
diff:c DiffDelete |hl-DiffDelete|
*'foldclose'* *'fcl'*
'foldclose' 'fcl' string (default "")
global
{not in Vi}
{not available when compiled without the |+folding|
feature}
When set to "all", a fold is closed when the cursor isn't in it and
its level is higher than 'foldlevel'. Useful if you want folds to
automatically close when moving out of them.
*'foldcolumn'* *'fdc'*
'foldcolumn' 'fdc' number (default 0)
local to window
{not in Vi}
{not available when compiled without the |+folding|
feature}
When non-zero, a column with the specified width is shown at the side
of the window which indicates open and closed folds. The maximum
value is 12.
See |folding|.
*'foldexpr'* *'fde'*
'foldexpr' 'fde' string (default: "0")
local to window
{not in Vi}
{not available when compiled without the |+folding|
or |+eval| features}
The expression used for when 'foldmethod' is "expr". It is evaluated
for each line to obtain its fold level. See |fold-expr|.
The expression may be evaluated in the |sandbox|, see
|sandbox-option|.
This option can't be set from a |modeline| when the 'diff' option is
on.
It is not allowed to change text or jump to another window while
evaluating 'foldexpr' |textlock|.
*'foldignore'* *'fdi'*
'foldignore' 'fdi' string (default: "#")
local to window
{not in Vi}
{not available when compiled without the |+folding|
feature}
Used only when 'foldmethod' is "indent". Lines starting with
characters in 'foldignore' will get their fold level from surrounding
lines. White space is skipped before checking for this character.
The default "#" works well for C programs. See |fold-indent|.
*'foldlevel'* *'fdl'*
'foldlevel' 'fdl' number (default: 0)
local to window
{not in Vi}
{not available when compiled without the |+folding|
feature}
Sets the fold level: Folds with a higher level will be closed.
Setting this option to zero will close all folds. Higher numbers will
close fewer folds.
This option is set by commands like |zm|, |zM| and |zR|.
See |fold-foldlevel|.
*'foldlevelstart'* *'fdls'*
*'foldmethod'* *'fdm'*
'foldmethod' 'fdm' string (default: "manual")
local to window
{not in Vi}
{not available when compiled without the |+folding|
feature}
The kind of folding used for the current window. Possible values:
|fold-manual| manual Folds are created manually.
|fold-indent| indent Lines with equal indent form a fold.
|fold-expr| expr 'foldexpr' gives the fold level of a line.
|fold-marker| marker Markers are used to specify folds.
|fold-syntax| syntax Syntax highlighting items specify folds.
|fold-diff| diff Fold text that is not changed.
*'foldminlines'* *'fml'*
'foldminlines' 'fml' number (default: 1)
local to window
{not in Vi}
{not available when compiled without the |+folding|
feature}
Sets the number of screen lines above which a fold can be displayed
closed. Also for manually closed folds. With the default value of
one a fold can only be closed if it takes up two or more screen lines.
Set to zero to be able to close folds of just one screen line.
Note that this only has an effect of what is displayed. After using
"zc" to close a fold, which is displayed open because it's smaller
than 'foldminlines', a following "zc" may close a containing fold.
*'foldnestmax'* *'fdn'*
'foldnestmax' 'fdn' number (default: 20)
local to window
{not in Vi}
{not available when compiled without the |+folding|
feature}
Sets the maximum nesting of folds for the "indent" and "syntax"
methods. This avoids that too many folds will be created. Using more
than 20 doesn't work, because the internal limit is 20.
*'foldopen'* *'fdo'*
'foldopen' 'fdo' string (default: "block,hor,mark,percent,quickfix,
search,tag,undo")
global
{not in Vi}
{not available when compiled without the |+folding|
feature}
Specifies for which type of commands folds will be opened, if the
command moves the cursor into a closed fold. It is a comma separated
list of items.
NOTE: When the command is part of a mapping this option is not used.
Add the |zv| command to the mapping to get the same effect.
(rationale: the mapping may want to control opening folds itself)
item commands
all any
block "(", "{", "[[", "[{", etc.
hor horizontal movements: "l", "w", "fx", etc.
insert any command in Insert mode
jump far jumps: "G", "gg", etc.
mark jumping to a mark: "'m", CTRL-O, etc.
percent "%"
quickfix ":cn", ":crew", ":make", etc.
search search for a pattern: "/", "n", "*", "gd", etc.
(not for a search pattern in a ":" command)
Also for |[s| and |]s|.
tag jumping to a tag: ":ta", CTRL-T, etc.
undo undo or redo: "u" and CTRL-R
When a movement command is used for an operator (e.g., "dl" or "y%")
this option is not used. This means the operator will include the
whole closed fold.
Note that vertical movements are not here, because it would make it
very difficult to move onto a closed fold.
In insert mode the folds containing the cursor will always be open
when text is inserted.
To close folds you can re-apply 'foldlevel' with the |zx| command or
set the 'foldclose' option to "all".
*'foldtext'* *'fdt'*
'foldtext' 'fdt' string (default: "foldtext()")
local to window
{not in Vi}
{not available when compiled without the |+folding|
feature}
An expression which is used to specify the text displayed for a closed
fold. See |fold-foldtext|.
The expression may be evaluated in the |sandbox|, see
|sandbox-option|.
It is not allowed to change text or jump to another window while
evaluating 'foldtext' |textlock|.
*'formatoptions'* *'fo'*
'formatoptions' 'fo' string (Vim default: "tcq", Vi default: "vt")
local to buffer
{not in Vi}
This is a sequence of letters which describes how automatic
formatting is to be done. See |fo-table|. When the 'paste' option is
on, no formatting is done (like 'formatoptions' is empty). Commas can
be inserted for readability.
To avoid problems with flags that are added in the future, use the
"+=" and "-=" feature of ":set" |add-option-flags|.
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
*'formatlistpat'* *'flp'*
'formatlistpat' 'flp' string (default: "^\s*\d\+[\]:.)}\t ]\s*")
local to buffer
{not in Vi}
A pattern that is used to recognize a list header. This is used for
the "n" flag in 'formatoptions'.
The pattern must match exactly the text that will be the indent for
the line below it. You can use |/\ze| to mark the end of the match
while still checking more characters. There must be a character
following the pattern, when it matches the whole line it is handled
like there is no match.
The default recognizes a number, followed by an optional punctuation
character and white space.
*'formatprg'* *'fp'*
'formatprg' 'fp' string (default "")
global
{not in Vi}
The name of an external program that will be used to format the lines
selected with the |gq| operator. The program must take the input on
stdin and produce the output on stdout. The Unix program "fmt" is
such a program.
If the 'formatexpr' option is not empty it will be used instead.
Otherwise, if 'formatprg' option is an empty string, the internal
format function will be used |C-indenting|.
Environment variables are expanded |:set_env|. See |option-backslash|
about including spaces and backslashes.
The expression may be evaluated in the |sandbox|, see
|sandbox-option|.
*'formatexpr'* *'fex'*
'formatexpr' 'fex' string (default "")
local to buffer
{not in Vi}
{not available when compiled without the |+eval|
feature}
Expression which is evaluated to format a range of lines for the |gq|
operator or automatic formatting (see 'formatoptions'). When this
option is empty 'formatprg' is used.
The |v:lnum| variable holds the first line to be formatted.
The |v:count| variable holds the number of lines to be formatted.
The |v:char| variable holds the character that is going to be
inserted if the expression is being evaluated due to
automatic formatting. This can be empty. Don't insert
it yet!
Example:
:set formatexpr=mylang#Format()
This will invoke the mylang#Format() function in the
autoload/mylang.vim file in 'runtimepath'. |autoload|
The expression is also evaluated when 'textwidth' is set and adding
text beyond that limit. This happens under the same conditions as
when internal formatting is used. Make sure the cursor is kept in the
same spot relative to the text then! The |mode()| function will
return "i" or "R" in this situation.
When the expression evaluates to non-zero Vim will fall back to using
the internal format mechanism.
The expression may be evaluated in the |sandbox|, see
|sandbox-option|. That stops the option from working, since changing
the buffer text is not allowed.
*'fsync'* *'fs'*
'fsync' 'fs' boolean (default on)
global
{not in Vi}
When on, the library function fsync() will be called after writing a
file. This will flush a file to disk, ensuring that it is safely
written even on filesystems which do metadata-only journaling. This
will force the harddrive to spin up on Linux systems running in laptop
mode, so it may be undesirable in some situations. Be warned that
turning this off increases the chances of data loss after a crash. On
systems without an fsync() implementation, this variable is always
off.
Also see 'swapsync' for controlling fsync() on swap files.
*'grepformat'* *'gfm'*
'grepformat' 'gfm' string (default "%f:%l%m,%f %l%m")
global
{not in Vi}
Format to recognize for the ":grep" command output.
This is a scanf-like string that uses the same format as the
'errorformat' option: see |errorformat|.
*'grepprg'* *'gp'*
'grepprg' 'gp' string
(default "grep -n ",
Unix: "grep -n $* /dev/null",
Win32: "findstr /n" or "grep -n",
VMS: "SEARCH/NUMBERS ")
global or local to buffer |global-local|
{not in Vi}
Program to use for the |:grep| command. This option may contain '%'
and '#' characters, which are expanded like when used in a command-
line. The placeholder "$*" is allowed to specify where the arguments
will be included. Environment variables are expanded |:set_env|. See
|option-backslash| about including spaces and backslashes.
When your "grep" accepts the "-H" argument, use this to make ":grep"
also work well with a single file:
:set grepprg=grep\ -nH
Special value: When 'grepprg' is set to "internal" the |:grep| command
works like |:vimgrep|, |:lgrep| like |:lvimgrep|, |:grepadd| like
|:vimgrepadd| and |:lgrepadd| like |:lvimgrepadd|.
See also the section |:make_makeprg|, since most of the comments there
apply equally to 'grepprg'.
For Win32, the default is "findstr /n" if "findstr.exe" can be found,
otherwise it's "grep -n".
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'guifont'* *'gfn'*
*E235* *E596* *E610* *E611*
'guifont' 'gfn' string (default "")
global
{not in Vi}
{only available when compiled with GUI enabled}
This is a list of fonts which will be used for the GUI version of Vim.
In its simplest form the value is just one font name. When
the font cannot be found you will get an error message. To try other
font names a list can be specified, font names separated with commas.
The first valid font is used.
On systems where 'guifontset' is supported (X11) and 'guifontset' is
not empty, then 'guifont' is not used.
Spaces after a comma are ignored. To include a comma in a font name
precede it with a backslash. Setting an option requires an extra
backslash before a space and a backslash. See also
|option-backslash|. For example:
:set guifont=Screen15,\ 7x13,font\\,with\\,commas
will make Vim try to use the font "Screen15" first, and if it fails it
will try to use "7x13" and then "font,with,commas" instead.
If none of the fonts can be loaded, Vim will keep the current setting.
If an empty font list is given, Vim will try using other resource
settings (for X, it will use the Vim.font resource), and finally it
will try some builtin default which should always be there ("7x13" in
the case of X). The font names given should be "normal" fonts. Vim
will try to find the related bold and italic fonts.
For Win32, GTK, Motif, Mac OS and Photon:
:set guifont=*
will bring up a font requester, where you can pick the font you want.
The font name depends on the GUI used. See |setting-guifont| for a
way to set 'guifont' for various systems.
For the GTK+ 2 GUI the font name looks like this:
*'guifontset'* *'gfs'*
*E250* *E252* *E234* *E597* *E598*
'guifontset' 'gfs' string (default "")
global
{not in Vi}
{only available when compiled with GUI enabled and
with the |+xfontset| feature}
{not available in the GTK+ 2 GUI}
When not empty, specifies two (or more) fonts to be used. The first
one for normal English, the second one for your special language. See
|xfontset|.
Setting this option also means that all font names will be handled as
a fontset name. Also the ones used for the "font" argument of the
|:highlight| command.
The fonts must match with the current locale. If fonts for the
character sets that the current locale uses are not included, setting
'guifontset' will fail.
Note the difference between 'guifont' and 'guifontset': In 'guifont'
the comma-separated names are alternative names, one of which will be
used. In 'guifontset' the whole string is one fontset name,
including the commas. It is not possible to specify alternative
fontset names.
This example works on many X11 systems:
:set guifontset=-*-*-medium-r-normal--16-*-*-*-c-*-*-*
Note: The size of these fonts must be exactly twice as wide as the one
specified with 'guifont' and the same height.
All GUI versions but GTK+ 2:
'guifontwide' is only used when 'encoding' is set to "utf-8" and
'guifontset' is empty or invalid.
When 'guifont' is set and a valid font is found in it and
'guifontwide' is empty Vim will attempt to find a matching
double-width font and set 'guifontwide' to it.
*'guiheadroom'* *'ghr'*
'guiheadroom' 'ghr' number (default 50)
global
{not in Vi} {only for GTK and X11 GUI}
The number of pixels subtracted from the screen height when fitting
the GUI window on the screen. Set this before the GUI is started,
e.g., in your |gvimrc| file. When zero, the whole screen height will
be used by the window. When positive, the specified number of pixel
lines will be left for window decorations and other items on the
screen. Set it to a negative value to allow windows taller than the
screen.
*'guioptions'* *'go'*
'guioptions' 'go' string (default "gmrLtT" (MS-Windows),
"agimrLtT" (GTK, Motif and Athena))
global
{not in Vi}
{only available when compiled with GUI enabled}
This option only has an effect in the GUI version of Vim. It is a
sequence of letters which describes what components and options of the
GUI should be used.
To avoid problems with flags that are added in the future, use the
"+=" and "-=" feature of ":set" |add-option-flags|.
Valid letters are as follows:
*guioptions_a* *'go-a'*
'a' Autoselect: If present, then whenever VISUAL mode is started,
or the Visual area extended, Vim tries to become the owner of
the windowing system's global selection. This means that the
Visually highlighted text is available for pasting into other
applications as well as into Vim itself. When the Visual mode
ends, possibly due to an operation on the text, or when an
application wants to paste the selection, the highlighted text
is automatically yanked into the "* selection register.
Thus the selection is still available for pasting into other
applications after the VISUAL mode has ended.
If not present, then Vim won't become the owner of the
windowing system's global selection unless explicitly told to
by a yank or delete operation for the "* register.
The same applies to the modeless selection.
*'go-A'*
'A' Autoselect for the modeless selection. Like 'a', but only
applies to the modeless selection.
'guioptions' autoselect Visual autoselect modeless
"" - -
"a" yes yes
"A" - yes
"aA" yes yes
*'go-c'*
'c' Use console dialogs instead of popup dialogs for simple
choices.
*'go-e'*
'e' Add tab pages when indicated with 'showtabline'.
'guitablabel' can be used to change the text in the labels.
When 'e' is missing a non-GUI tab pages line may be used.
The GUI tabs are only supported on some systems, currently
GTK, Motif, Mac OS/X and MS-Windows.
*'go-f'*
'f' Foreground: Don't use fork() to detach the GUI from the shell
where it was started. Use this for programs that wait for the
editor to finish (e.g., an e-mail program). Alternatively you
can use "gvim -f" or ":gui -f" to start the GUI in the
foreground. |gui-fork|
Note: Set this option in the vimrc file. The forking may have
happened already when the |gvimrc| file is read.
*'go-i'*
'i' Use a Vim icon. For GTK with KDE it is used in the left-upper
corner of the window. It's black&white on non-GTK, because of
limitations of X11. For a color icon, see |X11-icon|.
*'go-m'*
'm' Menu bar is present.
*'go-M'*
'M' The system menu "$VIMRUNTIME/menu.vim" is not sourced. Note
that this flag must be added in the .vimrc file, before
switching on syntax or filetype recognition (when the |gvimrc|
file is sourced the system menu has already been loaded; the
":syntax on" and ":filetype on" commands load the menu too).
*'go-g'*
'g' Grey menu items: Make menu items that are not active grey. If
'g' is not included inactive menu items are not shown at all.
Exception: Athena will always use grey menu items.
*'go-t'*
't' Include tearoff menu items. Currently only works for Win32,
GTK+, and Motif 1.2 GUI.
*'go-T'*
'T' Include Toolbar. Currently only in Win32, GTK+, Motif, Photon
and Athena GUIs.
*'go-r'*
'r' Right-hand scrollbar is always present.
*'go-R'*
'R' Right-hand scrollbar is present when there is a vertically
split window.
*'go-l'*
'l' Left-hand scrollbar is always present.
*'go-L'*
'L' Left-hand scrollbar is present when there is a vertically
split window.
*'go-b'*
'b' Bottom (horizontal) scrollbar is present. Its size depends on
the longest visible line, or on the cursor line if the 'h'
flag is included. |gui-horiz-scroll|
*'go-h'*
'h' Limit horizontal scrollbar size to the length of the cursor
line. Reduces computations. |gui-horiz-scroll|
And yes, you may even have scrollbars on the left AND the right if
you really want to :-). See |gui-scrollbars| for more information.
*'go-v'*
'v' Use a vertical button layout for dialogs. When not included,
a horizontal layout is preferred, but when it doesn't fit a
vertical layout is used anyway.
*'go-p'*
'p' Use Pointer callbacks for X11 GUI. This is required for some
*'guipty'* *'noguipty'*
'guipty' boolean (default on)
global
{not in Vi}
{only available when compiled with GUI enabled}
Only in the GUI: If on, an attempt is made to open a pseudo-tty for
I/O to/from shell commands. See |gui-pty|.
*'guitablabel'* *'gtl'*
'guitablabel' 'gtl' string (default empty)
global
{not in Vi}
{only available when compiled with GUI enabled and
with the |+windows| feature}
When nonempty describes the text to use in a label of the GUI tab
pages line. When empty and when the result is empty Vim will use a
default label. See |setting-guitablabel| for more info.
The format of this option is like that of 'statusline'.
'guitabtooltip' is used for the tooltip, see below.
Only used when the GUI tab pages line is displayed. 'e' must be
present in 'guioptions'. For the non-GUI tab pages line 'tabline' is
used.
*'guitabtooltip'* *'gtt'*
'guitabtooltip' 'gtt' string (default empty)
global
{not in Vi}
{only available when compiled with GUI enabled and
with the |+windows| feature}
When nonempty describes the text to use in a tooltip for the GUI tab
pages line. When empty Vim will use a default tooltip.
This option is otherwise just like 'guitablabel' above.
You can include a line break. Simplest method is to use YXXY:let|:
:let &guitabtooltip = "line one\nline two"
*'helpfile'* *'hf'*
'helpfile' 'hf' string (default (MSDOS) "$VIMRUNTIME\doc\help.txt"
(others) "$VIMRUNTIME/doc/help.txt")
global
{not in Vi}
Name of the main help file. All distributed help files should be
placed together in one directory. Additionally, all "doc" directories
in 'runtimepath' will be used.
Environment variables are expanded |:set_env|. For example:
"$VIMRUNTIME/doc/help.txt". If $VIMRUNTIME is not set, $VIM is also
tried. Also see |$VIMRUNTIME| and |option-backslash| about including
spaces and backslashes.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'helpheight'* *'hh'*
'helpheight' 'hh' number (default 20)
global
{not in Vi}
{not available when compiled without the |+windows|
feature}
Minimal initial height of the help window when it is opened with the
":help" command. The initial height of the help window is half of the
current window, or (when the 'ea' option is on) the same as other
windows. When the height is less than 'helpheight', the height is
set to 'helpheight'. Set to zero to disable.
*'helplang'* *'hlg'*
'helplang' 'hlg' string (default: messages language or empty)
global
{only available when compiled with the |+multi_lang|
feature}
{not in Vi}
Comma separated list of languages. Vim will use the first language
for which the desired help can be found. The English help will always
be used as a last resort. You can add "en" to prefer English over
another language, but that will only find tags that exist in that
language and not in the English help.
Example:
:set helplang=de,it
This will first search German, then Italian and finally English help
files.
When using |CTRL-]| and ":help!" in a non-English help file Vim will
try to find the tag in the current language before using this option.
See |help-translated|.
*'highlight'* *'hl'*
'highlight' 'hl' string (default (as a single string):
"8:SpecialKey,@:NonText,d:Directory,
e:ErrorMsg,i:IncSearch,l:Search,m:MoreMsg,
M:ModeMsg,n:LineNr,r:Question,
s:StatusLine,S:StatusLineNC,c:VertSplit,
t:Title,v:Visual,w:WarningMsg,W:WildMenu,
f:Folded,F:FoldColumn,A:DiffAdd,
C:DiffChange,D:DiffDelete,T:DiffText,
>:SignColumn,B:SpellBad,P:SpellCap,
R:SpellRare,L:SpellLocal,-:Conceal,
+:Pmenu,=:PmenuSel,
x:PmenuSbar,X:PmenuThumb")
global
{not in Vi}
This option can be used to set highlighting mode for various
occasions. It is a comma separated list of character pairs. The
first character in a pair gives the occasion, the second the mode to
use for that occasion. The occasions are:
|hl-SpecialKey| 8 Meta and special keys listed with ":map"
|hl-NonText| @ '~' and '@' at the end of the window and
characters from 'showbreak'
|hl-Directory| d directories in CTRL-D listing and other special
things in listings
|hl-ErrorMsg| e error messages
h (obsolete, ignored)
|hl-IncSearch| i 'incsearch' highlighting
|hl-Search| l last search pattern highlighting (see 'hlsearch')
|hl-MoreMsg| m |more-prompt|
|hl-ModeMsg| M Mode (e.g., "-- INSERT --")
|hl-LineNr| n line number for ":number" and ":#" commands, and
when 'number' or 'relativenumber' option is set.
|hl-Question| r |hit-enter| prompt and yes/no questions
|hl-StatusLine| s status line of current window |status-line|
|hl-StatusLineNC| S status lines of not-current windows
|hl-Title| t Titles for output from ":set all", ":autocmd" etc.
|hl-VertSplit| c column used to separate vertically split windows
|hl-Visual| v Visual mode
|hl-VisualNOS| V Visual mode when Vim does is "Not Owning the
Selection" Only X11 Gui's |gui-x11| and
|xterm-clipboard|.
|hl-WarningMsg| w warning messages
|hl-WildMenu| W wildcard matches displayed for 'wildmenu'
*'history'* *'hi'*
'history' 'hi' number (Vim default: 20, Vi default: 0)
global
{not in Vi}
A history of ":" commands, and a history of previous search patterns
are remembered. This option decides how many entries may be stored in
each of these histories (see |cmdline-editing|).
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
Normally you would set 'allowrevins' and use CTRL-_ in insert mode to
toggle this option. See |rileft.txt|.
NOTE: This option is reset when 'compatible' is set.
*'icon'* *'noicon'*
'icon' boolean (default off, on when title can be restored)
global
{not in Vi}
{not available when compiled without the |+title|
feature}
When on, the icon text of the window will be set to the value of
'iconstring' (if it is not empty), or to the name of the file
currently being edited. Only the last part of the name is used.
Overridden by the 'iconstring' option.
Only works if the terminal supports setting window icons (currently
only X11 GUI and terminals with a non-empty 't_IS' option - these are
Unix xterm and iris-ansi by default, where 't_IS' is taken from the
builtin termcap).
When Vim was compiled with HAVE_X11 defined, the original icon will be
restored if possible |X11|. See |X11-icon| for changing the icon on
X11.
*'iconstring'*
'iconstring' string (default "")
global
{not in Vi}
{not available when compiled without the |+title|
feature}
When this option is not empty, it will be used for the icon text of
the window. This happens only when the 'icon' option is on.
Only works if the terminal supports setting window icon text
(currently only X11 GUI and terminals with a non-empty 't_IS' option).
Does not work for MS Windows.
When Vim was compiled with HAVE_X11 defined, the original icon will be
restored if possible |X11|.
When this option contains printf-style '%' items, they will be
expanded according to the rules used for 'statusline'. See
'titlestring' for example settings.
{not available when compiled without the |+statusline| feature}
*'imactivatekey'* *'imak'*
'imactivatekey' 'imak' string (default "")
global
{not in Vi}
{only available when compiled with |+xim| and
YXXY+GUI_GTK|} *E599*
Specifies the key that your Input Method in X-Windows uses for
activation. When this is specified correctly, vim can fully control
IM with 'imcmdline', 'iminsert' and 'imsearch'.
You can't use this option to change the activation key, the option
tells Vim what the key is.
Format:
[MODIFIER_FLAG-]KEY_STRING
*'iminsert'* *'imi'*
'iminsert' 'imi' number (default 0, 2 when an input method is supported)
local to buffer
{not in Vi}
Specifies whether :lmap or an Input Method (IM) is to be used in
Insert mode. Valid values:
0 :lmap is off and IM is off
1 :lmap is ON and IM is off
2 :lmap is off and IM is ON
2 is available only when compiled with the |+multi_byte_ime|, |+xim|
or |global-ime|.
To always reset the option to zero when leaving Insert mode with <Esc>
this can be used:
:inoremap <ESC> <ESC>:set iminsert=0<CR>
This makes :lmap and IM turn off automatically when leaving Insert
mode.
Note that this option changes when using CTRL-^ in Insert mode
|i_CTRL-^|.
The value is set to 1 when setting 'keymap' to a valid keymap name.
It is also used for the argument of commands like "r" and "f".
The value 0 may not work correctly with Athena and Motif with some XIM
methods. Use 'imdisable' to disable XIM then.
*'imsearch'* *'ims'*
'imsearch' 'ims' number (default 0, 2 when an input method is supported)
local to buffer
{not in Vi}
Specifies whether :lmap or an Input Method (IM) is to be used when
entering a search pattern. Valid values:
-1 the value of 'iminsert' is used, makes it look like
'iminsert' is also used when typing a search pattern
0 :lmap is off and IM is off
1 :lmap is ON and IM is off
2 :lmap is off and IM is ON
Note that this option changes when using CTRL-^ in Command-line mode
|c_CTRL-^|.
The value is set to 1 when it is not -1 and setting the 'keymap'
option to a valid keymap name.
The value 0 may not work correctly with Athena and Motif with some XIM
methods. Use 'imdisable' to disable XIM then.
*'include'* *'inc'*
'include' 'inc' string (default "^\s*#\s*include")
global or local to buffer |global-local|
{not in Vi}
{not available when compiled without the
|+find_in_path| feature}
Pattern to be used to find an include command. It is a search
pattern, just like for the "/" command (See |pattern|). The default
value is for C programs. This option is used for the commands "[i",
"]I", "[d", etc.
Normally the 'isfname' option is used to recognize the file name that
comes after the matched pattern. But if "\zs" appears in the pattern
then the text matched from "\zs" to the end, or until "\ze" if it
appears, is used as the file name. Use this to include characters
that are not in 'isfname', such as a space. You can then use
'includeexpr' to process the matched text.
See |option-backslash| about including spaces and backslashes.
*'includeexpr'* *'inex'*
'includeexpr' 'inex' string (default "")
local to buffer
{not in Vi}
{not available when compiled without the
|+find_in_path| or |+eval| features}
Expression to be used to transform the string found with the 'include'
option to a file name. Mostly useful to change "." to "/" for Java:
:set includeexpr=substitute(v:fname,'\\.','/','g')
The "v:fname" variable will be set to the file name that was detected.
Also used for the |gf| command if an unmodified file name can't be
found. Allows doing "gf" on the name after an 'include' statement.
Also used for |<cfile>|.
The expression may be evaluated in the |sandbox|, see
|sandbox-option|.
It is not allowed to change text or jump to another window while
evaluating 'includeexpr' |textlock|.
*'indentexpr'* *'inde'*
'indentexpr' 'inde' string (default "")
local to buffer
{not in Vi}
{not available when compiled without the |+cindent|
or |+eval| features}
Expression which is evaluated to obtain the proper indent for a line.
It is used when a new line is created, for the |=| operator and
in Insert mode as specified with the 'indentkeys' option.
When this option is not empty, it overrules the 'cindent' and
'smartindent' indenting.
When 'paste' is set this option is not used for indenting.
The expression is evaluated with |v:lnum| set to the line number for
which the indent is to be computed. The cursor is also in this line
when the expression is evaluated (but it may be moved around).
The expression must return the number of spaces worth of indent. It
can return "-1" to keep the current indent (this means 'autoindent' is
used for the indent).
Functions useful for computing the indent are |indent()|, |cindent()|
and |lispindent()|.
The evaluation of the expression must not have side effects! It must
not change the text, jump to another window, etc. Afterwards the
cursor position is always restored, thus the cursor may be moved.
Normally this option would be set to call a function:
:set indentexpr=GetMyIndent()
Error messages will be suppressed, unless the 'debug' option contains
"msg".
See |indent-expression|.
NOTE: This option is made empty when 'compatible' is set.
The expression may be evaluated in the |sandbox|, see
|sandbox-option|.
It is not allowed to change text or jump to another window while
evaluating 'indentexpr' |textlock|.
*'indentkeys'* *'indk'*
'indentkeys' 'indk' string (default "0{,0},:,0#,!^F,o,O,e")
local to buffer
{not in Vi}
{not available when compiled without the |+cindent|
feature}
A list of keys that, when typed in Insert mode, cause reindenting of
the current line. Only happens if 'indentexpr' isn't empty.
The format is identical to 'cinkeys', see |indentkeys-format|.
See |C-indenting| and |indent-expression|.
*'isfname'* *'isf'*
'isfname' 'isf' string (default for MS-DOS, Win32 and OS/2:
"@,48-57,/,\,.,-,_,+,,,#,$,%,{,},[,],:,@-@,!,~,="
for AMIGA: "@,48-57,/,.,-,_,+,,,$,:"
for VMS: "@,48-57,/,.,-,_,+,,,#,$,%,<,>,[,],:,;,~"
for OS/390: "@,240-249,/,.,-,_,+,,,#,$,%,~,="
otherwise: "@,48-57,/,.,-,_,+,,,#,$,%,~,=")
global
{not in Vi}
The characters specified by this option are included in file names and
path names. Filenames are used for commands like "gf", "[i" and in
the tags file. It is also used for "\f" in a |pattern|.
Multi-byte characters 256 and above are always included, only the
characters up to 255 are specified with this option.
For UTF-8 the characters 0xa0 to 0xff are included as well.
Think twice before adding white space to this option. Although a
space may appear inside a file name, the effect will be that Vim
doesn't know where a file name starts or ends when doing completion.
It most likely works better without a space in 'isfname'.
Note that on systems using a backslash as path separator, Vim tries to
do its best to make it work as you would expect. That is a bit
tricky, since Vi originally used the backslash to escape special
characters. Vim will not remove a backslash in front of a normal file
name character on these systems, but it will on Unix and alikes. The
'&' and '^' are not included by default, because these are special for
cmd.exe.
The format of this option is a list of parts, separated with commas.
Each part can be a single character number or a range. A range is two
character numbers with '-' in between. A character number can be a
decimal number between 0 and 255 or the ASCII character itself (does
not work for digits). Example:
"_,-,128-140,#-43" (include '_' and '-' and the range
128 to 140 and '#' to 43)
If a part starts with '^', the following character number or range
will be excluded from the option. The option is interpreted from left
to right. Put the excluded character after the range where it is
included. To include '^' itself use it as the last character of the
option or the end of a range. Example:
"^a-z,#,^" (exclude 'a' to 'z', include '#' and '^')
If the character is '@', all characters where isalpha() returns TRUE
are included. Normally these are the characters a to z and A to Z,
plus accented characters. To include '@' itself use "@-@". Examples:
"@,^a-z" All alphabetic characters, excluding lower
case ASCII letters.
"a-z,A-Z,@-@" All letters plus the '@' character.
A comma can be included by using it where a character number is
expected. Example:
"48-57,,,_" Digits, comma and underscore.
A comma can be excluded by prepending a '^'. Example:
" -~,^,,9" All characters from space to '~', excluding
comma, plus <Tab>.
See |option-backslash| about including spaces and backslashes.
*'isident'* *'isi'*
'isident' 'isi' string (default for MS-DOS, Win32 and OS/2:
"@,48-57,_,128-167,224-235"
otherwise: "@,48-57,_,192-255")
global
{not in Vi}
The characters given by this option are included in identifiers.
Identifiers are used in recognizing environment variables and after a
match of the 'define' option. It is also used for "\i" in a
|pattern|. See 'isfname' for a description of the format of this
option.
Careful: If you change this option, it might break expanding
environment variables. E.g., when '/' is included and Vim tries to
*'iskeyword'* *'isk'*
'iskeyword' 'isk' string (Vim default for MS-DOS and Win32:
"@,48-57,_,128-167,224-235"
otherwise: "@,48-57,_,192-255"
Vi default: "@,48-57,_")
local to buffer
{not in Vi}
Keywords are used in searching and recognizing with many commands:
"w", "*", "[i", etc. It is also used for "\k" in a |pattern|. See
'isfname' for a description of the format of this option. For C
programs you could use "a-z,A-Z,48-57,_,.,-,>".
For a help file it is set to all non-blank printable characters except
'*', '"'' and '|' (so that CTRL-] on a command finds the help for that
command).
When the 'lisp' option is on the '-' character is always included.
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
*'isprint'* *'isp'*
'isprint' 'isp' string (default for MS-DOS, Win32, OS/2 and Macintosh:
"@,~-255"; otherwise: "@,161-255")
global
{not in Vi}
The characters given by this option are displayed directly on the
screen. It is also used for "\p" in a |pattern|. The characters from
space (ASCII 32) to '~' (ASCII 126) are always displayed directly,
even when they are not included in 'isprint' or excluded. See
'isfname' for a description of the format of this option.
Non-printable characters are displayed with two characters:
0 - 31 "^@" - "^_"
32 - 126 always single characters
127 "^?"
128 - 159 "~@" - "~_"
160 - 254 "| " - "|~"
255 "~?"
When 'encoding' is a Unicode one, illegal bytes from 128 to 255 are
displayed as <xx>, with the hexadecimal value of the byte.
When 'display' contains "uhex" all unprintable characters are
displayed as <xx>.
The SpecialKey highlighting will be used for unprintable characters.
|hl-SpecialKey|
Multi-byte characters 256 and above are always included, only the
characters up to 255 are specified with this option. When a character
is printable but it is not available in the current font, a
replacement character will be shown.
Unprintable and zero-width Unicode characters are displayed as <xxxx>.
There is no option to specify these characters.
*'key'*
'key' string (default "")
local to buffer
{not in Vi}
{only available when compiled with the |+cryptv|
feature}
The key that is used for encrypting and decrypting the current buffer.
See |encryption| and 'cryptmethod'.
Careful: Do not set the key value by hand, someone might see the typed
key. Use the |:X| command. But you can make 'key' empty:
:set key=
It is not possible to get the value of this option with ":set key" or
"echo &key". This is to avoid showing it to someone who shouldn't
know. It also means you cannot see it yourself once you have set it,
be careful not to make a typing error!
*'keymodel'* *'km'*
'keymodel' 'km' string (default "")
global
{not in Vi}
List of comma separated words, which enable special things that keys
can do. These values can be used:
startsel Using a shifted special key starts selection (either
Select mode or Visual mode, depending on "key" being
present in 'selectmode').
stopsel Using a not-shifted special key stops selection.
Special keys in this context are the cursor keys, <End>, <Home>,
<PageUp> and <PageDown>.
The 'keymodel' option is set by the |:behave| command.
*'keywordprg'* *'kp'*
'keywordprg' 'kp' string
(default "man" or "man -s", DOS: ":help",
OS/2: "view /", VMS: "help")
global or local to buffer |global-local|
{not in Vi}
Program to use for the |K| command. Environment variables are
expanded |:set_env|. ":help" may be used to access the Vim internal
help. (Note that previously setting the global option to the empty
value did this, which is now deprecated.)
When "man" is used, Vim will automatically translate a count for the
"K" command to a section number. Also for "man -s", in which case the
"-s" is removed when there is no count.
See |option-backslash| about including spaces and backslashes.
Example:
:set keywordprg=man\ -s
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
Example: "aA,fgh;FGH,cCdDeE"
Special characters need to be preceded with a backslash. These are
";", ',' and backslash itself.
This will allow you to activate vim actions without having to switch
back and forth between the languages. Your language characters will
be understood as normal vim English characters (according to the
langmap mappings) in the following cases:
o Normal/Visual mode (commands, buffer/register names, user mappings)
o Insert/Replace Mode: Register names after CTRL-R
o Insert/Replace Mode: Mappings
Characters entered in Command-line mode will NOT be affected by
this option. Note that this option can be changed at any time
allowing to switch between mappings for different languages/encodings.
Use a mapping to avoid having to type it each time!
*'langmenu'* *'lm'*
'langmenu' 'lm' string (default "")
global
{not in Vi}
{only available when compiled with the |+menu| and
|+multi_lang| features}
Language to use for menu translation. Tells which file is loaded
from the "lang" directory in 'runtimepath':
"lang/menu_" . &langmenu . ".vim"
(without the spaces). For example, to always use the Dutch menus, no
matter what $LANG is set to:
:set langmenu=nl_NL.ISO_8859-1
When 'langmenu' is empty, |v:lang| is used.
Only normal file name characters can be used, "/\*?[|<>" are illegal.
If your $LANG is set to a non-English language but you do want to use
the English menus:
:set langmenu=none
This option must be set before loading menus, switching on filetype
detection or syntax highlighting. Once the menus are defined setting
this option has no effect. But you could do this:
:source $VIMRUNTIME/delmenu.vim
:set langmenu=de_DE.ISO_8859-1
:source $VIMRUNTIME/menu.vim
Warning: This deletes all menus that you defined yourself!
*'laststatus'* *'ls'*
'laststatus' 'ls' number (default 1)
global
{not in Vi}
The value of this option influences when the last window will have a
status line:
0: never
1: only if there are at least two windows
2: always
The screen looks nicer with a status line if you have several
windows, but it takes another screen line. |status-line|
*'lines'* *E593*
'lines' number (default 24 or terminal height)
global
Number of lines of the Vim window.
Normally you don't need to set this. It is done automatically by the
terminal initialization code. Also see |posix-screen-size|.
When Vim is running in the GUI or in a resizable window, setting this
option will cause the window size to be changed. When you only want
to use the size for the GUI, put the command in your |gvimrc| file.
Vim limits the number of lines to what fits on the screen. You can
use this command to get the tallest window possible:
:set lines=999
Minimum value is 2, maximum value is 1000.
If you get less lines than expected, check the 'guiheadroom' option.
When you set this option and Vim is unable to change the physical
number of lines of the display, the display may be messed up.
*'linespace'* *'lsp'*
'linespace' 'lsp' number (default 0, 1 for Win32 GUI)
global
{not in Vi}
{only in the GUI}
Number of pixel lines inserted between characters. Useful if the font
uses the full character cell height, making lines touch each other.
When non-zero there is room for underlining.
With some fonts there can be too much room between lines (to have
space for ascents and descents). Then it makes sense to set
'linespace' to a negative value. This may cause display problems
though!
*'lisp'* *'nolisp'*
'lisp' boolean (default off)
local to buffer
{not available when compiled without the |+lispindent|
feature}
Lisp mode: When <Enter> is typed in insert mode set the indent for
the next line to Lisp standards (well, sort of). Also happens with
"cc" or "S". 'autoindent' must also be on for this to work. The 'p'
flag in 'cpoptions' changes the method of indenting: Vi compatible or
better. Also see 'lispwords'.
The '-' character is included in keyword characters. Redefines the
"=" operator to use this same indentation algorithm rather than
calling an external program if 'equalprg' is empty.
This option is not used when 'paste' is set.
{Vi: Does it a little bit differently}
*'lispwords'* *'lw'*
'lispwords' 'lw' string (default is very long)
global
{not in Vi}
{not available when compiled without the |+lispindent|
feature}
Comma separated list of words that influence the Lisp indenting.
|'lisp'|
*'list'* *'nolist'*
'list' boolean (default off)
local to window
List mode: Show tabs as CTRL-I is displayed, display $ after end of
line. Useful to see the difference between tabs and spaces and for
trailing blanks. Further changed by the 'listchars' option.
The cursor is displayed at the start of the space a Tab character
occupies, not at the end as usual in Normal mode. To get this cursor
position while displaying Tabs with spaces, use:
:set list lcs=tab\ \
Note that list mode will also affect formatting (set with 'textwidth'
or 'wrapmargin') when 'cpoptions' includes 'L'. See 'listchars' for
changing the way tabs are displayed.
*'listchars'* *'lcs'*
'listchars' 'lcs' string (default "eol:$")
global
{not in Vi}
Strings to use in 'list' mode and for the |:list| command. It is a
comma separated list of string settings.
eol:c Character to show at the end of each line. When
omitted, there is no extra character at the end of the
line.
tab:xy Two characters to be used to show a tab. The first
char is used once. The second char is repeated to
fill the space that the tab normally occupies.
"tab:>-" will show a tab that takes four spaces as
">---". When omitted, a tab is show as ^I.
trail:c Character to show for trailing spaces. When omitted,
trailing spaces are blank.
extends:c Character to show in the last column, when 'wrap' is
off and the line continues beyond the right of the
screen.
precedes:c Character to show in the first column, when 'wrap'
is off and there is text preceding the character
visible in the first column.
conceal:c Character to show in place of concealed text, when
'conceallevel' is set to 1.
nbsp:c Character to show for a non-breakable space (character
0xA0, 160). Left blank when omitted.
The characters ':' and ',' should not be used. UTF-8 characters can
be used when 'encoding' is "utf-8", otherwise only printable
characters are allowed. All characters must be single width.
Examples:
:set lcs=tab:>-,trail:-
:set lcs=tab:>-,eol:<,nbsp:%
:set lcs=extends:>,precedes:<
The "NonText" highlighting will be used for "eol", "extends" and
"precedes". "SpecialKey" for "nbsp", "tab" and "trail".
|hl-NonText| |hl-SpecialKey|
*'macatsui'* *'nomacatsui'*
'macatsui' boolean (default on)
global
{only available in Mac GUI version}
This is a workaround for when drawing doesn't work properly. When set
and compiled with multi-byte support ATSUI text drawing is used. When
not set ATSUI text drawing is not used. Switch this option off when
you experience drawing problems. In a future version the problems may
be solved and this option becomes obsolete. Therefore use this method
to unset it:
if exists('&macatsui')
set nomacatsui
endif
Another option to check if you have drawing problems is
'termencoding'.
*'magic'* *'nomagic'*
'magic' boolean (default on)
global
Changes the special characters that can be used in search patterns.
See |pattern|.
NOTE: To avoid portability problems with using patterns, always keep
this option at the default "on". Only switch it off when working with
old Vi scripts. In any other situation write patterns that work when
'magic' is on. Include "\M" when you want to |/\M|.
*'makeef'* *'mef'*
'makeef' 'mef' string (default: "")
global
{not in Vi}
{not available when compiled without the |+quickfix|
feature}
Name of the errorfile for the |:make| command (see |:make_makeprg|)
and the |:grep| command.
When it is empty, an internally generated temp file will be used.
When "##" is included, it is replaced by a number to make the name
unique. This makes sure that the ":make" command doesn't overwrite an
existing file.
NOT used for the ":cf" command. See 'errorfile' for that.
Environment variables are expanded |:set_env|.
See |option-backslash| about including spaces and backslashes.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'makeprg'* *'mp'*
'makeprg' 'mp' string (default "make", VMS: "MMS")
global or local to buffer |global-local|
{not in Vi}
Program to use for the ":make" command. See |:make_makeprg|.
This option may contain '%' and '#' characters, which are expanded to
the current and alternate file name. |:_%| |:_#|
Environment variables are expanded |:set_env|. See |option-backslash|
about including spaces and backslashes.
Note that a '|' must be escaped twice: once for ":set" and once for
the interpretation of a command. When you use a filter called
"myfilter" do it like this:
:set makeprg=gmake\ \\\|\ myfilter
The placeholder "$*" can be given (even multiple times) to specify
where the arguments will be included, for example:
:set makeprg=latex\ \\\\nonstopmode\ \\\\input\\{$*}
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'matchpairs'* *'mps'*
'matchpairs' 'mps' string (default "(:),{:},[:]")
local to buffer
{not in Vi}
Characters that form pairs. The |%| command jumps from one to the
other. Currently only single byte character pairs are allowed, and
they must be different. The characters must be separated by a colon.
The pairs must be separated by a comma. Example for including '<' and
'>' (HTML):
:set mps+=<:>
A more exotic example, to jump between the '=' and ';' in an
assignment, useful for languages like C and Java:
:au FileType c,cpp,java set mps+==:;
For a more advanced way of using "%", see the matchit.vim plugin in
the $VIMRUNTIME/macros directory. |add-local-help|
*'matchtime'* *'mat'*
'matchtime' 'mat' number (default 5)
global
{not in Vi}{in Nvi}
Tenths of a second to show the matching paren, when 'showmatch' is
set. Note that this is not in milliseconds, like other options that
set a time. This is to be compatible with Nvi.
*'maxcombine'* *'mco'*
'maxcombine' 'mco' number (default 2)
global
{not in Vi}
{only available when compiled with the |+multi_byte|
feature}
The maximum number of combining characters supported for displaying.
Only used when 'encoding' is "utf-8".
The default is OK for most languages. Hebrew may require 4.
Maximum value is 6.
Even when this option is set to 2 you can still edit text with more
combining characters, you just can't see them. Use |g8| or |ga|.
See |mbyte-combining|.
*'maxfuncdepth'* *'mfd'*
*'maxmem'* *'mm'*
'maxmem' 'mm' number (default between 256 to 5120 (system
dependent) or half the amount of memory
available)
global
{not in Vi}
Maximum amount of memory (in Kbyte) to use for one buffer. When this
limit is reached allocating extra memory for a buffer will cause
other memory to be freed. The maximum usable value is about 2000000.
Use this to work without a limit. Also see 'maxmemtot'.
*'maxmempattern'* *'mmp'*
'maxmempattern' 'mmp' number (default 1000)
global
{not in Vi}
Maximum amount of memory (in Kbyte) to use for pattern matching.
The maximum value is about 2000000. Use this to work without a limit.
*E363*
When Vim runs into the limit it gives an error message and mostly
behaves like CTRL-C was typed.
Running into the limit often means that the pattern is very
inefficient or too complex. This may already happen with the pattern
"\(.\)*" on a very long line. ".*" works much better.
Vim may run out of memory before hitting the 'maxmempattern' limit.
*'maxmemtot'* *'mmt'*
'maxmemtot' 'mmt' number (default between 2048 and 10240 (system
dependent) or half the amount of memory
available)
global
{not in Vi}
Maximum amount of memory in Kbyte to use for all buffers together.
The maximum usable value is about 2000000 (2 Gbyte). Use this to work
without a limit. On 64 bit machines higher values might work. But
hey, do you really need more than 2 Gbyte for text editing?
Also see 'maxmem'.
*'menuitems'* *'mis'*
'menuitems' 'mis' number (default 25)
global
{not in Vi}
{not available when compiled without the |+menu|
feature}
Maximum number of items to use in a menu. Used for menus that are
generated from a list of items, e.g., the Buffers menu. Changing this
option has no direct effect, the menu must be refreshed first.
*'mkspellmem'* *'msm'*
'mkspellmem' 'msm' string (default "460000,2000,500")
global
{not in Vi}
{not available when compiled without the |+syntax|
feature}
Parameters for |:mkspell|. This tunes when to start compressing the
word tree. Compression can be slow when there are many words, but
it's needed to avoid running out of memory. The amount of memory used
per word depends very much on how similar the words are, that's why
this tuning is complicated.
There are three numbers, separated by commas:
{start},{inc},{added}
For most languages the uncompressed word tree fits in memory. {start}
gives the amount of memory in Kbyte that can be used before any
compression is done. It should be a bit smaller than the amount of
memory that is available to Vim.
When going over the {start} limit the {inc} number specifies the
amount of memory in Kbyte that can be allocated before another
compression is done. A low number means compression is done after
less words are added, which is slow. A high number means more memory
will be allocated.
After doing compression, {added} times 1024 words can be added before
the {inc} limit is ignored and compression is done when any extra
amount of memory is needed. A low number means there is a smaller
chance of hitting the {inc} limit, less memory is used but it's
slower.
The languages for which these numbers are important are Italian and
Hungarian. The default works for when you have about 512 Mbyte. If
you have 1 Gbyte you could use:
:set mkspellmem=900000,3000,800
If you have less than 512 Mbyte |:mkspell| may fail for some
languages, no matter what you set 'mkspellmem' to.
*'more'* *'nomore'*
'more' boolean (Vim default: on, Vi default: off)
global
{not in Vi}
When on, listings pause when the whole screen is filled. You will get
the |more-prompt|. When this option is off there are no pauses, the
listing continues until finished.
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
*'mouse'* *E538*
'mouse' string (default "", "a" for GUI, MS-DOS and Win32)
global
{not in Vi}
Enable the use of the mouse. Only works for certain terminals
(xterm, MS-DOS, Win32 |win32-mouse|, QNX pterm, *BSD console with
sysmouse and Linux console with gpm). For using the mouse in the
GUI, see |gui-mouse|.
The mouse can be enabled for different modes:
n Normal mode
v Visual mode
i Insert mode
c Command-line mode
h all previous modes when editing a help file
a all previous modes
r for |hit-enter| and |more-prompt| prompt
Normally you would enable the mouse in all four modes with:
:set mouse=a
When the mouse is not enabled, the GUI will still use the mouse for
modeless selection. This doesn't move the text cursor.
See |mouse-using|. Also see |'clipboard'|.
Note: When enabling the mouse in a terminal, copy/paste will use the
"* register if there is access to an X-server. The xterm handling of
the mouse buttons can still be used by keeping the shift key pressed.
Also see the 'clipboard' option.
*'mousemodel'* *'mousem'*
'mousemodel' 'mousem' string (default "extend", "popup" for MS-DOS and Win32)
global
{not in Vi}
Sets the model to use for the mouse. The name mostly specifies what
the right mouse button is used for:
extend Right mouse button extends a selection. This works
like in an xterm.
popup Right mouse button pops up a menu. The shifted left
mouse button extends a selection. This works like
with Microsoft Windows.
popup_setpos Like "popup", but the cursor will be moved to the
position where the mouse was clicked, and thus the
selected operation will act upon the clicked object.
If clicking inside a selection, that selection will
be acted upon, i.e. no cursor move. This implies of
course, that right clicking outside a selection will
end Visual mode.
:set mouseshape=s:udsizing,m:no
will make the mouse turn to a sizing arrow over the status lines and
indicate no input when the hit-enter prompt is displayed (since
clicking the mouse has no effect in this state.)
*'mousetime'* *'mouset'*
'mousetime' 'mouset' number (default 500)
global
{not in Vi}
Only for GUI, MS-DOS, Win32 and Unix with xterm. Defines the maximum
time in msec between two mouse clicks for the second click to be
recognized as a multi click.
*'mzquantum'* *'mzq'*
'mzquantum' 'mzq' number (default 100)
global
{not in Vi}
{not available when compiled without the |+mzscheme|
feature}
The number of milliseconds between polls for MzScheme threads.
Negative or zero value means no thread scheduling.
*'nrformats'* *'nf'*
'nrformats' 'nf' string (default "octal,hex")
local to buffer
{not in Vi}
This defines what bases Vim will consider for numbers when using the
CTRL-A and CTRL-X commands for adding to and subtracting from a number
respectively; see |CTRL-A| for more info on these commands.
alpha If included, single alphabetical characters will be
incremented or decremented. This is useful for a list with a
letter index a), b), etc. *octal-number*
octal If included, numbers that start with a zero will be considered
to be octal. Example: Using CTRL-A on "007" results in "010".
hex If included, numbers starting with "0x" or "0X" will be
considered to be hexadecimal. Example: Using CTRL-X on
"0x100" results in "0x0ff".
Numbers which simply begin with a digit in the range 1-9 are always
considered decimal. This also happens for numbers that are not
recognized as octal or hex.
*'numberwidth'* *'nuw'*
'numberwidth' 'nuw' number (Vim default: 4 Vi default: 8)
local to window
{not in Vi}
{only available when compiled with the |+linebreak|
feature}
Minimal number of columns to use for the line number. Only relevant
when the 'number' or 'relativenumber' option is set or printing lines
with a line number. Since one space is always between the number and
the text, there is one less character for the number itself.
The value is the minimum width. A bigger width is used when needed to
fit the highest line number in the buffer respectively the number of
rows in the window, depending on whether 'number' or 'relativenumber'
is set. Thus with the Vim default of 4 there is room for a line number
up to 999. When the buffer has 1000 lines five columns will be used.
The minimum value is 1, the maximum value is 10.
NOTE: 'numberwidth' is reset to 8 when 'compatible' is set.
*'omnifunc'* *'ofu'*
*'operatorfunc'* *'opfunc'*
'operatorfunc' 'opfunc' string (default: empty)
global
{not in Vi}
This option specifies a function to be called by the |g@| operator.
See |:map-operator| for more info and an example.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'paragraphs'* *'para'*
'paragraphs' 'para' string (default "IPLPPPQPP TPHPLIPpLpItpplpipbp")
global
Specifies the nroff macros that separate paragraphs. These are pairs
of two letters (see |object-motions|).
*'paste'* *'nopaste'*
'paste' boolean (default off)
global
{not in Vi}
Put Vim in Paste mode. This is useful if you want to cut or copy
some text from one window and paste it in Vim. This will avoid
unexpected effects.
Setting this option is useful when using Vim in a terminal, where Vim
cannot distinguish between typed text and pasted text. In the GUI, Vim
knows about pasting and will mostly do the right thing without 'paste'
being set. The same is true for a terminal where Vim handles the
mouse clicks itself.
This option is reset when starting the GUI. Thus if you set it in
your .vimrc it will work in a terminal, but not in the GUI. Setting
'paste' in the GUI has side effects: e.g., the Paste toolbar button
will no longer work in Insert mode, because it uses a mapping.
When the 'paste' option is switched on (also when it was already on):
- mapping in Insert mode and Command-line mode is disabled
*'pastetoggle'* *'pt'*
'pastetoggle' 'pt' string (default "")
global
{not in Vi}
When non-empty, specifies the key sequence that toggles the 'paste'
option. This is like specifying a mapping:
:map {keys} :set invpaste<CR>
Where {keys} is the value of 'pastetoggle'.
The difference is that it will work even when 'paste' is set.
'pastetoggle' works in Insert mode and Normal mode, but not in
Command-line mode.
Mappings are checked first, thus overrule 'pastetoggle'. However,
when 'paste' is on mappings are ignored in Insert mode, thus you can do
this:
:map <F10> :set paste<CR>
:map <F11> :set nopaste<CR>
:imap <F10> <C-O>:set paste<CR>
:imap <F11> <nop>
:set pastetoggle=<F11>
This will make <F10> start paste mode and <F11> stop paste mode.
Note that typing <F10> in paste mode inserts "<F10>", since in paste
mode everything is inserted literally, except the 'pastetoggle' key
sequence.
When the value has several bytes 'ttimeoutlen' applies.
*'pex'* *'patchexpr'*
'patchexpr' 'pex' string (default "")
global
{not in Vi}
{not available when compiled without the |+diff|
feature}
Expression which is evaluated to apply a patch to a file and generate
the resulting new version of the file. See |diff-patchexpr|.
Only normal file name characters can be used, "/\*?[|<>" are illegal.
*'previewheight'* *'pvh'*
*'previewwindow'* *'nopreviewwindow'*
*'pvw'* *'nopvw'* *E590*
'previewwindow' 'pvw' boolean (default off)
local to window
{not in Vi}
{not available when compiled without the |+windows| or
|+quickfix| features}
Identifies the preview window. Only one window can have this option
set. It's normally not set directly, but by using one of the commands
|:ptag|, |:pedit|, etc.
*'printdevice'* *'pdev'*
'printdevice' 'pdev' string (default empty)
global
{not in Vi}
{only available when compiled with the |+printer|
feature}
The name of the printer to be used for |:hardcopy|.
See |pdev-option|.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'printencoding'* *'penc'*
'printencoding' 'penc' String (default empty, except for some systems)
global
{not in Vi}
{only available when compiled with the |+printer|
and |+postscript| features}
Sets the character encoding used when printing.
See |penc-option|.
*'printexpr'* *'pexpr'*
'printexpr' 'pexpr' String (default: see below)
global
{not in Vi}
{only available when compiled with the |+printer|
and |+postscript| features}
Expression used to print the PostScript produced with |:hardcopy|.
See |pexpr-option|.
*'printfont'* *'pfn'*
'printfont' 'pfn' string (default "courier")
global
{not in Vi}
{only available when compiled with the |+printer|
feature}
The name of the font that will be used for |:hardcopy|.
See |pfn-option|.
*'printheader'* *'pheader'*
'printheader' 'pheader' string (default "%<%f%h%m%=Page %N")
global
{not in Vi}
{only available when compiled with the |+printer|
feature}
The format of the header produced in |:hardcopy| output.
See |pheader-option|.
*'printmbcharset'* *'pmbcs'*
'printmbcharset' 'pmbcs' string (default "")
global
{not in Vi}
{only available when compiled with the |+printer|,
|+postscript| and |+multi_byte| features}
The CJK character set to be used for CJK output from |:hardcopy|.
See |pmbcs-option|.
*'printmbfont'* *'pmbfn'*
'printmbfont' 'pmbfn' string (default "")
global
{not in Vi}
{only available when compiled with the |+printer|,
|+postscript| and |+multi_byte| features}
List of font names to be used for CJK output from |:hardcopy|.
See |pmbfn-option|.
*'printoptions'* *'popt'*
'printoptions' 'popt' string (default "")
global
{not in Vi}
{only available when compiled with |+printer| feature}
List of items that control the format of the output of |:hardcopy|.
See |popt-option|.
*'prompt'* *'noprompt'*
'prompt' boolean (default on)
global
When on a ":" prompt is used in Ex mode.
*'pumheight'* *'ph'*
'pumheight' 'ph' number (default 0)
global
{not available when compiled without the
|+insert_expand| feature}
{not in Vi}
Determines the maximum number of items to show in the popup menu for
Insert mode completion. When zero as much space as available is used.
|ins-completion-menu|.
*'quoteescape'* *'qe'*
'quoteescape' 'qe' string (default "\")
local to buffer
{not in Vi}
The characters that are used to escape quotes in a string. Used for
objects like a', a" and a` |a'|.
When one of the characters in this option is found inside a string,
the following character will be skipped. The default value makes the
text "foo\"bar\\" considered to be one string.
*'redrawtime'* *'rdt'*
'redrawtime' 'rdt' number (default 2000)
global
{not in Vi}
{only available when compiled with the |+reltime|
feature}
The time in milliseconds for redrawing the display. This applies to
searching for patterns for 'hlsearch' and |:match| highlighting.
When redrawing takes more than this many milliseconds no further
matches will be highlighted. This is used to avoid that Vim hangs
when using a very complicated pattern.
{not in Vi}
Show the line number relative to the line with the cursor in front of
each line. Relative line numbers help you use the |count| you can
precede some vertical motion commands (e.g. j k + -) with, without
having to calculate it yourself. Especially useful in combination with
other commands (e.g. y d c < > gq gw =).
When the 'n' option is excluded from 'cpoptions' a wrapped
line will not use the column of line numbers (this is the default when
'compatible' isn't set).
The 'numberwidth' option can be used to set the room used for the line
number.
When a long, wrapped line doesn't start with the first character, '-'
characters are put before the number.
See |hl-LineNr| for the highlighting used for the number.
When setting this option, 'number' is reset.
*'remap'* *'noremap'*
'remap' boolean (default on)
global
Allows for mappings to work recursively. If you do not want this for
a single entry, use the :noremap[!] command.
NOTE: To avoid portability problems with Vim scripts, always keep
this option at the default "on". Only switch it off when working with
old Vi scripts.
*'report'*
'report' number (default 2)
global
Threshold for reporting number of lines changed. When the number of
changed lines is more than 'report' a message will be given for most
":" commands. If you want it always, set 'report' to 0.
For the ":substitute" command the number of substitutions is used
instead of the number of lines.
*'rightleftcmd'* *'rlc'*
'rightleftcmd' 'rlc' string (default "search")
local to window
{not in Vi}
{only available when compiled with the |+rightleft|
feature}
Each word in this option enables the command line editing to work in
right-to-left mode for a group of commands:
search "/" and "?" commands
This is useful for languages such as Hebrew, Arabic and Farsi.
The 'rightleft' option must be set for 'rightleftcmd' to take effect.
*'rulerformat'* *'ruf'*
'rulerformat' 'ruf' string (default empty)
global
{not in Vi}
{not available when compiled without the |+statusline|
feature}
When this option is not empty, it determines the content of the ruler
string, as displayed for the 'ruler' option.
The format of this option is like that of 'statusline'.
The default ruler width is 17 characters. To make the ruler 15
characters wide, put "%15(" at the start and "%)" at the end.
Example:
:set rulerformat=%15(%c%V\ %p%%%)
$VIM:vimfiles:after"
RISC-OS: "Choices:vimfiles,
$VIMRUNTIME,
Choices:vimfiles/after"
VMS: "sys$login:vimfiles,
$VIM/vimfiles,
$VIMRUNTIME,
$VIM/vimfiles/after,
sys$login:vimfiles/after")
global
{not in Vi}
This is a list of directories which will be searched for runtime
files:
filetype.vim filetypes by file name |new-filetype|
scripts.vim filetypes by file contents |new-filetype-scripts|
autoload/ automatically loaded scripts |autoload-functions|
colors/ color scheme files |:colorscheme|
compiler/ compiler files |:compiler|
doc/ documentation |write-local-help|
ftplugin/ filetype plugins |write-filetype-plugin|
indent/ indent scripts |indent-expression|
keymap/ key mapping files |mbyte-keymap|
lang/ menu translations |:menutrans|
menu.vim GUI menus |menu.vim|
plugin/ plugin scripts |write-plugin|
print/ files for printing |postscript-print-encoding|
spell/ spell checking files |spell|
syntax/ syntax files |mysyntaxfile|
tutor/ files for vimtutor |tutor|
And any other file searched for with the |:runtime| command.
The defaults for most systems are setup to search five locations:
1. In your home directory, for your personal preferences.
2. In a system-wide Vim directory, for preferences from the system
administrator.
3. In $VIMRUNTIME, for files distributed with Vim.
*after-directory*
4. In the "after" directory in the system-wide Vim directory. This is
for the system administrator to overrule or add to the distributed
defaults (rarely needed)
5. In the "after" directory in your home directory. This is for
personal preferences to overrule or add to the distributed defaults
or system-wide settings (rarely needed).
Note that, unlike 'path', no wildcards like "**" are allowed. Normal
wildcards are allowed, but can significantly slow down searching for
runtime files. For speed, use as few items as possible and avoid
wildcards.
See |:runtime|.
Example:
:set runtimepath=~/vimruntime,/mygroup/vim,$VIMRUNTIME
This will use the directory "~/vimruntime" first (containing your
personal Vim runtime files), then "/mygroup/vim" (shared between a
group of people) and finally "$VIMRUNTIME" (the distributed runtime
files).
You probably should always include $VIMRUNTIME somewhere, to use the
distributed runtime files. You can put a directory before $VIMRUNTIME
to find files which replace a distributed runtime files. You can put
a directory after $VIMRUNTIME to find files which add to distributed
runtime files.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'scroll'* *'scr'*
'scroll' 'scr' number (default: half the window height)
local to window
Number of lines to scroll with CTRL-U and CTRL-D commands. Will be
set to half the number of lines in the window when the window size
changes. If you give a count to the CTRL-U or CTRL-D command it will
be used as the new value for 'scroll'. Reset to half the window
height with ":set scroll=0". {Vi is a bit different: 'scroll' gives
the number of screen lines instead of file lines, makes a difference
when lines wrap}
local to window
{not in Vi}
{not available when compiled without the |+scrollbind|
feature}
See also |scroll-binding|. When this option is set, the current
window scrolls as other scrollbind windows (windows that also have
this option set) scroll. This option is useful for viewing the
differences between two versions of a file, see 'diff'.
See |'scrollopt'| for options that determine how this option should be
interpreted.
This option is mostly reset when splitting a window to edit another
file. This means that ":split | edit file" results in two windows
with scroll-binding, but ":split file" does not.
*'scrolljump'* *'sj'*
'scrolljump' 'sj' number (default 1)
global
{not in Vi}
Minimal number of lines to scroll when the cursor gets off the
screen (e.g., with "j"). Not used for scroll commands (e.g., CTRL-E,
CTRL-D). Useful if your terminal scrolls very slowly.
When set to a negative number from -1 to -100 this is used as the
percentage of the window height. Thus -50 scrolls half the window
height.
NOTE: This option is set to 1 when 'compatible' is set.
*'scrolloff'* *'so'*
'scrolloff' 'so' number (default 0)
global
{not in Vi}
Minimal number of screen lines to keep above and below the cursor.
This will make some context visible around where you are working. If
you set it to a very large value (999) the cursor line will always be
in the middle of the window (except at the start or end of the file or
when long lines wrap).
For scrolling horizontally see 'sidescrolloff'.
NOTE: This option is set to 0 when 'compatible' is set.
*'scrollopt'* *'sbo'*
'scrollopt' 'sbo' string (default "ver,jump")
global
{not available when compiled without the |+scrollbind|
feature}
{not in Vi}
This is a comma-separated list of words that specifies how
'scrollbind' windows should behave. 'sbo' stands for ScrollBind
Options.
The following words are available:
ver Bind vertical scrolling for 'scrollbind' windows
hor Bind horizontal scrolling for 'scrollbind' windows
jump Applies to the offset between two windows for vertical
scrolling. This offset is the difference in the first
displayed line of the bound windows. When moving
around in a window, another 'scrollbind' window may
reach a position before the start or after the end of
the buffer. The offset is not changed though, when
moving back the 'scrollbind' window will try to scroll
to the desired position when possible.
When now making that window the current one, two
things can be done with the relative offset:
1. When "jump" is not included, the relative offset is
adjusted for the scroll position in the new current
window. When going back to the other window, the
new relative offset will be used.
2. When "jump" is included, the other windows are
scrolled to keep the same relative offset. When
going back to the other window, it still uses the
same relative offset.
Also see |scroll-binding|.
When 'diff' mode is active there always is vertical scroll binding,
even when "ver" isn't there.
*'sections'* *'sect'*
'sections' 'sect' string (default "SHNHH HUnhsh")
global
Specifies the nroff macros that separate sections. These are pairs of
*'selection'* *'sel'*
'selection' 'sel' string (default "inclusive")
global
{not in Vi}
This option defines the behavior of the selection. It is only used
in Visual and Select mode.
Possible values:
value past line inclusive
old no yes
inclusive yes yes
exclusive yes no
"past line" means that the cursor is allowed to be positioned one
character past the line.
"inclusive" means that the last character of the selection is included
in an operation. For example, when "x" is used to delete the
selection.
Note that when "exclusive" is used and selecting from the end
backwards, you cannot include the last character of a line, when
starting in Normal mode and 'virtualedit' empty.
The 'selection' option is set by the |:behave| command.
*'selectmode'* *'slm'*
'selectmode' 'slm' string (default "")
global
{not in Vi}
This is a comma separated list of words, which specifies when to start
Select mode instead of Visual mode, when a selection is started.
Possible values:
mouse when using the mouse
key when using shifted special keys
cmd when using "v", "V" or CTRL-V
See |Select-mode|.
The 'selectmode' option is set by the |:behave| command.
*'sessionoptions'* *'ssop'*
'sessionoptions' 'ssop' string (default: "blank,buffers,curdir,folds,
help,options,tabpages,winsize")
global
{not in Vi}
{not available when compiled without the |+mksession|
feature}
Changes the effect of the |:mksession| command. It is a comma
separated list of words. Each word enables saving and restoring
something:
word save and restore
blank empty windows
buffers hidden and unloaded buffers, not just those in windows
curdir the current directory
folds manually created folds, opened/closed folds and local
fold options
globals global variables that start with an uppercase letter
and contain at least one lowercase letter. Only
String and Number types are stored.
help the help window
localoptions options and mappings local to a window or buffer (not
global values for local options)
options all options and mappings (also global values for local
options)
*'shellcmdflag'* *'shcf'*
'shellcmdflag' 'shcf' string (default: "-c", MS-DOS and Win32, when 'shell'
does not contain "sh" somewhere: "/c")
global
{not in Vi}
Flag passed to the shell to execute "!" and ":!" commands; e.g.,
"bash.exe -c ls" or "command.com /c dir". For the MS-DOS-like
systems, the default is set according to the value of 'shell', to
reduce the need to set this option by the user. It's not used for
OS/2 (EMX figures this out itself). See |option-backslash| about
including spaces and backslashes. See |dos-shell|.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'shellpipe'* *'sp'*
'shellpipe' 'sp' string (default ">", "| tee", "|& tee" or "2>&1| tee")|||
global
{not in Vi}
{not available when compiled without the |+quickfix|
feature}
String to be used to put the output of the ":make" command in the
error file. See also |:make_makeprg|. See |option-backslash| about
including spaces and backslashes.
*'shellquote'* *'shq'*
'shellquote' 'shq' string (default: ""; MS-DOS and Win32, when 'shell'
contains "sh" somewhere: "\"")
global
{not in Vi}
Quoting character(s), put around the command passed to the shell, for
the "!" and ":!" commands. The redirection is kept outside of the
quoting. See 'shellxquote' to include the redirection. It's
probably not useful to set both options.
This is an empty string by default. Only known to be useful for
third-party shells on MS-DOS-like systems, such as the MKS Korn Shell
or bash, where it should be "\"". The default is adjusted according
the value of 'shell', to reduce the need to set this option by the
user. See |dos-shell|.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'shellredir'* *'srr'*
'shellredir' 'srr' string (default ">", ">&" or ">%s 2>&1")
global
{not in Vi}
String to be used to put the output of a filter command in a temporary
file. See also |:!|. See |option-backslash| about including spaces
and backslashes.
The name of the temporary file can be represented by "%s" if necessary
(the file name is appended automatically if no %s appears in the value
of this option).
The default is ">". For Unix, if the 'shell' option is "csh", "tcsh"
or "zsh" during initializations, the default becomes ">&". If the
'shell' option is "sh", "ksh" or "bash" the default becomes
">%s 2>&1". This means that stderr is also included.
For Win32, the Unix checks are done and additionally "cmd" is checked
for, which makes the default ">%s 2>&1". Also, the same names with
".exe" appended are checked for.
The initialization of this option is done after reading the ".vimrc"
and the other initializations, so that when the 'shell' option is set
there, the 'shellredir' option changes automatically unless it was
explicitly set before.
In the future pipes may be used for filtering and this option will
become obsolete (at least for Unix).
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
existing file names, thus this option needs to be set before opening
any file for best results. This might change in the future.
'shellslash' only works when a backslash can be used as a path
separator. To test if this is so use:
if exists('+shellslash')
*'shelltype'* *'st'*
'shelltype' 'st' number (default 0)
global
{not in Vi} {only for the Amiga}
On the Amiga this option influences the way how the commands work
which use a shell.
0 and 1: always use the shell
2 and 3: use the shell only to filter lines
4 and 5: use shell only for ':sh' command
When not using the shell, the command is executed directly.
0 and 2: use "shell 'shellcmdflag' cmd" to start external commands
1 and 3: use "shell cmd" to start external commands
*'shellxquote'* *'sxq'*
'shellxquote' 'sxq' string (default: "";
for Win32, when 'shell' contains "sh"
somewhere: "\""
for Unix, when using system(): "\"")
global
{not in Vi}
Quoting character(s), put around the command passed to the shell, for
the "!" and ":!" commands. Includes the redirection. See
'shellquote' to exclude the redirection. It's probably not useful
to set both options.
This is an empty string by default. Known to be useful for
third-party shells when using the Win32 version, such as the MKS Korn
Shell or bash, where it should be "\"". The default is adjusted
according the value of 'shell', to reduce the need to set this option
by the user. See |dos-shell|.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'shiftwidth'* *'sw'*
'shiftwidth' 'sw' number (default 8)
local to buffer
Number of spaces to use for each step of (auto)indent. Used for
|'cindent'|, |>>|, |<<|, etc.
*'shortmess'* *'shm'*
'shortmess' 'shm' string (Vim default "filnxtToO", Vi default: "",
POSIX default: "A")
global
{not in Vi}
This option helps to avoid all the |hit-enter| prompts caused by file
messages, for example with CTRL-G, and to avoid some other messages.
It is a list of flags:
flag meaning when present
f use "(3 of 5)" instead of "(file 3 of 5)"
i use "[noeol]" instead of "[Incomplete last line]"
l use "999L, 888C" instead of "999 lines, 888 characters"
m use "[+]" instead of "[Modified]"
n use "[New]" instead of "[New File]"
r use "[RO]" instead of "[readonly]"
w use "[w]" instead of "written" for file write message
and "[a]" instead of "appended" for ':w >> file' command
x use "[dos]" instead of "[dos format]", "[unix]" instead of
"[unix format]" and "[mac]" instead of "[mac format]".
a all of the above abbreviations
o overwrite message for writing a file with subsequent message
for reading a file (useful for ":wn" or when 'autowrite' on)
O message for reading a file overwrites any previous message.
Also for quickfix message (e.g., ":cn").
s don't give "search hit BOTTOM, continuing at TOP" or "search
hit TOP, continuing at BOTTOM" messages
t truncate file message at the start if it is too long to fit
on the command-line, "<" will appear in the left most column.
Ignored in Ex mode.
T truncate other messages in the middle if they are too long to
fit on the command line. "..." will appear in the middle.
Ignored in Ex mode.
W don't give "written" or "[w]" when writing a file
A don't give the "ATTENTION" message when an existing swap file
is found.
I don't give the intro message when starting Vim |:intro|.
This gives you the opportunity to avoid that a change between buffers
requires you to hit <Enter>, but still gives as useful a message as
possible for the space available. To get the whole message that you
would have got with 'shm' empty, use ":file!"
Useful values:
shm= No abbreviation of message.
shm=a Abbreviation, but no loss of information.
shm=at Abbreviation, and truncate message when necessary.
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
*'showtabline'* *'stal'*
'showtabline' 'stal' number (default 1)
global
{not in Vi}
{not available when compiled without the |+windows|
feature}
The value of this option specifies when the line with tab page labels
will be displayed:
0: never
1: only if there are at least two tab pages
2: always
This is both for the GUI and non-GUI implementation of the tab pages
line.
See |tab-page| for more information about tab pages.
*'sidescroll'* *'ss'*
'sidescroll' 'ss' number (default 0)
global
{not in Vi}
The minimal number of columns to scroll horizontally. Used only when
the 'wrap' option is off and the cursor is moved off of the screen.
When it is zero the cursor will be put in the middle of the screen.
When using a slow terminal set it to a large number or 0. When using
a fast terminal use a small number or 1. Not used for "zh" and "zl"
commands.
*'sidescrolloff'* *'siso'*
'sidescrolloff' 'siso' number (default 0)
global
{not in Vi}
The minimal number of screen columns to keep to the left and to the
right of the cursor if 'nowrap' is set. Setting this option to a
value greater than 0 while having |'sidescroll'| also at a non-zero
value makes some context visible in the line you are scrolling in
horizontally (except at beginning of the line). Setting this option
to a large value (like 999) has the effect of keeping the cursor
horizontally centered in the window, as long as one does not come too
close to the beginning of the line.
NOTE: This option is set to 0 when 'compatible' is set.
Example: Try this together with 'sidescroll' and 'listchars' as
in the following example to never allow the cursor to move
onto the "extends" character:
:set nowrap sidescroll=1 listchars=extends:>,precedes:<
:set sidescrolloff=1
*'softtabstop'* *'sts'*
'softtabstop' 'sts' number (default 0)
local to buffer
{not in Vi}
Number of spaces that a <Tab> counts for while performing editing
operations, like inserting a <Tab> or using <BS>. It "feels" like
<Tab>s are being inserted, while in fact a mix of spaces and <Tab>s is
used. This is useful to keep the 'ts' setting at its standard value
of 8, while being able to edit like it is set to 'sts'. However,
commands like "x" still work on the actual characters.
When 'sts' is zero, this feature is off.
'softtabstop' is set to 0 when the 'paste' option is set.
See also |ins-expandtab|. When 'expandtab' is not set, the number of
spaces is minimized by using <Tab>s.
The 'L' flag in 'cpoptions' changes how tabs are used when 'list' is
set.
NOTE: This option is set to 0 when 'compatible' is set.
*'spell'* *'nospell'*
'spell' boolean (default off)
local to window
{not in Vi}
{not available when compiled without the |+syntax|
feature}
When on spell checking will be done. See |spell|.
The languages are specified with 'spelllang'.
*'spellcapcheck'* *'spc'*
'spellcapcheck' 'spc' string (default "[.?!]\_[\])'"' \t]\+")
local to buffer
{not in Vi}
{not available when compiled without the |+syntax|
feature}
Pattern to locate the end of a sentence. The following word will be
checked to start with a capital letter. If not then it is highlighted
with SpellCap |hl-SpellCap| (unless the word is also badly spelled).
When this check is not wanted make this option empty.
Only used when 'spell' is set.
Be careful with special characters, see |option-backslash| about
including spaces and backslashes.
To set this option automatically depending on the language, see
|set-spc-auto|.
*'spellfile'* *'spf'*
'spellfile' 'spf' string (default empty)
local to buffer
{not in Vi}
{not available when compiled without the |+syntax|
feature}
Name of the word list file where words are added for the |zg| and |zw|
commands. It must end in ".{encoding}.add". You need to include the
path, otherwise the file is placed in the current directory.
*E765*
It may also be a comma separated list of names. A count before the
|zg| and |zw| commands can be used to access each. This allows using
a personal word list file and a project word list file.
When a word is added while this option is empty Vim will set it for
you: Using the first directory in 'runtimepath' that is writable. If
there is no "spell" directory yet it will be created. For the file
name the first language name that appears in 'spelllang' is used,
ignoring the region.
The resulting ".spl" file will be used for spell checking, it does not
have to appear in 'spelllang'.
Normally one file is used for all regions, but you can add the region
name if you want to. However, it will then only be used when
'spellfile' is set to it, for entries in 'spelllang' only files
without region name will be found.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'spelllang'* *'spl'*
'spelllang' 'spl' string (default "en")
local to buffer
{not in Vi}
{not available when compiled without the |+syntax|
feature}
A comma separated list of word list names. When the 'spell' option is
on spellchecking will be done for these languages. Example:
set spelllang=en_us,nl,medical
This means US English, Dutch and medical words are recognized. Words
that are not recognized will be highlighted.
The word list name must not include a comma or dot. Using a dash is
recommended to separate the two letter language name from a
specification. Thus "en-rare" is used for rare English words.
A region name must come last and have the form "_xx", where "xx" is
the two-letter, lower case region name. You can use more than one
region by listing them: "en_us,en_ca" supports both US and Canadian
English, but not words specific for Australia, New Zealand or Great
Britain.
*E757*
As a special case the name of a .spl file can be given as-is. The
first "_xx" in the name is removed and used as the region name
(_xx is an underscore, two letters and followed by a non-letter).
This is mainly for testing purposes. You must make sure the correct
encoding is used, Vim doesn't check it.
When 'encoding' is set the word lists are reloaded. Thus it's a good
idea to set 'spelllang' after setting 'encoding' to avoid loading the
files twice.
How the related spell files are found is explained here: |spell-load|.
If the |spellfile.vim| plugin is active and you use a language name
for which Vim cannot find the .spl file in 'runtimepath' the plugin
will ask you if you want to download the file.
After this option has been set successfully, Vim will source the files
"spell/LANG.vim" in 'runtimepath'. "LANG" is the value of 'spelllang'
up to the first comma, dot or underscore.
Also see |set-spc-auto|.
*'spellsuggest'* *'sps'*
'spellsuggest' 'sps' string (default "best")
global
{not in Vi}
{not available when compiled without the |+syntax|
feature}
Methods used for spelling suggestions. Both for the |z=| command and
the |spellsuggest()| function. This is a comma-separated list of
items:
best Internal method that works best for English. Finds
changes like "fast" and uses a bit of sound-a-like
scoring to improve the ordering.
double Internal method that uses two methods and mixes the
results. The first method is "fast", the other method
computes how much the suggestion sounds like the bad
word. That only works when the language specifies
sound folding. Can be slow and doesn't always give
better results.
fast Internal method that only checks for simple changes:
character inserts/deletes/swaps. Works well for
*'suffixes'* *'su'*
'suffixes' 'su' string (default ".bak,~,.o,.h,.info,.swp,.obj")
global
{not in Vi}
Files with these suffixes get a lower priority when multiple files
match a wildcard. See |suffixes|. Commas can be used to separate the
suffixes. Spaces after the comma are ignored. A dot is also seen as
the start of a suffix. To avoid a dot or comma being recognized as a
separator, precede it with a backslash (see |option-backslash| about
including spaces and backslashes).
See 'wildignore' for completely ignoring files.
The use of |:set+=| and |:set-=| is preferred when adding or removing
suffixes from the list. This avoids problems when a future version
uses another default.
*'suffixesadd'* *'sua'*
'suffixesadd' 'sua' string (default "")
local to buffer
{not in Vi}
{not available when compiled without the
|+file_in_path| feature}
Comma separated list of suffixes, which are used when searching for a
file for the "gf", "[I", etc. commands. Example:
:set suffixesadd=.java
*'swapsync'* *'sws'*
'swapsync' 'sws' string (default "fsync")
global
{not in Vi}
When this option is not empty a swap file is synced to disk after
writing to it. This takes some time, especially on busy unix systems.
When this option is empty parts of the swap file may be in memory and
not written to disk. When the system crashes you may lose more work.
On Unix the system does a sync now and then without Vim asking for it,
so the disadvantage of setting this option off is small. On some
systems the swap file will not be written at all. For a unix system
setting it to "sync" will use the sync() call instead of the default
fsync(), which may work better on some systems.
The 'fsync' option is used for the actual file.
*'switchbuf'* *'swb'*
'switchbuf' 'swb' string (default "")
global
{not in Vi}
This option controls the behavior when switching between buffers.
Possible values (comma separated list):
useopen If included, jump to the first open window that
contains the specified buffer (if there is one).
Otherwise: Do not examine other windows.
This setting is checked with |quickfix| commands, when
jumping to errors (":cc", ":cn", "cp", etc.). It is
also used in all buffer related split commands, for
example ":sbuffer", ":sbnext", or ":sbrewind".
usetab Like "useopen", but also consider windows in other tab
pages.
split If included, split the current window before loading
*'synmaxcol'* *'smc'*
'synmaxcol' 'smc' number (default 3000)
local to buffer
{not in Vi}
{not available when compiled without the |+syntax|
feature}
Maximum column in which to search for syntax items. In long lines the
text after this column is not highlighted and following lines may not
be highlighted correctly, because the syntax state is cleared.
This helps to avoid very slow redrawing for an XML file that is one
long line.
Set to zero to remove the limit.
*'syntax'* *'syn'*
'syntax' 'syn' string (default empty)
local to buffer
{not in Vi}
{not available when compiled without the |+syntax|
feature}
When this option is set, the syntax with this name is loaded, unless
syntax highlighting has been switched off with ":syntax off".
Otherwise this option does not always reflect the current syntax (the
b:current_syntax variable does).
This option is most useful in a modeline, for a file which syntax is
not automatically recognized. Example, in an IDL file:
/* vim: set syntax=idl : */
When a dot appears in the value then this separates two filetype
names. Example:
/* vim: set syntax=c.doxygen : */
This will use the "c" syntax first, then the "doxygen" syntax.
Note that the second one must be prepared to be loaded as an addition,
otherwise it will be skipped. More than one dot may appear.
To switch off syntax highlighting for the current file, use:
:set syntax=OFF
To switch syntax highlighting on according to the current value of the
'filetype' option:
:set syntax=ON
What actually happens when setting the 'syntax' option is that the
Syntax autocommand event is triggered with the value as argument.
This option is not copied to another buffer, independent of the 's' or
'S' flag in 'cpoptions'.
Only normal file name characters can be used, "/\*?[|<>" are illegal.
*'tabline'* *'tal'*
'tabline' 'tal' string (default empty)
global
{not in Vi}
{not available when compiled without the |+windows|
feature}
When nonempty, this option determines the content of the tab pages
line at the top of the Vim window. When empty Vim will use a default
tab pages line. See |setting-tabline| for more info.
The tab pages line only appears as specified with the 'showtabline'
option and only when there is no GUI tab line. When 'e' is in
'guioptions' and the GUI supports a tab line 'guitablabel' is used
instead. Note that the two tab pages lines are very different.
The value is evaluated like with 'statusline'. You can use
|tabpagenr()|, |tabpagewinnr()| and |tabpagebuflist()| to figure out
the text to be displayed. Use "%1T" for the first label, "%2T" for
the second one, etc. Use "%X" items for closing labels.
Keep in mind that only one of the tab pages is the current one, others
are invisible and you can't jump to their windows.
*'tabpagemax'* *'tpm'*
'tabpagemax' 'tpm' number (default 10)
global
{not in Vi}
*'tabstop'* *'ts'*
'tabstop' 'ts' number (default 8)
local to buffer
Number of spaces that a <Tab> in the file counts for. Also see
|:retab| command, and 'softtabstop' option.
Note: Setting 'tabstop' to any other value than 8 can make your file
appear wrong in many places (e.g., when printing it).
There are four main ways to use tabs in Vim:
1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4
(or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim
will use a mix of tabs and spaces, but typing <Tab> and <BS> will
behave like a tab appears every 4 (or 3) characters.
2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use
'expandtab'. This way you will always insert spaces. The
formatting will never be messed up when 'tabstop' is changed.
3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a
|modeline| to set these values when editing the file again. Only
works when using Vim to edit the file.
4. Always set 'tabstop' and 'shiftwidth' to the same value, and
'noexpandtab'. This should then work (for initial indents only)
for any tabstop setting that people use. It might be nice to have
tabs after the first non-blank inserted as spaces if you do this
though. Otherwise aligned comments will be wrong when 'tabstop' is
changed.
*'taglength'* *'tl'*
'taglength' 'tl' number (default 0)
global
If non-zero, tags are significant up to this number of characters.
*'termbidi'* *'tbidi'*
*'notermbidi'* *'notbidi'*
'termbidi' 'tbidi' boolean (default off, on for "mlterm")
global
{not in Vi}
{only available when compiled with the |+arabic|
feature}
The terminal is in charge of Bi-directionality of text (as specified
by Unicode). The terminal is also expected to do the required shaping
that some languages (such as Arabic) require.
Setting this option implies that 'rightleft' will not be set when
'arabic' is set and the value of 'arabicshape' will be ignored.
Note that setting 'termbidi' has the immediate effect that
'arabicshape' is ignored, but 'rightleft' isn't changed automatically.
This option is reset when the GUI is started.
For further details see |arabic.txt|.
*'termencoding'* *'tenc'*
'termencoding' 'tenc' string (default ""; with GTK+ 2 GUI: "utf-8"; with
Macintosh GUI: "macroman")
global
{only available when compiled with the |+multi_byte|
feature}
{not in Vi}
Encoding used for the terminal. This specifies what character
encoding the keyboard produces and the display will understand. For
the GUI it only applies to the keyboard ('encoding' is used for the
display). Except for the Mac when 'macatsui' is off, then
'termencoding' should be "macroman".
In the Win32 console version the default value is the console codepage
when it differs from the ANSI codepage.
*E617*
Note: This does not apply to the GTK+ 2 GUI. After the GUI has been
successfully initialized, 'termencoding' is forcibly set to "utf-8".
Any attempts to set a different value will be rejected, and an error
message is shown.
For the Win32 GUI 'termencoding' is not used for typed characters,
because the Win32 system always passes Unicode characters.
When empty, the same encoding is used as for the 'encoding' option.
This is the normal value.
Not all combinations for 'termencoding' and 'encoding' are valid. See
|encoding-table|.
The value for this option must be supported by internal conversions or
iconv(). When this is not possible no conversion will be done and you
will probably experience problems with non-ASCII characters.
Example: You are working with the locale set to euc-jp (Japanese) and
want to edit a UTF-8 file:
:let &termencoding = &encoding
:set encoding=utf-8
You need to do this when your system has no locale support for UTF-8.
*'terse'* *'noterse'*
'terse' boolean (default off)
global
When set: Add 's' flag to 'shortmess' option (this makes the message
for a search that hits the start or end of the file not being
displayed). When reset: Remove 's' flag from 'shortmess' option. {Vi
shortens a lot of messages}
local to buffer
{not in Vi}
This option is obsolete. Use 'fileformat'.
For backwards compatibility, when 'textmode' is set, 'fileformat' is
set to "dos". When 'textmode' is reset, 'fileformat' is set to
"unix".
*'textwidth'* *'tw'*
'textwidth' 'tw' number (default 0)
local to buffer
{not in Vi}
Maximum width of text that is being inserted. A longer line will be
broken after white space to get this width. A zero value disables
this. 'textwidth' is set to 0 when the 'paste' option is set. When
'textwidth' is zero, 'wrapmargin' may be used. See also
'formatoptions' and |ins-textwidth|.
When 'formatexpr' is set it will be used to break the line.
NOTE: This option is set to 0 when 'compatible' is set.
*'thesaurus'* *'tsr'*
'thesaurus' 'tsr' string (default "")
global or local to buffer |global-local|
{not in Vi}
List of file names, separated by commas, that are used to lookup words
for thesaurus completion commands |i_CTRL-X_CTRL-T|. Each line in
the file should contain words with similar meaning, separated by
non-keyword characters (white space is preferred). Maximum line
length is 510 bytes.
To obtain a file to be used here, check out the wordlist FAQ at
http://www.hyphenologist.co.uk .
To include a comma in a file name precede it with a backslash. Spaces
after a comma are ignored, otherwise spaces are included in the file
name. See |option-backslash| about using backslashes.
The use of |:set+=| and |:set-=| is preferred when adding or removing
directories from the list. This avoids problems when a future version
uses another default.
Backticks cannot be used in this option for security reasons.
*'timeoutlen'* *'tm'*
'timeoutlen' 'tm' number (default 1000)
global
{not in all versions of Vi}
*'ttimeoutlen'* *'ttm'*
'ttimeoutlen' 'ttm' number (default -1)
global
{not in Vi}
The time in milliseconds that is waited for a key code or mapped key
sequence to complete. Also used for CTRL-\ CTRL-N and CTRL-\ CTRL-G
when part of a command has been typed.
Normally only 'timeoutlen' is used and 'ttimeoutlen' is -1. When a
different timeout value for key codes is desired set 'ttimeoutlen' to
a non-negative number.
ttimeoutlen mapping delay key code delay
< 0 'timeoutlen' 'timeoutlen'
>= 0 'timeoutlen' 'ttimeoutlen'
The timeout only happens when the 'timeout' and 'ttimeout' options
tell so. A useful setting would be
:set timeout timeoutlen=3000 ttimeoutlen=100
(time out on mapping after three seconds, time out on key codes after
a tenth of a second).
*'title'* *'notitle'*
'title' boolean (default off, on when title can be restored)
global
{not in Vi}
{not available when compiled without the |+title|
feature}
When on, the title of the window will be set to the value of
'titlestring' (if it is not empty), or to:
filename [+=-] (path) - VIM
Where:
filename the name of the file being edited
- indicates the file cannot be modified, 'ma' off
+ indicates the file was modified
= indicates the file is read-only
=+ indicates the file is read-only and modified
(path) is the path of the file being edited
- VIM the server name |v:servername| or "VIM"
Only works if the terminal supports setting window titles
(currently Amiga console, Win32 console, all GUI versions and
terminals with a non- empty 't_ts' option - these are Unix xterm and
iris-ansi by default, where 't_ts' is taken from the builtin termcap).
*X11*
When Vim was compiled with HAVE_X11 defined, the original title will
be restored if possible. The output of ":version" will include "+X11"
when HAVE_X11 was defined, otherwise it will be "-X11". This also
works for the icon name |'icon'|.
But: When Vim was started with the |-X| argument, restoring the title
will not work (except in the GUI).
If the title cannot be restored, it is set to the value of 'titleold'.
You might want to restore the title outside of Vim then.
When using an xterm from a remote machine you can use this command:
rsh machine_name xterm -display $DISPLAY &
then the WINDOWID environment variable should be inherited and the
title of the window should change back to what it should be after
exiting Vim.
*'titlelen'*
'titlelen' number (default 85)
global
{not in Vi}
{not available when compiled without the |+title|
feature}
Gives the percentage of 'columns' to use for the length of the window
title. When the title is longer, only the end of the path name is
shown. A '<' character before the path name is used to indicate this.
Using a percentage makes this adapt to the width of the window. But
*'titleold'*
'titleold' string (default "Thanks for flying Vim")
global
{not in Vi}
{only available when compiled with the |+title|
feature}
This option will be used for the window title when exiting Vim if the
original title cannot be restored. Only happens if 'title' is on or
'titlestring' is not empty.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'titlestring'*
'titlestring' string (default "")
global
{not in Vi}
{not available when compiled without the |+title|
feature}
When this option is not empty, it will be used for the title of the
window. This happens only when the 'title' option is on.
Only works if the terminal supports setting window titles (currently
Amiga console, Win32 console, all GUI versions and terminals with a
non-empty 't_ts' option).
When Vim was compiled with HAVE_X11 defined, the original title will
be restored if possible |X11|.
When this option contains printf-style '%' items, they will be
expanded according to the rules used for 'statusline'.
Example:
:auto BufEnter * let &titlestring = hostname() . "/" . expand("%:p")
:set title titlestring=%<%F%=%l/%L-%P titlelen=70
The value of 'titlelen' is used to align items in the middle or right
of the available space.
Some people prefer to have the file name first:
:set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:~:.:h\")})%)%(\ %a%)
Note the use of "%{ }" and an expression to get the path of the file,
without the file name. The "%( %)" constructs are used to add a
separating space only when needed.
NOTE: Use of special characters in 'titlestring' may cause the display
to be garbled (e.g., when it contains a CR or NL character).
{not available when compiled without the |+statusline| feature}
*'toolbar'* *'tb'*
'toolbar' 'tb' string (default "icons,tooltips")
global
{only for |+GUI_GTK|, |+GUI_Athena|, |+GUI_Motif| and
YXXY+GUI_Photon|}
The contents of this option controls various toolbar settings. The
possible values are:
icons Toolbar buttons are shown with icons.
text Toolbar buttons shown with text.
horiz Icon and text of a toolbar button are
horizontally arranged. {only in GTK+ 2 GUI}
tooltips Tooltips are active for toolbar buttons.
Tooltips refer to the popup help text which appears after the mouse
cursor is placed over a toolbar button for a brief moment.
If you want the toolbar to be shown with icons as well as text, do the
following:
:set tb=icons,text
Motif and Athena cannot display icons and text at the same time. They
will show icons if both are requested.
If none of the strings specified in 'toolbar' are valid or if
'toolbar' is empty, this option is ignored. If you want to disable
the toolbar, you need to set the 'guioptions' option. For example:
:set guioptions-=T
Also see |gui-toolbar|.
*'toolbariconsize'* *'tbis'*
'toolbariconsize' 'tbis' string (default "small")
global
{not in Vi}
{only in the GTK+ 2 GUI}
Controls the size of toolbar icons. The possible values are:
tiny Use tiny toolbar icons.
small Use small toolbar icons (default).
medium Use medium-sized toolbar icons.
large Use large toolbar icons.
The exact dimensions in pixels of the various icon sizes depend on
the current theme. Common dimensions are large=32x32, medium=24x24,
small=20x20 and tiny=16x16.
If 'toolbariconsize' is empty, the global default size as determined
by user preferences or the current theme is used.
*'ttymouse'* *'ttym'*
'ttymouse' 'ttym' string (default depends on 'term')
global
{not in Vi}
{only in Unix and VMS, doesn't work in the GUI; not
available when compiled without YXXY+mouse|}
Name of the terminal type for which mouse codes are to be recognized.
Currently these strings are valid:
*xterm-mouse*
xterm xterm-like mouse handling. The mouse generates
"<Esc>[Mscr", where "scr" is three bytes:
"s" = button state
"c" = column plus 33
"r" = row plus 33
This only works up to 223 columns! See "dec" for a
solution.
xterm2 Works like "xterm", but with the xterm reporting the
mouse position while the mouse is dragged. This works
much faster and more precise. Your xterm must at
least at patchlevel 88 / XFree 3.3.3 for this to
work. See below for how Vim detects this
automatically.
*netterm-mouse*
netterm NetTerm mouse handling. The mouse generates
"<Esc>}r,c<CR>", where "r,c" are two decimal numbers
for the row and column.
*dec-mouse*
dec DEC terminal mouse handling. The mouse generates a
rather complex sequence, starting with "<Esc>[".
This is also available for an Xterm, if it was
configured with "--enable-dec-locator".
*jsbterm-mouse*
jsbterm JSB term mouse handling.
*pterm-mouse*
pterm QNX pterm mouse handling.
The mouse handling must be enabled at compile time |+mouse_xterm|
|+mouse_dec| |+mouse_netterm|.
Only "xterm"(2) is really recognized. NetTerm mouse codes are always
recognized, if enabled at compile time. DEC terminal mouse codes
are recognized if enabled at compile time, and 'ttymouse' is not
"xterm" (because the xterm and dec mouse codes conflict).
This option is automatically set to "xterm", when the 'term' option is
set to a name that starts with "xterm", and 'ttymouse' is not "xterm"
or "xterm2" already. The main use of this option is to set it to
"xterm", when the terminal name doesn't start with "xterm", but it can
handle xterm mouse codes.
The "xterm2" value will be set if the xterm version is reported to be
95 or higher. This only works when compiled with the |+termresponse|
feature and if |t_RV| is set to the escape sequence to request the
xterm version number. Otherwise "xterm2" must be set explicitly.
If you do not want 'ttymouse' to be set to "xterm2" automatically, set
t_RV to an empty string:
:set t_RV=
*'ttyscroll'* *'tsl'*
'ttyscroll' 'tsl' number (default 999)
global
Maximum number of lines to scroll the screen. If there are more lines
to scroll the window is redrawn. For terminals where scrolling is
very slow and redrawing is not slow this can be set to a small number,
e.g., 3, to speed up displaying.
*'ttytype'* *'tty'*
'ttytype' 'tty' string (default from $TERM)
global
Alias for 'term', see above.
*'undodir'* *'udir'*
'undodir' 'udir' string (default ".")
global
{not in Vi}
{only when compiled with the |+persistent_undo| feature}
List of directory names for undo files, separated with commas.
See |'backupdir'| for details of the format.
"." means using the directory of the file. The undo file name for
"file.txt" is ".file.txt.un~".
For other directories the file name is the full path of the edited
file, with path separators replaced with "%".
When writing: The first directory that exists is used. "." always
works, no directories after "." will be used for writing.
When reading all entries are tried to find an undo file. The first
undo file that exists is used. When it cannot be read an error is
given, no further entry is used.
See |undo-persistence|.
*'undofile'* *'udf'*
'undofile' 'udf' boolean (default off)
local to buffer
{not in Vi}
{only when compiled with the |+persistent_undo| feature}
When on, Vim automatically saves undo history to an undo file when
writing a buffer to a file, and restores undo history from the same
file on buffer read.
The directory where the undo file is stored is specified by 'undodir'.
For more information about this feature see |undo-persistence|.
The undo file is not read when 'undoreload' causes the buffer from
before a reload to be saved for undo.
WARNING: this is a very new feature. Use at your own risk!
*'undolevels'* *'ul'*
'undolevels' 'ul' number (default 100, 1000 for Unix, VMS,
Win32 and OS/2)
global
{not in Vi}
Maximum number of changes that can be undone. Since undo information
is kept in memory, higher numbers will cause more memory to be used
(nevertheless, a single change can use an unlimited amount of memory).
Set to 0 for Vi compatibility: One level of undo and "u" undoes
itself:
set ul=0
But you can also get Vi compatibility by including the 'u' flag in
'cpoptions', and still be able to use CTRL-R to repeat undo.
Also see |undo-two-ways|.
Set to a negative number for no undo at all:
set ul=-1
This helps when you run out of memory for a single change.
Also see |clear-undo|.
*'undoreload'* *'ur'*
'undoreload' 'ur' number (default 10000)
global
{not in Vi}
Save the whole buffer for undo when reloading it. This applies to the
":e!" command and reloading for when the buffer changed outside of
Vim. |FileChangedShell|
The save only happens when this options is negative or when the number
of lines is smaller than the value of this option.
Set this option to zero to disable undo for a reload.
When saving undo for a reload, any undo file is not read.
Note that this causes the whole buffer to be stored in memory. Set
this option to a lower value if you run out of memory.
*'updatecount'* *'uc'*
'updatecount' 'uc' number (default: 200)
global
{not in Vi}
After typing this many characters the swap file will be written to
disk. When zero, no swap file will be created at all (see chapter on
recovery |crash-recovery|). 'updatecount' is set to zero by starting
Vim with the "-n" option, see |startup|. When editing in readonly
mode this option will be initialized to 10000.
The swapfile can be disabled per buffer with |'swapfile'|.
When 'updatecount' is set from zero to non-zero, swap files are
created for all buffers that have 'swapfile' set. When 'updatecount'
is set to zero, existing swap files are not deleted.
Also see |'swapsync'|.
This option has no meaning in buffers where |'buftype'| is "nofile"
or "nowrite".
*'updatetime'* *'ut'*
'updatetime' 'ut' number (default 4000)
global
{not in Vi}
If this many milliseconds nothing is typed the swap file will be
written to disk (see |crash-recovery|). Also used for the
|CursorHold| autocommand event.
*'verbose'* *'vbs'*
'verbose' 'vbs' number (default 0)
global
{not in Vi, although some versions have a boolean
verbose option}
When bigger than zero, Vim will give messages about what it is doing.
Currently, these messages are given:
>= 1 When the viminfo file is read or written.
>= 2 When a file is ":source"'ed.
>= 5 Every searched tags file and include file.
>= 8 Files for which a group of autocommands is executed.
>= 9 Every executed autocommand.
>= 12 Every executed function.
>= 13 When an exception is thrown, caught, finished, or discarded.
>= 14 Anything pending in a ":finally" clause.
>= 15 Every executed Ex command (truncated at 200 characters).
This option can also be set with the "-V" argument. See |-V|.
This option is also set by the |:verbose| command.
When the 'verbosefile' option is set then the verbose messages are not
displayed.
*'verbosefile'* *'vfile'*
'verbosefile' 'vfile' string (default empty)
global
{not in Vi}
When not empty all messages are written in a file with this name.
When the file exists messages are appended.
Writing to the file ends when Vim exits or when 'verbosefile' is made
empty. Writes are buffered, thus may not show up for some time.
Setting 'verbosefile' to a new value is like making it empty first.
The difference with |:redir| is that verbose messages are not
displayed when 'verbosefile' is set.
*'viewdir'* *'vdir'*
'viewdir' 'vdir' string (default for Amiga, MS-DOS, OS/2 and Win32:
"$VIM/vimfiles/view",
for Unix: "~/.vim/view",
for Macintosh: "$VIM:vimfiles:view"
for VMS: "sys$login:vimfiles/view"
for RiscOS: "Choices:vimfiles/view")
global
{not in Vi}
{not available when compiled without the |+mksession|
feature}
Name of the directory where to store files for |:mkview|.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'viewoptions'* *'vop'*
'viewoptions' 'vop' string (default: "folds,options,cursor")
global
{not in Vi}
{not available when compiled without the |+mksession|
feature}
Changes the effect of the |:mkview| command. It is a comma separated
list of words. Each word enables saving and restoring something:
word save and restore
cursor cursor position in file and in window
folds manually created folds, opened/closed folds and local
fold options
options options and mappings local to a window or buffer (not
global values for local options)
slash backslashes in file names replaced with forward
slashes
unix with Unix end-of-line format (single <NL>), even when
on Windows or DOS
"slash" and "unix" are useful on Windows when sharing view files
with Unix. The Unix version of Vim cannot source dos format scripts,
but the Windows version of Vim can source unix format scripts.
" Maximum number of lines saved for each register. Old name of
the '<' item, with the disadvantage that you need to put a
backslash before the ", otherwise it will be recognized as the
start of a comment!
% When included, save and restore the buffer list. If Vim is
started with a file name argument, the buffer list is not
restored. If Vim is started without a file name argument, the
buffer list is restored from the viminfo file. Buffers
without a file name and buffers for help files are not written
to the viminfo file.
When followed by a number, the number specifies the maximum
number of buffers that are stored. Without a number all
buffers are stored.
'' Maximum number of previously edited files for which the marks
are remembered. This parameter must always be included when
'viminfo' is non-empty.
Including this item also means that the |jumplist| and the
|changelist| are stored in the viminfo file.
/ Maximum number of items in the search pattern history to be
saved. If non-zero, then the previous search and substitute
patterns are also saved. When not included, the value of
'history' is used.
: Maximum number of items in the command-line history to be
saved. When not included, the value of 'history' is used.
< Maximum number of lines saved for each register. If zero then
registers are not saved. When not included, all lines are
saved. '"'' is the old name for this item.
Also see the 's' item below: limit specified in Kbyte.
@ Maximum number of items in the input-line history to be
saved. When not included, the value of 'history' is used.
c When included, convert the text in the viminfo file from the
'encoding' used when writing the file to the current
'encoding'. See |viminfo-encoding|.
f Whether file marks need to be stored. If zero, file marks ('0
to '9, 'A to 'Z) are not stored. When not present or when
non-zero, they are all stored. '0 is used for the current
cursor position (when exiting or when doing ":wviminfo").
h Disable the effect of 'hlsearch' when loading the viminfo
file. When not included, it depends on whether ":nohlsearch"
has been used since the last search command.
n Name of the viminfo file. The name must immediately follow
the 'n'. Must be the last one! If the "-i" argument was
given when starting Vim, that file name overrides the one
given here with 'viminfo'. Environment variables are expanded
when opening the file, not when setting the option.
r Removable media. The argument is a string (up to the next
','). This parameter can be given several times. Each
specifies the start of a path for which no marks will be
stored. This is to avoid removable media. For MS-DOS you
could use "ra:,rb:", for Amiga "rdf0:,rdf1:,rdf2:". You can
also use it for temp files, e.g., for Unix: "r/tmp". Case is
ignored. Maximum length of each 'r' argument is 50
characters.
s Maximum size of an item in Kbyte. If zero then registers are
not saved. Currently only applies to registers. The default
"s10" will exclude registers with more than 10 Kbyte of text.
Also see the '<' item above: line count limit.
Example:
:set viminfo='50,<1000,s100,:0,n~/vim/viminfo
'50 Marks will be remembered for the last 50 files you
edited.
<1000 Contents of registers (up to 1000 lines each) will be
remembered.
s100 Registers with more than 100 Kbyte text are skipped.
:0 Command-line history will not be saved.
n~/vim/viminfo The name of the file to use is "~/vim/viminfo".
no / Since '/' is not specified, the default will be used,
that is, save all of the search history, and also the
previous search and substitute patterns.
no % The buffer list will not be saved nor read back.
no h 'hlsearch' highlighting will be restored.
When setting 'viminfo' from an empty value you can use |:rviminfo| to
load the contents of the file, this is not done automatically.
This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
*'virtualedit'* *'ve'*
'virtualedit' 've' string (default "")
global
{not in Vi}
{not available when compiled without the
|+virtualedit| feature}
A comma separated list of these words:
block Allow virtual editing in Visual block mode.
insert Allow virtual editing in Insert mode.
all Allow virtual editing in all modes.
onemore Allow the cursor to move just past the end of the line
Virtual editing means that the cursor can be positioned where there is
no actual character. This can be halfway into a tab or beyond the end
of the line. Useful for selecting a rectangle in Visual mode and
editing a table.
"onemore" is not the same, it will only allow moving the cursor just
after the last character of the line. This makes some commands more
consistent. Previously the cursor was always past the end of the line
if the line was empty. But it is far from Vi compatible. It may also
break some plugins or Vim scripts. For example because |l| can move
the cursor after the last character. Use with care!
Using the |$| command will move to the last character in the line, not
past it. This may actually move the cursor to the left!
It doesn't make sense to combine "all" with "onemore", but you will
not get a warning for it.
*'warn'* *'nowarn'*
'warn' boolean (default on)
global
Give a warning message when a shell command is used while the buffer
has been changed.
*'whichwrap'* *'ww'*
'whichwrap' 'ww' string (Vim default: "b,s", Vi default: "")
global
{not in Vi}
Allow specified keys that move the cursor left/right to move to the
previous/next line when the cursor is on the first/last character in
the line. Concatenate characters to allow this for these keys:
char key mode
b <BS> Normal and Visual
s <Space> Normal and Visual
h "h" Normal and Visual (not recommended)
l "l" Normal and Visual (not recommended)
< <Left> Normal and Visual
> <Right> Normal and Visual
~ "~" Normal
[ <Left> Insert and Replace
] <Right> Insert and Replace
For example:
:set ww=<,>,[,]
allows wrap only when cursor keys are used.
When the movement keys are used in combination with a delete or change
operator, the <EOL> also counts for a character. This makes "3h"
different from "3dh" when the cursor crosses the end of a line. This
is also true for "x" and "X", because they do the same as "dl" and
"dh". If you use this, you may also want to use the mapping
":map <BS> X" to make backspace delete the character in front of the
cursor.
When 'l' is included and it is used after an operator at the end of a
line then it will not move to the next line. This makes "dl", "cl",
"yl" etc. work normally.
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
*'wildchar'* *'wc'*
'wildchar' 'wc' number (Vim default: <Tab>, Vi default: CTRL-E)
global
{not in Vi}
Character you have to type to start wildcard expansion in the
command-line, as specified with 'wildmode'.
More info here: |cmdline-completion|.
The character is not recognized when used inside a macro. See
'wildcharm' for that.
Although 'wc' is a number option, you can set it to a special key:
:set wc=<Esc>
NOTE: This option is set to the Vi default value when 'compatible' is
set and to the Vim default value when 'compatible' is reset.
*'wildcharm'* *'wcm'*
'wildcharm' 'wcm' number (default: none (0))
global
{not in Vi}
'wildcharm' works exactly like 'wildchar', except that it is
recognized when used inside a macro. You can find "spare" command-line
keys suitable for this option by looking at |ex-edit-index|. Normally
you'll never actually type 'wildcharm', just use it in mappings that
automatically invoke completion mode, e.g.:
:set wcm=<C-Z>
:cnoremap ss so $vim/sessions/*.vim<C-Z>
Then after typing :ss you can use CTRL-P & CTRL-N.
*'wildignore'* *'wig'*
'wildignore' 'wig' string (default "")
global
{not in Vi}
{not available when compiled without the |+wildignore|
feature}
A list of file patterns. A file that matches with one of these
patterns is ignored when completing file or directory names, and
influences the result of |expand()|, |glob()| and |globpath()| unless
a flag is passed to disable this.
The pattern is used like with |:autocmd|, see |autocmd-patterns|.
Also see 'suffixes'.
Example:
:set wildignore=*.o,*.obj
The use of |:set+=| and |:set-=| is preferred when adding or removing
a pattern from the list. This avoids problems when a future version
uses another default.
*'wildmode'* *'wim'*
'wildmode' 'wim' string (Vim default: "full")
global
{not in Vi}
Completion mode that is used for the character specified with
'wildchar'. It is a comma separated list of up to four parts. Each
part specifies what to do for each consecutive use of 'wildchar'. The
first part specifies the behavior for the first use of 'wildchar',
The second part for the second use, etc.
These are the possible values for each part:
"" Complete only the first match.
"full" Complete the next full match. After the last match,
the original string is used and then the first match
again.
"longest" Complete till longest common string. If this doesn't
result in a longer string, use the next part.
"longest:full" Like "longest", but also start 'wildmenu' if it is
enabled.
"list" When more than one match, list all matches.
"list:full" When more than one match, list all matches and
complete first match.
"list:longest" When more than one match, list all matches and
complete till longest common string.
When there is only a single match, it is fully completed in all cases.
Examples:
:set wildmode=full
Complete first full match, next match, etc. (the default)
:set wildmode=longest,full
Complete longest common string, then each full match
:set wildmode=list:full
List all matches and complete each full match
:set wildmode=list,full
List all matches without completing, then each full match
:set wildmode=longest,list
Complete longest common string, then list alternatives.
More info here: |cmdline-completion|.
*'wildoptions'* *'wop'*
'wildoptions' 'wop' string (default "")
global
{not in Vi}
*'winaltkeys'* *'wak'*
'winaltkeys' 'wak' string (default "menu")
global
{not in Vi}
{only used in Win32, Motif, GTK and Photon GUI}
Some GUI versions allow the access to menu entries by using the ALT
key in combination with a character that appears underlined in the
menu. This conflicts with the use of the ALT key for mappings and
entering special characters. This option tells what to do:
no Don't use ALT keys for menus. ALT key combinations can be
mapped, but there is no automatic handling. This can then be
done with the |:simalt| command.
yes ALT key handling is done by the windowing system. ALT key
combinations cannot be mapped.
menu Using ALT in combination with a character that is a menu
shortcut key, will be handled by the windowing system. Other
keys can be mapped.
If the menu is disabled by excluding 'm' from 'guioptions', the ALT
key is never used for the menu.
This option is not used for <F10>; on Win32 and with GTK <F10> will
select the menu, unless it has been mapped.
*'window'* *'wi'*
'window' 'wi' number (default screen height - 1)
global
Window height. Do not confuse this with the height of the Vim window,
use 'lines' for that.
Used for |CTRL-F| and |CTRL-B| when there is only one window and the
value is smaller than 'lines' minus one. The screen will scroll
'window' minus two lines, with a minimum of one.
When 'window' is equal to 'lines' minus one CTRL-F and CTRL-B scroll
in a much smarter way, taking care of wrapping lines.
When resizing the Vim window, the value is smaller than 1 or more than
or equal to 'lines' it will be set to 'lines' minus 1.
{Vi also uses the option to specify the number of displayed lines}
Keep the window height when windows are opened or closed and
'equalalways' is set. Also for |CTRL-W_=|. Set by default for the
|preview-window| and |quickfix-window|.
The height may be changed anyway when running out of room.
*'winminheight'* *'wmh'*
'winminheight' 'wmh' number (default 1)
global
{not in Vi}
{not available when compiled without the |+windows|
feature}
The minimal height of a window, when it's not the current window.
This is a hard minimum, windows will never become smaller.
When set to zero, windows may be "squashed" to zero lines (i.e. just a
status bar) if necessary. They will return to at least one line when
they become active (since the cursor has to have somewhere to go.)
Use 'winheight' to set the minimal height of the current window.
This option is only checked when making a window smaller. Don't use a
large number, it will cause errors when opening more than a few
windows. A value of 0 to 3 is reasonable.
*'winminwidth'* *'wmw'*
'winminwidth' 'wmw' number (default 1)
global
{not in Vi}
{not available when compiled without the |+vertsplit|
feature}
The minimal width of a window, when it's not the current window.
This is a hard minimum, windows will never become smaller.
When set to zero, windows may be "squashed" to zero columns (i.e. just
a vertical separator) if necessary. They will return to at least one
line when they become active (since the cursor has to have somewhere
to go.)
Use 'winwidth' to set the minimal width of the current window.
This option is only checked when making a window smaller. Don't use a
large number, it will cause errors when opening more than a few
windows. A value of 0 to 12 is reasonable.
*'wrap'* *'nowrap'*
'wrap' boolean (default on)
local to window
{not in Vi}
This option changes how text is displayed. It doesn't change the text
in the buffer, see 'textwidth' for that.
When on, lines longer than the width of the window will wrap and
displaying continues on the next line. When off lines will not wrap
and only part of long lines will be displayed. When the cursor is
moved to a part that is not shown, the screen will scroll
horizontally.
*'wrapmargin'* *'wm'*
'wrapmargin' 'wm' number (default 0)
local to buffer
Number of characters from the right window border where wrapping
starts. When typing text beyond this limit, an <EOL> will be inserted
and inserting continues on the next line.
Options that add a margin, such as 'number' and 'foldcolumn', cause
the text width to be further reduced. This is Vi compatible.
When 'textwidth' is non-zero, this option is not used.
See also 'formatoptions' and |ins-textwidth|. {Vi: works differently
and less usefully}
*'write'* *'nowrite'*
'write' boolean (default on)
global
{not in Vi}
Allows writing files. When not set, writing a file is not allowed.
Can be used for a view-only mode, where modifications to the text are
still allowed. Can be reset with the |-m| or |-M| command line
argument. Filtering text is still possible, even though this requires
writing a temporary file.
*'writedelay'* *'wd'*
'writedelay' 'wd' number (default 0)
global
{not in Vi}
The number of microseconds to wait for each character sent to the
screen. When non-zero, characters are sent to the terminal one by
one. For MS-DOS pcterm this does not work. For debugging purposes.
top - main help file
*quickref* *Contents*
tag subject tag subject
|Q_ct| list of help files |Q_re| Repeating commands
|Q_lr| motion: Left-right |Q_km| Key mapping
|Q_ud| motion: Up-down |Q_ab| Abbreviations
|Q_tm| motion: Text object |Q_op| Options
|Q_pa| motion: Pattern searches |Q_ur| Undo/Redo commands
|Q_ma| motion: Marks |Q_et| External commands
|Q_vm| motion: Various |Q_qf| Quickfix commands
|Q_ta| motion: Using tags |Q_vc| Various commands
|Q_sc| Scrolling |Q_ce| Ex: Command-line editing
|Q_in| insert: Inserting text |Q_ra| Ex: Ranges
|Q_ai| insert: Keys |Q_ex| Ex: Special characters
|Q_ss| insert: Special keys |Q_st| Starting Vim
|Q_di| insert: Digraphs |Q_ed| Editing a file
|Q_si| insert: Special inserts |Q_fl| Using the argument list
|Q_de| change: Deleting text |Q_wq| Writing and quitting
|Q_cm| change: Copying and moving |Q_ac| Automatic commands
|Q_ch| change: Changing text |Q_wi| Multi-window commands
|Q_co| change: Complex |Q_bu| Buffer list commands
|Q_vi| Visual mode |Q_sy| Syntax highlighting
|Q_to| Text objects |Q_gu| GUI commands
|Q_fo| Folding
------------------------------------------------------------------------------
N is used to indicate an optional count that can be given before the command.
------------------------------------------------------------------------------
*Q_lr* Left-right motions
|h| N h left (also: CTRL-H, <BS>, or <Left> key)
|l| N l right (also: <Space> or <Right> key)
|0| 0 to first character in the line (also: <Home> key)
|^| ^ to first non-blank character in the line
|$| N $ to the last character in the line (N-1 lines lower)
(also: <End> key)
|g0| g0 to first character in screen line (differs from "0"
when lines wrap)
|g^| g^ to first non-blank character in screen line (differs
from "^" when lines wrap)
|g$| N g$ to last character in screen line (differs from "$"
when lines wrap)
|gm| gm to middle of the screen line
|bar| N | to column N (default: 1)
|f| N f{char} to the Nth occurrence of {char} to the right
|F| N F{char} to the Nth occurrence of {char} to the left
|t| N t{char} till before the Nth occurrence of {char} to the right
|T| N T{char} till before the Nth occurrence of {char} to the left
|;| N ; repeat the last "f", "F", "t", or "T" N times
|,| N , repeat the last "f", "F", "t", or "T" N times in
opposite direction
------------------------------------------------------------------------------
*Q_ud* Up-down motions
|ga| ga
show ascii value of character under cursor in
decimal, hex, and octal
|g8| g8 for utf-8 encoding: show byte sequence for
character under cursor in hex
|g_CTRL-G| g CTRL-G show cursor column, line, and character
position
|CTRL-C| CTRL-C during searches: Interrupt the search
|dos-CTRL-Break| CTRL-Break MS-DOS: during searches: Interrupt the search
|<Del>| <Del> while entering a count: delete last character
|:version| :ve[rsion] show version information
|:mode| :mode N MS-DOS: set screen mode to N (number, C80,
C4350, etc.)
|:normal| :norm[al][!] {commands}
execute Normal mode commands
|Q| Q switch to "Ex" mode
|:redir| :redir >{file} redirect messages to {file}
|:silent| :silent[!] {command}
execute {command} silently
|:confirm| :confirm {command}
quit, write, etc., asking about
unsaved changes or read-only files
|:browse| :browse {command} open/read/write file, using a
file selection dialog
------------------------------------------------------------------------------
*Q_ce* Command-line editing
|c_<Esc>| <Esc> abandon command-line (if 'wildchar' is
<Esc>, type it twice)
|c_CTRL-V| CTRL-V {char} insert {char} literally
|c_CTRL-V| CTRL-V {number} enter decimal value of character (up to
three digits)
|c_CTRL-K| CTRL-K {char1} {char2}
enter digraph (See |Q_di|)
|c_CTRL-R| CTRL-R {0-9a-z"%#:-=}
insert the contents of a register
|c_<Left>| <Left>/<Right> cursor left/right
|c_<S-Left>| <S-Left>/<S-Right> cursor one word left/right
|c_CTRL-B| CTRL-B/CTRL-E cursor to beginning/end of command-line
|c_<BS>| <BS> delete the character in front of the cursor
|c_<Del>| <Del> delete the character under the cursor
|c_CTRL-W| CTRL-W delete the word in front of the cursor
|c_CTRL-U| CTRL-U remove all characters
|c_<Up>| <Up>/<Down> recall older/newer command-line that starts
with current command
|c_<S-Up>| <S-Up>/<S-Down> recall older/newer command-line from history
|:history| :his[tory] show older command-lines
Context-sensitive completion on the command-line:
|c_wildchar| 'wildchar'
(default: <Tab>)
do completion on the pattern in front of the
cursor; if there are multiple matches,
beep and show the first one; further
'wildchar' will show the next ones
|c_CTRL-D| CTRL-D list all names that match the pattern in
front of the cursor
|c_CTRL-A| CTRL-A insert all names that match pattern in front
of cursor
|c_CTRL-L| CTRL-L insert longest common part of names that
match pattern
|c_CTRL-N| CTRL-N after 'wildchar' with multiple matches: go
to next match
|c_CTRL-P| CTRL-P after 'wildchar' with multiple matches: go
to previous match
------------------------------------------------------------------------------
*Q_ra* Ex ranges
|:range| , separates two line numbers
|:range| ; idem, set cursor to the first line number
before interpreting the second one
|:range| {number} an absolute line number
|:range| . the current line
|:range| $ the last line in the file
|:range| % equal to 1,$ (the entire file)
value. |Dictionary|
Example: {'blue': "#0000ff", 'red': "#ff0000"}
The Number and String types are converted automatically, depending on how they
are used.
Conversion from a Number to a String is by making the ASCII representation of
the Number. Examples:
Number 123 --> String "123"
Number 0 --> String "0"
Number -1 --> String "-1"
*octal*
Conversion from a String to a Number is done by converting the first digits
to a number. Hexadecimal "0xf9" and Octal "017" numbers are recognized. If
the String doesn't start with digits, the result is zero. Examples:
String "456" --> Number 456
String "6bar" --> Number 6
String "foo" --> Number 0
String "0xf1" --> Number 241
String "0100" --> Number 64
String "-8" --> Number -8
String "+8" --> Number 0
To force conversion from String to Number, add zero to it:
:echo "0100" + 0
64
To avoid a leading zero to cause octal conversion, or for using a different
base, use |str2nr()|.
For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE.
Note that in the command
:if "foo"
"foo" is converted to 0, which means FALSE. To test for a non-empty string,
use strlen():
:if strlen("foo")
*E745* *E728* *E703* *E729* *E730* *E731*
List, Dictionary and Funcref types are not automatically converted.
*E706* *sticky-type-checking*
You will get an error if you try to change the type of a variable. You need
to |:unlet| it first to avoid this error. String and Number are considered
equivalent though, as well are Float and Number. Consider this sequence of
commands:
:let l = "string"
:let l = 44 " changes type from String to Number
:let l = [1, 2, 3] " error! l is still a Number
:let l = 4.4 " changes type from Number to Float
:let l = "string" " error!
: let self.val = 0
:endfunction
The key of the Dictionary can start with a lower case letter. The actual
function name is not used here. Also see |numbered-function|.
A Funcref can also be used with the |:call| command:
:call Fn()
:call dict.init()
The name of the referenced function can be obtained with |string()|.
:let func = string(Fn)
You can use |call()| to invoke a Funcref and use a list variable for the
arguments:
:let r = call(Fn, mylist)
1.3 Lists
*List* *Lists* *E686*
A List is an ordered sequence of items. An item can be of any type. Items
can be accessed by their index number. Items can be added and removed at any
position in the sequence.
List creation
*E696* *E697*
A List is created with a comma separated list of items in square brackets.
Examples:
:let mylist = [1, two, 3, "four"]
:let emptylist = []
An item can be any expression. Using a List for an item creates a
List of Lists:
:let nestlist = [[11, 12], [21, 22], [31, 32]]
An extra comma after the last item is ignored.
List index
*list-index* *E684*
An item in the List can be accessed by putting the index in square brackets
after the List. Indexes are zero-based, thus the first item has index zero.
:let item = mylist[0] " get the first item: 1
:let item = mylist[2] " get the third item: 3
When the resulting item is a list this can be repeated:
:let item = nestlist[0][1] " get the first list, second item: 12
A negative index is counted from the end. Index -1 refers to the last item in
the List, -2 to the last but one item, etc.
:let last = mylist[-1] " get the last item: "four"
To avoid an error for an invalid index use the |get()| function. When an item
is not available it returns zero or the default value you specify:
:echo get(mylist, idx)
:echo get(mylist, idx, "NONE")
List concatenation
Two lists can be concatenated with the "+" operator:
:let longlist = mylist + [5, 6]
:let mylist += [7, 8]
To prepend or append an item turn the item into a list by putting [] around
it. To change a list in-place see |list-modification| below.
Sublist
A part of the List can be obtained by specifying the first and last index,
separated by a colon in square brackets:
:let shortlist = mylist[2:-1] " get List [3, "four"]
Omitting the first index is similar to zero. Omitting the last index is
similar to -1.
:let endlist = mylist[2:] " from item 2 to the end: [3, "four"]
:let shortlist = mylist[2:2] " List with one item: [3]
:let otherlist = mylist[:] " make a copy of the List
If the first index is beyond the last item of the List or the second item is
before the first item, the result is an empty list. There is no error
message.
If the second index is equal to or greater than the length of the list the
length minus one is used:
:let mylist = [0, 1, 2, 3]
:echo mylist[2:8] " result: [2, 3]
NOTE: mylist[s:e] means using the variable "s:e" as index. Watch out for
using a single letter variable before the ":". Insert a space when needed:
mylist[s : e].
List identity
*list-identity*
When variable "aa" is a list and you assign it to another variable "bb", both
variables refer to the same list. Thus changing the list "aa" will also
change "bb":
:let aa = [1, 2, 3]
:let bb = aa
:call add(aa, 4)
:echo bb
[1, 2, 3, 4]
Making a copy of a list is done with the |copy()| function. Using [:] also
works, as explained above. This creates a shallow copy of the list: Changing
a list item in the list will also change the item in the copied list:
:let aa = [[1, 'a'], 2, 3]
:let bb = copy(aa)
:call add(aa, 4)
:let aa[0][1] = 'aaa'
:echo aa
[[1, aaa], 2, 3, 4]
:echo bb
[[1, aaa], 2, 3]
To make a completely independent list use |deepcopy()|. This also makes a
copy of the values in the list, recursively. Up to a hundred levels deep.
The operator "is" can be used to check if two variables refer to the same
List. "isnot" does the opposite. In contrast "==" compares if two lists have
the same value.
:let alist = [1, 2, 3]
:let blist = [1, 2, 3]
:echo alist is blist
0
:echo alist == blist
1
Note about comparing lists: Two lists are considered equal if they have the
same length and all items compare equal, as with using "==". There is one
exception: When comparing a number with a string they are considered
different. There is no automatic type conversion, as with using "==" on
variables. Example:
echo 4 == "4"
1
echo [4] == ["4"]
0
Thus comparing Lists is more strict than comparing numbers and strings. You
can compare simple values this way too by putting them in a list:
:let a = 5
:let b = "5"
:echo a == b
1
:echo [a] == [b]
0
List unpack
To unpack the items in a list to individual variables, put the variables in
square brackets, like list items:
:let [var1, var2] = mylist
When the number of variables does not match the number of items in the list
this produces an error. To handle any extra items from the list append ";"
and a variable name:
:let [var1, var2; rest] = mylist
This works like:
:let var1 = mylist[0]
:let var2 = mylist[1]
:let rest = mylist[2:]
Except that there is no error if there are only two items. "rest" will be an
empty list then.
List modification
*list-modification*
To change a specific item of a list use |:let| this way:
:let list[4] = "four"
:let listlist[0][3] = item
To change part of a list you can specify the first and last item to be
modified. The value must at least have the number of items in the range:
:let list[3:5] = [3, 4, 5]
Adding and removing items from a list is done with functions. Here are a few
examples:
:call insert(list, 'a') " prepend item 'a'
:call insert(list, 'a', 3) " insert item 'a' before list[3]
:call add(list, "new") " append String item
:call add(list, [1, 2]) " append a List as one new item
:call extend(list, [1, 2]) " extend the list with two more items
:let i = remove(list, 3) " remove item 3
:unlet list[3] " idem
:let l = remove(list, 3, -1) " remove items 3 to last item
:unlet list[3 : ] " idem
:call filter(list, 'v:val !~ "x"') " remove items with an 'x'
Changing the order of items in a list:
:call sort(list) " sort a list alphabetically
:call reverse(list) " reverse the order of items
For loop
The |:for| loop executes commands for each item in a list. A variable is set
to each item in the list in sequence. Example:
:for item in mylist
: call Doit(item)
:endfor
This works like:
:let index = 0
:while index < len(mylist)
: let item = mylist[index]
: :call Doit(item)
: let index = index + 1
:endwhile
Note that all items in the list should be of the same type, otherwise this
results in error |E706|. To avoid this |:unlet| the variable at the end of
the loop.
If all you want to do is modify each item in the list then the |map()|
function will be a simpler method than a for loop.
Just like the |:let| command, |:for| also accepts a list of variables. This
requires the argument to be a list of lists.
:for [lnum, col] in [[1, 3], [2, 8], [3, 0]]
: call Doit(lnum, col)
:endfor
This works like a |:let| command is done for each list item. Again, the types
must remain the same to avoid an error.
It is also possible to put remaining items in a List variable:
:for [i, j; rest] in listlist
: call Doit(i, j)
: if !empty(rest)
: echo "remainder: " . string(rest)
: endif
:endfor
List functions
*E714*
Functions that are useful with a List:
:let r = call(funcname, list) " call a function with an argument list
:if empty(list) " check if list is empty
:let l = len(list) " number of items in list
:let big = max(list) " maximum value in list
:let small = min(list) " minimum value in list
:let xs = count(list, 'x') " count nr of times 'x' appears in list
:let i = index(list, 'x') " index of first 'x' in list
:let lines = getline(1, 10) " get ten text lines from buffer
:call append('$', lines) " append text lines in buffer
:let list = split("a b c") " create list from items in a string
:let string = join(list, ', ') " create string from list items
:let s = string(list) " String representation of list
:call map(list, '">> " . v:val') " prepend ">> " to each item
Don't forget that a combination of features can make things simple. For
example, to add up all the numbers in a list:
:exe 'let sum = ' . join(nrlist, '+')
1.4 Dictionaries
*Dictionaries* *Dictionary*
A Dictionary is an associative array: Each entry has a key and a value. The
entry can be located with the key. The entries are stored without a specific
ordering.
Dictionary creation
*E720* *E721* *E722* *E723*
A Dictionary is created with a comma separated list of entries in curly
braces. Each entry has a key and a value, separated by a colon. Each key can
only appear once. Examples:
:let mydict = {1: 'one', 2: 'two', 3: 'three'}
:let emptydict = {}
*E713* *E716* *E717*
A key is always a String. You can use a Number, it will be converted to a
String automatically. Thus the String '4' and the number 4 will find the same
entry. Note that the String '04' and the Number 04 are different, since the
Number will be converted to the String '4'.
A value can be any expression. Using a Dictionary for a value creates a
nested Dictionary:
:let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}}
An extra comma after the last entry is ignored.
Accessing entries
The normal way to access an entry is by putting the key in square brackets:
:let val = mydict["one"]
:let mydict["four"] = 4
You can add new entries to an existing Dictionary this way, unlike Lists.
For keys that consist entirely of letters, digits and underscore the following
form can be used YXXYexpr-entry|:
:let val = mydict.one
:let mydict.four = 4
Since an entry can be any type, also a List and a Dictionary, the indexing and
key lookup can be repeated:
:echo dict.key[idx].key
Dictionary identity
*dict-identity*
Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a
Dictionary. Otherwise, assignment results in referring to the same
Dictionary:
:let onedict = {'a': 1, 'b': 2}
:let adict = onedict
:let adict['a'] = 11
:echo onedict['a']
11
Two Dictionaries compare equal if all the key-value pairs compare equal. For
more info see |list-identity|.
Dictionary modification
*dict-modification*
To change an already existing entry of a Dictionary, or to add a new entry,
use |:let| this way:
:let dict[4] = "four"
:let dict['one'] = item
Removing an entry from a Dictionary is done with |remove()| or |:unlet|.
Three ways to remove the entry with key "aaa" from dict:
:let i = remove(dict, 'aaa')
:unlet dict.aaa
:unlet dict['aaa']
Merging a Dictionary with another is done with YXXYextend()|:
:call extend(adict, bdict)
This extends adict with all entries from bdict. Duplicate keys cause entries
in adict to be overwritten. An optional third argument can change this.
Note that the order of entries in a Dictionary is irrelevant, thus don't
expect ":echo adict" to show the items from bdict after the older entries in
adict.
Weeding out entries from a Dictionary can be done with YXXYfilter()|:
:call filter(dict, 'v:val =~ "x"')
This removes all entries from "dict" with a value not matching 'x'.
Dictionary function
*Dictionary-function* *self* *E725*
When a function is defined with the "dict" attribute it can be used in a
special way with a dictionary. Example:
*numbered-function* *anonymous-function*
To avoid the extra name for the function it can be defined and directly
assigned to a Dictionary in this way:
:let mydict = {'data': [0, 1, 2, 3]}
:function mydict.len() dict
: return len(self.data)
:endfunction
:echo mydict.len()
The function will then get a number and the value of dict.len is a |Funcref|
that references this function. The function can only be used through a
|Funcref|. It will automatically be deleted when there is no |Funcref|
remaining that refers to it.
It is not necessary to use the "dict" attribute for a numbered function.
If you get an error for a numbered function, you can find out what it is with
a trick. Assuming the function is 42, the command is:
:function {42}
:echo lnum == 1
:\ ? "top"
:\ : lnum == 1000
:\ ? "last"
:\ : lnum
You should always put a space before the ':', otherwise it can be mistaken for
use in a variable such as "a:1".
*expr-barbar* *expr-&&*
The "||" and "&&" operators take one argument on each side. The arguments
are (converted to) Numbers. The result is:
input output
n1 n2 n1 || n2 n1 && n2
zero zero zero zero
zero non-zero non-zero zero
non-zero zero non-zero zero
non-zero non-zero non-zero non-zero
The operators can be concatenated, for example:
&nu || &list && &shell == "csh"
Note that "&&" takes precedence over "||", so this has the meaning of:
&nu || (&list && &shell == "csh")
Once the result is known, the expression "short-circuits", that is, further
arguments are not evaluated. This is like what happens in C. For example:
let a = 1
echo a || b
This is valid even if there is no variable called "b" because "a" is non-zero,
so the result must be non-zero. Similarly below:
echo exists("b") && b == "yes"
This is valid whether "b" has been defined or not. The second clause will
only be evaluated if "b" has been defined.
expr4 *expr4*
expr5 {cmp} expr5
Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1
if it evaluates to true.
same instance is
different instance isnot
Examples:
"abc" ==# "Abc" evaluates to 0
"abc" ==? "Abc" evaluates to 1
"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
*E691* *E692*
A |List| can only be compared with a |List| and only "equal", "not equal" and
"is" can be used. This compares the values of the list, recursively.
Ignoring case means case is ignored when comparing item values.
*E735* *E736*
A |Dictionary| can only be compared with a |Dictionary| and only "equal", "not
equal" and "is" can be used. This compares the key/values of the |Dictionary|
recursively. Ignoring case means case is ignored when comparing item values.
*E693* *E694*
A |Funcref| can only be compared with a |Funcref| and only "equal" and "not
equal" can be used. Case is never ignored.
When using "is" or "isnot" with a |List| this checks if the expressions are
referring to the same |List| instance. A copy of a |List| is different from
the original |List|. When using "is" without a |List| it is equivalent to
using "equal", using "isnot" equivalent to using "not equal". Except that a
different type means the values are different. "4 == '4'"' is true, "4 is '4'"'
is false.
When comparing a String with a Number, the String is converted to a Number,
and the comparison is done on Numbers. This means that "0 == 'x'"' is TRUE,
because 'x' converted to a Number is zero.
When comparing two Strings, this is done with strcmp() or stricmp(). This
results in the mathematical difference (comparing byte values), not
necessarily the alphabetical difference in the local language.
When using the operators with a trailing '#', or the short version and
'ignorecase' is off, the comparing is done with strcmp(): case matters.
When using the operators with a trailing '?', or the short version and
'ignorecase' is set, the comparing is done with stricmp(): case is ignored.
'smartcase' is not used.
The "=~" and "!~" operators match the lefthand argument with the righthand
argument, which is used as a pattern. See |pattern| for what a pattern is.
This matching is always done like 'magic' was set and 'cpoptions' is empty, no
matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
portable. To avoid backslashes in the regexp pattern to be doubled, use a
single-quote string, see |literal-string|.
Since a string is considered to be a single line, a multi-line pattern
(containing \n, backslash-n) will not match. However, a literal NL character
can be matched like an ordinary character. Examples:
"foo\nbar" =~ "\n" evaluates to 1
"foo\nbar" =~ "\\n" evaluates to 0
expr7 *expr7*
! expr7 logical NOT *expr-!*
- expr7 unary minus *expr-unary--*
+ expr7 unary plus *expr-unary-+*
For '!' non-zero becomes zero, zero becomes one.
For '-' the sign of the number is changed.
For '+' the number is unchanged.
A String will be converted to a Number first.
These three can be repeated and mixed. Examples:
!-1 == 0
!!8 == 1
--9 == 9
expr8 *expr8*
expr8[expr1] item of String or |List| *expr-[]* *E111*
If expr8 is a Number or String this results in a String that contains the
expr1'th single byte from expr8. expr8 is used as a String, expr1 as a
Number. This doesn't recognize multi-byte encodings, see |byteidx()| for
an alternative.
Index zero gives the first character. This is like it works in C. Careful:
text column numbers start with one! Example, to get the character under the
cursor:
:let c = getline(".")[col(".") - 1]
If the length of the String is less than the index, the result is an empty
String. A negative index always results in an empty string (reason: backwards
compatibility). Use [-1:] to get the last byte.
If expr8 is a |List| then it results the item at index expr1. See |list-index|
for possible index values. If the index is out of range this results in an
error. Example:
:let item = mylist[-1] " get last item
Generally, if a |List| index is equal to or higher than the length of the
|List|, or more negative than the length of the |List|, this results in an
error.
*sublist* *slice*
If expr8 is a |List| this results in a new |List| with the items indicated by
the indexes expr1a and expr1b. This works like with a String, as explained
just above, except that indexes out of range cause an error. Examples:
:let l = mylist[:3] " first four items
:let l = mylist[4:4] " List with one item
:let l = mylist[:] " shallow copy of a List
Using expr8[expr1] or expr8[expr1a : expr1b] on a |Funcref| results in an
error.
*expr9*
number
number number constant *expr-number*
Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0).
*floating-point-format*
Floating point numbers can be written in two forms:
[-+]{N}.{M}
[-+]{N}.{M}e[-+]{exp}
{N} and {M} are numbers. Both {N} and {M} must be present and can only
contain digits.
[-+] means there is an optional plus or minus sign.
{exp} is the exponent, power of 10.
Only a decimal point is accepted, not a comma. No matter what the current
locale is.
{only when compiled with the |+float| feature}
Examples:
123.456
+0.0001
55.0
-0.123
1.234e03
1.0E-6
-3.1416e+88
These are INVALID:
3. empty {M}
1e40 missing .{M}
*float-pi* *float-e*
A few useful values to copy&paste:
:let pi = 3.14159265359
:let e = 2.71828182846
Rationale:
Before floating point was introduced, the text "123.456" was interpreted as
the two numbers "123" and "456", both converted to a string and concatenated,
resulting in the string "123456". Since this was considered pointless, and we
could not find it intentionally being used in Vim scripts, this backwards
incompatibility was accepted in favor of being able to use the normal notation
for floating point numbers.
*floating-point-precision*
The precision and range of floating points numbers depends on what "double"
means in the library Vim was compiled with. There is no way to change this at
runtime.
The default for displaying a |Float| is to use 6 decimal places, like using
printf("%g", ff). You can select something else when using the |printf()|
function. Example:
:echo printf('%.15e', atan(1))
7.853981633974483e-01
Note that "\xff" is stored as the byte 255, which may be invalid in some
encodings. Use "\u00ff" to store character 255 according to the current value
of 'encoding'.
Note that "\000" and "\x00" force the end of the string.
==============================================================================
3. Internal variable *internal-variables* *E461*
An internal variable name can be made up of letters, digits and '_'. But it
cannot start with a digit. It's also possible to use curly braces, see
|curly-braces-names|.
An internal variable is created with the ":let" command |:let|.
An internal variable is explicitly destroyed with the ":unlet" command
|:unlet|.
Using a name that is not an internal variable or refers to a variable that has
been destroyed results in an error.
There are several name spaces for variables. Which one is to be used is
specified by what is prepended:
(nothing) In a function: local to a function; otherwise: global
|buffer-variable| b: Local to the current buffer.
|window-variable| w: Local to the current window.
|tabpage-variable| t: Local to the current tab page.
|global-variable| g: Global.
|local-variable| l: Local to a function.
|script-variable| s: Local to a |:source|'ed Vim script.
|function-argument| a: Function argument (only inside a function).
|vim-variable| v: Global, predefined by Vim.
The scope name by itself can be used as a |Dictionary|. For example, to
delete all script-local variables:
:for k in keys(s:)
: unlet s:[k]
:endfor
*buffer-variable* *b:var*
A variable name that is preceded with "b:" is local to the current buffer.
Thus you can have several "b:foo" variables, one for each buffer.
This kind of variable is deleted when the buffer is wiped out or deleted with
|:bdelete|.
One local buffer variable is predefined:
*b:changedtick-variable* *changetick*
b:changedtick The total number of changes to the current buffer. It is
incremented for each change. An undo command is also a change
in this case. This can be used to perform an action only when
the buffer has changed. Example:
:if my_changedtick != b:changedtick
: let my_changedtick = b:changedtick
: call My_Update()
:endif
*window-variable* *w:var*
A variable name that is preceded with "w:" is local to the current window. It
is deleted when the window is closed.
*tabpage-variable* *t:var*
A variable name that is preceded with "t:" is local to the current tab page,
It is deleted when the tab page is closed. {not available when compiled
without the |+windows| feature}
*global-variable* *g:var*
Inside functions global variables are accessed with "g:". Omitting this will
access a variable local to a function. But "g:" can also be used in any other
place if you like.
*local-variable* *l:var*
Inside functions local variables are accessed without prepending anything.
But you can also prepend "l:" if you like. However, without prepending "l:"
you may run into reserved variable names. For example "count". By itself it
refers to "v:count". Using "l:count" you can have a local variable with the
same name.
*script-variable* *s:var*
In a Vim script variables starting with "s:" can be used. They cannot be
accessed from outside of the scripts, thus are local to the script.
They can be used in:
- commands executed while the script is sourced
- functions defined in the script
- autocommands defined in the script
- functions and autocommands defined in functions and autocommands which were
defined in the script (recursively)
- user defined commands defined in the script
Thus not in:
- other scripts sourced from this one
- mappings
- menus
- etc.
Script variables can be used to avoid conflicts with global variable names.
Take this example:
let s:counter = 0
function MyCounter()
let s:counter = s:counter + 1
echo s:counter
endfunction
command Tick call MyCounter()
You can now invoke "Tick" from any script, and the "s:counter" variable in
that script will not be changed, only the "s:counter" in the script where
"Tick" was defined is used.
Another example that does the same:
let s:counter = 0
command Tick let s:counter = s:counter + 1 | echo s:counter
When calling a function and invoking a user-defined command, the context for
script variables is set to the script where the function or command was
defined.
The script variables are also available when a function is defined inside a
function that is defined in a script. Example:
let s:counter = 0
function StartCounting(incr)
if a:incr
function MyCounter()
let s:counter = s:counter + 1
endfunction
else
function MyCounter()
let s:counter = s:counter - 1
endfunction
endif
endfunction
This defines the MyCounter() function either for counting up or counting down
when calling StartCounting(). It doesn't matter from where StartCounting() is
called, the s:counter variable will be accessible in MyCounter().
When the same script is sourced again it will use the same script variables.
They will remain valid as long as Vim is running. This can be used to
maintain a counter:
if !exists("s:counter")
let s:counter = 1
echo "script executed for the first time"
else
let s:counter = s:counter + 1
*v:beval_col* *beval_col-variable*
v:beval_col The number of the column, over which the mouse pointer is.
This is the byte index in the |v:beval_lnum| line.
Only valid while evaluating the 'balloonexpr' option.
*v:beval_bufnr* *beval_bufnr-variable*
v:beval_bufnr The number of the buffer, over which the mouse pointer is. Only
valid while evaluating the 'balloonexpr' option.
*v:beval_lnum* *beval_lnum-variable*
v:beval_lnum The number of the line, over which the mouse pointer is. Only
valid while evaluating the 'balloonexpr' option.
*v:beval_text* *beval_text-variable*
v:beval_text The text under or after the mouse pointer. Usually a word as
it is useful for debugging a C program. 'iskeyword' applies,
but a dot and "->" before the position is included. When on a
']' the text before it is used, including the matching '[' and
word before it. When on a Visual area within one line the
highlighted text is used.
Only valid while evaluating the 'balloonexpr' option.
*v:beval_winnr* *beval_winnr-variable*
v:beval_winnr The number of the window, over which the mouse pointer is. Only
valid while evaluating the 'balloonexpr' option. The first
window has number zero (unlike most other places where a
window gets a number).
*v:char* *char-variable*
v:char Argument for evaluating 'formatexpr' and used for the typed
character when using <expr> in an abbreviation |:map-<expr>|.
*v:charconvert_from* *charconvert_from-variable*
v:charconvert_from
The name of the character encoding of a file to be converted.
Only valid while evaluating the 'charconvert' option.
*v:charconvert_to* *charconvert_to-variable*
v:charconvert_to
The name of the character encoding of a file after conversion.
Only valid while evaluating the 'charconvert' option.
*v:cmdarg* *cmdarg-variable*
v:cmdarg This variable is used for two purposes:
1. The extra arguments given to a file read/write command.
Currently these are "++enc=" and "++ff=". This variable is
set before an autocommand event for a file read/write
command is triggered. There is a leading space to make it
possible to append this variable directly after the
read/write command. Note: The "+cmd" argument isn't
included here, because it will be executed anyway.
2. When printing a PostScript file with ":hardcopy" this is
the argument for the ":hardcopy" command. This can be used
in 'printexpr'.
*v:cmdbang* *cmdbang-variable*
v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
was used the value is 1, otherwise it is 0. Note that this
can only be used in autocommands. For user commands |<bang>|
can be used.
*v:count* *count-variable*
v:count The count given for the last Normal mode command. Can be used
to get the count before a mapping. Read-only. Example:
:map _x :<C-U>echo "the count is " . v:count<CR>
Note: The <C-U> is required to remove the line range that you
get when typing ':' after a count.
When there are two counts, as in "3d2w", they are multiplied,
just like what happens in the command, "d6w" for the example.
Also used for evaluating the 'formatexpr' option.
"count" also works, for backwards compatibility.
*v:count1* *count1-variable*
v:count1 Just like "v:count", but defaults to one when no count is
used.
*v:ctype* *ctype-variable*
v:ctype The current locale setting for characters of the runtime
environment. This allows Vim scripts to be aware of the
current locale encoding. Technical: it's the value of
LC_CTYPE. When not using a locale the value is "C".
This variable can not be set directly, use the |:language|
command.
See |multi-lang|.
*v:dying* *dying-variable*
v:dying Normally zero. When a deadly signal is caught it's set to
one. When multiple signals are caught the number increases.
Can be used in an autocommand to check if Vim didn't
terminate normally. {only works on Unix}
Example:
:au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
Note: if another deadly signal is caught when v:dying is one,
VimLeave autocommands will not be executed.
*v:errmsg* *errmsg-variable*
v:errmsg Last given error message. It's allowed to set this variable.
Example:
:let v:errmsg = ""
:silent! next
:if v:errmsg != ""
: ... handle error
"errmsg" also works, for backwards compatibility.
*v:exception* *exception-variable*
v:exception The value of the exception most recently caught and not
finished. See also |v:throwpoint| and |throw-variables|.
Example:
:try
: throw "oops"
:catch /.*/
: echo "caught" v:exception
:endtry
Output: "caught oops".
*v:fcs_reason* *fcs_reason-variable*
v:fcs_reason The reason why the |FileChangedShell| event was triggered.
Can be used in an autocommand to decide what to do and/or what
to set v:fcs_choice to. Possible values:
deleted file no longer exists
conflict file contents, mode or timestamp was
changed and buffer is modified
changed file contents has changed
mode mode of file changed
time only file timestamp changed
*v:fcs_choice* *fcs_choice-variable*
v:fcs_choice What should happen after a |FileChangedShell| event was
triggered. Can be used in an autocommand to tell Vim what to
do with the affected buffer:
*v:fname_in* *fname_in-variable*
v:fname_in The name of the input file. Valid while evaluating:
option used for
'charconvert' file to be converted
'diffexpr' original file
'patchexpr' original file
'printexpr' file to be printed
And set to the swap file name for |SwapExists|.
*v:fname_out* *fname_out-variable*
v:fname_out The name of the output file. Only valid while
evaluating:
option used for
'charconvert' resulting converted file (*)
'diffexpr' output of diff
'patchexpr' resulting patched file
(*) When doing conversion for a write command (e.g., ":w
file") it will be equal to v:fname_in. When doing conversion
for a read command (e.g., ":e file") it will be a temporary
file and different from v:fname_in.
*v:fname_new* *fname_new-variable*
v:fname_new The name of the new version of the file. Only valid while
evaluating 'diffexpr'.
*v:fname_diff* *fname_diff-variable*
v:fname_diff The name of the diff (patch) file. Only valid while
evaluating 'patchexpr'.
*v:folddashes* *folddashes-variable*
v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
fold.
Read-only in the |sandbox|. |fold-foldtext|
*v:foldlevel* *foldlevel-variable*
v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Read-only in the |sandbox|. |fold-foldtext|
*v:foldend* *foldend-variable*
v:foldend Used for 'foldtext': last line of closed fold.
Read-only in the |sandbox|. |fold-foldtext|
*v:foldstart* *foldstart-variable*
v:foldstart Used for 'foldtext': first line of closed fold.
Read-only in the |sandbox|. |fold-foldtext|
*v:insertmode* *insertmode-variable*
v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
events. Values:
i Insert mode
r Replace mode
v Virtual Replace mode
*v:key* *key-variable*
v:key Key of the current item of a |Dictionary|. Only valid while
evaluating the expression used with |map()| and |filter()|.
Read-only.
*v:lang* *lang-variable*
v:lang The current locale setting for messages of the runtime
environment. This allows Vim scripts to be aware of the
current language. Technical: it's the value of LC_MESSAGES.
The value is system dependent.
This variable can not be set directly, use the |:language|
command.
It can be different from |v:ctype| when messages are desired
in a different language than what is used for character
encoding. See |multi-lang|.
*v:lc_time* *lc_time-variable*
v:lc_time The current locale setting for time messages of the runtime
environment. This allows Vim scripts to be aware of the
current language. Technical: it's the value of LC_TIME.
This variable can not be set directly, use the |:language|
command. See |multi-lang|.
*v:lnum* *lnum-variable*
v:lnum Line number for the 'foldexpr' |fold-expr|, 'formatexpr' and
'indentexpr' expressions, tab page number for 'guitablabel'
and 'guitabtooltip'. Only valid while one of these
expressions is being evaluated. Read-only when in the
|sandbox|.
*v:mouse_win* *mouse_win-variable*
v:mouse_win Window number for a mouse click obtained with |getchar()|.
First window has number 1, like with |winnr()|. The value is
zero when there was no mouse button click.
*v:mouse_lnum* *mouse_lnum-variable*
v:mouse_lnum Line number for a mouse click obtained with |getchar()|.
This is the text line number, not the screen line number. The
value is zero when there was no mouse button click.
*v:mouse_col* *mouse_col-variable*
v:mouse_col Column number for a mouse click obtained with |getchar()|.
This is the screen column number, like with |virtcol()|. The
value is zero when there was no mouse button click.
*v:oldfiles* *oldfiles-variable*
v:oldfiles List of file names that is loaded from the |viminfo| file on
startup. These are the files that Vim remembers marks for.
The length of the List is limited by the '' argument of the
'viminfo' option (default is 100).
Also see |:oldfiles| and |c_#<|.
The List can be modified, but this has no effect on what is
stored in the |viminfo| file later. If you use values other
than String this will cause trouble.
{only when compiled with the |+viminfo| feature}
*v:operator* *operator-variable*
v:operator The last operator given in Normal mode. This is a single
character except for commands starting with <g> or <z>,
in which case it is two characters. Best used alongside
|v:prevcount| and |v:register|. Useful if you want to cancel
Operator-pending mode and then use the operator, e.g.:
:omap O <Esc>:call MyMotion(v:operator)<CR>
The value remains set until another operator is entered, thus
don't expect it to be empty.
v:operator is not set for |:delete|, |:yank| or other Ex
commands.
Read-only.
*v:prevcount* *prevcount-variable*
v:prevcount The count given for the last but one Normal mode command.
This is the v:count value of the previous command. Useful if
you want to cancel Visual or Operator-pending mode and then
use the count, e.g.:
:vmap % <Esc>:call MyFilter(v:prevcount)<CR>
Read-only.
*v:profiling* *profiling-variable*
v:profiling Normally zero. Set to one after using ":profile start".
See |profiling|.
*v:progname* *progname-variable*
v:progname Contains the name (with path removed) with which Vim was
invoked. Allows you to do special initialisations for "view",
"evim" etc., or any other name you might symlink to Vim.
Read-only.
*v:register* *register-variable*
v:register The name of the register in effect for the current normal mode
command. If none is supplied it is the default register.
Also see |getreg()| and |setreg()|
*v:scrollstart* *scrollstart-variable*
v:scrollstart String describing the script or function that caused the
screen to scroll up. It's only set when it is empty, thus the
first reason is remembered. It is set to "Unknown" for a
typed command.
This can be used to find out why your script causes the
hit-enter prompt.
*v:servername* *servername-variable*
v:servername The resulting registered |x11-clientserver| name if any.
Read-only.
*v:shell_error* *shell_error-variable*
v:shell_error Result of the last shell command. When non-zero, the last
shell command had an error. When zero, there was no problem.
This only works when the shell returns the error code to Vim.
The value -1 is often used when the command could not be
executed. Read-only.
Example:
:!mv foo bar
:if v:shell_error
: echo 'could not rename "foo" to "bar"!'
:endif
"shell_error" also works, for backwards compatibility.
*v:statusmsg* *statusmsg-variable*
v:statusmsg Last given status message. It's allowed to set this variable.
*v:swapname* *swapname-variable*
v:swapname Only valid when executing |SwapExists| autocommands: Name of
the swap file found. Read-only.
*v:swapchoice* *swapchoice-variable*
v:swapchoice |SwapExists| autocommands can set this to the selected choice
for handling an existing swap file:
'o' Open read-only
'e' Edit anyway
'r' Recover
'd' Delete swapfile
'q' Quit
'a' Abort
The value should be a single-character string. An empty value
results in the user being asked, as would happen when there is
no SwapExists autocommand. The default is empty.
*v:swapcommand* *swapcommand-variable*
v:swapcommand Normal mode command to be executed after a file has been
opened. Can be used for a |SwapExists| autocommand to have
another Vim open the file and jump to the right place. For
example, when jumping to a tag the value is ":tag tagname\r".
For ":edit +cmd file" the value is ":cmd\r".
*v:termresponse* *termresponse-variable*
v:termresponse The escape sequence returned by the terminal for the |t_RV|
termcap entry. It is set when Vim receives an escape sequence
that starts with ESC [ or CSI and ends in a 'c', with only
digits, ';' and '.' in between.
When this option is set, the TermResponse autocommand event is
fired, so that you can react to the response from the
terminal.
The response from a new xterm is: "<Esc>[ Pp ; Pv ; Pc c". Pp
is the terminal type: 0 for vt100 and 1 for vt220. Pv is the
patch level (since this was introduced in patch 95, it's
always 95 or bigger). Pc is always zero.
{only when compiled with |+termresponse| feature}
*v:this_session* *this_session-variable*
v:this_session Full filename of the last loaded or saved session file. See
|:mksession|. It is allowed to set this variable. When no
session file has been saved, this variable is empty.
"this_session" also works, for backwards compatibility.
*v:throwpoint* *throwpoint-variable*
v:throwpoint The point where the exception most recently caught and not
finished was thrown. Not set when commands are typed. See
also |v:exception| and |throw-variables|.
Example:
:try
: throw "oops"
:catch /.*/
: echo "Exception from" v:throwpoint
:endtry
Output: "Exception from test.vim, line 2"
*v:val* *val-variable*
v:val Value of the current item of a |List| or |Dictionary|. Only
valid while evaluating the expression used with |map()| and
|filter()|. Read-only.
*v:version* *version-variable*
v:version Version number of Vim: Major version number times 100 plus
minor version number. Version 5.0 is 500. Version 5.1 (5.01)
is 501. Read-only. "version" also works, for backwards
compatibility.
Use |has()| to check if a certain patch was included, e.g.:
if has("patch123")
Note that patch numbers are specific to the version, thus both
version 5.0 and 5.1 may have a patch 123, but these are
completely different.
*v:warningmsg* *warningmsg-variable*
v:warningmsg Last given warning message. It's allowed to set this variable.
*v:windowid* *windowid-variable*
v:windowid When any X11 based GUI is running or when running in a
terminal and Vim connects to the X server (|-X|) this will be
set to the window ID.
When an MS-Windows GUI is running this will be set to the
window handle.
Otherwise the value is zero.
Note: for windows inside Vim use |winnr()|.
==============================================================================
4. Builtin Functions *functions*
See |function-list| for a list grouped by what the function is used for.
(Use CTRL-] on the function name to jump to the full explanation.)
USAGE RESULT DESCRIPTION
abs( {expr}) Float or Number absolute value of {expr}
acos( {expr}) Float arc cosine of {expr}
add( {list}, {item}) List append {item} to |List| {list}
append( {lnum}, {string}) Number append {string} below line {lnum}
append( {lnum}, {list}) Number append lines {list} below line {lnum}
argc() Number number of files in the argument list
argidx() Number current index in the argument list
argv( {nr}) String {nr} entry of the argument list
argv( ) List the argument list
asin( {expr}) Float arc sine of {expr}
atan( {expr}) Float arc tangent of {expr}
atan2( {expr}, {expr}) Float arc tangent of {expr1} / {expr2}
browse( {save}, {title}, {initdir}, {default})
String put up a file requester
browsedir( {title}, {initdir}) String put up a directory requester
bufexists( {expr}) Number TRUE if buffer {expr} exists
buflisted( {expr}) Number TRUE if buffer {expr} is listed
bufloaded( {expr}) Number TRUE if buffer {expr} is loaded
bufname( {expr}) String Name of the buffer {expr}
bufnr( {expr}) Number Number of the buffer {expr}
bufwinnr( {expr}) Number window number of buffer {expr}
byte2line( {byte}) Number line number at byte count {byte}
byteidx( {expr}, {nr}) Number byte index of {nr}'th char in {expr}
call( {func}, {arglist} [, {dict}])
any call {func} with arguments {arglist}
ceil( {expr}) Float round {expr} up
changenr() Number current change number
char2nr( {expr}) Number ASCII value of first char in {expr}
cindent( {lnum}) Number C indent for line {lnum}
clearmatches() none clear all matches
col( {expr}) Number column nr of cursor or mark
complete( {startcol}, {matches}) none set Insert mode completion
complete_add( {expr}) Number add completion match
complete_check() Number check for key typed during completion
confirm( {msg} [, {choices} [, {default} [, {type}]]])
Number number of choice picked by user
copy( {expr}) any make a shallow copy of {expr}
cos( {expr}) Float cosine of {expr}
cosh( {expr}) Float hyperbolic cosine of {expr}
count( {list}, {expr} [, {start} [, {ic}]])
Number count how many {expr} are in {list}
cscope_connection( [{num} , {dbpath} [, {prepend}]])
Number checks existence of cscope connection
cursor( {lnum}, {col} [, {coladd}])
Number move cursor to {lnum}, {col}, {coladd}
cursor( {list}) Number move cursor to position in {list}
deepcopy( {expr}) any make a full copy of {expr}
delete( {fname}) Number delete file {fname}
did_filetype() Number TRUE if FileType autocommand event used
diff_filler( {lnum}) Number diff filler lines about {lnum}
diff_hlID( {lnum}, {col}) Number diff highlighting at {lnum}/{col}
empty( {expr}) Number TRUE if {expr} is empty
escape( {string}, {chars}) String escape {chars} in {string} with '\'
eval( {string}) any evaluate {string} into its value
eventhandler( ) Number TRUE if inside an event handler
executable( {expr}) Number 1 if executable {expr} exists
exists( {expr}) Number TRUE if {expr} exists
extend( {expr1}, {expr2} [, {expr3}])
List/Dict insert items of {expr2} into {expr1}
exp( {expr}) Float exponential of {expr}
expand( {expr} [, {flag}]) String expand special keywords in {expr}
feedkeys( {string} [, {mode}]) Number add key sequence to typeahead buffer
filereadable( {file}) Number TRUE if {file} is a readable file
filewritable( {file}) Number TRUE if {file} is a writable file
filter( {expr}, {string}) List/Dict remove items from {expr} where
{string} is 0
finddir( {name}[, {path}[, {count}]])
String find directory {name} in {path}
findfile( {name}[, {path}[, {count}]])
String find file {name} in {path}
float2nr( {expr}) Number convert Float {expr} to a Number
floor( {expr}) Float round {expr} down
fmod( {expr1}, {expr2}) Float remainder of {expr1} / {expr2}
fnameescape( {fname}) String escape special characters in {fname}
abs({expr}) *abs()*
Return the absolute value of {expr}. When {expr} evaluates to
a |Float| abs() returns a |Float|. When {expr} can be
converted to a |Number| abs() returns a |Number|. Otherwise
abs() gives an error message and returns -1.
Examples:
echo abs(1.456)
1.456
echo abs(-5.456)
5.456
echo abs(-4)
4
acos({expr}) *acos()*
Return the arc cosine of {expr} measured in radians, as a
|Float| in the range of [0, pi].
{expr} must evaluate to a |Float| or a |Number| in the range
[-1, 1].
Examples:
:echo acos(0)
1.570796
:echo acos(-0.5)
2.094395
{only available when compiled with the |+float| feature}
*argc()*
argc() The result is the number of files in the argument list of the
current window. See |arglist|.
*argidx()*
argidx() The result is the current index in the argument list. 0 is
the first file. argc() - 1 is the last one. See |arglist|.
*argv()*
argv([{nr}]) The result is the {nr}th file in the argument list of the
current window. See |arglist|. "argv(0)" is the first one.
Example:
:let i = 0
:while i < argc()
: let f = escape(fnameescape(argv(i)), '.')
: exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
: let i = i + 1
:endwhile
Without the {nr} argument a |List| with the whole |arglist| is
returned.
asin({expr}) *asin()*
Return the arc sine of {expr} measured in radians, as a |Float|
in the range of [-pi/2, pi/2].
{expr} must evaluate to a |Float| or a |Number| in the range
[-1, 1].
Examples:
:echo asin(0.8)
0.927295
:echo asin(-0.5)
-0.523599
{only available when compiled with the |+float| feature}
atan({expr}) *atan()*
Return the principal value of the arc tangent of {expr}, in
the range [-pi/2, +pi/2] radians, as a |Float|.
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo atan(100)
1.560797
:echo atan(-4.01)
-1.326405
{only available when compiled with the |+float| feature}
*browse()*
browse({save}, {title}, {initdir}, {default})
Put up a file requester. This only works when "has("browse")"
returns non-zero (only in some GUI versions).
The input fields are:
{save} when non-zero, select file to write
{title} title for the requester
{initdir} directory to start browsing in
{default} default file name
When the "Cancel" button is hit, something went wrong, or
browsing is not possible, an empty string is returned.
*browsedir()*
browsedir({title}, {initdir})
Put up a directory requester. This only works when
"has("browse")" returns non-zero (only in some GUI versions).
On systems where a directory browser is not supported a file
browser is used. In that case: select a file in the directory
to be used.
The input fields are:
{title} title for the requester
{initdir} directory to start browsing in
When the "Cancel" button is hit, something went wrong, or
browsing is not possible, an empty string is returned.
bufexists({expr}) *bufexists()*
The result is a Number, which is non-zero if a buffer called
{expr} exists.
If the {expr} argument is a number, buffer numbers are used.
If the {expr} argument is a string it must match a buffer name
exactly. The name can be:
- Relative to the current directory.
- A full path.
- The name of a buffer with 'buftype' set to "nofile".
- A URL name.
Unlisted buffers will be found.
Note that help files are listed by their short name in the
output of |:buffers|, but bufexists() requires using their
long name to be able to find them.
bufexists() may report a buffer exists, but to use the name
with a |:buffer| command you may need to use |expand()|. Esp
for MS-Windows 8.3 names in the form "c:\DOCUME~1"
Use "bufexists(0)" to test for the existence of an alternate
file name.
*buffer_exists()*
Obsolete name: buffer_exists().
buflisted({expr}) *buflisted()*
The result is a Number, which is non-zero if a buffer called
{expr} exists and is listed (has the 'buflisted' option set).
bufloaded({expr}) *bufloaded()*
The result is a Number, which is non-zero if a buffer called
{expr} exists and is loaded (shown in a window or hidden).
The {expr} argument is used like with |bufexists()|.
bufname({expr}) *bufname()*
The result is the name of a buffer, as it is displayed by the
":ls" command.
If {expr} is a Number, that buffer number's name is given.
Number zero is the alternate buffer for the current window.
If {expr} is a String, it is used as a |file-pattern| to match
with the buffer names. This is always done like 'magic' is
set and 'cpoptions' is empty. When there is more than one
match an empty string is returned.
"" or "%" can be used for the current buffer, "#" for the
alternate buffer.
A full match is preferred, otherwise a match at the start, end
or middle of the buffer name is accepted. If you only want a
full match then put "^" at the start and "$" at the end of the
pattern.
Listed buffers are found first. If there is a single match
with a listed buffer, that one is returned. Next unlisted
buffers are searched for.
If the {expr} is a String, but you want to use it as a buffer
number, force it to be a Number by adding zero to it:
:echo bufname("3" + 0)
If the buffer doesn't exist, or doesn't have a name, an empty
string is returned.
bufname("#") alternate buffer name
bufname(3) name of buffer 3
bufname("%") name of current buffer
bufname("file2") name of buffer where "file2" matches.
*buffer_name()*
Obsolete name: buffer_name().
*bufnr()*
bufnr({expr} [, {create}])
The result is the number of a buffer, as it is displayed by
the ":ls" command. For the use of {expr}, see |bufname()|
above.
If the buffer doesn't exist, -1 is returned. Or, if the
{create} argument is present and not zero, a new, unlisted,
buffer is created and its number is returned.
bufnr("$") is the last buffer:
:let last_buffer = bufnr("$")
The result is a Number, which is the highest buffer number
of existing buffers. Note that not all buffers with a smaller
number necessarily exist, because ":bwipeout" may have removed
them. Use bufexists() to test for the existence of a buffer.
*buffer_number()*
Obsolete name: buffer_number().
*last_buffer_nr()*
Obsolete name for bufnr("$"): last_buffer_nr().
bufwinnr({expr}) *bufwinnr()*
The result is a Number, which is the number of the first
window associated with buffer {expr}. For the use of {expr},
see |bufname()| above. If buffer {expr} doesn't exist or
there is no such window, -1 is returned. Example:
echo "A window containing buffer 1 is " . (bufwinnr(1))
The number can be used with |CTRL-W_w| and ":wincmd w"
|:wincmd|.
Only deals with the current tab page.
byte2line({byte}) *byte2line()*
Return the line number that contains the character at byte
ceil({expr}) *ceil()*
Return the smallest integral value greater than or equal to
{expr} as a |Float| (round up).
{expr} must evaluate to a |Float| or a |Number|.
Examples:
echo ceil(1.456)
2.0
echo ceil(-5.456)
-5.0
echo ceil(4.0)
4.0
{only available when compiled with the |+float| feature}
changenr() *changenr()*
Return the number of the most recent change. This is the same
number as what is displayed with |:undolist| and can be used
with the |:undo| command.
When a change was made it is the number of that change. After
redo it is the number of the redone change. After undo it is
one less than the number of the undone change.
char2nr({expr}) *char2nr()*
Return number value of the first char in {expr}. Examples:
char2nr(" ") returns 32
char2nr("ABC") returns 65
The current 'encoding' is used. Example for "utf-8":
char2nr("á") returns 225
char2nr("á"[0]) returns 195
|nr2char()| does the opposite.
cindent({lnum}) *cindent()*
Get the amount of indent for line {lnum} according the C
indenting rules, as with 'cindent'.
The indent is counted in spaces, the value of 'tabstop' is
relevant. {lnum} is used just like in |getline()|.
When {lnum} is invalid or Vim was not compiled the |+cindent|
feature, -1 is returned.
See |C-indenting|.
clearmatches() *clearmatches()*
Clears all matches previously defined by |matchadd()| and the
|:match| commands.
*col()*
col({expr}) The result is a Number, which is the byte index of the column
position given with {expr}. The accepted positions are:
. the cursor position
$ the end of the cursor line (the result is the
number of characters in the cursor line plus one)
'x position of mark x (if the mark is not set, 0 is
returned)
Additionally {expr} can be [lnum, col]: a |List| with the line
and column number. Most useful when the column is "$", to get
the last column of a specific line. When "lnum" or "col" is
out of range then col() returns zero.
To get the line number use |line()|. To get both use
|getpos()|.
For the screen column position use |virtcol()|.
Note that only marks in the current file can be used.
Examples:
col(".") column of cursor
col("$") length of cursor line plus one
col("'t") column of mark t
col("'" . markname) column of mark markname
The first column is 1. 0 is returned for an error.
For an uppercase mark the column may actually be in another
buffer.
For the cursor position, when 'virtualedit' is active, the
column is one higher if the cursor is after the end of the
line. This can be used to obtain the column in Insert mode:
:imap <F2> <C-O>:let save_ve = &ve<CR>
\<C-O>:set ve=all<CR>
\<C-O>:echo col(".") . "\n" <Bar>
\let &ve = save_ve<CR>
complete_add({expr}) *complete_add()*
Add {expr} to the list of matches. Only to be used by the
function specified with the 'completefunc' option.
Returns 0 for failure (empty string or out of memory),
1 when the match was added, 2 when the match was already in
the list.
See |complete-functions| for an explanation of {expr}. It is
the same as one item in the list that 'omnifunc' would return.
complete_check() *complete_check()*
Check for a key typed while looking for completion matches.
This is to be used when looking for matches takes some time.
Returns non-zero when searching for matches is to be aborted,
zero otherwise.
Only to be used by the function specified with the
'completefunc' option.
*confirm()*
confirm({msg} [, {choices} [, {default} [, {type}]]])
Confirm() offers the user a dialog, from which a choice can be
made. It returns the number of the choice. For the first
choice this is 1.
Note: confirm() is only supported when compiled with dialog
support, see |+dialog_con| and |+dialog_gui|.
{msg} is displayed in a |dialog| with {choices} as the
alternatives. When {choices} is missing or empty, "&OK" is
used (and translated).
{msg} is a String, use '\n' to include a newline. Only on
some systems the string is wrapped when it doesn't fit.
{choices} is a String, with the individual choices separated
by '\n', e.g.
confirm("Save changes?", "&Yes\n&No\n&Cancel")
The letter after the '&' is the shortcut key for that choice.
Thus you can type 'c' to select "Cancel". The shortcut does
not need to be the first letter:
confirm("file has been modified", "&Save\nSave &All")
For the console, the first letter of each choice is used as
the default shortcut key.
The optional {default} argument is the number of the choice
that is made if the user hits <CR>. Use 1 to make the first
choice the default one. Use 0 to not set a default. If
{default} is omitted, 1 is used.
The optional {type} argument gives the type of dialog. This
is only used for the icon of the GTK, Mac, Motif and Win32
GUI. It can be one of these values: "Error", "Question",
"Info", "Warning" or "Generic". Only the first character is
relevant. When {type} is omitted, "Generic" is used.
If the user aborts the dialog by pressing <Esc>, CTRL-C,
or another valid interrupt key, confirm() returns 0.
An example:
:let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2)
:if choice == 0
: echo "make up your mind!"
:elseif choice == 3
: echo "tasteful"
:else
: echo "I prefer bananas myself."
:endif
In a GUI dialog, buttons are used. The layout of the buttons
depends on the 'v' flag in 'guioptions'. If it is included,
the buttons are always put vertically. Otherwise, confirm()
tries to put the buttons in one horizontal line. If they
don't fit, a vertical layout is used anyway. For some systems
the horizontal layout is always used.
*copy()*
copy({expr}) Make a copy of {expr}. For Numbers and Strings this isn't
different from using {expr} directly.
When {expr} is a |List| a shallow copy is created. This means
that the original |List| can be changed without changing the
copy, and vice versa. But the items are identical, thus
changing an item changes the contents of both |Lists|. Also
see |deepcopy()|.
cos({expr}) *cos()*
Return the cosine of {expr}, measured in radians, as a |Float|.
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo cos(100)
0.862319
:echo cos(-4.01)
-0.646043
{only available when compiled with the |+float| feature}
cosh({expr}) *cosh()*
Return the hyperbolic cosine of {expr} as a |Float| in the range
[1, inf].
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo cosh(0.5)
1.127626
:echo cosh(-0.5)
-1.127626
{only available when compiled with the |+float| feature}
*cscope_connection()*
cscope_connection([{num} , {dbpath} [, {prepend}]])
Checks for the existence of a |cscope| connection. If no
parameters are specified, then the function returns:
0, if cscope was not available (not compiled in), or
if there are no cscope connections;
1, if there is at least one cscope connection.
If parameters are specified, then the value of {num}
determines how existence of a cscope connection is checked:
{num} Description of existence check
----- ------------------------------
0 Same as no parameters (e.g., "cscope_connection()").
1 Ignore {prepend}, and use partial string matches for
{dbpath}.
2 Ignore {prepend}, and use exact string matches for
{dbpath}.
3 Use {prepend}, use partial string matches for both
{dbpath} and {prepend}.
4 Use {prepend}, use exact string matches for both
{dbpath} and {prepend}.
Note: All string comparisons are case sensitive!
Examples. Suppose we had the following (from ":cs show"):
# pid database name prepend path
0 27664 cscope.out /usr/local
Invocation Return Val
---------- ----------
cscope_connection() 1
cscope_connection(1, "out") 1
cscope_connection(2, "out") 0
cscope_connection(3, "out") 0
cscope_connection(3, "out", "local") 1
cscope_connection(4, "out") 0
cscope_connection(4, "out", "local") 0
cscope_connection(4, "cscope.out", "/usr/local") 1
delete({fname}) *delete()*
Deletes the file by the name {fname}. The result is a Number,
which is 0 if the file was deleted successfully, and non-zero
when the deletion failed.
Use |remove()| to delete an item from a |List|.
*did_filetype()*
did_filetype() Returns non-zero when autocommands are being executed and the
FileType event has been triggered at least once. Can be used
to avoid triggering the FileType event again in the scripts
that detect the file type. |FileType|
When editing another file, the counter is reset, thus this
really checks if the FileType event has been triggered for the
current buffer. This allows an autocommand that starts
editing another buffer to set 'filetype' and load a syntax
file.
diff_filler({lnum}) *diff_filler()*
Returns the number of filler lines above line {lnum}.
These are the lines that were inserted at this point in
another diff'ed window. These filler lines are shown in the
display but don't exist in the buffer.
{lnum} is used like with |getline()|. Thus "." is the current
line, "'m" mark m, etc.
Returns 0 if the current window is not in diff mode.
empty({expr}) *empty()*
Return the Number 1 if {expr} is empty, zero otherwise.
A |List| or |Dictionary| is empty when it does not have any
items. A Number is empty when its value is zero.
*eval()*
eval({string}) Evaluate {string} and return the result. Especially useful to
turn the result of |string()| back into the original value.
This works for Numbers, Floats, Strings and composites of
them. Also works for |Funcref|s that refer to existing
functions.
eventhandler() *eventhandler()*
Returns 1 when inside an event handler. That is that Vim got
interrupted while waiting for the user to type a character,
e.g., when dropping a file on Vim. This means interactive
commands cannot be used. Otherwise zero is returned.
executable({expr}) *executable()*
This function checks if an executable with the name {expr}
exists. {expr} must be the name of the program without any
arguments.
executable() uses the value of $PATH and/or the normal
searchpath for programs. *PATHEXT*
On MS-DOS and MS-Windows the ".exe", ".bat", etc. can
optionally be included. Then the extensions in $PATHEXT are
tried. Thus if "foo.exe" does not exist, "foo.exe.bat" can be
found. If $PATHEXT is not set then ".exe;.com;.bat;.cmd" is
used. A dot by itself can be used in $PATHEXT to try using
the name without an extension. When 'shell' looks like a
Unix shell, then the name is also tried without adding an
extension.
On MS-DOS and MS-Windows it only checks if the file exists and
is not a directory, not if it's really executable.
On MS-Windows an executable in the same directory as Vim is
always found. Since this directory is added to $PATH it
should also work to execute it |win32-PATH|.
The result is a Number:
1 exists
0 does not exist
-1 not implemented on this system
*exists()*
exists({expr}) The result is a Number, which is non-zero if {expr} is
defined, zero otherwise. The {expr} argument is a string,
which contains one of these:
&option-name Vim option (only checks if it exists,
not if it really works)
+option-name Vim option that works.
$ENVNAME environment variable (could also be
done by comparing with an empty
string)
*funcname built-in function (see |functions|)
or user defined function (see
|user-functions|).
varname internal variable (see
|internal-variables|). Also works
for |curly-braces-names|, |Dictionary|
entries, |List| items, etc. Beware
that evaluating an index may cause an
error message for an invalid
expression. E.g.:
:let l = [1, 2, 3]
:echo exists("l[5]")
0
:echo exists("l[xx]")
E121: Undefined variable: xx
0
exp({expr}) *exp()*
Return the exponential of {expr} as a |Float| in the range
[0, inf].
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo exp(2)
7.389056
:echo exp(-1)
0.367879
{only available when compiled with the |+float| feature}
When {expr} starts with '%', '#' or '<', the expansion is done
like for the |cmdline-special| variables with their associated
modifiers. Here is a short overview:
% current file name
# alternate file name
#n alternate file name n
<cfile> file name under the cursor
<afile> autocmd file name
<abuf> autocmd buffer number (as a String!)
<amatch> autocmd matched name
<sfile> sourced script file name
<slnum> sourced script file line number
<cword> word under the cursor
<cWORD> WORD under the cursor
<client> the {clientid} of the last received
message |server2client()|
Modifiers:
:p expand to full path
:h head (last path component removed)
:t tail (last path component only)
:r root (one extension removed)
:e extension only
Example:
:let &tags = expand("%:p:h") . "/tags"
Note that when expanding a string that starts with '%', '#' or
'<', any following text is ignored. This does NOT work:
:let doesntwork = expand("%:h.bak")
Use this:
:let doeswork = expand("%:h") . ".bak"
Also note that expanding "<cfile>" and others only returns the
referenced file name without further expansion. If "<cfile>"
is "~/.cshrc", you need to do another expand() to have the
"~/" expanded into the path of the home directory:
:echo expand(expand("<cfile>"))
There cannot be white space between the variables and the
following modifier. The |fnamemodify()| function can be used
to modify normal file names.
When using '%' or '#', and the current or alternate file name
is not defined, an empty string is used. Using "%:p" in a
buffer with no name, results in the current directory, with a
'/' added.
When {expr} does not start with '%', '#' or '<', it is
expanded like a file name is expanded on the command line.
'suffixes' and 'wildignore' are used, unless the optional
{flag} argument is given and it is non-zero. Names for
non-existing files are included. The "**" item can be used to
search in a directory tree. For example, to find all "README"
files in the current directory and below:
:echo expand("**/README")
Expand() can also be used to expand variables and environment
variables that are only known in a shell. But this can be
slow, because a shell must be started. See |expr-env-expand|.
The expanded variable is still handled like a list of file
names. When an environment variable cannot be expanded, it is
left unchanged. Thus ":echo expand('$FOOBAR')" results in
"$FOOBAR".
See |glob()| for finding existing files. See |system()| for
getting the raw output of an external command.
filereadable({file}) *filereadable()*
The result is a Number, which is TRUE when a file with the
name {file} exists, and can be read. If {file} doesn't exist,
or is a directory, the result is FALSE. {file} is any
expression, which is used as a String.
If you don't care about the file being readable you can use
|glob()|.
*file_readable()*
Obsolete name: file_readable().
filewritable({file}) *filewritable()*
The result is a Number, which is 1 when a file with the
name {file} exists, and can be written. If {file} doesn't
exist, or is not writable, the result is 0. If {file} is a
directory, and we can write to it, the result is 2.
float2nr({expr}) *float2nr()*
Convert {expr} to a Number by omitting the part after the
decimal point.
{expr} must evaluate to a |Float| or a Number.
When the value of {expr} is out of range for a |Number| the
result is truncated to 0x7fffffff or -0x7fffffff. NaN results
in -0x80000000.
Examples:
echo float2nr(3.95)
3
echo float2nr(-23.45)
-23
echo float2nr(1.0e100)
2147483647
echo float2nr(-1.0e150)
-2147483647
echo float2nr(1.0e-100)
0
{only available when compiled with the |+float| feature}
floor({expr}) *floor()*
Return the largest integral value less than or equal to
{expr} as a |Float| (round down).
{expr} must evaluate to a |Float| or a |Number|.
Examples:
echo floor(1.856)
1.0
echo floor(-5.456)
-6.0
echo floor(4.0)
4.0
{only available when compiled with the |+float| feature}
fnameescape({string}) *fnameescape()*
Escape {string} for use as file name command argument. All
characters that have a special meaning, such as '%' and '|'
are escaped with a backslash.
For most systems the characters escaped are
" \t\n*?[{`$\\%#'\"|!<". For systems where a backslash
appears in a filename, it depends on the value of 'isfname'.
A leading '+' and '>' is also escaped (special after |:edit|
and |:write|). And a "-" by itself (special after |:cd|).
Example:
:let fname = '+some str%nge|name'
:exe "edit " . fnameescape(fname)
results in executing:
edit \+some\ str\%nge\|name
foldclosed({lnum}) *foldclosed()*
The result is a Number. If the line {lnum} is in a closed
fold, the result is the number of the first line in that fold.
If the line {lnum} is not in a closed fold, -1 is returned.
foldclosedend({lnum}) *foldclosedend()*
The result is a Number. If the line {lnum} is in a closed
fold, the result is the number of the last line in that fold.
If the line {lnum} is not in a closed fold, -1 is returned.
foldlevel({lnum}) *foldlevel()*
The result is a Number, which is the foldlevel of line {lnum}
in the current buffer. For nested folds the deepest level is
returned. If there is no fold at line {lnum}, zero is
returned. It doesn't matter if the folds are open or closed.
When used while updating folds (from 'foldexpr') -1 is
returned for lines where folds are still to be updated and the
foldlevel is unknown. As a special case the level of the
previous line is usually available.
*foldtext()*
foldtext() Returns a String, to be displayed for a closed fold. This is
the default function used for the 'foldtext' option and should
only be called from evaluating 'foldtext'. It uses the
|v:foldstart|, |v:foldend| and |v:folddashes| variables.
The returned string looks like this:
+-- 45 lines: abcdef
The number of dashes depends on the foldlevel. The "45" is
the number of lines in the fold. "abcdef" is the text in the
first non-blank line of the fold. Leading white space, "//"
or "/*" and the text from the 'foldmarker' and 'commentstring'
options is removed.
{not available when compiled without the |+folding| feature}
foldtextresult({lnum}) *foldtextresult()*
Returns the text that is displayed for the closed fold at line
{lnum}. Evaluates 'foldtext' in the appropriate context.
When there is no closed fold at {lnum} an empty string is
returned.
{lnum} is used like with |getline()|. Thus "." is the current
line, "'m" mark m, etc.
Useful when exporting folded text, e.g., to HTML.
{not available when compiled without the |+folding| feature}
*foreground()*
foreground() Move the Vim window to the foreground. Useful when sent from
a client to a Vim server. |remote_send()|
On Win32 systems this might not work, the OS does not always
allow a window to bring itself to the foreground. Use
|remote_foreground()| instead.
{only in the Win32, Athena, Motif and GTK GUI versions and the
Win32 console version}
garbagecollect([at_exit]) *garbagecollect()*
Cleanup unused |Lists| and |Dictionaries| that have circular
references. There is hardly ever a need to invoke this
function, as it is automatically done when Vim runs out of
memory or is waiting for the user to press a key after
'updatetime'. Items without circular references are always
freed when they become unused.
This is useful if you have deleted a very big |List| and/or
|Dictionary| with circular references in a script that runs
for a long time.
When the optional "at_exit" argument is one, garbage
collection will also be done when exiting Vim, if it wasn't
done before. This is useful when checking for memory leaks.
*getbufline()*
getbufline({expr}, {lnum} [, {end}])
Return a |List| with the lines starting from {lnum} to {end}
(inclusive) in the buffer {expr}. If {end} is omitted, a
|List| with only the line {lnum} is returned.
For the use of {expr}, see |bufname()| above.
For {lnum} and {end} "$" can be used for the last line of the
buffer. Otherwise a number must be used.
When {lnum} is smaller than 1 or bigger than the number of
lines in the buffer, an empty |List| is returned.
When {end} is greater than the number of lines in the buffer,
it is treated as {end} is set to the number of lines in the
buffer. When {end} is before {lnum} an empty |List| is
returned.
This function works only for loaded buffers. For unloaded and
non-existing buffers, an empty |List| is returned.
Example:
:let lines = getbufline(bufnr("myfile"), 1, "$")
getchar([expr]) *getchar()*
Get a single character from the user or input stream.
If [expr] is omitted, wait until a character is available.
If [expr] is 0, only get a character when one is available.
Return zero otherwise.
If [expr] is 1, only check if a character is available, it is
not consumed. Return zero if no character available.
Without {expr} and when {expr} is 0 a whole character or
special key is returned. If it is an 8-bit character, the
result is a number. Use nr2char() to convert it to a String.
Otherwise a String is returned with the encoded character.
For a special key it's a sequence of bytes starting with 0x80
(decimal: 128). This is the same value as the string
"\<Key>", e.g., "\<Left>". The returned value is also a
String when a modifier (shift, control, alt) was used that is
not included in the character.
When {expr} is 1 only the first byte is returned. For a
one-byte character it is the character itself as a number.
Use nr2char() to convert it to a String.
When the user clicks a mouse button, the mouse event will be
returned. The position can then be found in |v:mouse_col|,
|v:mouse_lnum| and |v:mouse_win|. This example positions the
mouse as it would normally happen:
let c = getchar()
if c == "\<LeftMouse>" && v:mouse_win > 0
exe v:mouse_win . "wincmd w"
exe v:mouse_lnum
exe "normal " . v:mouse_col . "|"
endif
There is no prompt, you will somehow have to make clear to the
user that a character has to be typed.
There is no mapping for the character.
Key codes are replaced, thus when the user presses the <Del>
key you get the code for the <Del> key, not the raw character
sequence. Examples:
getchar() == "\<Del>"
getchar() == "\<S-Left>"
This example redefines "f" to ignore case:
:nmap f :call FindChar()<CR>
:function FindChar()
: let c = nr2char(getchar())
: while col('.') < col('$') - 1
: normal l
: if getline('.')[col('.') - 1] ==? c
: break
: endif
: endwhile
:endfunction
getcharmod() *getcharmod()*
The result is a Number which is the state of the modifiers for
the last obtained character with getchar() or in another way.
These values are added together:
2 shift
4 control
8 alt (meta)
getcmdline() *getcmdline()*
Return the current command-line. Only works when the command
line is being edited, thus requires use of |c_CTRL-\_e| or
|c_CTRL-R_=|.
Example:
:cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
Also see |getcmdtype()|, |getcmdpos()| and |setcmdpos()|.
getcmdpos() *getcmdpos()*
Return the position of the cursor in the command line as a
byte count. The first column is 1.
Only works when editing the command line, thus requires use of
|c_CTRL-\_e| or |c_CTRL-R_=|. Returns 0 otherwise.
Also see |getcmdtype()|, |setcmdpos()| and |getcmdline()|.
getcmdtype() *getcmdtype()*
Return the current command-line type. Possible return values
are:
: normal Ex command
> debug mode command |debug-mode|
/ forward search command
? backward search command
@ |input()| command
- |:insert| or |:append| command
Only works when editing the command line, thus requires use of
|c_CTRL-\_e| or |c_CTRL-R_=|. Returns an empty string
otherwise.
Also see |getcmdpos()|, |setcmdpos()| and |getcmdline()|.
*getcwd()*
getcwd() The result is a String, which is the name of the current
working directory.
getfsize({fname}) *getfsize()*
The result is a Number, which is the size in bytes of the
given file {fname}.
If {fname} is a directory, 0 is returned.
If the file {fname} can't be found, -1 is returned.
If the size of {fname} is too big to fit in a Number then -2
is returned.
getfontname([{name}]) *getfontname()*
Without an argument returns the name of the normal font being
used. Like what is used for the Normal highlight group
|hl-Normal|.
With an argument a check is done whether {name} is a valid
font name. If not then an empty string is returned.
Otherwise the actual font name is returned, or {name} if the
GUI does not support obtaining the real name.
Only works when the GUI is running, thus not in your vimrc or
gvimrc file. Use the |GUIEnter| autocommand to use this
function just after the GUI has started.
Note that the GTK 2 GUI accepts any font name, thus checking
for a valid name does not work.
getfperm({fname}) *getfperm()*
The result is a String, which is the read, write, and execute
permissions of the given file {fname}.
If {fname} does not exist or its directory cannot be read, an
empty string is returned.
The result is of the form "rwxrwxrwx", where each group of
"rwx" flags represent, in turn, the permissions of the owner
of the file, the group the file belongs to, and other users.
If a user does not have a given permission the flag for this
is replaced with the string "-". Example:
:echo getfperm("/etc/passwd")
This will hopefully (from a security point of view) display
the string "rw-r--r--" or even "rw-------".
getftime({fname}) *getftime()*
The result is a Number, which is the last modification time of
the given file {fname}. The value is measured as seconds
since 1st Jan 1970, and may be passed to strftime(). See also
|localtime()| and |strftime()|.
If the file {fname} can't be found -1 is returned.
getftype({fname}) *getftype()*
The result is a String, which is a description of the kind of
file of the given file {fname}.
If {fname} does not exist an empty string is returned.
Here is a table over different kinds of files and their
results:
Normal file "file"
Directory "dir"
Symbolic link "link"
Block device "bdev"
Character device "cdev"
Socket "socket"
FIFO "fifo"
All other "other"
Example:
getftype("/home")
Note that a type such as "link" will only be returned on
systems that support it. On some systems only "dir" and
"file" are returned.
*getline()*
getline({lnum} [, {end}])
Without {end} the result is a String, which is line {lnum}
from the current buffer. Example:
getline(1)
When {lnum} is a String that doesn't start with a
digit, line() is called to translate the String into a Number.
To get the line under the cursor:
getline(".")
When {lnum} is smaller than 1 or bigger than the number of
lines in the buffer, an empty string is returned.
When {end} is given the result is a |List| where each item is
a line from the current buffer in the range {lnum} to {end},
including line {end}.
{end} is used in the same way as {lnum}.
Non-existing lines are silently omitted.
When {end} is before {lnum} an empty |List| is returned.
Example:
:let start = line('.')
:let end = search("^$") - 1
:let lines = getline(start, end)
To get lines from another buffer see |getbufline()|
getloclist({nr}) *getloclist()*
Returns a list with all the entries in the location list for
window {nr}. When {nr} is zero the current window is used.
For a location list window, the displayed location list is
returned. For an invalid window number {nr}, an empty list is
returned. Otherwise, same as |getqflist()|.
getmatches() *getmatches()*
Returns a |List| with all matches previously defined by
|matchadd()| and the |:match| commands. |getmatches()| is
useful in combination with |setmatches()|, as |setmatches()|
can restore a list of matches saved by |getmatches()|.
Example:
:echo getmatches()
[{'group': 'MyGroup1', 'pattern': 'TODO',
'priority': 10, 'id': 1}, {'group': 'MyGroup2',
'pattern': 'FIXME', 'priority': 10, 'id': 2}]
:let m = getmatches()
:call clearmatches()
:echo getmatches()
[]
:call setmatches(m)
:echo getmatches()
[{'group': 'MyGroup1', 'pattern': 'TODO',
'priority': 10, 'id': 1}, {'group': 'MyGroup2',
'pattern': 'FIXME', 'priority': 10, 'id': 2}]
:unlet m
getqflist() *getqflist()*
Returns a list with all the current quickfix errors. Each
list item is a dictionary with these entries:
bufnr number of buffer that has the file name, use
bufname() to get the name
lnum line number in the buffer (first line is 1)
col column number (first column is 1)
vcol non-zero: "col" is visual column
zero: "col" is byte index
nr error number
pattern search pattern used to locate the error
text description of the error
type type of the error, 'E', '1', etc.
valid non-zero: recognized error message
When there is no error list or it's empty an empty list is
returned. Quickfix list entries with non-existing buffer
number are returned with "bufnr" set to zero.
Useful application: Find pattern matches in multiple files and
do something with them:
:vimgrep /theword/jg *.c
:for d in getqflist()
: echo bufname(d.bufnr) ':' d.lnum '=' d.text
:endfor
getregtype([{regname}]) *getregtype()*
The result is a String, which is type of register {regname}.
The value will be one of:
"v" for |characterwise| text
"V" for |linewise| text
"<CTRL-V>{width}" for |blockwise-visual| text
0 for an empty or unknown register
<CTRL-V> is one character with value 0x16.
If {regname} is not specified, |v:register| is used.
*getwinposx()*
getwinposx() The result is a Number, which is the X coordinate in pixels of
the left hand side of the GUI Vim window. The result will be
-1 if the information is not available.
*getwinposy()*
getwinposy() The result is a Number, which is the Y coordinate in pixels of
the top of the GUI Vim window. The result will be -1 if the
information is not available.
*has()*
has({feature}) The result is a Number, which is 1 if the feature {feature} is
supported, zero otherwise. The {feature} argument is a
string. See |feature-list| below.
Also see |exists()|.
haslocaldir() *haslocaldir()*
The result is a Number, which is 1 when the current
window has set a local path via |:lcd|, and 0 otherwise.
otherwise 0 is returned.
Examples:
Clear expression register history:
:call histdel("expr")
Remove all entries starting with "*" from the search history:
:call histdel("/", '^\*')
The following three are equivalent:
:call histdel("search", histnr("search"))
:call histdel("search", -1)
:call histdel("search", '^'.histget("search", -1).'$')
To delete the last search pattern and use the last-but-one for
the "n" command and 'hlsearch':
:call histdel("search", -1)
:let @/ = histget("search", -1)
histnr({history}) *histnr()*
The result is the Number of the current entry in {history}.
See |hist-names| for the possible values of {history}.
If an error occurred, -1 is returned.
Example:
:let inp_index = histnr("expr")
hlexists({name}) *hlexists()*
The result is a Number, which is non-zero if a highlight group
called {name} exists. This is when the group has been
defined in some way. Not necessarily when highlighting has
been defined for it, it may also have been used for a syntax
item.
*highlight_exists()*
Obsolete name: highlight_exists().
*hlID()*
hlID({name}) The result is a Number, which is the ID of the highlight group
with name {name}. When the highlight group doesn't exist,
zero is returned.
This can be used to retrieve information about the highlight
group. For example, to get the background color of the
"Comment" group:
:echo synIDattr(synIDtrans(hlID("Comment")), "bg")
*highlightID()*
Obsolete name: highlightID().
hostname() *hostname()*
The result is a String, which is the name of the machine on
which Vim is currently running. Machine names greater than
256 characters long are truncated.
*indent()*
indent({lnum}) The result is a Number, which is indent of line {lnum} in the
current buffer. The indent is counted in spaces, the value
of 'tabstop' is relevant. {lnum} is used just like in
|getline()|.
When {lnum} is invalid -1 is returned.
inputlist({textlist}) *inputlist()*
{textlist} must be a |List| of strings. This |List| is
displayed, one string per line. The user will be prompted to
enter a number, which is returned.
The user can also select an item by clicking on it with the
mouse. For the first string 0 is returned. When clicking
above the first item a negative number is returned. When
clicking on the prompt one more than the length of {textlist}
is returned.
Make sure {textlist} has less than 'lines' entries, otherwise
it won't work. It's a good idea to put the entry number at
the start of the string. And put a prompt in the first item.
Example:
let color = inputlist(['Select color:', '1. red',
\ '2. green', '3. blue'])
inputrestore() *inputrestore()*
Restore typeahead that was saved with a previous |inputsave()|.
Should be called the same number of times inputsave() is
called. Calling it more often is harmless though.
Returns 1 when there is nothing to restore, 0 otherwise.
inputsave() *inputsave()*
Preserve typeahead (also from mappings) and clear it, so that
a following prompt gets input from the user. Should be
followed by a matching inputrestore() after the prompt. Can
be used several times, in which case there must be just as
many inputrestore() calls.
Returns 1 when out of memory, 0 otherwise.
isdirectory({directory}) *isdirectory()*
The result is a Number, which is non-zero when a directory
with the name {directory} exists. If {directory} doesn't
exist, or isn't a directory, the result is FALSE. {directory}
is any expression, which is used as a String.
items({dict}) *items()*
Return a |List| with all the key-value pairs of {dict}. Each
|List| item is a list with two items: the key of a {dict}
entry and the value of this entry. The |List| is in arbitrary
order.
keys({dict}) *keys()*
Return a |List| with all the keys of {dict}. The |List| is in
arbitrary order.
*len()* *E701*
len({expr}) The result is a Number, which is the length of the argument.
When {expr} is a String or a Number the length in bytes is
used, as with |strlen()|.
When {expr} is a |List| the number of items in the |List| is
returned.
When {expr} is a |Dictionary| the number of entries in the
|Dictionary| is returned.
Otherwise an error is given.
*libcallnr()*
libcallnr({libname}, {funcname}, {argument})
Just like |libcall()|, but used for a function that returns an
int instead of a string.
{only in Win32 on some Unix versions, when the |+libcall|
feature is present}
Examples:
:echo libcallnr("/usr/lib/libc.so", "getpid", "")
:call libcallnr("libc.so", "printf", "Hello World!\n")
:call libcallnr("libc.so", "sleep", 10)
*line()*
line({expr}) The result is a Number, which is the line number of the file
position given with {expr}. The accepted positions are:
. the cursor position
$ the last line in the current buffer
'x position of mark x (if the mark is not set, 0 is
returned)
w0 first line visible in current window
w$ last line visible in current window
v In Visual mode: the start of the Visual area (the
cursor is the end). When not in Visual mode
returns the cursor position. Differs from |'<| in
that it's updated right away.
Note that a mark in another file can be used. The line number
then applies to another buffer.
To get the column number use |col()|. To get both use
|getpos()|.
Examples:
line(".") line number of the cursor
line("'t") line number of mark t
line("'" . marker) line number of mark marker
*last-position-jump*
This autocommand jumps to the last known position in a file
just after opening it, if the '"' mark is set:
:au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" |
endif
line2byte({lnum}) *line2byte()*
Return the byte count from the start of the buffer for line
{lnum}. This includes the end-of-line character, depending on
the 'fileformat' option for the current buffer. The first
line returns 1.
This can also be used to get the byte count for the line just
below the last line:
line2byte(line("$") + 1)
This is the file size plus one.
lispindent({lnum}) *lispindent()*
Get the amount of indent for line {lnum} according the lisp
indenting rules, as with 'lisp'.
The indent is counted in spaces, the value of 'tabstop' is
relevant. {lnum} is used just like in |getline()|.
When {lnum} is invalid or Vim was not compiled the
|+lispindent| feature, -1 is returned.
localtime() *localtime()*
Return the current time, measured as seconds since 1st Jan
1970. See also |strftime()| and |getftime()|.
log({expr}) *log()*
Return the natural logarithm (base e) of {expr} as a |Float|.
{expr} must evaluate to a |Float| or a |Number| in the range
(0, inf].
Examples:
:echo log(10)
2.302585
:echo log(exp(5))
5.0
{only available when compiled with the |+float| feature}
log10({expr}) *log10()*
Return the logarithm of Float {expr} to base 10 as a |Float|.
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo log10(1000)
3.0
:echo log10(0.01)
-2.0
{only available when compiled with the |+float| feature}
command.
{mode} can be one of these strings:
"n" Normal
"v" Visual (including Select)
"o" Operator-pending
"i" Insert
"c" Cmd-line
"s" Select
"x" Visual
"l" langmap |language-mapping|
"" Normal, Visual and Operator-pending
When {mode} is omitted, the modes for "" are used.
When {abbr} is there and it is non-zero use abbreviations
instead of mappings.
When {dict} is there and it is non-zero return a dictionary
containing all the information of the mapping with the
following items:
"lhs" The {lhs} of the mapping.
"rhs" The {rhs} of the mapping as typed.
"silent" 1 for a |:map-silent| mapping, else 0.
"noremap" 1 if the {rhs} of the mapping is not remappable.
"expr" 1 for an expression mapping (|:map-<expr>|).
"buffer" 1 for a buffer local mapping (|:map-local|).
"mode" Modes for which the mapping is defined. In
addition to the modes mentioned above, these
characters will be used:
" " Normal, Visual and Operator-pending
"!" Insert and Commandline mode
(|mapmode-ic|)
"sid" The script local ID, used for <sid> mappings
(|<SID>|).
The mappings local to the current buffer are checked first,
then the global mappings.
This function can be used to map a key even when it's already
mapped, and have it do the original mapping too. Sketch:
exe 'nnoremap <Tab> ==' . maparg('<Tab>', 'n')
matcharg({nr}) *matcharg()*
Selects the {nr} match item, as set with a |:match|,
|:2match| or |:3match| command.
Return a |List| with two elements:
The name of the highlight group used
The pattern used.
When {nr} is not 1, 2 or 3 returns an empty |List|.
When there is no match item set returns ['', ''].
This is useful to save and restore a |:match|.
Highlighting matches using the |:match| commands are limited
to three matches. |matchadd()| does not have this limitation.
*max()*
max({list}) Return the maximum value of all items in {list}.
If {list} is not a list or one of the items in {list} cannot
be used as a Number this results in an error.
An empty |List| results in zero.
*min()*
min({list}) Return the minimum value of all items in {list}.
If {list} is not a list or one of the items in {list} cannot
be used as a Number this results in an error.
An empty |List| results in zero.
*mkdir()* *E739*
mkdir({name} [, {path} [, {prot}]])
Create directory {name}.
If {path} is "p" then intermediate directories are created as
necessary. Otherwise it must be "".
If {prot} is given it is used to set the protection bits of
the new directory. The default is 0755 (rwxr-xr-x: r/w for
the user readable for others). Use 0700 to make it unreadable
for others. This is only used for the last part of {name}.
Thus if you create /tmp/foo/bar then /tmp/foo will be created
with 0755.
Example:
:call mkdir($HOME . "/tmp/foo/bar", "p", 0700)
This function is not available in the |sandbox|.
Not available on all systems. To check use:
:if exists("*mkdir")
*mode()*
mode([expr]) Return a string that indicates the current mode.
If [expr] is supplied and it evaluates to a non-zero Number or
a non-empty String (|non-zero-arg|), then the full mode is
returned, otherwise only the first letter is returned. Note
that " " and "0" are also non-empty strings.
n Normal
no Operator-pending
v Visual by character
V Visual by line
CTRL-V Visual blockwise
s Select by character
S Select by line
CTRL-S Select blockwise
i Insert
R Replace |R|
Rv Virtual Replace |gR|
c Command-line
cv Vim Ex mode |gQ|
ce Normal Ex mode |Q|
r Hit-enter prompt
rm The -- more -- prompt
r? A |:confirm| query of some sort
! Shell or external command is executing
This is useful in the 'statusline' option or when used
with |remote_expr()| In most other places it always returns
"c" or "n".
Also see |visualmode()|.
mzeval({expr}) *mzeval()*
Evaluate MzScheme expression {expr} and return its result
convert to Vim data structures.
Numbers and strings are returned as they are.
Pairs (including lists and improper lists) and vectors are
returned as Vim |Lists|.
Hash tables are represented as Vim |Dictionary| type with keys
converted to strings.
All other types are converted to string with display function.
Examples:
:mz (define l (list 1 2 3))
:mz (define h (make-hash)) (hash-set! h "list" l)
:echo mzeval("l")
:echo mzeval("h")
{only available when compiled with the |+mzscheme| feature}
nextnonblank({lnum}) *nextnonblank()*
Return the line number of the first line at or below {lnum}
that is not blank. Example:
if getline(nextnonblank(1)) =~ "Java"
When {lnum} is invalid or there is no non-blank line at or
below it, zero is returned.
See also |prevnonblank()|.
nr2char({expr}) *nr2char()*
Return a string with a single character, which has the number
value {expr}. Examples:
nr2char(64) returns "@"
nr2char(32) returns " "
The current 'encoding' is used. Example for "utf-8":
nr2char(300) returns I with bow character
Note that a NUL character in the file is specified with
nr2char(10), because NULs are represented with newline
characters. nr2char(0) is a real NUL and terminates the
string, thus results in an empty string.
*getpid()*
getpid() Return a Number which is the process ID of the Vim process.
On Unix and MS-Windows this is a unique number, until Vim
exits. On MS-DOS it's always zero.
*getpos()*
getpos({expr}) Get the position for {expr}. For possible values of {expr}
see |line()|.
The result is a |List| with four numbers:
[bufnum, lnum, col, off]
"bufnum" is zero, unless a mark like '0 or 'A is used, then it
is the buffer number of the mark.
"lnum" and "col" are the position in the buffer. The first
column is 1.
The "off" number is zero, unless 'virtualedit' is used. Then
it is the offset in screen columns from the start of the
character. E.g., a position within a <Tab> or after the last
character.
This can be used to save and restore the cursor position:
let save_cursor = getpos(".")
MoveTheCursorAround
call setpos('.', save_cursor)
Also see |setpos()|.
pathshorten({expr}) *pathshorten()*
Shorten directory names in the path {expr} and return the
result. The tail, the file name, is kept as-is. The other
components in the path are reduced to single letters. Leading
'~' and '.' characters are kept. Example:
:echo pathshorten('~/.vim/autoload/myfile.vim')
~/.v/a/myfile.vim
It doesn't matter if the path exists or not.
prevnonblank({lnum}) *prevnonblank()*
Return the line number of the first line at or above {lnum}
that is not blank. Example:
let ind = indent(prevnonblank(v:lnum - 1))
When {lnum} is invalid or there is no non-blank line at or
above it, zero is returned.
Also see |nextnonblank()|.
*printf-c*
c The Number argument is converted to a byte, and the
resulting character is written.
*printf-s*
s The text of the String argument is used. If a
precision is specified, no more bytes than the number
specified are used.
*printf-f* *E807*
f The Float argument is converted into a string of the
form 123.456. The precision specifies the number of
digits after the decimal point. When the precision is
zero the decimal point is omitted. When the precision
is not specified 6 is used. A really big number
(out of range or dividing by zero) results in "inf".
"0.0 / 0.0" results in "nan".
Example:
echo printf("%.2f", 12.115)
12.12
Note that roundoff depends on the system libraries.
Use |round()| when in doubt.
*printf-e* *printf-E*
e E The Float argument is converted into a string of the
form 1.234e+03 or 1.234E+03 when using 'E'. The
precision specifies the number of digits after the
decimal point, like with 'f'.
*printf-g* *printf-G*
g G The Float argument is converted like with 'f' if the
value is between 0.001 (inclusive) and 10000000.0
(exclusive). Otherwise 'e' is used for 'g' and 'E'
for 'G'. When no precision is specified superfluous
zeroes and '+' signs are removed, except for the zero
immediately after the decimal point. Thus 10000000.0
results in 1.0e7.
*printf-%*
% A '%' is written. No argument is converted. The
complete conversion specification is "%%".
When a Number argument is expected a String argument is also
accepted and automatically converted.
When a Float or String argument is expected a Number argument
is also accepted and automatically converted.
Any other argument type results in an error message.
*E766* *E767*
The number of {exprN} arguments must exactly match the number
of "%" items. If there are not sufficient or too many
arguments an error is given. Up to 18 arguments can be used.
pumvisible() *pumvisible()*
Returns non-zero when the popup menu is visible, zero
otherwise. See |ins-completion-menu|.
This can be used to avoid some things that would remove the
popup menu.
*E726* *E727*
range({expr} [, {max} [, {stride}]]) *range()*
Returns a |List| with Numbers:
- If only {expr} is specified: [0, 1, ..., {expr} - 1]
- If {max} is specified: [{expr}, {expr} + 1, ..., {max}]
- If {stride} is specified: [{expr}, {expr} + {stride}, ...,
{max}] (increasing {expr} with {stride} each time, not
producing a value past {max}).
When the maximum is one before the start the result is an
empty list. When the maximum is more than one before the
start this is an error.
Examples:
range(4) " [0, 1, 2, 3]
range(2, 4) " [2, 3, 4]
range(2, 9, 3) " [2, 5, 8]
range(2, -2, -1) " [2, 1, 0, -1, -2]
range(0) " []
range(2, 0) " error!
*readfile()*
readfile({fname} [, {binary} [, {max}]])
Read file {fname} and return a |List|, each line of the file
as an item. Lines broken at NL characters. Macintosh files
separated with CR will result in a single long line (unless a
NL appears somewhere).
All NUL characters are replaced with a NL character.
When {binary} is equal to "b" binary mode is used:
- When the last line ends in a NL an extra empty list item is
added.
- No CR characters are removed.
Otherwise:
- CR characters that appear before a NL are removed.
- Whether the last line ends in a NL or not does not matter.
- When 'encoding' is Unicode any UTF-8 byte order mark is
removed from the text.
When {max} is given this specifies the maximum number of lines
to be read. Useful if you only want to check the first ten
lines of a file:
:for line in readfile(fname, '', 10)
: if line =~ 'Date' | echo line | endif
:endfor
When {max} is negative -{max} lines from the end of the file
are returned, or as many as there are.
When {max} is zero the result is an empty list.
Note that without {max} the whole file is read into memory.
Also note that there is no recognition of encoding. Read a
file into a buffer if you need to.
When the file can't be opened an error message is given and
the result is an empty list.
reltimestr({time}) *reltimestr()*
Return a String that represents the time value of {time}.
This is the number of seconds, a dot and the number of
microseconds. Example:
let start = reltime()
call MyFunction()
echo reltimestr(reltime(start))
Note that overhead for the commands will be added to the time.
The accuracy depends on the system.
Leading spaces are used to make the string align nicely. You
can use split() to remove it.
echo split(reltimestr(reltime(start)))[0]
Also see |profiling|.
{only available when compiled with the |+reltime| feature}
*remote_expr()* *E449*
remote_expr({server}, {string} [, {idvar}])
Send the {string} to {server}. The string is sent as an
expression and the result is returned after evaluation.
The result must be a String or a |List|. A |List| is turned
into a String by joining the items with a line break in
between (not at the end), like with join(expr, "\n").
If {idvar} is present, it is taken as the name of a
variable and a {serverid} for later use with
remote_read() is stored there.
See also |clientserver| |RemoteReply|.
This function is not available in the |sandbox|.
{only available when compiled with the |+clientserver| feature}
Note: Any errors will cause a local error message to be issued
and the result will be the empty string.
Examples:
:echo remote_expr("gvim", "2+2")
:echo remote_expr("gvim1", "b:current_syntax")
remote_foreground({server}) *remote_foreground()*
Move the Vim server with the name {server} to the foreground.
This works like:
remote_expr({server}, "foreground()")
Except that on Win32 systems the client does the work, to work
around the problem that the OS doesn't always allow the server
to bring itself to the foreground.
Note: This does not restore the window if it was minimized,
like foreground() does.
This function is not available in the |sandbox|.
{only in the Win32, Athena, Motif and GTK GUI versions and the
Win32 console version}
remote_read({serverid}) *remote_read()*
Return the oldest available reply from {serverid} and consume
it. It blocks until a reply is available.
See also |clientserver|.
This function is not available in the |sandbox|.
{only available when compiled with the |+clientserver| feature}
Example:
:echo remote_read(id)
*remote_send()* *E241*
remote_send({server}, {string} [, {idvar}])
Send the {string} to {server}. The string is sent as input
keys and the function returns immediately. At the Vim server
the keys are not mapped |:map|.
If {idvar} is present, it is taken as the name of a variable
and a {serverid} for later use with remote_read() is stored
there.
See also |clientserver| |RemoteReply|.
This function is not available in the |sandbox|.
{only available when compiled with the |+clientserver| feature}
Note: Any errors will be reported in the server and may mess
up the display.
Examples:
:echo remote_send("gvim", ":DropAndReply ".file, "serverid").
\ remote_read(serverid)
:autocmd NONE RemoteReply *
\ echo remote_read(expand("<amatch>"))
:echo remote_send("gvim", ":sleep 10 | echo ".
\ 'server2client(expand("<client>"), "HELLO")<CR>')
*reverse()*
reverse({list}) Reverse the order of items in {list} in-place. Returns
{list}.
If you want a list to remain unmodified make a copy first:
:let revlist = reverse(copy(mylist))
round({expr}) *round()*
Round off {expr} to the nearest integral value and return it
as a |Float|. If {expr} lies halfway between two integral
values, then use the larger one (away from zero).
{expr} must evaluate to a |Float| or a |Number|.
Examples:
echo round(0.456)
0.0
echo round(4.5)
5.0
echo round(-4.5)
-5.0
{only available when compiled with the |+float| feature}
*searchpair()*
searchpair({start}, {middle}, {end} [, {flags} [, {skip}
[, {stopline} [, {timeout}]]]])
Search for the match of a nested start-end pair. This can be
used to find the "endif" that matches an "if", while other
if/endif pairs in between are ignored.
The search starts at the cursor. The default is to search
forward, include 'b' in {flags} to search backward.
If a match is found, the cursor is positioned at it and the
line number is returned. If no match is found 0 or -1 is
returned and the cursor doesn't move. No error message is
given.
{start}, {middle} and {end} are patterns, see |pattern|. They
must not contain \( \) pairs. Use of \%( \) is allowed. When
{middle} is not empty, it is found when searching from either
direction, but only when not in a nested start-end pair. A
typical use is:
searchpair('\<if\>', '\<else\>', '\<endif\>')
By leaving {middle} empty the "else" is skipped.
{flags} 'b', 'c', 'n', 's', 'w' and 'W' are used like with
|search()|. Additionally:
'r' Repeat until no more matches found; will find the
*searchpairpos()*
searchpairpos({start}, {middle}, {end} [, {flags} [, {skip}
[, {stopline} [, {timeout}]]]])
Same as |searchpair()|, but returns a |List| with the line and
column position of the match. The first element of the |List|
is the line number and the second element is the byte index of
the column position of the match. If no match is found,
returns [0, 0].
:let [lnum,col] = searchpairpos('{', '', '}', 'n')
See |match-parens| for a bigger and more useful example.
serverlist() *serverlist()*
Return a list of available server names, one per line.
When there are no servers or the information is not available
an empty string is returned. See also |clientserver|.
{only available when compiled with the |+clientserver| feature}
Example:
:echo serverlist()
setcmdpos({pos}) *setcmdpos()*
Set the cursor position in the command line to byte position
{pos}. The first position is 1.
Use |getcmdpos()| to obtain the current position.
Only works while editing the command line, thus you must use
|c_CTRL-\_e|, |c_CTRL-R_=| or |c_CTRL-R_CTRL-R| with '='. For
|c_CTRL-\_e| and |c_CTRL-R_CTRL-R| with '=' the position is
set after the command line is set to the expression. For
|c_CTRL-R_=| it is set after evaluating the expression but
before inserting the resulting text.
When the number is too big the cursor is put at the end of the
line. A number smaller than one has undefined results.
Returns 0 when successful, 1 when not editing the command
line.
setmatches({list}) *setmatches()*
Restores a list of matches saved by |getmatches()|. Returns 0
if successful, otherwise -1. All current matches are cleared
before the list is restored. See example for |getmatches()|.
*setpos()*
setpos({expr}, {list})
Set the position for {expr}. Possible values:
. the cursor
'x mark x
{list} must be a |List| with four numbers:
[bufnum, lnum, col, off]
"bufnum" is the buffer number. Zero can be used for the
current buffer. Setting the cursor is only possible for
the current buffer. To set a mark in another buffer you can
use the |bufnr()| function to turn a file name into a buffer
number.
Does not change the jumplist.
"lnum" and "col" are the position in the buffer. The first
column is 1. Use a zero "lnum" to delete a mark. If "col" is
smaller than 1 then 1 is used.
The "off" number is only used when 'virtualedit' is set. Then
it is the offset in screen columns from the start of the
character. E.g., a position within a <Tab> or after the last
character.
Returns 0 when the position could be set, -1 otherwise.
An error message is given if {expr} is invalid.
Also see |getpos()|
This does not restore the preferred column for moving
vertically. See |winrestview()| for that.
cleared.
Note that the list is not exactly the same as what
|getqflist()| returns.
If {action} is set to 'a', then the items from {list} are
added to the existing quickfix list. If there is no existing
list, then a new list is created. If {action} is set to 'r',
then the items from the current quickfix list are replaced
with the items from {list}. If {action} is not present or is
set to '' '', then a new list is created.
Returns zero for success, -1 for failure.
This function can be used to create a quickfix list
independent of the 'errorformat' setting. Use a command like
":cc 1" to jump to the first position.
*setreg()*
setreg({regname}, {value} [,{options}])
Set the register {regname} to {value}.
If {options} contains "a" or {regname} is upper case,
then the value is appended.
{options} can also contain a register type specification:
"c" or "v" |characterwise| mode
"l" or "V" |linewise| mode
"b" or "<CTRL-V>" |blockwise-visual| mode
If a number immediately follows "b" or "<CTRL-V>" then this is
used as the width of the selection - if it is not specified
then the width of the block is set to the number of characters
in the longest line (counting a <Tab> as 1 character).
If {options} contains no register settings, then the default
is to use character mode unless {value} ends in a <NL>.
Setting the '=' register is not possible.
Returns zero for success, non-zero for failure.
Examples:
:call setreg(v:register, @*)
:call setreg('*', @%, 'ac')
:call setreg('a', "1\n2\n3", 'b5')
This example shows using the functions to save and restore a
register.
:let var_a = getreg('a', 1)
:let var_amode = getregtype('a')
....
:call setreg('a', var_a, var_amode)
You can also change the type of a register by appending
nothing:
:call setreg('a', '', 'al')
simplify({filename}) *simplify()*
Simplify the file name as much as possible without changing
the meaning. Shortcuts (on MS-Windows) or symbolic links (on
Unix) are not resolved. If the first path component in
{filename} designates the current directory, this will be
valid for the result as well. A trailing path separator is
not removed either.
Example:
simplify("./dir/.././/file/") == "./file/"
Note: The combination "dir/.." is only removed if "dir" is
a searchable directory or does not exist. On Unix, it is also
removed when "dir" is a symbolic link within the same
directory. In order to resolve all the involved symbolic
links before simplifying the path name, use |resolve()|.
sin({expr}) *sin()*
Return the sine of {expr}, measured in radians, as a |Float|.
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo sin(100)
-0.506366
:echo sin(-4.01)
0.763301
{only available when compiled with the |+float| feature}
sinh({expr}) *sinh()*
Return the hyperbolic sine of {expr} as a |Float| in the range
[-inf, inf].
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo sinh(0.5)
0.521095
:echo sinh(-0.9)
-1.026517
{only available when compiled with the |+float| feature}
*soundfold()*
soundfold({word})
Return the sound-folded equivalent of {word}. Uses the first
language in 'spelllang' for the current window that supports
soundfolding. 'spell' must be set. When no sound folding is
possible the {word} is returned unmodified.
This can be used for making spelling suggestions. Note that
the method can be quite slow.
*spellbadword()*
spellbadword([{sentence}])
Without argument: The result is the badly spelled word under
or after the cursor. The cursor is moved to the start of the
bad word. When no bad word is found in the cursor line the
result is an empty string and the cursor doesn't move.
With argument: The result is the first word in {sentence} that
is badly spelled. If there are no spelling mistakes the
result is an empty string.
The return value is a list with two items:
- The badly spelled word or an empty string.
- The type of the spelling error:
"bad" spelling mistake
"rare" rare word
"local" word only valid in another region
"caps" word should start with Capital
Example:
echo spellbadword("the quik brown fox")
['quik', 'bad']
The spelling information for the current window is used. The
'spell' option must be set and the value of 'spelllang' is
used.
*spellsuggest()*
spellsuggest({word} [, {max} [, {capital}]])
Return a |List| with spelling suggestions to replace {word}.
When {max} is given up to this number of suggestions are
returned. Otherwise up to 25 suggestions are returned.
When the {capital} argument is given and it's non-zero only
suggestions with a leading capital will be given. Use this
after a match with 'spellcapcheck'.
{word} can be a badly spelled word followed by other text.
This allows for joining two words that were split. The
suggestions also include the following text, thus you can
replace a line.
{word} may also be a good word. Similar words will then be
sqrt({expr}) *sqrt()*
Return the non-negative square root of Float {expr} as a
|Float|.
{expr} must evaluate to a |Float| or a |Number|. When {expr}
is negative the result is NaN (Not a Number).
Examples:
:echo sqrt(100)
10.0
:echo sqrt(-4.01)
nan
"nan" may be different, it depends on system libraries.
{only available when compiled with the |+float| feature}
strchars({expr}) *strchars()*
The result is a Number, which is the number of characters
String {expr} occupies. Composing characters are counted
separately.
*string()*
string({expr}) Return {expr} converted to a String. If {expr} is a Number,
Float, String or a composition of them, then the result can be
parsed back with |eval()|.
{expr} type result
String 'string'
Number 123
Float 123.123456 or 1.123456e8
Funcref function('name')
List [item, item]
Dictionary {key: value, key: value}
Note that in String values the '' character is doubled.
Also see |strtrans()|.
*strlen()*
strlen({expr}) The result is a Number, which is the length of the String
{expr} in bytes.
If you want to count the number of multi-byte characters (not
counting composing characters) use something like this:
strtrans({expr}) *strtrans()*
The result is a String, which is {expr} with all unprintable
characters translated into printable characters |'isprint'|.
Like they are shown in a window. Example:
echo strtrans(@a)
This displays a newline in register a as "^@" instead of
starting a new line.
strwidth({expr}) *strwidth()*
The result is a Number, which is the number of display cells
String {expr} occupies. A Tab character is counted as one
cell, alternatively use |strdisplaywidth()|.
When {expr} contains characters with East Asian Width Class
Ambiguous, this function's return value depends on 'ambiwidth'.
Also see |strlen()|, |strdisplaywidth()| and |strchars()|.
submatch({nr}) *submatch()*
Only for an expression in a |:substitute| command. Returns
the {nr}'th submatch of the matched text. When {nr} is 0
the whole matched text is returned.
Example:
:s/\d\+/\=submatch(0) + 1/
This finds the first number in the line and adds one to it.
A line break is included as a newline character.
synIDtrans({synID}) *synIDtrans()*
The result is a Number, which is the translated syntax ID of
{synID}. This is the syntax group ID of what is being used to
highlight the character. Highlight links given with
":highlight link" are followed.
tabpagebuflist([{arg}]) *tabpagebuflist()*
The result is a |List|, where each item is the number of the
buffer associated with each window in the current tab page.
{arg} specifies the number of tab page to be used. When
omitted the current tab page is used.
When {arg} is invalid the number zero is returned.
To get a list of all buffers in all tabs use this:
tablist = []
for i in range(tabpagenr('$'))
call extend(tablist, tabpagebuflist(i + 1))
endfor
Note that a buffer may appear in more than one window.
tabpagenr([{arg}]) *tabpagenr()*
The result is a Number, which is the number of the current
tab page. The first tab page has number 1.
When the optional argument is "$", the number of the last tab
page is returned (the tab page count).
The number can be used with the |:tab| command.
*tagfiles()*
tagfiles() Returns a |List| with the file names used to search for tags
for the current buffer. This is the 'tags' option expanded.
taglist({expr}) *taglist()*
Returns a list of tags matching the regular expression {expr}.
Each list item is a dictionary with at least the following
entries:
name Name of the tag.
filename Name of the file where the tag is
defined. It is either relative to the
current directory or a full path.
cmd Ex command used to locate the tag in
the file.
kind Type of the tag. The value for this
entry depends on the language specific
kind values. Only available when
using a tags file generated by
Exuberant ctags or hdrtag.
static A file specific tag. Refer to
|static-tag| for more information.
More entries may be present, depending on the content of the
tags file: access, implementation, inherits and signature.
Refer to the ctags documentation for information about these
fields. For C code the fields "struct", "class" and "enum"
may appear, they give the name of the entity the tag is
contained in.
The ex-command 'cmd' can be either an ex search pattern, a
line number or a line number followed by a byte number.
If there are no matching tags, then an empty list is returned.
To get an exact tag match, the anchors '^' and '$' should be
used in {expr}. Refer to |tag-regexp| for more information
about the tag search regular expression pattern.
Refer to |'tags'| for information about how the tags file is
located by Vim. Refer to |tags-file-format| for the format of
the tags file generated by the different ctags tools.
tan({expr}) *tan()*
Return the tangent of {expr}, measured in radians, as a |Float|
in the range [-inf, inf].
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo tan(10)
0.648361
:echo tan(-4.01)
-1.181502
{only available when compiled with the |+float| feature}
tanh({expr}) *tanh()*
Return the hyperbolic tangent of {expr} as a |Float| in the
range [-1, 1].
{expr} must evaluate to a |Float| or a |Number|.
Examples:
:echo tanh(0.5)
0.462117
:echo tanh(-1)
-0.761594
{only available when compiled with the |+float| feature}
tolower({expr}) *tolower()*
The result is a copy of the String given, with all uppercase
characters turned into lowercase (just like applying |gu| to
the string).
toupper({expr}) *toupper()*
The result is a copy of the String given, with all lowercase
characters turned into uppercase (just like applying |gU| to
the string).
trunc({expr}) *trunc()*
Return the largest integral value with magnitude less than or
equal to {expr} as a |Float| (truncate towards zero).
{expr} must evaluate to a |Float| or a |Number|.
Examples:
echo trunc(1.456)
1.0
echo trunc(-5.456)
-5.0
echo trunc(4.0)
4.0
{only available when compiled with the |+float| feature}
*type()*
type({expr}) The result is a Number, depending on the type of {expr}:
Number: 0
String: 1
Funcref: 2
List: 3
Dictionary: 4
Float: 5
To avoid the magic numbers it should be used this way:
:if type(myvar) == type(0)
:if type(myvar) == type("")
:if type(myvar) == type(function("tr"))
:if type(myvar) == type([])
:if type(myvar) == type({})
:if type(myvar) == type(0.0)
undofile({name}) *undofile()*
Return the name of the undo file that would be used for a file
with name {name} when writing. This uses the 'undodir'
option, finding directories that exist. It does not check if
the undo file exists.
{name} is always expanded to the full path, since that is what
is used internally.
Useful in combination with |:wundo| and |:rundo|.
When compiled without the +persistent_undo option this always
returns an empty string.
undotree() *undotree()*
Return the current state of the undo tree in a dictionary with
the following items:
"seq_last" The highest undo sequence number used.
"seq_cur" The sequence number of the current position in
the undo tree. This differs from "seq_last"
when some changes were undone.
"time_cur" Time last used for |:earlier| and related
commands. Use |strftime()| to convert to
something readable.
"save_last" Number of the last file write. Zero when no
write yet.
"save_cur" Number of the current position in the undo
tree.
"synced" Non-zero when the last undo block was synced.
This happens when waiting from input from the
user. See |undo-blocks|.
"entries" A list of dictionaries with information about
undo blocks.
The first item in the "entries" list is the oldest undo item.
Each List item is a Dictionary with these items:
"seq" Undo sequence number. Same as what appears in
|:undolist|.
"time" Timestamp when the change happened. Use
|strftime()| to convert to something readable.
"newhead" Only appears in the item that is the last one
that was added. This marks the last change
and where further changes will be added.
"curhead" Only appears in the item that is the last one
that was undone. This marks the current
position in the undo tree, the block that will
be used by a redo command. When nothing was
undone after the last change this item will
not appear anywhere.
"save" Only appears on the last block before a file
write. The number is the write count. The
first write has number 1, the last one the
"save_last" mentioned above.
"alt" Alternate entry. This is again a List of undo
blocks. Each item may again have an "alt"
item.
values({dict}) *values()*
Return a |List| with all the values of {dict}. The |List| is
in arbitrary order.
virtcol({expr}) *virtcol()*
The result is a Number, which is the screen column of the file
position given with {expr}. That is, the last screen position
occupied by the character at that position, when the screen
would be of unlimited width. When there is a <Tab> at the
position, the returned Number will be the column at the end of
the <Tab>. For example, for a <Tab> in column 1, with 'ts'
set to 8, it returns 8.
For the byte position use |col()|.
For the use of {expr} see |col()|.
When 'virtualedit' is used {expr} can be [lnum, col, off], where
"off" is the offset in screen columns from the start of the
character. E.g., a position within a <Tab> or after the last
character.
When Virtual editing is active in the current mode, a position
beyond the end of the line can be returned. |'virtualedit'|
The accepted positions are:
. the cursor position
$ the end of the cursor line (the result is the
number of displayed characters in the cursor line
plus one)
'x position of mark x (if the mark is not set, 0 is
returned)
Note that only marks in the current file can be used.
Examples:
virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5
virtcol("$") with text "foo^Lbar", returns 9
virtcol("'t") with text " there", with 't at 'h', returns 6
The first column is 1. 0 is returned for an error.
A more advanced example that echoes the maximum length of
all lines:
echo max(map(range(1, line('$')), "virtcol([v:val, '$'])"))
visualmode([expr]) *visualmode()*
The result is a String, which describes the last Visual mode
used in the current buffer. Initially it returns an empty
string, but once Visual mode has been used, it returns "v",
"V", or "<CTRL-V>" (a single CTRL-V character) for
character-wise, line-wise, or block-wise Visual mode
respectively.
Example:
:exe "normal " . visualmode()
This enters the same Visual mode as before. It is also useful
in scripts if you wish to act differently depending on the
Visual mode that was used.
If Visual mode is active, use |mode()| to get the Visual mode
(e.g., in a |:vmap|).
*non-zero-arg*
If [expr] is supplied and it evaluates to a non-zero Number or
a non-empty String, then the Visual mode will be cleared and
the old value is returned. Note that " " and "0" are also
non-empty strings, thus cause the mode to be cleared. A List,
Dictionary or Float is not a Number or String, thus does not
cause the mode to be cleared.
*winbufnr()*
winbufnr({nr}) The result is a Number, which is the number of the buffer
associated with window {nr}. When {nr} is zero, the number of
the buffer in the current window is returned. When window
{nr} doesn't exist, -1 is returned.
Example:
:echo "The file in the current window is " . bufname(winbufnr(0))
*wincol()*
wincol() The result is a Number, which is the virtual column of the
cursor in the window. This is counting screen cells from the
left side of the window. The leftmost column is one.
winheight({nr}) *winheight()*
The result is a Number, which is the height of window {nr}.
When {nr} is zero, the height of the current window is
returned. When window {nr} doesn't exist, -1 is returned.
An existing window always has a height of zero or more.
Examples:
:echo "The current window has " . winheight(0) . " lines."
*winline()*
winline() The result is a Number, which is the screen line of the cursor
in the window. This is counting screen lines from the top of
*winnr()*
winnr([{arg}]) The result is a Number, which is the number of the current
window. The top window has number 1.
When the optional argument is "$", the number of the
last window is returned (the window count).
When the optional argument is "#", the number of the last
accessed window is returned (where |CTRL-W_p| goes to).
If there is no previous window or it is in another tab page 0
is returned.
The number can be used with |CTRL-W_w| and ":wincmd w"
|:wincmd|.
Also see |tabpagewinnr()|.
*winrestcmd()*
winrestcmd() Returns a sequence of |:resize| commands that should restore
the current window sizes. Only works properly when no windows
are opened or closed and the current window and tab page is
unchanged.
Example:
:let cmd = winrestcmd()
:call MessWithWindowSizes()
:exe cmd
*winrestview()*
winrestview({dict})
Uses the |Dictionary| returned by |winsaveview()| to restore
the view of the current window.
If you have changed the values the result is unpredictable.
If the window size changed the result won't be the same.
*winsaveview()*
winsaveview() Returns a |Dictionary| that contains information to restore
the view of the current window. Use |winrestview()| to
restore the view.
This is useful if you have a mapping that jumps around in the
buffer and you want to go back to the original view.
This does not save fold information. Use the 'foldenable'
option to temporarily switch off folding, so that folds are
not opened when moving around.
The return value includes:
lnum cursor line number
col cursor column
coladd cursor column offset for 'virtualedit'
curswant column for vertical movement
topline first line in the window
topfill filler lines, only in diff mode
leftcol first column displayed
skipcol columns skipped
Note that no option values are saved.
winwidth({nr}) *winwidth()*
The result is a Number, which is the width of window {nr}.
When {nr} is zero, the width of the current window is
returned. When window {nr} doesn't exist, -1 is returned.
An existing window always has a width of zero or more.
Examples:
:echo "The current window has " . winwidth(0) . " columns."
:if winwidth(0) <= 50
: exe "normal 50\<C-W>|"
:endif
*writefile()*
writefile({list}, {fname} [, {binary}])
Write |List| {list} to file {fname}. Each list item is
separated with a NL. Each list item must be a String or
Number.
When {binary} is equal to "b" binary mode is used: There will
not be a NL after the last list item. An empty item at the
end does cause the last line in the file to end in a NL.
All NL characters are replaced with a NUL character.
Inserting CR characters needs to be done before passing {list}
to writefile().
An existing file is overwritten, if possible.
When the write fails -1 is returned, otherwise 0. There is an
error message if the file can't be created or when writing
fails.
Also see |readfile()|.
To copy a file byte for byte:
:let fl = readfile("foo", "b")
:call writefile(fl, "foocopy", "b")
*feature-list*
There are three types of features:
1. Features that are only supported when they have been enabled when Vim
was compiled |+feature-list|. Example:
:if has("cindent")
2. Features that are only supported when certain conditions have been met.
Example:
:if has("gui_running")
*has-patch*
3. Included patches. First check |v:version| for the version of Vim.
Then the "patch123" feature means that patch 123 has been included for
this version. Example (checking version 6.2.148 or later):
:if v:version > 602 || v:version == 602 && has("patch148")
Note that it's possible for patch 147 to be omitted even though 148 is
included.
all_builtin_terms Compiled with all builtin terminals enabled.
amiga Amiga version of Vim.
arabic Compiled with Arabic support |Arabic|.
arp Compiled with ARP support (Amiga).
autocmd Compiled with autocommand support. |autocommand|
balloon_eval Compiled with |balloon-eval| support.
balloon_multiline GUI supports multiline balloons.
beos BeOS version of Vim.
browse Compiled with |:browse| support, and browse() will
work.
builtin_terms Compiled with some builtin terminals.
byte_offset Compiled with support for 'o' in 'statusline'
cindent Compiled with 'cindent' support.
clientserver Compiled with remote invocation support |clientserver|.
clipboard Compiled with 'clipboard' support.
cmdline_compl Compiled with |cmdline-completion| support.
cmdline_hist Compiled with |cmdline-history| support.
cmdline_info Compiled with 'showcmd' and 'ruler' support.
comments Compiled with |'comments'| support.
compatible Compiled to be very Vi compatible.
cryptv Compiled with encryption support |encryption|.
cscope Compiled with |cscope| support.
debug Compiled with "DEBUG" defined.
dialog_con Compiled with console dialog support.
dialog_gui Compiled with GUI dialog support.
diff Compiled with |vimdiff| and 'diff' support.
digraphs Compiled with support for digraphs.
dnd Compiled with support for the "~ register |quote_~|.
dos16 16 bits DOS version of Vim.
dos32 32 bits DOS (DJGPP) version of Vim.
ebcdic Compiled on a machine with ebcdic character set.
emacs_tags Compiled with support for Emacs tags.
eval Compiled with expression evaluation support. Always
true, of course!
ex_extra Compiled with extra Ex commands |+ex_extra|.
extra_search Compiled with support for |'incsearch'| and
|'hlsearch'|
farsi Compiled with Farsi support |farsi|.
file_in_path Compiled with support for |gf| and |<cfile>|
filterpipe When 'shelltemp' is off pipes are used for shell
read/write/filter commands
find_in_path Compiled with support for include file searches
|+find_in_path|.
float Compiled with support for |Float|.
fname_case Case in file names matters (for Amiga, MS-DOS, and
Windows this is not present).
folding Compiled with |folding| support.
footer Compiled with GUI footer support. |gui-footer|
*string-match*
Matching a pattern in a String
A regexp pattern as explained at |pattern| is normally used to find a match in
the buffer lines. When a pattern is used to find a match in a String, almost
everything works in the same way. The difference is that a String is handled
like it is one line. When it contains a "\n" character, this is not seen as a
line break for the pattern. It can be matched with a "\n" in the pattern, or
with ".". Example:
:let a = "aaaa\nxxxx"
:echo matchstr(a, "..\n..")
aa
xx
:echo matchstr(a, "a.x")
a
x
Don't forget that "^" will only match at the first character of the String and
"$" at the last character of the string. They don't match after or before a
"\n".
==============================================================================
5. Defining functions *user-functions*
New functions can be defined. These can be called just like builtin
functions. The function executes a sequence of Ex commands. Normal mode
commands can be executed with the |:normal| command.
The function name must start with an uppercase letter, to avoid confusion with
builtin functions. To prevent from using the same name in different scripts
avoid obvious, short names. A good habit is to start the function name with
the name of the script, e.g., "HTMLcolor()".
It's also possible to use curly braces, see |curly-braces-names|. And the
|autoload| facility is useful to define a function only when it's called.
*local-function*
A function local to a script must start with "s:". A local script function
can only be called from within the script and from functions, user commands
and autocommands defined in the script. It is also possible to call the
function from a mapping defined in the script, but then |<SID>| must be used
instead of "s:" when the mapping is expanded outside of the script.
*:function-verbose*
When 'verbose' is non-zero, listing a function will also display where it was
last defined. Example:
:verbose function SetFileTypeSH
function SetFileTypeSH(name)
Last set from /usr/share/vim/vim-7.0/filetype.vim
See |:verbose-cmd| for more information.
*E124* *E125*
:fu[nction][!] {name}([arguments]) [range] [abort] [dict]
Define a new function by the name {name}. The name
must be made of alphanumeric characters and '_', and
must start with a capital or "s:" (see above).
{name} can also be a |Dictionary| entry that is a
YXXYFuncref|:
:function dict.init(arg)
"dict" must be an existing dictionary. The entry
"init" is added if it didn't exist yet. Otherwise [!]
is required to overwrite an existing function. The
result is a |Funcref| to a numbered function. The
function can only be used with a |Funcref| and will be
deleted if there are no more references to it.
*E127* *E122*
When a function by this name already exists and [!] is
not used an error message is given. When [!] is used,
an existing function is silently replaced. Unless it
is currently being executed, that is an error.
For the {arguments} see |function-argument|.
*a:firstline* *a:lastline*
When the [range] argument is added, the function is
expected to take care of a range itself. The range is
passed as "a:firstline" and "a:lastline". If [range]
is excluded, ":{range}call" will call the function for
each line in the range, with the cursor on the start
of each line. See |function-range-example|.
When the [abort] argument is added, the function will
abort as soon as an error is detected.
When the [dict] argument is added, the function must
be invoked through an entry in a |Dictionary|. The
local variable "self" will then be set to the
dictionary. See |Dictionary-function|.
*function-search-undo*
The last used search pattern and the redo command "."
will not be changed by the function. This also
implies that the effect of |:nohlsearch| is undone
when the function returns.
*function-argument* *a:var*
An argument can be defined by giving its name. In the function this can then
be used as "a:name" ("a:" for argument).
*a:0* *a:1* *a:000* *E740* *...*
Up to 20 arguments can be given, separated by commas. After the named
arguments an argument "..." can be specified, which means that more arguments
may optionally be following. In the function the extra arguments can be used
as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
can be 0). "a:000" is set to a |List| that contains these arguments. Note
that "a:1" is the same as "a:000[0]".
*E742*
The a: scope and the variables in it cannot be changed, they are fixed.
However, if a |List| or |Dictionary| is used, you can change their contents.
Thus you can pass a |List| to a function and have the function add an item to
it. If you want to make sure the function cannot change a |List| or
|Dictionary| use |:lockvar|.
When not using "...", the number of arguments in a function call must be equal
to the number of named arguments. When using "...", the number of arguments
may be larger.
It is also possible to define a function without any arguments. You must
still supply the () then. The body of the function follows in the next lines,
until the matching |:endfunction|. It is allowed to define another function
inside a function body.
*local-variables*
Inside a function variables can be used. These are local variables, which
will disappear when the function returns. Global variables need to be
accessed with "g:".
Example:
:function Table(title, ...)
: echohl Title
: echo a:title
: echohl None
: echo a:0 . " items:"
: for s in a:000
: echon ' ' . s
: endfor
:endfunction
This function can then be called with:
*E132*
The recursiveness of user functions is restricted with the |'maxfuncdepth'|
option.
Using an autocommand
This is introduced in the user manual, section |41.14|.
The autocommand is useful if you have a plugin that is a long Vim script file.
You can define the autocommand and quickly quit the script with |:finish|.
That makes Vim startup faster. The autocommand should then load the same file
again, setting a variable to skip the |:finish| command.
Use the FuncUndefined autocommand event with a pattern that matches the
function(s) to be defined. Example:
:au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
The file "~/vim/bufnetfuncs.vim" should then define functions that start with
"BufNet". Also see |FuncUndefined|.
*curly-braces-function-names*
You can call and define functions by an evaluated name in a similar way.
Example:
:let func_end='whizz'
:call my_func_{func_end}(parameter)
This would call the function "my_func_whizz(parameter)".
==============================================================================
7. Commands *expression-commands*
*E711* *E719*
:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710*
Set a sequence of items in a |List| to the result of
the expression {expr1}, which must be a list with the
correct number of items.
{idx1} can be omitted, zero is used instead.
{idx2} can be omitted, meaning the end of the list.
When the selected range of items is partly past the
end of the list, items will be added.
*E121*
:let {var-name} .. List the value of variable {var-name}. Multiple
variable names may be given. Special names recognized
here: *E738*
g: global variables
b: local buffer variables
w: local window variables
t: local tab page variables
s: script-local variables
l: local function variables
v: Vim variables.
:let List the values of all variables. The type of the
variable is indicated before the value:
<nothing> String
# Number
* Funcref
*:ec* *:echo*
:ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
first {expr1} starts on a new line.
Also see |:comment|.
Use "\n" to start a new line. Use "\r" to move the
cursor to the first column.
Uses the highlighting set by the |:echohl| command.
Cannot be followed by a comment.
Example:
:echo "the value of 'shell' is" &shell
*:echo-redraw*
A later redraw may make the message disappear again.
And since Vim mostly postpones redrawing until it's
finished with a sequence of commands this happens
quite often. To avoid that a command from before the
":echo" causes a redraw afterwards (redraws are often
postponed until you type something), force a redraw
with the |:redraw| command. Example:
:new | redraw | echo "there is a new window"
*:echon*
:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
|:comment|.
Uses the highlighting set by the |:echohl| command.
Cannot be followed by a comment.
Example:
:echon "the value of 'shell' is " &shell
Note the difference between using ":echo", which is a
Vim command, and ":!echo", which is an external shell
command:
:!echo % --> filename
The arguments of ":!" are expanded, see |:_%|.
:!echo "%" --> filename or "filename"
Like the previous example. Whether you see the double
quotes or not depends on your 'shell'.
:echo % --> nothing
The '%' is an illegal character in an expression.
:echo "%" --> %
This just echoes the '%' character.
:echo expand("%") --> filename
This calls the expand() function to expand the '%'.
*:echoh* *:echohl*
:echoh[l] {name} Use the highlight group {name} for the following
|:echo|, |:echon| and |:echomsg| commands. Also used
for the |input()| prompt. Example:
:echohl WarningMsg | echo "Don't panic!" | echohl None
Don't forget to set the group back to "None",
otherwise all following echo's will be highlighted.
*:echom* *:echomsg*
:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
message in the |message-history|.
Spaces are placed between the arguments as with the
|:echo| command. But unprintable characters are
displayed, not interpreted.
The parsing works slightly different from |:echo|,
more like |:execute|. All the expressions are first
evaluated and concatenated before echoing anything.
The expressions must evaluate to a Number or String, a
*:exe* *:execute*
:exe[cute] {expr1} .. Executes the string that results from the evaluation
of {expr1} as an Ex command.
Multiple arguments are concatenated, with a space in
between. To avoid the extra space use the "."
operator to concatenate strings into one argument.
{expr1} is used as the processed command, command line
editing keys are not recognized.
Cannot be followed by a comment.
Examples:
:execute "buffer" nextbuf
:execute "normal" count . "w"
":execute" can be used to append a command to commands
that don't accept a '|'. Example:
:execute '!ls' | echo "theend"
":execute" is also a nice way to avoid having to type
control characters in a Vim script for a ":normal"
command:
:execute "normal ixxx\<Esc>"
This has an <Esc> character, see |expr-string|.
Be careful to correctly escape special characters in
file names. The |fnameescape()| function can be used
for Vim commands, |shellescape()| for |:!| commands.
Examples:
:execute "e " . fnameescape(filename)
:execute "!ls " . shellescape(expand('%:h'), 1)
Note: The executed string may be any command-line, but
you cannot start or end a "while", "for" or "if"
command. Thus this is illegal:
:execute 'while i > 5'
:execute 'echo "test" | break'
It is allowed to have a "while" or "if" command
completely in the executed string:
:execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
*:exe-comment*
":execute", ":echo" and ":echon" cannot be followed by
a comment directly, because they see the '"'' as the
start of a string. But, you can use '|' followed by a
comment. Example:
:echo "foo" | "this is a comment
==============================================================================
8. Exception handling *exception-handling*
The Vim script language comprises an exception handling feature. This section
explains how it can be used in a Vim script.
Exceptions may be raised by Vim on an error or on interrupt, see
This throws "arrgh", and "in Bar" is not displayed since Bar() is not
executed.
:throw Foo("foo") + Bar()
however displays "in Bar" and throws 4711.
Any other command that takes an expression as argument might also be
abandoned by an (uncaught) exception during the expression evaluation. The
exception is then propagated to the caller of the command.
Example:
:if Foo("arrgh")
: echo "then"
:else
: echo "else"
:endif
Here neither of "then" or "else" is displayed.
*catch-order*
Exceptions can be caught by a try conditional with one or more |:catch|
commands, see |try-conditionals|. The values to be caught by each ":catch"
command can be specified as a pattern argument. The subsequent catch clause
gets executed when a matching exception is caught.
Example:
:function! Foo(value)
: try
: throw a:value
: catch /^\d\+$/
: echo "Number thrown"
: catch /.*/
: echo "String thrown"
: endtry
:endfunction
:
:call Foo(0x1267)
:call Foo('string')
The first call to Foo() displays "Number thrown", the second "String thrown".
An exception is matched against the ":catch" commands in the order they are
specified. Only the first match counts. So you should place the more
specific ":catch" first. The following order does not make sense:
: catch /.*/
: echo "String thrown"
: catch /^\d\+$/
: echo "Number thrown"
The first ":catch" here matches always, so that the second catch clause is
never taken.
*throw-variables*
If you catch an exception by a general pattern, you may access the exact value
in the variable YXXYv:exception|:
: catch /^\d\+$/
: echo "Number thrown. Value is" v:exception
You may also be interested where an exception was thrown. This is stored in
|v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
exception most recently caught as long it is not finished.
Example:
:function! Caught()
: if v:exception != ""
: echo 'Caught "' . v:exception . '" in ' . v:throwpoint
: else
: echo 'Nothing caught'
: endif
:endfunction
:
:function! Foo()
: try
: try
: try
: throw 4711
: finally
: call Caught()
: endtry
: catch /.*/
: call Caught()
: throw "oops"
: endtry
: catch /.*/
: call Caught()
: finally
: call Caught()
: endtry
:endfunction
:
:call Foo()
This displays
Nothing caught
Caught "4711" in function Foo, line 4
Caught "oops" in function Foo, line 10
Nothing caught
A practical example: The following command ":LineNumber" displays the line
number in the script or function where it has been used:
:function! LineNumber()
: return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
:endfunction
:command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
*try-nested*
An exception that is not caught by a try conditional can be caught by
a surrounding try conditional:
:try
: try
: throw "foo"
: catch /foobar/
: echo "foobar"
: finally
: echo "inner finally"
: endtry
:catch /foo/
: echo "foo"
:endtry
The inner try conditional does not catch the exception, just its finally
clause is executed. The exception is then caught by the outer try
conditional. The example displays "inner finally" and then "foo".
*throw-from-catch*
You can catch an exception and throw a new one to be caught elsewhere from the
catch clause:
:function! Foo()
: throw "foo"
:endfunction
:
:function! Bar()
: try
: call Foo()
: catch /foo/
: echo "Caught foo, throw bar"
: throw "bar"
: endtry
:endfunction
:
:try
: call Bar()
:catch /.*/
: echo "Caught" v:exception
:endtry
This displays "Caught foo, throw bar" and then "Caught bar".
*rethrow*
There is no real rethrow in the Vim script language, but you may throw
"v:exception" instead:
:function! Bar()
: try
: call Foo()
: catch /.*/
: echo "Rethrow" v:exception
: throw v:exception
: endtry
:endfunction
*try-echoerr*
Note that this method cannot be used to "rethrow" Vim error or interrupt
exceptions, because it is not possible to fake Vim internal exceptions.
Trying so causes an error exception. You should throw your own exception
denoting the situation. If you want to cause a Vim error exception containing
the original error exception value, you can use the |:echoerr| command:
:try
: try
: asdf
: catch /.*/
: echoerr v:exception
: endtry
:catch /.*/
: echo v:exception
:endtry
This code displays
Vim(echoerr):Vim:E492: Not an editor command: asdf
*break-finally*
Cleanup code works also when the try block or a catch clause is left by
a ":continue", ":break", ":return", or ":finish".
Example:
:let first = 1
:while 1
: try
: if first
: echo "first"
: let first = 0
: continue
: else
: throw "second"
: endif
: catch /.*/
: echo v:exception
: break
: finally
: echo "cleanup"
: endtry
: echo "still in while"
:endwhile
:echo "end"
This displays "first", "cleanup", "second", "cleanup", and "end".
:function! Foo()
: try
: return 4711
: finally
: echo "cleanup\n"
: endtry
: echo "Foo still active"
:endfunction
:
:echo Foo() "returned by Foo"
This displays "cleanup" and "4711 returned by Foo". You don't need to add an
extra ":return" in the finally clause. (Above all, this would override the
return value.)
*except-from-finally*
Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
a finally clause is possible, but not recommended since it abandons the
cleanup actions for the try conditional. But, of course, interrupt and error
exceptions might get raised from a finally clause.
Example where an error in the finally clause stops an interrupt from
working correctly:
:try
: try
: echo "Press CTRL-C for interrupt"
: while 1
: endwhile
: finally
: unlet novar
: endtry
:catch /novar/
:endtry
:echo "Script still running"
:sleep 1
If you need to put commands that could fail into a finally clause, you should
think about catching or ignoring the errors in these commands, see
|catch-errors| and |ignore-errors|.
{cmdname} is the name of the command that failed; the second form is used when
the command name is not known. {errmsg} is the error message usually produced
when the error occurs outside try conditionals. It always begins with
a capital "E", followed by a two or three-digit error number, a colon, and
a space.
Examples:
The command
:unlet novar
normally produces the error message
E108: No such variable: "novar"
which is converted inside try conditionals to an exception
Vim(unlet):E108: No such variable: "novar"
The command
:dwim
normally produces the error message
E492: Not an editor command: dwim
which is converted inside try conditionals to an exception
Vim:E492: Not an editor command: dwim
You can catch all ":unlet" errors by a
:catch /^Vim(unlet):/
or all errors for misspelled command names by a
:catch /^Vim:E492:/
Some error messages may be produced by different commands:
:function nofunc
and
:delfunction nofunc
both produce the error message
E128: Function name must start with a capital: nofunc
which is converted inside try conditionals to an exception
Vim(function):E128: Function name must start with a capital: nofunc
or
Vim(delfunction):E128: Function name must start with a capital: nofunc
respectively. You can catch the error by its number independently on the
command that caused it if you use the following pattern:
:catch /^Vim(\a\+):E128:/
Some commands like
:let x = novar
produce multiple error messages, here:
E121: Undefined variable: novar
E15: Invalid expression: novar
Only the first is used for the exception value, since it is the most specific
one (see |except-several-errors|). So you can catch it by
:catch /^Vim(\a\+):E121:/
You can catch all errors related to the name "nofunc" by
:catch /\<nofunc\>/
You can catch all Vim errors in the ":write" and ":read" commands by
:catch /^Vim(\(write\|read\)):E\d\+:/
You can catch all Vim errors by the pattern
:catch /^Vim\((\a\+)\)\=:E\d\+:/
*catch-text*
NOTE: You should never catch the error message text itself:
:catch /No such variable/
only works in the english locale, but not when the user has selected
a different language by the |:language| command. It is however helpful to
cite the message text in a comment:
:catch /^Vim(\a\+):E108:/ " No such variable
But you are strongly recommended NOT to use this simple form, since it could
catch more than you want. With the ":write" command, some autocommands could
be executed and cause errors not related to writing, for instance:
:au BufWritePre * unlet novar
There could even be such errors you are not responsible for as a script
writer: a user of your script might have defined such autocommands. You would
then hide the error from the user.
It is much better to use
:try
: write
:catch /^Vim(write):/
:endtry
which only catches real write errors. So catch only what you'd like to ignore
intentionally.
For a single command that does not cause execution of autocommands, you could
even suppress the conversion of errors to exceptions by the ":silent!"
command:
:silent! nunmap k
This works also when a try conditional is active.
:catch //
:catch
catch everything, error exceptions, interrupt exceptions and exceptions
explicitly thrown by the |:throw| command. This is useful at the top level of
a script in order to catch unexpected things.
Example:
:try
:
: " do the hard work here
:
:catch /MyException/
:
: " handle known problem
:
:catch /^Vim:Interrupt$/
: echo "Script interrupted"
:catch /.*/
: echo "Internal error (" . v:exception . ")"
: echo " - occurred at " . v:throwpoint
:endtry
:" end of script
Note: Catching all might catch more things than you want. Thus, you are
strongly encouraged to catch only for problems that you can really handle by
specifying a pattern argument to the ":catch".
Example: Catching all could make it nearly impossible to interrupt a script
by pressing CTRL-C:
:while 1
: try
: sleep 1
: catch
: endtry
:endwhile
*except-autocmd-Pre*
For some commands, autocommands get executed before the main action of the
command takes place. If an exception is thrown and not caught in the sequence
of autocommands, the sequence and the command that caused its execution are
abandoned and the exception is propagated to the caller of the command.
Example:
:autocmd BufWritePre * throw "FAIL"
:autocmd BufWritePre * echo "Should not be displayed"
:
:try
: write
:catch
: echo "Caught:" v:exception "from" v:throwpoint
:endtry
Here, the ":write" command does not write the file currently being edited (as
you can see by checking 'modified'), since the exception from the BufWritePre
autocommand abandons the ":write". The exception is then caught and the
script displays:
Caught: FAIL from BufWrite Auto commands for "*"
*except-autocmd-Post*
For some commands, autocommands get executed after the main action of the
command has taken place. If this main action fails and the command is inside
an active try conditional, the autocommands are skipped and an error exception
is thrown that can be caught by the caller of the command.
Example:
:autocmd BufWritePost * echo "File successfully written!"
:
:try
: write /i/m/p/o/s/s/i/b/l/e
:catch
: echo v:exception
:endtry
This just displays:
Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
If you really need to execute the autocommands even when the main action
fails, trigger the event from the catch clause.
Example:
:autocmd BufWritePre * set noreadonly
:autocmd BufWritePost * set readonly
:
:try
: write /i/m/p/o/s/s/i/b/l/e
:catch
: doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
:endtry
You can also use ":silent!":
:let x = "ok"
:let v:errmsg = ""
:autocmd BufWritePost * if v:errmsg != ""
:autocmd BufWritePost * let x = "after fail"
:autocmd BufWritePost * endif
:try
: silent! write /i/m/p/o/s/s/i/b/l/e
:catch
:endtry
:echo x
This displays "after fail".
If the main action of the command does not fail, exceptions from the
autocommands will be catchable by the caller of the command:
:autocmd BufWritePost * throw ":-("
:autocmd BufWritePost * echo "Should not be displayed"
:
:try
: write
:catch
: echo v:exception
:endtry
*except-autocmd-Cmd*
For some commands, the normal action can be replaced by a sequence of
autocommands. Exceptions from that sequence will be catchable by the caller
of the command.
Example: For the ":write" command, the caller cannot know whether the file
had actually been written when the exception occurred. You need to tell it in
some way.
:if !exists("cnt")
: let cnt = 0
:
: autocmd BufWriteCmd * if &modified
: autocmd BufWriteCmd * let cnt = cnt + 1
: autocmd BufWriteCmd * if cnt % 3 == 2
: autocmd BufWriteCmd * throw "BufWriteCmdError"
: autocmd BufWriteCmd * endif
: autocmd BufWriteCmd * write | set nomodified
: autocmd BufWriteCmd * if cnt % 3 == 0
: autocmd BufWriteCmd * throw "BufWriteCmdError"
: autocmd BufWriteCmd * endif
: autocmd BufWriteCmd * echo "File successfully written!"
: autocmd BufWriteCmd * endif
:endif
:
:try
: write
:catch /^BufWriteCmdError$/
: if &modified
: echo "Error on writing (file contents not changed)"
: else
: echo "Error after writing"
: endif
:catch /^Vim(write):/
: echo "Error on writing"
:endtry
When this script is sourced several times after making changes, it displays
first
File successfully written!
then
Error on writing (file contents not changed)
then
Error after writing
etc.
*except-autocmd-ill*
You cannot spread a try conditional over autocommands for different events.
The following code is ill-formed:
:autocmd BufWritePre * try
:
:autocmd BufWritePost * catch
:autocmd BufWritePost * echo v:exception
:autocmd BufWritePost * endtry
:
:write
: throw "EXCEPT:MATHERR:OVERFLOW"
: endif
: return c
:endfunction
:
:function! Div(a, b)
: call CheckRange(a:a, "Div")
: call CheckRange(a:b, "Div")
: if (a:b == 0)
: throw "EXCEPT:MATHERR:ZERODIV"
: endif
: return a:a / a:b
:endfunction
:
:function! Write(file)
: try
: execute "write" fnameescape(a:file)
: catch /^Vim(write):/
: throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
: endtry
:endfunction
:
:try
:
: " something with arithmetics and I/O
:
:catch /^EXCEPT:MATHERR:RANGE/
: let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
: echo "Range error in" function
:
:catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
: echo "Math error"
:
:catch /^EXCEPT:IO/
: let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
: let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
: if file !~ '^/'
: let file = dir . "/" . file
: endif
: echo 'I/O error for "' . file . '"'
:
:catch /^EXCEPT/
: echo "Unspecified error"
:
:endtry
The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
exceptions with the "Vim" prefix; they are reserved for Vim.
Vim error exceptions are parameterized with the name of the command that
failed, if known. See |catch-errors|.
PECULIARITIES
*except-compat*
The exception handling concept requires that the command sequence causing the
exception is aborted immediately and control is transferred to finally clauses
and/or a catch clause.
In the Vim script language there are cases where scripts and functions
continue after an error: in functions without the "abort" flag or in a command
after ":silent!", control flow goes to the following line, and outside
functions, control flow goes to the line following the outermost ":endwhile"
or ":endif". On the other hand, errors should be catchable as exceptions
(thus, requiring the immediate abortion).
This problem has been solved by converting errors to exceptions and using
immediate abortion (if not suppressed by ":silent!") only when a try
conditional is active. This is no restriction since an (error) exception can
be caught only from an active try conditional. If you want an immediate
termination without catching the error, just use a try conditional without
catch clause. (You can cause cleanup code being executed before termination
by specifying a finally clause.)
When no try conditional is active, the usual abortion and continuation
behavior is used instead of immediate abortion. This ensures compatibility of
*except-syntax-err*
Syntax errors in the exception handling commands are never caught by any of
the ":catch" commands of the try conditional they belong to. Its finally
clauses, however, is executed.
Example:
:try
: try
: throw 4711
: catch /\(/
: echo "in catch with syntax error"
: catch
: echo "inner catch-all"
: finally
: echo "inner finally"
: endtry
:catch
: echo 'outer catch-all caught "' . v:exception . '"'
: finally
: echo "outer finally"
:endtry
This displays:
inner finally
outer catch-all caught "Vim(catch):E54: Unmatched \("
outer finally
The original exception is discarded and an error exception is raised, instead.
*except-single-line*
The ":try", ":catch", ":finally", and ":endtry" commands can be put on
a single line, but then syntax errors may make it difficult to recognize the
"catch" line, thus you better avoid this.
Example:
:try | unlet! foo # | catch | endtry
raises an error exception for the trailing characters after the ":unlet!"
argument, but does not see the ":catch" and ":endtry" commands, so that the
error exception is discarded and the "E488: Trailing characters" message gets
displayed.
*except-several-errors*
When several errors appear in a single command, the first error message is
usually the most specific one and therefor converted to the error exception.
Example:
echo novar
causes
E121: Undefined variable: novar
E15: Invalid expression: novar
The value of the error exception inside try conditionals is:
Vim(echo):E121: Undefined variable: novar
*except-syntax-error*
But when a syntax error is detected after a normal error in the same command,
the syntax error is used for the exception being thrown.
Example:
unlet novar #
causes
E108: No such variable: "novar"
E488: Trailing characters
The value of the error exception inside try conditionals is:
Vim(unlet):E488: Trailing characters
This is done because the syntax error might change the execution path in a way
Sorting lines
This example sorts lines with a specific compare function.
:func SortBuffer()
: let lines = getline(1, '$')
: call sort(lines, function("Strcmp"))
: call setline(1, lines)
:endfunction
As a one-liner:
:call setline(1, sort(getline(1, '$'), function("Strcmp")))
scanf() replacement
*sscanf*
There is no sscanf() function in Vim. If you need to extract parts from a
line, you can use matchstr() and substitute() to do it. This example shows
how to get the file name, line number and column number out of a line like
"foobar.txt, 123, 45".
:" Set up the match bit
:let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
:"get the part matching the whole expression
:let l = matchstr(line, mx)
:"get each item out of the match
:let file = substitute(l, mx, '\1', '')
:let lnum = substitute(l, mx, '\2', '')
:let col = substitute(l, mx, '\3', '')
The input is in the variable "line", the results in the variables "file",
"lnum" and "col". (idea from Michael Geddes)
" Split the output into lines and parse each line. Add an entry to the
" "scripts" dictionary.
let scripts = {}
for line in split(scriptnames_output, "\n")
" Only do non-blank lines.
if line =~ '\S'
" Get the first number in the line.
let nr = matchstr(line, '\d\+')
" Get the file name, remove the script number " 123: ".
let name = substitute(line, '.\+:\s*', '', '')
" Add an item to the Dictionary
let scripts[nr] = name
endif
endfor
unlet scriptnames_output
==============================================================================
10. No +eval feature *no-eval-feature*
When the |+eval| feature was disabled at compile time, none of the expression
evaluation commands are available. To prevent this from causing Vim scripts
to generate all kinds of errors, the ":if" and ":endif" commands are still
recognized, though the argument of the ":if" and everything between the ":if"
and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
only if the commands are at the start of the line. The ":else" command is not
recognized.
Example of how to avoid executing commands when the |+eval| feature is
missing:
:if 1
: echo "Expression evaluation is compiled in"
:else
: echo "You will _never_ see this message"
:endif
==============================================================================
11. The sandbox *eval-sandbox* *sandbox* *E48*
The 'foldexpr', 'formatexpr', 'includeexpr', 'indentexpr', 'statusline' and
'foldtext' options may be evaluated in a sandbox. This means that you are
protected from these expressions having nasty side effects. This gives some
safety for when these options are set from a modeline. It is also used when
the command from a tags file is executed and for CTRL-R = in the command line.
The sandbox is also used for the |:sandbox| command.
These items are not allowed in the sandbox:
- changing the buffer text
- defining or changing mapping, autocommands, functions, user commands
- setting certain options (see |option-summary|)
- setting certain v: variables (see |v:var|) *E794*
- executing a shell command
- reading or writing a file
- jumping to another buffer or editing a file
- executing Python, Perl, etc. commands
This is not guaranteed 100% secure, but it should block most attacks.
*:san* *:sandbox*
:san[dbox] {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
option that may have been set from a modeline, e.g.
'foldexpr'.
*sandbox-option*
A few options contain an expression. When this expression is evaluated it may
have to be done in the sandbox to avoid a security risk. But the sandbox is
restrictive, thus this only happens when the option was set from an insecure
location. Insecure in this context are:
- sourcing a .vimrc or .exrc in the current directory
- while executing in the sandbox
- value coming from a modeline
Note that when in the sandbox and saving an option value and restoring it, the
option will still be marked as it was set in the sandbox.
==============================================================================
12. Textlock *textlock*
In a few situations it is not allowed to change the text in the buffer, jump
to another window and some other things that might confuse or break what Vim
is currently doing. This mostly applies to things that happen when Vim is
actually doing something else. For example, evaluating the 'balloonexpr' may
happen any moment the mouse cursor is resting at some position.
This is not allowed when the textlock is active:
- changing the buffer text
- jumping to another buffer or window
- editing another file
- closing a window or quitting Vim
- etc.
- If you prefer to run in 'nocompatible' mode and do have a vimrc file, you
don't have to do anything.
- If you prefer to run in 'compatible' mode and do have a vimrc file, you
should put this line first in your vimrc file:
:set compatible
- If you prefer to run in 'nocompatible' mode and don't have a vimrc file,
you can do one of the following:
- Create an empty vimrc file (e.g.: "~/.vimrc" for Unix).
- Put this command in your .exrc file or $EXINIT:
:set nocompatible
- Start Vim with the "-N" argument.
If you are new to Vi and Vim, using 'nocompatible' is strongly recommended,
because Vi has a lot of unexpected side effects, which are avoided by this
setting. See 'compatible'.
If you like some things from 'compatible' and some not, you can tune the
compatibility with 'cpoptions'.
When you invoke Vim as "ex" or "gex", Vim always starts in compatible mode.
and syntax files. See |$VIM|. Starting with version 5.4, |$VIMRUNTIME| can
also be used.
For Unix, Vim sets a default value for $VIM when doing "make install".
When $VIM is not set, its default value is the directory from 'helpfile',
excluding "/doc/help.txt".
highlighting to HTML. The colors will be exactly the same as how you see them
in Vim. With a HTML viewer you can also print the file with colors.
dot to the swap file name. When long file names are used, the DJGPP and
Win32 versions also prepend a dot, in case a file on a mounted Unix file
system is edited. |:swapname| On MSDOS the hidden file attribute is NOT
set, because this causes problems with share.exe.
- 'updatecount' always defaults to non-zero, also for Vi compatible mode.
This means there is a swap file, which can be used for recovery.
Tags:
- Included ctags 2.0 (Darren Hiebert). The syntax for static tags changed
from
{tag}:{fname} {fname} {command}
to
{tag} {fname} {command};" file:
Which is both faster to parse, shorter and Vi compatible. The old format is
also still accepted, unless disabled in src/feature.h (see OLD_STATIC_TAGS).
|tags-file-format|
- Completion of tags now also includes static tags for other files, at the
end.
- Included "shtags" from Stephen Riehm.
- When finding a matching tag, but the file doesn't exist, continue searching
for another match. Helps when using the same tags file (with links) for
different versions of source code.
- Give a tag with a global match in the current file a higher priority than a
global match in another file.
Included xxd version V1.8 (Juergen Weigert).
Autocommands:
- VimLeave autocommands are executed after writing the viminfo file, instead
of before. |VimLeave|
- Allow changing autocommands while executing them. This allows for
self-modifying autocommands. (idea from Goldberg)
- When using autocommands with two or more patterns, could not split
":if/:endif" over two lines. Now all matching autocommands are executed in
one do_cmdline().
- Autocommands no longer change the command repeated with ".".
- Search patterns are restored after executing autocommands. This avoids
that the 'hlsearch' highlighting is messed up by autocommands.
- When trying to execute an autocommand, also try matching the pattern with
the short file name. Helps when short file name is different from full
file name (expanded symbolic links). |autocmd-patterns|
- Made the output of ":autocmd" shorter and look better.
- Expand <sfile> in an ":autocmd" when it is defined. |<sfile>|
- Added "nested" flag to ":autocmd", allows nesting. |autocmd-nested|
- Added [group] argument to ":autocmd". Overrides the currently set group.
|autocmd-groups|
- new events:
|BufUnload| before a buffer is unloaded
|BufDelete| before a buffer is deleted from the buffer list
|FileChangedShell| when a file's modification time has changed after
executing a shell command
|User| user-defined autocommand
- When 'modified' was set by a BufRead* autocommand, it was reset again
afterwards. Now the ":set modified" is remembered.
GUI:
- Improved GUI scrollbar handling when redrawing is slower than the scrollbar
events are generated.
- "vim -u NONE" now also stops loading the .gvimrc and other GUI inits. |-u|
Use "-U" to use another gvimrc file. |-U|
- Handle CTRL-C for external command, also for systems where "setsid()" is
supported.
- When starting the GUI, restrict the window size to the screen size.
- The default menus are read from $VIMRUNTIME/menu.vim. This allows for a
customized default menu. |menu.vim|
- Improved the default menus. Added File/Print, a Window menu, Syntax menu,
etc.
- Added priority to the ":menu" command. Now each menu can be put in a place
where you want it, independent of the order in which the menus are defined.
|menu-priority|
Give a warning in the intro screen when running the Win32 console version on
Windows 95 because there are problems using this version under Windows 95.
|win32-problems|
Added 'e' flag for ":substitute" command: Don't complain when not finding a
match (Campbell). |:s|
When using search commands in a mapping, only the last one is kept in the
history. Avoids that the history is trashed by long mappings.
Ignore characters after "ex", "view" and "gvim" when checking startup mode.
Allows the use of "gvim5" et. al. |gvim| "gview" starts the GUI in readonly
mode. |gview|
When resizing windows, the cursor is kept in the same relative position, if
possible. (Webb)
":all" and ":ball" no longer close and then open a window for the same buffer.
Avoids losing options, jumplist, and other info.
"-f" command-line argument is now ignored if Vim was compiled without GUI.
|-f|
In Visual block mode, the right mouse button picks up the nearest corner.
Changed default mappings for DOS et al. Removed the DOS-specific mappings,
only use the Windows ones. Added Shift-Insert, Ctrl-Insert, Ctrl-Del and
Shift-Del.
Changed the numbers in the output of ":jumps", so you can see where {count}
CTRL-O takes you. |:jumps|
Using "~" for $HOME now works for all systems. |$HOME|
Unix: Besides using CTRL-C, also use the INTR character from the tty settings.
Somebody has INTR set to DEL.
Allow a <LF> in a ":help" command argument to end the help command, so another
command can follow.
Doing "%" on a line that starts with " #if" didn't jump to matching "#else".
Don't recognize "#if", "#else" etc. for '%' when 'cpo' contains the '%' flag.
|%|
Insert mode expansion with "CTRL-N", "CTRL-P" and "CTRL-X" improved
YXXYins-completion|:
- 'complete' option added.
- When 'nowrapscan' is set, and no match found, report the searched direction
in the error message.
- Repeating CTRL-X commands adds following words/lines after the match.
- When adding-expansions, accept single character matches.
- Made repeated CTRL-X CTRL-N not break undo, and "." repeats the whole
insertion. Also fixes not being able to backspace over a word that has been
inserted with CTRL-N.
When copying characters in Insert mode from previous/next line, with CTRL-E or
CTRL-Y, 'textwidth' is no longer used. |i_CTRL-E|
Commands that move in the arglist, like ":n" and ":rew", keep the old cursor
position of the file (this is mostly Vi compatible).
Vim now remembers the '< and '> marks for each buffer. This fixes a problem
that a line-delete in one buffer invalidated the '< and '> marks in another
buffer. |'<|
For MSDOS, Unix and OS/2: When $VIM not set, use the path from the executable.
When using the executable path for $VIM, remove "src/" when present. Should
make Vim find the docs and syntax files when it is run directly after
compiling. |$VIM|
When quitting Visual mode with <Esc>, the cursor is put at start of the Visual
area (like after executing an operator).
Win32 and Unix version: Removed 1100 character limit on external commands.
Added possibility to include a space in a ":edit +command" argument, by
putting a backslash before it. |+cmd|
After recovery, BufReadPost autocommands are applied. |:recover|
Added color support for "os2ansi", OS/2 console. (Slootman) |os2ansi|
Allow "%:p:h" when % is empty. |:_%|
Included "<sfile>": file name from the ":source" command. |<sfile>|
Added "<Bslash>" special character. Helps for avoiding multiple backslashes
in mappings and menus.
In a help window, a double-click jumps to the tag under the cursor (like
CTRL-]).
<C-Left> and <C-Right> now work like <S-Left> and <S-Right>, move a word
forward/backward (Windows compatible). |<C-Left>|
Removed the requirement for a ":version" command in a .vimrc file. It wasn't
used for anything. You can use ":if" to handle differences between versions.
|:version|
For MS-DOS, Win32 and OS/2: When comparing file names for autocommands, don't
make a difference between '/' and '\' for path separator.
New termcap options:
"mb": blink. Can only be used by assigning it to one of the other highlight
options. |t_mb|
"bc": backspace character. |t_bc|
"nd": Used for moving the cursor right in the GUI, to avoid removing one line
of pixels from the last bold character. |t_nd|
"xs": highlighting not erased by overwriting, for hpterm. Combined with
'weirdinvert'. Visual mode works on hpterm now. |t_xs|
Unix: Set time of patch and backup file same as original file. (Hiebert).
Amiga: In QuickFix mode no longer opens another window. Shell commands can be
used now.
Added decmouse patches from David Binette. Can now use Dec and Netterm mouse.
But only when enabled at compile time.
Added '#' register: Alternate file name |quote#|. Display '#' register with
":dis" command. |:display|
Removed ':' from 'isfname' default for Unix. Check for "://" in a file name
anyway. Also check for ":\\", for MS-DOS.
Added count to "K"eyword command, when 'keywordprg' is "man", is inserted in
the man command. "2K" results in "!man 2 <cword>". |K|
When using "gf" on a relative path name, remove "../" from the file name, like
it's done for file names in the tags file. |gf|
When finishing recording, don't make the recorded register the default put
register.
When using "!!", don't put ":5,5!" on the command-line, but ":.!". And some
other enhancements to replace the line number with "." or "$" when possible.
MSDOS et al.: Renamed $VIM/viminfo to $VIM/_viminfo. It's more consistent:
.vimrc/_vimrc and .viminfo/_viminfo
For systems where case doesn't matter in file names (MSDOS, Amiga), ignore
case while sorting file names. For buffer names too.
When reading from stdin doesn't work, read from stderr (helps for "foo | xargs
vim").
32 bit MS-DOS version: Replaced csdpmi3 by csdpmi4.
Changed <C-Left> and <C-Right> to skip a WORD instead of a word.
Warning for changed modified time when overwriting a file now also works on
other systems than Unix.
Unix: Changed the defaults for configure to be the same as the defaults for
Makefile: include GUI, Perl, and Python.
Some versions of Motif require "-lXpm". Added check for this in configure.
Don't add "-L/usr/lib" to the link line, causes problems on a few systems.
==============================================================================
COMPILE TIME CHANGES *compile-changes-5*
When compiling, allow a choice for minimal, normal or maximal features in an
easy way, by changing a single line in src/feature.h.
The DOS16 version has been compiled with minimal features to avoid running
out of memory too quickly. |dos16|
The Win32, DJGPP, and OS/2 versions use maximal features, because they have
enough memory.
The Amiga version is available with normal and maximal features.
Added "make test" to Unix version Makefile. Allows for a quick check if most
"normal" commands work properly. Also tests a few specific commands.
Added setlocale() with codepage support for DJGPP version.
autoconf:
- Added autoconf check for -lXdmcp.
- Included check for -lXmu, no longer needed to edit the Makefile for this.
- Switched to autoconf 2.12.
- Added configure check for <poll.h>. Seems to be needed when including
Perl on Linux?
- termlib is now checked before termcap.
- Added configure check for strncasecmp(), stricmp() and strnicmp(). Added
vim_stricmp() for when there's no library function for stricmp().
- Use "datadir" in configure, instead of our own check for HELPDIR.
Removed "make proto" from Makefile.manx. Could not make it work without a lot
of #ifdefs.
Removed "proto/" from paths in proto.h. Needed for the Mac port.
Drastically changed Makefile.mint. Now it includes the Unix Makefile.
Added support for Dos16 in Makefile.b32 (renamed Makefile.b32 to Makefile.bor)
All source files are now edited with a tabstop of 8 instead of 4, which is
better when debugging and using other tools. 'softtabstop' is set to 4, to
make editing easier.
Unix: Added "link.sh" script, which removes a few unnecessary libraries from
the link command.
Don't use HPUX digraphs by default, but only when HPUX_DIGRAPHS is defined.
|digraphs-default|
==============================================================================
BUG FIXES *bug-fixes-5*
Note: Some of these fixes may only apply to test versions which were
created after version 4.6, but before 5.0.
When doing ":bdel", try going to the next loaded buffer. Don't rewind to the
start of the buffer list.
mch_isdir() for Unix returned TRUE for "" on some systems.
Win32: 'shell' set to "mksnt/sh.exe" breaks ":!" commands. Don't use
backslashes in the temp file names.
On linux, with a FAT file system, could get spurious "file xxx changed since
editing started" messages, because the time is rounded off to two seconds
unexpectedly.
Crash in GUI, when selecting a word (double click) and then extend until an
empty line.
For systems where isdigit() can't handle characters > 255, get_number() caused
a crash when moving the mouse during the prompt for recovery.
In Insert mode, "CTRL-O P" left the cursor on the last inserted character.
Now the cursor is left after the last putted character.
When quickfix found an error type other than 'e' or 'w', it was never printed.
A setting for 'errorfile' in a .vimrc overruled the "-q errorfile" argument.
Some systems create a file when generating a temp file name. Filtering would
then create a backup file for this, which was never deleted. Now no backup
file is made when filtering.
simplify_filename() could remove a ".." after a link, resulting in the wrong
file name. Made simplify_filename also work for MSDOS. Don't use it for
Amiga, since it doesn't have "../".
otherfile() was unreliable when using links. Could think that reading/writing
was for a different file, when it was the same.
Using <BS> to move the cursor left can sometimes erase a character. Now use
"le" termcap entry for this.
Keyword completion with regexp didn't work. e.g., for "b.*crat".
Fixed: With CTRL-O that jumps to another file, cursor could end up just after
the line.
Amiga: '$' was missing from character recognized as wildcards, causing $VIM
sometimes not to be expanded.
":change" didn't adjust marks for deleted lines.
":help [range]" didn't work. Also for [pattern], [count] and [quotex].
For 'cindent'ing, typing "class::method" doesn't align like a label when the
second ':' is typed.
When inserting a CR with 'cindent' set (and a bunch of other conditions) the
cursor went to a wrong location.
'cindent' was wrong for a line that ends in '}'.
'cindent' was wrong after "else {".
While editing the cmdline in the GUI, could not use the mouse to select text
from the command-line itself.
When deleting lines, marks in tag stack were only adjusted for the current
window, not for other windows on the same buffer.
Tag guessing could find a function "some_func" instead of the "func" we were
looking for.
Tags file name relative to the current file didn't work.
":g/pat2/s//pat2/g", causing the number of subs to be reported, used to cause
a scroll up. Now you no longer have to hit <CR>.
X11 GUI: Selecting text could cause a crash.
32 bit DOS version: CTRL-C in external command killed Vim. When SHELL is set
to "sh.exe", external commands didn't work. Removed using of command.com, no
longer need to set 'shellquote'.
Fixed crash when using ":g/pat/i".
Fixed (potential) crash for X11 GUI, when using an X selection. Was giving a
pointer on the stack to a callback function, now it's static.
Using "#" and "*" with an operator didn't work. E.g. "c#".
Command-line expansion didn't work properly after ":*". (Acevedo)
Setting 'weirdinvert' caused highlighting to be wrong in the GUI.
":e +4 #" didn't work, because the "4" was in unallocated memory (could cause
a crash).
Cursor position was wrong for ":e #", after ":e #" failed, because of changes
to the buffer.
When doing ":buf N", going to a buffer that was edited with ":view", the
readonly flag was reset. Now make a difference between ":e file" and ":buf
file": Only set/reset 'ro' for the first one.
Avoid |hit-enter| prompt when not able to write viminfo on exit.
When giving error messages in the terminal where the GUI was started, GUI
escape codes would be written to the terminal. In an xterm this could be seen
as a '$' after the message.
Mouse would not work directly after ":gui", because full_screen isn't set,
which causes starttermcap() not to do its work.
'incsearch' did not scroll the window in the same way as the actual search.
When 'nowrap' set, incsearch didn't show a match when it was off the side of
the screen. Now it also shows the whole match, instead of just the cursor
position (if possible).
":unmap", ":unab" and ":unmenu" did not accept a double quote, it was seen as
the start of a comment. Now it's Vi compatible.
When $DISPLAY not set, starting "gvim" (dropping back to vim) and then
selecting text with the mouse caused a crash.
"J", with 'joinspaces' set, on a line ending in ". ", caused one space too
many to be added. (Acevedo)
In insert mode, a CTRL-R {regname} which didn't insert anything left the '"''
on the screen.
":z10" didn't work. (Clapp)
"Help "*" didn't work.
Renamed a lot of functions, to avoid clashes with POSIX name space.
When adding characters to a line, making it wrap, the following lines were
sometimes not shifted down (e.g. after a tag jump).
CTRL-E, with 'so' set and cursor on last line, now does not move cursor as
long as the last line is on the screen.
When there are two windows, doing "^W+^W-" in the bottom window could cause
the status line to be doubled (not redrawn correctly).
This command would hang: ":n `cat`". Now connect stdin of the external
command to /dev/null, when expanding.
Fixed lalloc(0,) error for ":echo %:e:r". (Acevedo)
The "+command" argument to ":split" didn't work when there was no file name.
When selecting text in the GUI, which is the output of a command-line command
or an external command, the inversion would sometimes remain.
GUI: "-mh 70" argument was broken. Now, when menuheight is specified, it is
not changed anymore.
GUI: When using the scrollbar or mouse while executing an external command,
this caused garbage characters.
Showmatch sometimes jumped to the wrong position. Was caused by a call to
findmatch() when redrawing the display (when syntax highlighting is on).
Search pattern "\(a *\)\{3} did not work correctly, also matched "a a".
Problem with brace_count not being decremented.
Wildcard expansion added too many non-matching file names.
When 'iskeyword' contains characters like '~', "*" and "#" didn't work
properly. (Acevedo)
On Linux, on a FAT file system, modification time can change by one second.
Avoid a "file has changed" warning for a one second difference.
When using the page-switching in an xterm, Vim would position the cursor on
the last line of the window on exit. Also removed the cursor positioning for
":!" commands.
":g/pat/p" command (partly) overwrote the command. Now the output is on a
separate line.
With 'ic' and 'scs' set, a search for "Keyword", ignore-case matches were
highlighted too.
"^" on a line with only white space, put cursor beyond the end of the line.
When deleting characters before where insertion started ('bs' == 2), could not
use abbreviations.
CTRL-E at end of file puts cursor below the file, in Visual mode, when 'so' is
non-zero. CTRL-E didn't work when 'so' is big and the line below the window
wraps. CTRL-E, when 'so' is non-zero, at end of the file, caused jumping
up-down.
":retab" didn't work well when 'list' is set.
Amiga: When inserting characters at the last line on the screen, causing it
to wrap, messed up the display. It appears that a '\n' on the last line
doesn't always cause a scroll up.
In Insert mode "0<C-D><C-D>" deleted an extra character, because Vim thought
"vim -r" didn't work, it would just hang (using tgetent() while 'term' is
empty).
"gk" while 'nowrap' set moved two lines up.
When windows are split, a message that causes a scroll-up messed up one of the
windows, which required a CTRL-L to be typed.
Possible endless loop when using shell command in the GUI.
Menus defined in the .vimrc were removed when GUI started.
Crash when pasting with the mouse in insert mode.
Crash with ":unmenu *" in .gvimrc for Athena.
"5>>" shifted 5 lines 5 times, instead of 1 time.
CTRL-C when getting a prompt in ":global" didn't interrupt.
When 'so' is non-zero, and moving the scrollbar completely to the bottom,
there was a lot of flashing.
GUI: Scrollbar ident must be long for DEC Alpha.
Some functions called vim_regcomp() without setting reg_magic, which could
lead to unpredictable magicness.
Crash when clicking around the status line, could get a selection with a
backwards range.
When deleting more than one line characterwise, the last character wasn't
deleted.
GUI: Status line could be overwritten when moving the scrollbar quickly (or
when 'wd' is non-zero).
An ESC at the end of a ":normal" command caused a wait for a terminal code to
finish. Now, a terminal code is not recognized when its start comes from a
mapping or ":normal" command.
Included patches from Robert Webb for GUI. Layout of the windows is now done
inside Vim, instead of letting the layout manager do this. Makes Vim work
with Lesstif!
UMR warning in set_expand_context().
Memory leak: b_winlnum list was never freed.
Removed TIOCLSET/TIOCLGET code from os_unix.c. Was changing some of the
terminal settings, and looked like it wasn't doing anything good. (suggested
by Juergen Weigert).
Ruler overwrote "is a directory" message. When starting up, and 'cmdheight'
set to > 1, first message could still be in the last line.
Removed prototype for putenv() from proto.h, it's already in osdef2.h.in.
In replace mode, when moving the cursor and then backspacing, wrong characters
were inserted.
Win32 GUI was checking for a CTRL-C too often, making it slow.
Removed mappings for MS-DOS that were already covered by commands.
When visually selecting all lines in a file, cursor at last line, then "J".
Gave ml_get errors. Was a problem with scrolling down during redrawing.
When doing a linewise operator, and then an operator with a mouse click, it
was also linewise, instead of characterwise.
When 'list' is set, the column of the ruler was wrong.
Spurious error message for "/\(b\+\)*".
When visually selected many lines, message from ":w file" disappeared when
redrawing the screen.
":set <M-b>=^[b", then insert "^[b", waited for another character. And then
inserted "<M-b>" instead of the real <M-b> character. Was trying to insert
K SPECIAL x NUL.
Changed *changed-5.1*
The expand() function now separates file names with <NL> instead of a space.
This avoids problems for file names with embedded spaces. To get the old
result, use substitute(expand(foo), "\n", " ", "g").
For Insert-expanding dictionaries allow a backslash to be used for
wildchars. Allows expanding "ze\kra", when 'isk' includes a backslash.
New icon for the Win32 GUI.
":tag", ":tselect" etc. only use the argument as a regexp when it starts
with '/'. Avoids that ":tag xx~" gives an error message: "No previous sub.
regexp". Also, when the :tag argument contained wildcard characters, it was
not Vi compatible.
When using '/', the argument is taken literally too, with a higher priority,
so it's found before wildcard matches.
Only when the '/' is used are matches with different case found, even though
'ignorecase' isn't set.
Changed "g^]" to only do ":tselect" when there is more than on matching tag.
Changed some of the default colors, because they were not very readable on a
dark background.
A character offset to a search pattern can move the cursor to the next or
previous line. Also fixes that "/pattern/e+2" got stuck on "pattern" at the
end of a line.
Double-clicks in the status line do no longer start Visual mode. Dragging a
status line no longer stops Visual mode.
Perl interface: Buffers() and Windows() now use more logical arguments, like
they are used in the rest of Vim (Moore).
Init '"' mark to the first character of the first line. Makes it possible to
use '"' in an autocommand without getting an error message.
Added *added-5.1*
"shell_error" internal variable: result of last shell command.
":echohl" command: Set highlighting for ":echo".
'S' flag in 'highlight' and StatusLineNC highlight group: highlighting for
status line of not-current window. Default is to use bold for current
window.
Added buffer_name() and buffer_number() functions (Aaron).
Added flags argument "g" to substitute() function (Aaron).
Added winheight() function.
Win32: When an external command starts with "start ", no console is opened
for it (Aaron).
Win32 console: Use termcap codes for bold/reverse based on the current
console attributes.
Configure check for "strip". (Napier)
CTRL-R CTRL-R x in Insert mode: Insert the contents of a register literally,
instead of as typed.
Made a few "No match" error messages more informative by adding the pattern
that didn't match.
Fixed *fixed-5.1*
":ts" changed position in the tag stack when cancelled with <CR>.
":ts" changed the cursor position for CTRL-T when cancelled with <CR>.
":tn" would always jump to the second match. Was using the wrong entry in
the tag stack.
Doing "tag foo", then ":tselect", overwrote the original cursor position in
the tag stack.
"make install" changed the vim.1 manpage in a wrong way, causing "doc/doc"
to appear for the documentation files.
When compiled with MAX_FEAT, xterm mouse handling failed. Was caused by DEC
mouse handling interfering.
Was leaking memory when using selection in X11.
CTRL-D halfway a command-line left some characters behind the first line(s)
of the listing.
When expanding directories for ":set path=", put two extra backslashes
before a space in a directory name.
When 'lisp' set, first line of a function would be indented. Now its indent
is set to zero. And use the indent of the first previous line that is at
colors that were set by the user in the .gvimrc file. Now it only changes
colors that have not been set by the user.
Ignore special characters after a CSI in the GUI version. These could be
interpreted as special characters in a wrong way. (St-Amant)
Memory leak in farsi code, when using search or ":s" command.
Farsi string reversing for a mapping was only done for new mappings. Now it
also works for replacing a mapping.
Crash in Win32 when using a file name longer than _MAX_PATH. (Aaron)
When BufDelete autocommands were executed, some things for the buffer were
already deleted (esp. Perl stuff).
Perl interface: Buffer specific items were deleted too soon; fixes "screen
no longer exists" messages. (Moore)
The Perl functions didn't set the 'modified' flag.
link.sh did not return an error on exit, which may cause Vim to start
installing, even though there is no executable to install. (Riehm)
Vi incompatibility: In Vi "." redoes the "y" command. Added the 'y' flag to
'cpoptions'. Only for 'compatible' mode.
":echohl" defined a new group, when the argument was not an existing group.
"syn on" and ":syn off" could move the cursor, if there is a hidden buffer
that is shorter that the current cursor position.
The " mark was not set when doing ":b file".
When a "nextgroup" is used with "skipwhite" in syntax highlighting, space at
the end of the line made the nextgroup also be found in the next line.
":he g<CTRL-D>", then ":" and backspace to the start didn't redraw.
X11 GUI: "gvim -rv" reversed the colors twice on Sun. Now Vim checks if the
result is really reverse video (background darker than foreground).
"cat link.sh | vim -" didn't set syntax highlighting.
Win32: Expanding "file.sw?" matched ".file.swp". This is an error of
FindnextFile() that we need to work around. (Kilgore)
"gqgq" gave an "Invalid lnum" error on the last line.
Formatting with "gq" didn't format the first line after a change of comment
leader.
There was no check for out-of-memory in win_alloc().
"vim -h" didn't mention "-register" and "-unregister" for the OLE version.
Could not increase 'cmdheight' when the last window is only one line. Now
other windows are also made smaller, when necessary.
Added a few {} to avoid "suggest braces around" warnings from gcc 2.8.x.
Changed return type of main() from void to int. (Nam)
Using '~' twice in a substitute pattern caused a crash.
"syn on" and ":syn off" could scroll the window, if there is a hidden buffer
that is shorter that the current cursor position.
":if 0 | if 1 | endif | endif" didn't work. Same for ":while" and "elseif".
With two windows on modified files, with 'autowrite' set, cursor in second
window, ":qa" gave a warning for the file in the first window, but then
auto-wrote the file in the second window. (Webb)
Win32 GUI scrollbar could only handle 32767 lines. Also makes the
intellimouse wheel use the configurable number of scrolls. (Robinson)
When using 'patchmode', and the backup file is on another partition, the file
copying messed up the write-file message.
GUI X11: Alt-Backspace and Alt-Delete didn't work.
"`0" could put the cursor after the last character in the line, causing
trouble for other commands, like "i".
When completing tags in insert mode with ^X^], some matches were skipped,
because the compare with other tags was wrong. E.g., when "mnuFileSave" was
already there, "mnuFile" would be skipped. (Negri)
When scrolling up/down, a syntax item with "keepend" didn't work properly.
Now the flags are also stored for the syntax state at the start of each line.
When 'ic' was changed while 'hlsearch' is on, there was no redraw to show the
effect.
Win32 GUI: Don't display "No write since last chance" in a message box, but in
the Vim window.
==============================================================================
VERSION 5.2 *version-5.2*
Improvements made between version 5.1 and 5.2.
- Added 'selectmode' option: tells when to start Select mode instead of Visual
mode.
- Added 'mousemodel' option: Change use of mouse buttons.
- Added 'keymodel' option: tells to use shifted special keys to start a
Visual or Select mode selection.
- Added ":behave". Can be used to quickly set 'selectmode', 'mousemodel'
and 'keymodel' for MS-Windows and xterm behavior.
- The xterm-like selection is now called modeless selection.
- Visual mode mappings and menus are used in Select mode. They automatically
switch to Visual mode first. Afterwards, reselect the area, unless it was
deleted. The "gV" command can be used in a mapping to skip the reselection.
- Added the "gh", "gH" and "g^H" commands: start Select (highlight) mode.
- Backspace in Select mode deletes the selected area.
"mswin.vim" script. Sets behavior mostly like MS-Windows.
Changed *changed-5.2*
Renamed functions:
buffer_exists() -> bufexists()
buffer_name() -> bufname()
buffer_number() -> bufnr()
file_readable() -> filereadable()
highlight_exists() -> hlexists()
highlightID() -> hlID()
last_buffer_nr() -> bufnr("$")
The old ones are still there, for backwards compatibility.
The CTRL-_ command in Insert and Command-line mode is only available when the
new 'allowrevins' option is set. Avoids that people who want to type SHIFT-_
accidentally enter reverse Insert mode, and don't know how to get out.
When a file name path in ":tselect" listing is too long, remove a part in the
middle and put "..." there.
Win32 GUI: Made font selector appear inside Vim window, not just any odd
place. (Negri)
":bn" skips help buffers, unless currently in a help buffer. (Negri)
When there is a status line and only one window, don't show '^' in the status
line of the current window.
":*" used to be used for "'<,'>", the Visual area. But in Vi it's used as an
alternative for ":@". When 'cpoptions' includes '*' this is Vi compatible.
When 'insertmode' is set, using CTRL-O to execute a mapping will work like
'insertmode' was not set. This allows "normal" mappings to be used even when
'insertmode' is set.
When 'mouse' was set already (e.g., in the .vimrc file), don't automatically
set 'mouse' when the GUI starts.
Removed the 'N', 'I' and 'A' flags from the 'mouse' option.
Renamed "toggle option" to "boolean option". Some people thought that ":set
xyz" would toggle 'xyz' on/off each time.
The internal variable "shell_error" contains the error code from the shell,
instead of just 0 or 1.
When inserting or replacing, typing CTRL-V CTRL-<CR> used to insert "<C-CR>".
That is not very useful. Now the CTRL key is ignored and a <CR> is inserted.
Same for all other "normal" keys with modifiers. Mapping these modified key
combinations is still possible.
In Insert mode, <C-CR> and <S-Space> can be inserted by using CTRL-K and then
Added *added-5.2*
--with-motif-lib configure argument. Allows for using a static Motif library.
Support for mapping numeric keypad +,-,*,/ keys. (Negri)
When not mapped, they produce the normal character.
Win32 GUI: When directory dropped on Gvim, cd there and edit new buffer.
(Negri)
Win32 GUI: Made CTRL-Break work as interrupt, so that CTRL-C can be
used for mappings.
In the output of ":map", highlight the "*" to make clear it's not part of the
rhs. (Roemer)
When showing the Visual area, the cursor is not switched off, so that it can
be located. The Visual area is now highlighted with a grey background in the
GUI. This makes the cursor visible when it's also reversed.
Win32: When started with single full pathname (e.g. via double-clicked file),
cd to that file's directory. (Negri)
Win32 GUI: Tear-off menus, with ":tearoff <menu-name>" command. (Negri)
't' option to 'guioptions': Add tearoff menu items for Win32 GUI and Motif.
It's included by default.
Win32 GUI: tearoff menu with submenus is indicated with a ">>". (Negri)
Added ^Kaa and ^KAA digraphs.
Added "euro" symbol to digraph.c. (Corry)
Support for Motif menu shortcut keys, using '&' like MS-Windows (Ollis).
Other GUIs ignore '&' in a menu name.
DJGPP: Faster screen updating (John Lange).
Clustering of syntax groups ":syntax cluster" (Bigham).
Including syntax files: ":syntax include" (Bigham).
Keep column when switching buffers, when 'nosol' is set (Radics).
Number function for Perl interface.
Support for Intellimouse in Athena GUI. (Jensen)
Fixed *fixed-5.2*
Win32 GUI: Could draw text twice in one place, for fake-bold text. Removed
this, Windows will handle the bold text anyway. (Negri)
patch 5.1.1: Win32s GUI: pasting caused a crash (Negri)
patch 5.1.2: When entering another window, where characters before the cursor
have been deleted, could have a cursor beyond the end of the line.
patch 5.1.3: Win32s GUI: Didn't wait for external command to finish. (Negri)
patch 5.1.4: Makefile.w32 can now also be used to generate the OLE version
(Scott).
patch 5.1.5: Crashed when using syntax highlighting: cursor on a line that
doesn't fit in the window, and splitting that line in two.
patch 5.1.6: Visual highlighting bug: After ":set nowrap" go to end of line
(so that the window scrolls horizontally), ":set wrap" Following Visual
selection was wrong.
patch 5.1.7: When 'tagbsearch' off, and 'ignorecase' off, still could do
binary searching.
patch 5.1.8: Win32 GUI: dragging the scrollbar didn't update the ruler.
patch 5.1.9: Using ":gui" in .vimrc, caused xterm cursor to disappear.
patch 5.1.10: A CTRL-N in Insert mode could cause a crash, when a buffer
without a name exists.
patch 5.1.11: "make test" didn't work in the shadow directory. Also adjusted
"make shadow" for the links in the ctags directory.
patch 5.1.12: "buf 123foo" used "123" as a count, instead as the start of a
buffer name.
patch 5.1.13: When completing file names on the command-line, reallocating the
command-line may go wrong.
patch 5.1.14: ":[nvci]unmenu" removed menu for all modes, when full menu patch
specified.
Graceful handling of NULLs in drag-dropped file list. Handle passing NULL to
Fullname_save(). (Negri)
Win32: ":!start" to invoke a program without opening a console, swapping
screens, or waiting for completion in either console or gui version, e.g. you
can type ":!start winfile". ALSO fixes "can't delete swapfile after spawning
a shell" bug. (enhancement of Aaron patch) (Negri)
Win32 GUI: Fix CTRL-X default keymapping to be more Windows-like. (Negri)
Shorten filenames on startup. If in /foo/bar, entering "vim ../bar/bang.c"
displays "bang.c" in status bar, not "/foo/bar/bang.c" (Negri)
Win32 GUI: No copy to Windows clipboard when it's not desired.
Win32s: Fix pasting from clipboard - made an assumption not valid under
Win32s. (Negri)
Win32 GUI: Speed up calls to gui_mch_draw_string() and cursor drawing
functions. (Negri)
Win32 GUI: Middle mouse button emulation now works in GUI! (Negri)
Could skip messages when combining commands in one line, e.g.:
When using "*" or "#" on a string that includes '/' or '?' (when these are
included in 'isk'), they were not escaped. (Parmelan)
When adding a ToolBar menu in the Motif GUI, the submenu_id field was not
cleared, causing random problems.
When adding a menu, the check if this menu (or submenu) name already exists
didn't compare with the simplified version (no mnemonic or accelerator) of the
new menu. Could get two menus with the same name, e.g., "File" and "&File".
Breaking a line because of 'textwidth' at the last line in the window caused a
redraw of the whole window instead of a scroll. Speeds up normal typing with
'textwidth' a lot for slow terminals.
An invalid line number produced an "invalid range" error, even when it wasn't
to be executed (inside "if 0").
When the unnamed, first buffer is re-used, the "BufDelete" autocommand was
not called. It would stick in a buffer list menu.
When doing "%" on the NUL after the line, a "{" or "}" in the last character
of the line was not found.
The Insert mode menu was not used for the "s" command, the Operator-pending
menu was used instead.
With 'compatible' set, some syntax highlighting was not correct, because of
using "[\t]" for a search pattern. Now use the regexps for syntax
highlighting like the 'cpoptions' option is empty (as was documented already).
When using "map <M-Space> ms" or "map <Space> sss" the output of ":map" didn't
show any lhs for the mapping (if 'isprint' includes 160). Now always use
<Space> and <M-Space>, even when they are printable.
Adjusted the Syntax menu, so that the lowest entry fits on a small screen (for
Athena, where menus don't wrap).
When using CTRL-E or CTRL-Y in Insert mode for characters like 'o', 'x' and
digits, repeating the insert didn't work.
The file "tools/ccfilter.README.txt" could not be unpacked when using short
file names, because of the two dots. Renamed it to
"tools/ccfilter_README.txt".
For a dark 'background', using Blue for Directory and SpecialKey highlight
groups is not very readable. Use Cyan instead.
In the function uc_scan_attr() in ex_docmd.c there was a goto that jumped into
a block with a local variable. That's illegal for some compilers.
Win32 GUI: There was a row of pixels at the bottom of the window which was not
drawn. (Aaron)
Under DOS, editing "filename/" created a swap file of "filename/.swp". Should
be "filename/_swp".
Win32 GUI: pointer was hidden when executing an external command.
When 'so' is 999, "J" near the end of the file didn't redisplay correctly.
":0a" inserted after the first line, instead of before the first line.
Unix: Wildcard expansion didn't handle single quotes and {} patterns. Now
":file 'window.c'"' removes the quotes and ":e 'main*.c'"' works (literal '*').
":file {o}{n}{e}" now results in file name "one".
Memory leak when setting a string option back to its default value.
==============================================================================
VERSION 5.3 *version-5.3*
Version 5.3 was a bug-fix version of 5.2. There are not many changes.
Improvements made between version 5.2 and 5.3:
Changed *changed-5.3*
Renamed "IDE" menu to "Tools" menu.
Added *added-5.3*
Win32 GUI: Give a warning when Vim is activated, and one of the files changed
since editing started. (Negri)
Fixed *fixed-5.3*
5.2.1: Win32 GUI: space for external command was not properly allocated, could
cause a crash. (Aaron) This was the reason to bring out 5.3 quickly after
5.2.
5.2.2: Some commands didn't complain when used without an argument, although
they need one: ":badd", ":browse", ":call", ":confirm", ":behave",
":delfunction", ":delcommand" and ":tearoff".
":endfunction" outside of a function gave wrong error message: "Command not
implemented". Should be ":endfunction not inside a function".
5.2.3: Win32 GUI: When gvim was installed in "Program files", or another path
with a space in it, executing external commands with vimrun didn't work.
5.2.4: Pasting with the mouse in Insert mode left the cursor on the last
pasted character, instead of behind it.
5.2.5: In Insert mode, cursor after the end of the line, a shift-cursor-left
didn't include the last character in the selection.
5.2.6: When deleting text from Insert mode (with "<C-O>D" or the mouse), which
includes the last character in the line, the cursor could be left on the last
character in the line, instead of just after it.
5.2.7: Win32 GUI: scrollbar was one pixel too big.
5.2.8: Completion of "PopUp" menu showed the derivatives "PopUpc", "PopUPi",
etc. ":menu" also showed these.
5.2.9: When using two input() functions on a row, the prompt would not be
drawn in column 0.
5.2.10: A loop with input() could not be broken with CTRL-C.
5.2.11: ":call asdf" and ":call asdf(" didn't give an error message.
5.2.12: Recursively using ":normal" crashes Vim after a while. E.g.:
":map gq :normal gq<CR>"
5.2.13: Syntax highlighting used 'iskeyword' from wrong buffer. When using
":help", then "/\k*" in another window with 'hlsearch' set.
5.2.14: When using ":source" from a function, global variables would not be
available unless "g:" was used.
5.2.15: XPM files can have the extension ".pm", which is the same as for Perl
modules. Added "syntax/pmfile.vim" to handle this.
5.2.16: On Win32 and Amiga, "echo expand("%:p:h")" removed one dirname in an
empty buffer. mch_Fullname() didn't append a slash at the end of a directory
name.
Should include the character under the cursor in the Visual area when using
'selection' "exclusive". This wasn't done for "%", "e", "E", "t" and "f".
""p would always put register 0, instead of the unnamed (last used) register.
Reverse the change that ""x doesn't write in the unnamed (last used) register.
It would always write in register 0, which isn't very useful. Use "-x for the
paste mappings in Visual mode.
When there is one long line on the screen, and 'showcmd' is off, "0$" didn't
redraw the screen.
Win32 GUI: When using 'mousehide', the pointer would flicker when the cursor
shape is changed. (Negri)
When cancelling Visual mode, and the cursor moves to the start, the wanted
column wasn't set, "k" or "j" moved to the wrong column.
When using ":browse" or ":confirm", was checking for a comment and separating
bar, which can break some commands.
Included fixes for Macintosh. (Kielhorn)
==============================================================================
VERSION 5.4 *version-5.4*
Version 5.4 adds new features, useful changes and a lot of bug fixes.
Encryption *new-encryption*
Files can be encrypted when writing and decrypted when reading. Added the
'key' option, "-x" command line argument and ":X" command. |encryption| (based
on patch from Mohsin Ahmed)
When reading a file, there is an automatic detection whether it has been
crypted. Vim will then prompt for the key.
Note that the encryption method is not compatible with Vi. The encryption is
not unbreakable. This allows it to be exported from the US.
Changed *changed-5.4*
Unix: Use $TMPDIR for temporary files, if it is set and exists.
Removed "Empty buffer" message. It isn't useful and can cause a hit-enter
prompt. (Negri)
"ex -" now reads commands from stdin and works in silent mode. This is to be
compatible with the original "ex" command that is used for scripts.
Default range for ":tcldo" is the whole file.
Cancelling Visual mode with ESC moved the cursor. There appears to be no
reason for this. Now leave the cursor where it is.
The ":grep" and ":make" commands see " as part of the arguments, instead of
the start of a comment.
In expressions the "=~" and "!~" operators no longer are affected by
'ignorecase'.
Renamed vimrc_example to vimrc_example.vim and gvimrc_example to
gvimrc_example.vim. Makes them being recognized as vim scripts.
"gd" no longer starts searching at the end of the previous function, but at
the first blank line above the start of the current function. Avoids that
using "gd" in the first function finds global a variable.
Default for 'complete' changed from ".,b" to ".,w,b,u,t,i". Many more matches
will be found, at the cost of time (the search can be interrupted).
It is no longer possible to set 'shell*' options from a modeline. Previously
only a warning message was given. This reduces security risks.
The ordering of the index of documentation files was changed to make it more
easy to find a subject.
On MS-DOS and win32, when $VIM was not set, $HOME was used. This caused
trouble if $HOME was set to e.g., "C:\" for some other tool, the runtime files
would not be found. Now use $HOME only for _vimrc, _gvimrc, etc., not to find
the runtime file.
When 'tags' is "./{fname}" and there is no file name for the current buffer,
just use it. Previously it was skipped, causing "vim -t {tag}" not to find
many tags.
When trying to select text in the 'scrolloff' area by mouse dragging, the
resulting scrolling made this difficult. Now 'scrolloff' is temporarily set
to 0 or 1 to avoid this. But still allow scrolling in the top line to extend
to above the displayed text.
Default for 'comments' now includes "sl:/*,mb: *,ex:*/", to make javadoc
comments work. Also helps for C comments that start with "/*******".
CTRL-X CTRL-] Insert mode tag expansion tried to expand to all tags when used
after a non-ID character, which can take a very long time. Now limit this to
200 matches. Also used for command-line tag completion.
The OS/2 distribution has been split in two files. It was too big to fit on a
floppy. The same runtime archive as for the PC is now used.
In the documentation, items like <a-z> have been replaced with {a-z} for
non-optional arguments. This avoids confusion with key names: <C-Z> is a
CTRL-Z, not a character between C and Z, that is {C-Z}.
Added *added-5.4*
Color support for the iris-ansi builtin termcap entry. (Tubman)
Included VisVim version 1.3a. (Erhardt)
Win32 port for SNiFF+ interface. (Leherbauer)
Documentation file for sniff interface: if_sniff.txt. (Leherbauer)
Included the "SendToVim" and "OpenWithVim" programs in the OleVim directory.
To be used with the OLE version of gvim under MS-Windows. (Schaller)
Included Exuberant Ctags version 3.2.4 with Eiffel support. (Hiebert)
When a file that is being edited is deleted, give a warning (like when the
time stamp changed).
Included newer versions of the HTML-generating Awk and Perl scripts. (Colombo)
Linux console mouse support through "gpm". (Tsindlekht)
Security fix: Disallow changing 'secure' and 'exrc' from a modeline. When
'secure' is set, give a warning for changing options that contain a program
name.
Made the Perl interface work with Perl 5.005 and threads. (Verdoolaege)
When giving an error message for an ambiguous mapping, include the offending
mapping. (Roemer)
Command line editing:
- Command line completion of mappings. (Roemer)
- Command line completion for ":function", ":delfunction", ":let", ":call",
":if", etc. (Roemer)
- When using CTRL-D completion for user commands that have
"-complete=tag_listfiles" also list the file names. (Madsen)
- Complete the arguments of the ":command" command. (Webb)
- CTRL-R . in command line inserts last inserted text. CTRL-F, CTRL-P, CTRL-W
and CTRL-A after CTRL-R are used to insert an object from under the cursor.
(Madsen)
Made the text in uganda.txt about copying Vim a bit more clear.
Updated the Vim tutor. Added the "vimtutor" command, which copies the tutor
and starts Vim on it. "make install" now also copies the tutor.
In the output of ":clist" the current entry is highlighted, with the 'i'
highlighting (same as used for 'incsearch').
For the ":clist" command, you can scroll backwards with "b" (one screenful),
"u" (half a screenful) and "k" (one line).
Multi-byte support:
- X-input method for multi-byte characters. And various fixes for multi-byte
support. (Nam)
- Hangul input method feature: |hangul|. (Nam)
- Cleaned up configuration of multi-byte support, XIM, fontset and Hangul
input. Each is now configurable separately.
- Changed check for GTK_KEYBOARD to HANGUL_KEYBOARD_TYPE. (Nam)
- Added doc/hangulin.txt: Documentation for the Hangul input code. (Nam)
- XIM support for GTK+. (Nam)
- First attempt to include support for SJIS encoding. (Nagano)
- When a double-byte character doesn't fit at the end of the line, put a "~"
there and print it on the next line.
- Optimize output of multi-byte text. (Park)
- Win32 IME: preedit style is like over-the-spot. (Nagano)
- Win32 IME: IME mode change now done with ImmSetOpenStatus. (Nagano)
- GUI Athena: file selection dialog can display multi-byte characters.
(Nagano)
- Selection reply for XA_TEXT as XA_STRING. (Nagano)
"runtime/macros/diffwin.vim". Mappings to make a diff window. (Campbell)
Added ".obj" to the 'suffixes' option.
Reduced size of syntax/synload.vim by using the ":SynAu" user command.
Automated numbering of Syntax menu entries in menu.vim.
In the Syntax menu, insert separators between syntax names that start with
a different letter. (Geddes)
Xterm:
- Clipboard support when using the mouse in an xterm. (Madsen)
- When using the xterm mouse, track dragging of the mouse. Use xterm escape
sequences when possible. It is more precise than other methods, but
requires a fairly recent xterm version. It is enabled with "xterm2" in
'ttymouse'. (Madsen)
- Check xterm patch level, to set the value of 'ttymouse'. Has only been
added to xterm recently (patch level > 95). Uses the new 't_RV' termcap
option. Set 'ttymouse' to "xterm2" when a correct response is recognized.
Will make xterm mouse dragging work better.
- Support for shifted function keys on xterm. Changed codes for shifted
cursor keys to what the xterm actually produces. Added codes for shifted
<End> and <Home>.
- Added 't_WP' to set the window position in pixels and 't_WS' to set the
window size in characters. Xterm can now move (used for ":winpos") and
resize (use for ":set lines=" and ":set columns=").
X11:
- When in Visual mode but not owning the selection, display the Visual area
with the VisualNOS group to show this. (Madsen)
- Support for requesting the type of clipboard support. Used for AIX and
dtterm. (Wittig)
- Support compound_text selection (even when compiled without multi-byte).
Swap file:
- New variation for naming swap files: Replace path separators into %, place
all swap files in one directory. Used when a name in 'dir' ends in two path
separators. (Madsen)
- When a swap file is found, show whether it contains modifications or not in
the informative message. (Madsen)
- When dialogs are supported, use a dialog to ask the user what to do when a
swapfile already exists.
"popup_setpos" in 'mousemodel' option. Allows for moving the cursor when
using the right mouse button.
When a buffer is deleted, the selection for which buffer to display instead
now uses the most recent entry from the jump list. (Madsen)
When using CTRL-O/CTRL-I, skip deleted buffers.
A percentage is shown in the ruler, when there is room.
Used autoconf 1.13 to generate configure.
Included get_lisp_indent() from Dirk van Deun. Does better Lisp indenting
when 'p' flag in 'cpoptions' is not included.
Made the 2html.vim script quite a bit faster. (based on ideas from Geddes)
Unix:
- Included the name of the user that compiled Vim and the system name it was
compiled on in the version message.
- "make install" now also installs the "tools" directory. Makes them
available for everybody.
- "make check" now does the same as "make test". "make test" checks for
Visual block mode shift, insert, replace and change.
- Speed up comparing a file name with existing buffers by storing the
device/inode number with the buffer.
- Added configure arguments "--disable-gtk", "--disable-motif" and
"--disable-athena", to be able to disable a specific GUI (when it doesn't
work).
- Renamed the configure arguments for disabling the check for specific GUIs.
Should be clearer now. (Kahn)
- On a Digital Unix system ("OSF1") check for the curses library before
termlib and termcap. (Schild)
- "make uninstall_runtime" will only delete the version-specific files. Can
be used to delete the runtime files of a previous version.
Macintosh: (St-Amant)
- Dragging the scrollbar, like it's done for the Win32 GUI. Moved common code
from gui_w32.c to gui.c
- Added dialogs and file browsing.
- Resource fork preserved, warning when it will be lost.
- Copy original file attributes to newly written file.
- Set title/notitle bug solved.
- Filename completion improved.
- Grow box limit resize to a char by char size.
- Use of rgb.txt for more colors (but give back bad color).
- Apple menu works (beside the about...).
- Internal border now vim compliant.
- Removing a menu doesn't crash anymore.
- Weak-linking of Python 1.5.1 (only on PPC). Python is supported when the
library is available.
- If an error is encountered when sourcing the users .vimrc, the alert box now
shows right away with the OK button defaulted. There's no more "Delete"-key
sign at the start of each line
- Better management of environment variables. Now $VIM is calculated only
once, not regenerated every time it is used.
- No more CPU hog when in background.
- In a sourced Vim script the Mac file format can be recognized, just like DOS
file format is.
When both "unix" and "mac" are present in 'fileformats', prefer "mac" format
when there are more CR than NL characters.
When using "mac" fileformat, use CR instead of a NL, because NL is used for
NUL. Will preserve all characters in a file. (Madsen)
The DOS install.exe now contains checks for an existing installation. It
avoids setting $VIM and $PATH again.
The install program for Dos/Windows can now install Vim in the popup menu, by
adding two registry keys.
Port to EGCS/mingw32. New Makefile.ming. (Aaron)
DOS 16 bit: Don't include cursor shape stuff. Save some bytes.
TCL support to Makefile.w32. (Duperval)
OS/2: Use argv[0] to find runtime files.
When using "gf" to go to a buffer that has already been used, jump to the
line where the cursor last was.
Colored the output of ":tselect" a bit more. Different highlighting between
tag name and file name. Highlight field name ("struct:") separately from
argument.
Backtick expansion for non-Unix systems. Based on a patch from Aaron.
Allows the use of things like ":n `grep -l test *.c`" and
"echo expand('`ls m*`')".
Check for the 'complete' option when it is set. (Acevedo)
'd' flag in 'complete' searches for defined names or macros.
While searching for Insert mode completions in include files and tags files,
check for typeahead, so that you can use matches early. (Webb)
The '.' flag in 'complete' now scans the current buffer completely, ignoring
'nowrapscan'. (Webb)
Added '~' flag to 'whichwrap'. (Acevedo)
When ending the Visual mode (e.g., with ESC) don't grab ownership of the
selection.
In a color terminal, "fg" and "bg" can be used as color names. They stand for
the "Normal" colors.
A few cscope cleanups. (Kahn)
Included changed vimspell.sh from Schemenauer.
Concatenation of strings in an expression with "." is a bit faster. (Roemer)
The ":redir" command can now redirect to a register: ":redir @r". (Roemer)
Made the output of ":marks" and ":jumps" look similar. When the mark is in
the current file, show the text at the mark. Also for ":tags".
When configure finds ftello() and fseeko(), they are used in tag.c (for when
you have extremely big tags files).
Configure check for "-FOlimit,2000" argument for the compiler. (Borsenkow)
GUI:
- When using ":gui" in a non-GUI Vim, give a clear error message.
- "gvim -v" doesn't start the GUI (if console support is present).
- When in Ex mode, use non-Visual selection for the whole screen.
- When starting with "gvim -f" and using ":gui" in the .gvimrc file, Vim
forked anyway. Now the "-f" flag is remembered for ":gui". Added "gui -b"
to run gvim in the background anyway.
Motif GUI:
- Check for "-lXp" library in configure (but it doesn't work yet...).
- Let configure check for Lesstif in "/usr/local/Lesstif/Motif*". Changed the
order to let a local Motif version override a system standard version.
Win32 GUI:
- When using "-register" or "-unregister" in the non-OLE version, give an
error message.
- Use GTK toolbar icons. Make window border look better. Use sizing handles
on the lower left&right corners of the window. (Negri)
- When starting an external command with ":!start" and the command can not be
executed, give an error message. (Webb)
- Use sizing handles for the grey rectangles below the scrollbars. Can draw
toolbar in flat mode now, looks better. (Negri)
- Preparations for MS-Windows 3.1 addition. Mostly changing WIN32 to MSWIN
and USE_GUI_WIN32 to USE_GUI_MSWIN. (Negri)
Avoid allocating the same string four times in buflist_findpat(). (Williams)
Set title and icon text with termcap options 't_ts', 't_fs', 't_IS' and
't_IE'. Allows doing this on any terminal that supports setting the title
and/or icon text. (Schild)
New 'x' flag in 'comments': Automatically insert the end part when its last
character is typed. Helps to close a /* */ comment in C. (Webb)
When expand() has a second argument which is non-zero, don't use 'suffixes'
and 'wildignore', return all matches.
'O' flag in 'cpoptions: When not included, Vim will not overwrite a file, if
it didn't exist when editing started but it does exist when the buffer is
written to the file. The file must have been created outside of Vim, possibly
without the user knowing it. When this is detected after a shell command,
give a warning message.
When editing a new file, CTRL-G will show [New file]. When there were errors
while reading the file, CTRL-G will show [Read errors].
":wall" can now use a dialog and file-browsing when needed.
Grouped functionality into new features, mainly to reduce the size of the
minimal version:
+linebreak: 'showbreak', 'breakat' and 'linebreak'
+visualextra: "I"nsert and "A"ppend in Visual block mode, "c"hange all lines
in a block, ">" and "<": Shifting a block, "r": Replacing a
Visual area with one character.
+comments: 'comments'
+cmdline_info: 'ruler' and 'showcmd'. Replaces +showcmd.
"+title" Don't add code to set title or icon for MSDOS, this was not
possible anyway.
+cmdline_compl Disable commandline completion at compile time, except for
files, directories and help items.
Moved features from a list of function calls into an array. Should save a bit
of space.
While entering the body of a function, adjust indent according to "if" and
"while" commands.
VMS: Adjusted os_vms.mms a bit according to suggestions from Arpadffy.
The flags in the 'comments' option can now include an offset. This makes it
possible to align "/*****", "/* xxx" and "/*" comments with the same
'comments' setting. The default value for 'comments' uses this.
Added 'O' flag: Don't use this part for the "O" command. Useful for "set
com=sO:*\ -,mO:*\ \ ,exO:*/"
FileType autocommands recognize ".bak", ".orig" and "~" extensions and remove
them to find the relevant extension.
The tutorial for writing a Vim script file has been extended.
Some more highlighting in help files, for items that are not typed literally.
Can use "CTRL-W CTRL-G" like "CTRL-W g".
"make test" for OS/2.
Adjusted configure to automatically use the GUI for BeOS.
Fixed *fixed-5.4*
5.3.1: When using an autocommand for BufWritePre that changes the name of the
buffer, freed memory would be used. (Geddes)
Mac: Compiler didn't understand start of skip_class_name().
Win32 GUI:
- When cancelling the font requester, don't give an error message.
- When a tearoff-menu is open and its menu is deleted, Vim could crash.
(Negri)
- There was a problem on Windows 95 with (un)maximizing the window.
(Williams)
- when 'mousehide' is set, the mouse would stay hidden when a menu is dropped
with the keyboard. (Ralston)
- The tempname() function already created the file. Caused problems when
using ":w". Now the file is deleted.
- Cursor disappeared when ending up in the top-left character on the screen
after scrolling. (Webb)
- When adding a submenu for a torn-off menu, it was not updated.
- Menu tooltip was using the toolbar tooltip. (Negri)
- Setting 'notitle' didn't remove the title. (Steed)
- Using ":!start cmd" scrolled the screen one line up, and didn't wait for
return when the command wasn't found.
Cscope interface: Sorting of matches was wrong. Starting the interface could
fail. (Kahn)
Motif GUI: Could not compile with Motif 1.1, because some tear-off
functionality was not in #ifdefs.
Configure could sometimes not compile or link the test program for sizeof(int)
properly. This caused alignment problems for the undo structure allocations.
Added a safety check that SIZEOF_INT is not zero.
Added configure check to test if strings.h can be included after string.h.
Some systems can't handle it.
Some systems need both string.h and strings.h included. Adjusted vim.h for
that. Removed including string.h from os_unixx.h, since it's already in
vim.h. (Savage)
AIX: defining _NO_PROTO in os_unix.h causes a conflict between string.h and
strings.h, but after the configure check said it was OK. Also define
_NO_PROTO for AIX in the configure check. (Winn)
When closing a window with CTRL-W c, the value of 'hidden' was not taken into
account, the buffer was always unloaded. (Negri)
Unix Makefile: "make install" always tried to rename an older executable and
remove it. This caused an error message when it didn't exit. Added a check
for the existence of an old executable.
The command line for "make install" could get too long, because of the many
syntax files. Now first do a "cd" to reduce the length.
On RISCOS and MSDOS, reading a file could fail, because the short filename was
used, which can be wrong after a ":!cd".
In the DOS versions, the wrong install.exe was included (required Windows).
Now the install.exe version is included that is the same as the Vim version.
This also supports long file names where possible.
When recording, and stopping while in Insert mode with CTRL-O q, the CTRL-O
would also be recorded.
32bit DOS version: "vim \file", while in a subdirectory, resulted in "new
file" for "file" in the local directory, while "\file" did exist. When
"file" in the current directory existed, this didn't happen.
MSDOS: Mouse could not go beyond 80 columns in 132 columns mode. (Young)
"make test" failed in the RedHat RPM, because compatible is off by default.
In Insert mode <C-O><C-W><C-W> changes to other window, but the status bars
were not updated until another character was typed.
MSDOS: environment options in lowercase didn't work, although they did in the
Win32 versions. (Negri)
After ":nohlsearch", a tag command switched highlighting back on.
When using "append" command as the last line in an autocommand, Vim would
crash.
RISCOS: The scroll bumpers (?) were not working properly. (Leonard)
"zl" and "zh" could move the cursor, but this didn't set the column in which
e.g., "k" would move the cursor.
When doing ":set all&" the value of 'scroll' was not set correctly. This
caused an error message when later setting any other number option.
When 'hlsearch' highlighting has been disabled with ":nohlsearch",
incremental searching would switch it back on too early.
When listing tags for ":tselect", and using a non-search command, and the last
character was equal to the first (e.g., "99"), the last char would not be
shown.
When searching for tags with ":tag" Vim would assume that all matches had been
found when there were still more (e.g. from another tags file).
Win32: Didn't recognize "c:\" (e.g., in tags file) as absolute path when
upper/lowercase was different.
Some xterms (Debian) send <Esc>OH for HOME and <Esc>OF for END. Added these
to the builtin-xterm.
In ex mode, any CR was seen as the end of the line. Only a NL should be
handled that way. broke ":s/foo/some^Mtext/".
In menu.vim, a vmenu was used to override an amenu. That didn't work, because
the system menu file doesn't overwrite existing menus. Added explicit vunmenu
to solve this.
Configure check for terminal library could find a library that doesn't work at
runtime (Solaris: shared library not found). Added a check that a program
with tgoto() can run correctly.
Unix: "echo -n" in the Makefile doesn't work on all systems, causing errors
compiling pathdef.c. Replaced it with "tr".
Perl: DO_JOIN was redefined by Perl. Undefined it in the perl files.
Various XIM and multi-byte fixes:
- Fix user cannot see his language while he is typing his language with
off-the-spot method. (Nagano)
- Fix preedit position using text/edit area (using gui.wid). (Nagano)
- remove 'fix dead key' codes. It was needed since XNFocusWindow was
"x11_window", XNFocusWindow is now gui.wid. (Nagano)
- Remove some compile warnings and fix typos. (Namsh)
- For status area, check the gtk+ version while Vim runs. I believe it is
better than compile time check. (Namsh)
- Remove one FIXME for gtk+-xim. (Namsh)
- XIM: Dead keys didn't work for Czech. (Vyskovsky)
- Multibyte: If user input only 3byte such as mb1 mb2 eng or eng mb1 mb2 VIM
(Peters)
GUI: When checking for a ".gvimrc" file in the current directory, didn't check
for a "_gvimrc" file too.
Motif GUI: When using the popup menu and then adding an item to the menu bar,
the menu bar would get very high.
Mouse clicks and special keys (e.g. cursor keys) quit the more prompt and
dialogs. Now they are ignored.
When at the more-prompt, xterm selection didn't work. Now use the 'r' flag in
'mouse' also for the more-prompt.
When selecting a Visual area of more than 1023 lines, with 'guioptions' set to
"a", could mess up the display because of a message in free_yank(). Removed
that message, except for the Amiga.
Moved auto-selection from ui_write() to the screen update functions. Avoids
unexpected behavior from a low-level function. Also makes the different
feedback of owning the selection possible.
Vi incompatibility: Using "i<CR>" in an indent, with 'ai' set, used the
original indent instead of truncating it at the cursor. (Webb)
":echo x" didn't stop at "q" for the more prompt.
Various fixes for Macintosh. (St-Amant)
When using 'selectmode' set to "exclusive", selecting a word and then using
CTRL-] included the character under the cursor.
Using ":let a:name" in a function caused a crash. (Webb)
When using ":append", an empty line didn't scroll up.
DOS etc.: A file name starting with '!' didn't work. Added '!' to default for
'isfname'.
BeOS: Compilation problem with prototype of skip_class_name(). (Price)
When deleting more than one line, e.g., with "de", could still use "U"
command, which didn't work properly then.
Amiga: Could not compile ex_docmd.c, it was getting too big. Moved some
functions to ex_cmds.c.
The expand() function would add a trailing slash for directories.
Didn't give an error message when trying to assign a value to an argument of a
function. (Webb)
Moved including sys/ptem.h to after termios.h. Needed for Sinix.
OLE interface: Don't delete the object in CVimCF::Release() when the reference
count becomes zero. (Cordell)
VisVim could still crash on exit. (Erhardt)
"case a: case b:" (two case statements in one line) aligned with the second
case. Now it uses one 'sw' for indent. (Webb)
Font initialisation wasn't right for Athena/Motif GUI. Moved the call to
highlight_gui_started() gui_mch_init() to gui_mch_open(). (Nam)
In Replace mode, backspacing over a TAB before where the replace mode started
while 'sts' is different from 'ts', would delete the TAB.
Win32 console: When executing external commands and switching between the two
console screens, Vim would copy the text between the buffers. That caused the
screen to be messed up for backtick expansion.
":winpos -1" then ":winpos" gave wrong error message.
Windows commander creates files called c:\tmp\$wc\abc.txt. Don't remove the
backslash before the $. Environment variables were not expanded anyway,
because of the backslash before the dollar.
Using "-=" with ":set" could remove half a part when it contains a "\,".
E.g., ":set path+=a\\,b" and then "set path-=b" removed ",b".
When Visually selecting lines, with 'selection' set to "inclusive", including
the last char of the line, "<<" moved an extra line. Also for other operators
that always work on lines.
link.sh changed "-lnsl_s" to "_s" when looking for "nsl" to be removed.
Now it only remove whole words.
When jumped to a mark or using "fz", and there is an error, the current column
was lost. E.g. when using "$fzj".
The "g CTRL-G" command could not be interrupted, even though it can take a
long time.
Some terminals do have <F4> and <xF4>. <xF4> was always interpreted as <F4>.
Now map <xF4> to <F4>, so that the user can override this.
When compiling os_win32.c with MIN_FEAT the apply_autocmds() should not be
used. (Aaron)
This autocommand looped forever: ":au FileChangedShell * nested e <afile>"
Now FileChangeShell never nests. (Roemer)
When evaluating an ":elseif" that was not going to matter anyway, ignore
errors. (Roemer)
GUI Lesstif: Tearoff bar was the last item, instead of the first.
GUI Motif: Colors of tear-off widgets was wrong when 't' flag added to
'guioptions' afterwards. When 't' flag in 'guioptions' is excluded, would
still get a tearoff item in a new menu.
An inode number can be "long long". Use ino_t instead of long. Added
configure check for ino_t.
Binary search for tags was using a file offset "long" instead of "off_t".
Insert mode completion of tags was not using 'ignorecase' properly.
In Insert mode, the <xFn> keys were not properly mapped to <Fn> for the
default mappings. Also caused errors for ":mkvimrc" and ":mksession".
When jumping to another window while in Insert mode, would get the "warning:
changing readonly file" even when not making a change.
A '(' or '{' inside a trailing "//" comment would disturb C-indenting.
When using two labels below each other, the second one was not indented
properly. Comments could mess up C-indenting in many places. (Roemer)
Could delete or redefine a function while it was being used. Could cause a
crash.
In a function it's logical to prepend "g:" to a system variable, but this
didn't work. (Roemer)
Hangul input: Buffer would overflow when user inputs invalid key sequence.
(Nam)
When BufLoad or BufEnter autocommands change the topline of the buffer in the
window, it was overruled and the cursor put halfway the window. Now only put
the cursor halfway if the autocommands didn't change the topline.
Calling exists("&option") always returned 1. (Roemer)
Win32: Didn't take actually available memory into account. (Williams)
White space after an automatically inserted comment leader was not removed
when 'ai' is not set and <CR> hit just after inserting it. (Webb)
A few menus had duplicated accelerators. (Roemer)
Spelling errors in documentation, quite a few "the the". (Roemer)
Missing prototypes for Macintosh. (Kielhorn)
Win32: When using 'shellquote' or 'shellxquote', the "!start cmd" wasn't
executed in a disconnected process.
When resizing the window, causing a line before the cursor to wrap or unwrap,
the cursor was displayed in the wrong position.
There was quite a bit of dead code when compiling with minimal features.
When doing a ":%s///" command that makes lines shorter, such that lines above
the final cursor position no longer wrap, the cursor position was not updated.
get_id_list() could allocate an array one too small, when a "contains=" item
has a wildcard that matches a group name that is added just after it. E.g.:
"contains=a.*b,axb". Give an error message for it.
When yanking a Visual area and using the middle mouse button -> crash. When
clipboard doesn't work, now make "* always use "".
Win32: Using ":buf a\ b\file" didn't work, it was interpreted as "ab\file".
Using ":ts ident", then hit <CR>, with 'cmdheight' set to 2: command line was
not cleared, the tselect prompt was on the last but one line.
mksession didn't restore the cursor column properly when it was after a tab.
Could not get all windows back when using a smaller terminal screen. Didn't
restore all windows when "winsize" was not in 'sessionoptions'. (Webb)
Command line completion for ":buffer" depended on 'ignorecase' for Unix, but
not for DOS et al.. Now don't use 'ignorecase', but let it depend on whether
file names are case sensitive or not (like when expanding file names).
Win32 GUI: (Negri)
- Redrawing the background caused flicker when resizing the window. Removed
_OnEraseBG(). Removed CS_HREDRAW and CS_VREDRAW flags from the
sndclass.style.
- Some parts of the window were drawn in grey, instead of using the color from
the user color scheme.
- Dropping a file on gvim didn't activate the window.
- When there is no menu ('guioptions' excludes 'm'), never use the ALT key for
it.
GUI: When resizing the window, would make the window height a bit smaller.
Now round off to the nearest char cell size. (Negri)
In Vi the ")" and "(" commands don't stop at a single space after a dot.
Added 'J' flag in 'cpoptions' to make this behave Vi compatible. (Roemer)
When saving a session without any buffers loaded, there would be a ":normal"
command without arguments in it. (Webb)
Memory leaks fixed: (Madsen)
- eval.c: forgot to release func structure when func deleted
- ex_docmd.c: forgot to release string after "<sfile>"
- misc1.c: leak when completion pattern had no matches.
- os_unix.c: forgot to release regexp after file completions
Could crash when using a buffer without a name. (Madsen)
Could crash when doing file name completion, because of backslash_halve().
(Madsen)
":@a" would do mappings on register a, which is not Vi compatible. (Roemer)
":g/foo.*()/s/foobar/_&/gc" worked fine, but then "n" searched for "foobar"
and displayed "/foo.*()". (Roemer)
OS/2: get_cmd_output() was not included. Didn't check for $VIM/.vimrc file.
Command line completion of options didn't work after "+=" and "-=".
Unix configure: Test for memmove()/bcopy()/memcpy() tried redefining these
functions, which could fail if they are defined already. Use mch_memmove() to
redefine.
Unix: ":let a = expand("`xterm`&")" started an xterm asynchronously, but
":let a = expand("`xterm&`")" generated an error message, because the
redirection was put after the '&'.
Win32 GUI: Dialog buttons could not be selected properly with cursor keys,
when the default is not the first button. (Webb)
The "File has changed since editing started" (when regaining focus) could not
always be seen. (Webb)
When starting with "ex filename", the file message was overwritten with
the "entering Ex mode" message.
Output of ":tselect" listed name of file directly from the tags file. Now it
is corrected for the position of the tags file.
When 'backspace' is 0, could backspace over autoindent. Now it is no longer
When using the ":edit" command to re-edit the same file, an autocommand to
jump to the last cursor position caused the cursor to move. Now set the last
used cursor position to avoid this.
When 'comments' has a part that starts with white space, formatting the
comment didn't work.
At the ":tselect" prompt Normal mode mappings were used. That has been
disabled.
When 'selection' is not "old", some commands still didn't allow the cursor
past the end-of-line in Visual mode.
Athena: When a menu was deleted, it would appear again (but not functional)
when adding another menu. Now they don't reappear anymore (although they are
not really deleted either).
Borland C++ 4.x had an optimizer problem in fill_breakat_flags(). (Negri)
"ze" didn't work when 'number' was on. (Davis)
Win32 GUI: Intellimouse code didn't work properly on Windows 98. (Robinson)
A few files were including proto.h a second time, after vim.h had already done
that, which could cause problems with the vim_realloc() macro.
Win32 console: <M-x> or ALT-x was not recognized. Also keypad '+', '-' and
'*'. (Negri)
MS-DOS: <M-x> didn't work, produced a two-byte code. Now the alphabetic and
number keys work. (Negri)
When finding a lot of matches for a tag completion, the check for avoiding
double matches could take a lot of time. Add a line_breakcheck() to be able
to interrupt this. (Deshpande)
When the command line was getting longer than the screen, the more-prompt
would be given regularly, and the cursor position would be wrong. Now only
show the part of the command line that fits on the screen and force the cursor
to be positioned on the visible part. There can be text after the cursor
which isn't editable.
At the more prompt and with the console dialog, a cursor key was interpreted
as <Esc> and OA. Now recognize special keys in get_keystroke(). Ignore mouse
and scrollbar events.
When typing a BS after inserting a middle comment leader, typing the last char
of the end comment leader still changed it into the end comment leader. (Webb)
When a file system is full, writing to a swap file failed. Now first try to
write one block to the file. Try next entry in 'dir' if it fails.
When "~" is in 'whichwrap', doing "~" on last char of a line didn't update the
display.
Unix: Expanding wildcards for ":file {\\}" didn't work, because "\}" was
translated to "}" before the shell got it. Now don't remove backslashes when
wildcards are going to be expanded.
Unix: ":e /tmp/$uid" didn't work. When expanding environment variables in a
file name doesn't work, use the shell to expand the file name. ":e /tmp/$tty"
still doesn't work though.
"make test" didn't always work on DOS/Windows for test30, because it depended
on the external "echo" command.
The link.sh script used "make" instead of $MAKE from the Makefile. Caused
problems for generating pathdef.c when "make" doesn't work properly.
On versions that can do console and GUI: In the console a typed CSI code could
cause trouble.
The patterns in expression evaluation didn't ignore the 'l' flag in
'cpoptions'. This broke the working of <CR> in the options window.
When 'hls' off and 'ai' on, "O<Esc>" did remove the indent, but it was still
highlighted red for trailing space.
Win32 GUI: Dropping an encrypted file on a running gvim didn't work right. Vim
would loop while outputting "*" characters. vgetc() was called recursively,
thus it returns NUL. Added safe vgetc(), which reads input directly from the
Patch 5.4m.21
Problem: When starting up, the screen structures were first allocated at
the minimal size, then initializations were done with Rows
possibly different from screen_Rows. Caused a crash in rare
situations (GTK with XIM and fontset).
Solution: Call screenalloc() in main() only after calling ui_get_winsize().
Also avoids a potential delay because of calling screenclear()
while "starting" is non-zero.
Files: src/main.c
Patch 5.4m.22
Problem: In the GUI it was possible that the screen was resized and the
screen structures re-allocated while redrawing the screen. This
could cause a crash (hard to reproduce). The call sequence goes
through update_screen() .. syntax_start() .. ui_breakcheck() ..
gui_resize_window() .. screenalloc().
Solution: Set updating_screen while redrawing. If the window is resized
remember the new size and handle it only after redrawing is
finished.
This also fixes that resizing the screen while still redrawing
(slow syntax highlighting) would not work properly.
Also disable display_hint, it was never used.
Files: src/globals.h, src/gui.c, src/screen.c, src/proto/gui.pro
Patch 5.4m.23
Problem: When using expand("<cword>") when there was no word under the
cursor, would get an error message. Same for <cWORD> and <cfile>.
Solution: Don't give an error message, return an empty string.
Files: src/eval.c
Patch 5.4m.24
Problem: ":help \|" didn't find anything. It was translated to "/\\|".
Solution: Translate "\|" into "\\bar". First check the table for specific
translations before checking for "\x".
Files: src/ex_cmds.c
Patch 5.4m.25
Problem: Unix: When using command line completion on files that contain
''', '"'' or '|' the file name could not be used.
Adding this file name to the Buffers menu caused an error message.
Solution: Insert a backslash before these three characters.
Adjust Mungename() function to insert a backslash before '|'.
Files: src/ex_getln.c, runtime/menu.vim
Patch 5.4m.26
Problem: When using a mapping of two function keys, e.g., <F1><F1>, and
only the first char of the second key has been read, the mapping
would not be recognized. Noticed on some Unix systems with xterm.
Solution: Add 'K' flag to 'cpoptions' to wait for the whole key code, even
when halfway a mapping.
Files: src/option.h, src/term.c
Patch 5.4m.27
Problem: When making test33 without the lisp feature it hangs. Interrupting
the execution of the script then might cause a crash.
Solution: In inchar(), after closing a script, don't use buf[] anymore.
closescript() has freed typebuf[] and buf[] might be pointing
inside typebuf[].
Avoid that test33 hangs when the lisp feature is missing.
Files: src/getchar.c src/testdir/test33.in
"os2" was missing from the feature list. Useful for has("os2").
BeOS:
- Included patches from Richard Offer for BeOS R4.5.
- menu code didn't work right. Crashed in the Buffers menu. The window title
wasn't set. (Offer)
Patch 5.4n.3
Problem: C-indenting was wrong after " } else". The white space was not
skipped. Visible when 'cino' has "+10".
Solution: Skip white space before calling cin_iselse(). (Norbert Zeh)
Files: src/misc1.c
Patch 5.4n.4
Problem: When the 't' flag in 'cpoptions' is included, after a
":nohlsearch" the search highlighting would not be enabled again
after a tag search. (Norbert Zeh)
Solution: When setting the new search pattern in jumpto_tag(), don't restore
no_hlsearch.
Files: src/tag.c
Patch 5.4n.5
Problem: When using ":normal" from a CursorHold autocommand Vim hangs. The
autocommand is executed down from vgetc(). Calling vgetc()
recursively to execute the command doesn't work then.
Solution: Forbid the use of ":normal" when vgetc_busy is set. Give an error
message when this happens.
Files: src/ex_docmd.c, runtime/doc/autocmd.txt
Patch 5.4n.6
Problem: "gv" could reselect a Visual that starts and/or ends past the end
of a line. (Robert Webb)
Solution: Check that the start and end of the Visual area are on a valid
character by calling adjust_cursor().
Files: src/normal.c
Patch 5.4n.8
Problem: When a mark was on a non existing line (e.g., when the .viminfo
was edited), jumping to it caused ml_get errors. (Alexey
Marinichev).
Solution: Added check_cursor_lnum() in nv_gomark().
Files: src/normal.c
Patch 5.4n.9
Problem: ":-2" moved the cursor to a negative line number. (Ralf Schandl)
Solution: Give an error message for a negative line number.
Files: src/ex_docmd.c
Patch 5.4n.10
Problem: Win32 GUI: At the hit-enter prompt, it was possible to scroll the
text. This erased the prompt and made Vim look like it is in
Normal mode, while it is actually still waiting for a <CR>.
Solution: Disallow scrolling at the hit-enter prompt for systems that use
on the fly scrolling.
Files: src/message.c
Patch 5.4n.14
Problem: Win32 GUI: When using ":winsize 80 46" and the height is more than
what fits on the screen, the window size was made smaller than
asked for (that's OK) and Vim crashed (that's not OK)>
Solution: Call check_winsize() from gui_set_winsize() to resize the windows.
Files: src/gui.c
Patch 5.4n.16
Problem: Win32 GUI: The <F10> key both selected the menu and was handled as
a key hit.
Solution: Apply 'winaltkeys' to <F10>, like it is used for Alt keys.
Files: src/gui_w32.c
Patch 5.4n.17
Problem: Local buffer variables were freed when the buffer is unloaded.
That's not logical, since options are not freed. (Ron Aaron)
Solution: Free local buffer variables only when deleting the buffer.
Files: src/buffer.c
Patch 5.4n.19
Problem: Doing ":e" (without argument) in an option-window causes trouble.
The mappings for <CR> and <Space> are not removed. When there is
another buffer loaded, the swap file for it gets mixed up.
(Steve Mueller)
Solution: Also remove the mappings at the BufUnload event, if they are still
present.
When re-editing the same file causes the current buffer to be
deleted, don't try editing it.
Also added a test for this situation.
Files: runtime/optwin.vim, src/ex_cmds.c, src/testdir/test13.in,
src/testdir/test13.ok
Patch 5.4n.24
Problem: BeOS: configure never enabled the GUI, because $with_x was "no".
Unix prototypes caused problems, because Display and Widget are
undefined.
Freeing fonts on exit caused a crash.
Solution: Only disable the GUI when $with_x is "no" and $BEOS is not "yes".
Add dummy defines for Display and Widget in proto.h.
Don't free the fonts in gui_exit() for BeOS.
Files: src/configure.in, src/configure, src/proto.h, src/gui.c.
Patch 5.4o.2
Problem: Crash when using "gf" on "file.c://comment here". (Scott Graham)
Solution: Fix wrong use of pointers in get_file_name_in_path().
Files: src/window.c
Patch 5.4o.3
Problem: The horizontal scrollbar was not sized correctly when 'number' is
set and 'wrap' not set.
Athena: Horizontal scrollbar wasn't updated when the cursor was
positioned with a mouse click just after dragging.
Solution: Subtract 8 from the size when 'number' set and 'wrap' not set.
Reset gui.dragged_sb when a mouse click is received.
Files: src/gui.c
Patch 5.4o.4
Problem: When running in an xterm and $WINDOWID is set to an illegal value,
Vim would exit with "Vim: Got X error".
Solution: When using the display which was opened for the xterm clipboard,
check if x11_window is valid by trying to obtain the window title.
Also add a check in setup_xterm_clip(), for when using X calls to
get the pointer position in an xterm.
Files: src/os_unix.c
Patch 5.4o.5
Problem: Motif version with Lesstif: When removing the menubar and then
using a menu shortcut key, Vim would crash. (raf)
Solution: Disable the menu mnemonics when the menu bar is removed.
Files: src/gui_motif.c
Patch 5.4o.9
Problem: The DOS install.exe program used the "move" program. That doesn't
work on Windows NT, where "move" is internal to cmd.exe.
Solution: Don't use an external program for moving the executables. Use C
functions to copy the file and delete the original.
Files: src/dosinst.c
Motif and Athena obtained the status area height differently from GTK. Moved
status_area_enabled from global.h to gui_x11.c and call
xim_get_status_area_height() to get the status area height.
Patch 5.4p.1
Problem: When using auto-select, and the "gv" command is used, would not
always obtain ownership of the selection. Caused by the Visual
area still being the same, but ownership taken away by another
program.
Solution: Reset the clipboard Visual mode to force updating the selection.
Files: src/normal.c
Patch 5.4p.2
Problem: Motif and Athena with XIM: Typing 3-byte
<multibyte><multibyte><space> doesn't work correctly with Ami XIM.
Solution: Avoid using key_sym XK_VoidSymbol. (Nam)
Files: src/multbyte.c, src/gui_x11.c
Patch 5.4p.4
Problem: Win32 GUI: The scrollbar values were reduced for a file with more
than 32767 lines. But this info was kept global for all
scrollbars, causing a mixup between the windows.
Changed *changed-5.5*
The DJGPP version is now compiled with "-O2" instead of "-O4" to reduce the
size of the executables.
Moved the src/STYLE file to runtime/doc/develop.txt. Added the design goals
to it.
Added *added-5.5*
Included Exuberant Ctags version 3.3. (Darren Hiebert)
In runtime/mswin.vim, map CTRL-Q to CTRL-V, so that CTRL-Q can be used
everywhere to do what CTRL-V used to do.
Support for decompression of bzip2 files in vimrc_example.vim.
When a patch is included, the patch number is entered in a table in version.c.
This allows skipping a patch without breaking a next one.
Support for mouse scroll wheel in X11. See patch 5.5a.14.
line2byte() can be used to get the size of the buffer. See patch 5.4.35.
The CTRL-R CTRL-O r and CTRL-R CTRL-P r commands in Insert mode are used to
insert a register literally. See patch 5.4.48.
Uninstall program for MS-Windows. To be able to remove the registry entries
for "Edit with Vim". It is registered to be run from the "Add/Remove
programs" application. See patch 5.4.x7.
Fixed *fixed-5.5*
When using vimrc_example.vim: An error message when the cursor is on a line
higher than the number of lines in the compressed file. Move the autocommand
for jumping to the last known cursor position to after the decompressing
autocommands.
":mkexrc" and ":mksession" wrote the current value of 'textmode'. That may
mark a file as modified, which causes problems. This is a buffer-specific
setting, it should not affect all files.
"vim --version" wrote two empty lines.
Unix: The alarm signal could kill Vim. It is generated by the Perl alarm()
function. Ignore SIGALRM.
Win32 GUI: Toolbar still had the yellow bitmap for running a Vim script.
BeOS: "tmo" must be bigtime_t, instead of double. (Seibert)
Patch 5.4.1
Problem: Test11 fails when $GZIP is set to "-v". (Matthew Jackson)
Solution: Set $GZIP to an empty string.
Files: src/testdir/test11.in
Patch 5.4.2
Problem: Typing <Esc> at the crypt key prompt caused a crash. (Kallingal)
Solution: Check for a NULL pointer returned from get_crypt_key().
Files: src/fileio.c
Patch 5.4.3
Problem: Python: Trying to use the name of an unnamed buffer caused a
crash. (Daniel Burrows)
Solution: Check for b_fname being a NULL pointer.
Files: src/if_python.c
Patch 5.4.4
Problem: Win32: When compiled without toolbar, but the 'T' flag is in
'guioptions', there would be an empty space for the toolbar.
Solution: Add two #ifdefs where checking for the 'T' flag. (Vince Negri)
Files: src/gui.c
Patch 5.4.5
Problem: Athena GUI: Using the Buffers.Refresh menu entry caused a crash.
Looks like any ":unmenu" command may cause trouble.
Solution: Disallow ":unmenu" in the Athena version. Disable the Buffers
menu, because the Refresh item would not work.
Files: src/menu.c, runtime/menu.vim
Patch 5.4.6
Problem: GTK GUI: Using ":gui" in the .gvimrc file caused an error. Only
Patch 5.4.19
Problem: In a terminal with 25 lines, there is a more prompt after the
ATTENTION message. When hitting 'q' here the dialog prompt
doesn't appear and file loading is interrupted. (Will Day)
Solution: Don't allow quitting the printing of a message for the dialog
prompt. Added the msg_noquit_more flag for this.
Files: src/message.c
Patch 5.4.20
Problem: GTK: When starting gvim, would send escape sequences to the
terminal to switch the cursor off and on.
Solution: Don't call msg_start() if the GUI is expected to start.
Files: src/main.c
Patch 5.4.21
Problem: Motif: Toplevel menu ordering was wrong when using tear-off items.
Solution: Don't add one to the index for a toplevel menu.
Files: src/gui_motif.c
Patch 5.4.22
Problem: In Insert mode, <C-Left>, <S-Left>, <C-Right> and <S-Right> didn't
update the column used for vertical movement.
Solution: Set curwin->w_set_curswant for those commands.
Files: src/edit.c
Patch 5.4.23
Problem: When a Visual selection is lost to another program, and then the
same text is Visually selected again, the clipboard ownership
wasn't regained.
Solution: Set clipboard.vmode to NUL to force regaining the clipboard.
Files: src/normal.c
Patch 5.4.24
Problem: Encryption: When using ":r file" while 'key' has already entered,
the 'key' option would be messed up. When writing the file it
would be encrypted with an unknown key and lost! (Brad Despres)
Solution: Don't free cryptkey when it is equal to the 'key' option.
Files: src/fileio.c
Patch 5.4.25
Problem: When 'cindent' is set, but 'autoindent' isn't, comments are not
properly indented when starting a new line. (Mitterand)
Solution: When there is a comment leader for the new line, but 'autoindent'
isn't set, do C-indenting.
Files: src/misc1.c
Patch 5.4.26
Problem: Multi-byte: a multi-byte character is never recognized in a file
name, causing a backslash before it to be removed on Windows.
Solution: Assume that a leading-byte character is a file name character in
vim_isfilec().
Files: src/charset.c
Patch 5.4.27
Problem: Entries in the PopUp[nvic] menus were added for several modes, but
only deleted for the mode they were used for. This resulted in
the entry remaining in the PopUp menu.
When removing a PopUp[nvic] menu, the name had been truncated,
could result in greying-out the whole PopUp menu.
Solution: Remove entries for all modes from the PopUp[nvic] menus. Remove
the PopUp[nvic] menu entries first, before the name is changed.
Files: src/menu.c
Patch 5.4.28
Problem: When using a BufWritePre autocommand to change 'fileformat', the
new value would not be used for writing the file.
Solution: Check 'fileformat' after executing the autocommands instead of
before.
Files: src/fileio.c
Patch 5.4.29
Problem: Athena GUI: When removing the 'g' flag from 'guioptions', using a
menu can result in a crash.
Solution: Always grey-out menus for Athena, don't hide them.
Files: src/menu.c
Patch 5.4.30
Problem: BeOS: Suspending Vim with CTRL-Z didn't work (killed Vim). The
first character typed after ":sh" goes to Vim, instead of the
started shell.
Solution: Don't suspend Vim, start a new shell. Kill the async read thread
Files: src/ex_docmd.c
Patch 5.4.42
Problem: ":w" would also cause a truncated message to appear in the message
history.
Solution: Don't put a kept message in the message history when it starts
with "<".
Files: src/message.c
Patch 5.4.43 (depends on 5.4.37)
Problem: Mixing long lines with multiple lines in a register causes errors
when writing the viminfo file. (Robinson)
Solution: When reading the viminfo file to skip register contents, skip
lines that start with "<".
Files: src/ops.c
Patch 5.4.44
Problem: When 'whichwrap' includes '~', a "~" command that goes on to the
next line cannot be properly undone. (Zellner)
Solution: Save each line for undo in n_swapchar().
Files: src/normal.c
Patch 5.4.45 (also see 5.4.x8)
Problem: When expand("$ASDF") fails, there is an error message.
Solution: Remove the global expand_interactively. Pass a flag down to skip
the error message.
Also: expand("$ASDF") returns an empty string if $ASDF isn't set.
Previously it returned "$ASDF" when 'shell' is "sh".
Also: system() doesn't print an error when the command returns an
error code.
Files: many
Patch 5.4.46
Problem: Backspacing did not always use 'softtabstop' after hitting <CR>,
inserting a register, moving the cursor, etc.
Solution: Reset inserted_space much more often in edit().
Files: src/edit.c
Patch 5.4.47
Problem: When executing BufWritePre or BufWritePost autocommands for a
hidden buffer, the cursor could be moved to a non-existing
position. (Vince Negri)
Solution: Save and restore the cursor and topline for the current window
when it is going to be used to execute autocommands for a hidden
buffer. Use an existing window for the buffer when it's not
hidden.
Files: src/fileio.c
Patch 5.4.48
Problem: A paste with the mouse in Insert mode was not repeated exactly the
same with ".". For example, when 'autoindent' is set and pasting
text with leading indent. (Perry)
Solution: Add the CTRL-R CTRL-O r and CTRL-R CTRL-P r commands in Insert
mode, which insert the contents of a register literally.
Files: src/edit.c, src/normal.c, runtime/doc/insert.txt
Patch 5.4.49
Problem: When pasting text with [ <MiddleMouse>, the cursor could end up
after the last character of the line.
Solution: Correct the cursor position for the change in indent.
Files: src/ops.c
Patch 5.4.x1 (note: Replaces patch 5.4.9)
Problem: Win32 GUI: menu hints were never used, because WANT_MENU is not
defined until vim.h is included.
Solution: Move the #ifdef WANT_MENU from where MENUHINTS is defined to where
it is used.
Files: src/gui_w32.c
Patch 5.4.x2
Problem: BeOS: When pasting text, one character was moved to the end.
Solution: Re-enable the BeOS code in fill_input_buf(), and fix timing out
with acquire_sem_etc(). (Will Day)
Files: src/os_beos.c, src/ui.c
Patch 5.4.x3
Problem: Win32 GUI: When dropping a directory on a running gvim it crashes.
Solution: Avoid using a NULL file name. Also display a message to indicate
that the current directory was changed.
Files: src/gui_w32.c
Patch 5.4.x4
Problem: Win32 GUI: Removing an item from the popup menu doesn't work.
Solution: Don't remove the item from the menubar, but from the parent popup
menu.
Files: src/gui_w32.c
Patch 5.4.x5 (addition to 5.4.34)
Files: src/gui_w32.c
Patch 5.4.x6
Problem: Win32: Expanding (dir)name starting with a dot doesn't work.
(McCormack) Only when there is a path before it.
Solution: Fix the check, done before expansion, if the file name pattern
starts with a dot.
Files: src/os_win32.c
Patch 5.4.x7
Problem: Win32 GUI: Removing "Edit with Vim" from registry is difficult.
Solution: Add uninstall program to remove the registry keys. It is installed
in the "Add/Remove programs" list for ease of use.
Also: don't set $VIM when the executable is with the runtime files.
Also: Add a text file with a step-by-step description of how to
uninstall Vim for DOS and Windows.
Files: src/uninstal.c, src/dosinst.c, src/Makefile.w32, uninstal.txt
Patch 5.4.x8 (addition to 5.4.45)
Files: many
Patch 5.4.x9
Problem: Win32 GUI: After executing an external command, focus is not
always regained (when using focus-follows-mouse).
Solution: Add SetFocus() in mch_system(). (Mike Steed)
Files: src/os_win32.c
Patch 5.5a.1
Problem: ":let @* = @:" did not work. The text was not put on the
I clipboard. (Fisher)
Solution: Own the clipboard and put the text on it.
Files: src/ops.c
Patch 5.5a.2
Problem: append() did not mark the buffer modified. Marks below the
new line were not adjusted.
Solution: Fix the f_append() function.
Files: src/eval.c
Patch 5.5a.3
Problem: Editing compressed ".gz" files doesn't work on non-Unix systems,
because there is no "mv" command.
Solution: Add the rename() function and use it instead of ":!mv".
Also: Disable the automatic jump to the last position, because it
changes the jumplist.
Files: src/eval.c, runtime/doc/eval.txt, runtime/vimrc_example.vim
Patch 5.5a.4
Problem: When using whole-line completion in insert mode while the cursor
is in the indent, get "out of memory" error. (Stekrt)
Solution: Don't allocate a negative amount of memory in ins_complete().
Files: src/edit.c
Patch 5.5a.5
Problem: Win32: The 'path' option can hold only up to 256 characters,
because _MAX_PATH is 256. (Robert Webb)
Solution: Use a fixed path length of 1024.
Files: src/os_win32.h
Patch 5.5a.6
Problem: Compiling with gcc on Win32, using the Unix Makefile, didn't work.
Solution: Add $(SUFFIX) to all places where an executable is used. Also
pass it to ctags. (Reynolds)
Files: src/Makefile
Patch 5.5a.7
Problem: When using "cat | vim -" in an xterm, the xterm version reply
would end up in the file.
Solution: Read the file from stdin before switching the terminal to RAW
mode. Should also avoid problems with programs that use a
specific terminal setting.
Also: when using the GUI, print "Reading from stdin..." in the GUI
window, to give a hint why it doesn't do anything.
Changed *changed-5.6*
Small changes to OleVim files. (Christian Schaller)
Inserted "/**/" between patch numbers in src/version.c. This allows for one
line of context, which some versions of patch need.
Reordered the Syntax menu to avoid long submenus. Removed keyboard shortcuts
for alphabetical items to avoid a clash with fixed items.
Added *added-5.6*
Included Exuberant Ctags version 3.4. (Darren Hiebert)
OpenWithVim in Python. (Christian Schaller)
Win32 GUI: gvimext.dll, for the context menu "Edit with Vim" entry. Avoids
the reported problems with the MS Office taskbar. Now it's a Shell Extension.
(Tianmiao Hu)
New syntax files:
abel Abel (John Cook)
aml Arc Macro Language (Nikki Knuit)
apachestyle Apache-style config file (Christian Hammers)
cf Cold Fusion (Jeff Lanzarotta)
ctrlh files with CTRL-H sequences (Bram Moolenaar)
cupl CUPL (John Cook)
cuplsim CUPL simulation (John Cook)
erlang Erlang (Kresimir Marzic)
gedcom Gedcom (Paul Johnson)
icon Icon (Wendell Turner)
ist MakeIndex style (Peter Meszaros)
jsp Java Server Pages (Rafael Garcia-Suarez)
rcslog Rcslog (Joe Karthauser)
remind Remind (Davide Alberani)
sqr Structured Query Report Writer (Paul Moore)
tads TADS (Amir Karger)
texinfo Texinfo (Sandor Kopanyi)
xpm2 X Pixmap v2 (Steve Wall)
The 'C' flag in 'cpoptions' can be used to switch off concatenation for
sourced lines. See patch 5.5.013 below. |line-continuation|
"excludenl" argument for the ":syntax" command. See patch 5.5.032 below.
|:syn-excludenl|
Implemented |z+| and |z^| commands. See patch 5.5.050 below.
Vim logo in Corel Draw format. Can be scaled to any resolution.
Fixed *fixed-5.6*
Using this mapping in Select mode, terminated completion:
":vnoremap <C-N> <Esc>a<C-N>" (Benji Fisher)
Ignore K_SELECT in ins_compl_prep().
VMS (Zoltan Arpadffy, David Elins):
- ioctl() in pty.c caused trouble, #ifndef VMS added.
- Cut & paste mismatch corrected.
- Popup menu line crash corrected. (Patch 5.5.047)
- Motif directories during open and save as corrected.
- Handle full file names with version numbers. (Patch 5.5.046)
Patch 5.5.001
Problem: Configure in the top directory did not pass on an argument with a
space correctly. For example "./configure --previs="/My home".
(Stephane Chazelas)
Solution: Use '"'$@"' instead of '$*' to pass on the arguments.
Files: configure
Patch 5.5.002
Problem: Compilation error for using "fds[] & POLLIN". (Jeff Walker)
Solution: Use "fds[].revents & POLLIN".
Files: src/os_unix.c
Patch 5.5.003
Problem: The autoconf check for sizeof(int) is wrong on machines where
sizeof(size_t) != sizeof(int).
Solution: Use our own configure check. Also fixes the warning for
cross-compiling.
Files: src/configure.in, src/configure
Patch 5.5.004
Problem: On Unix it's not possible to interrupt ":sleep 100".
Solution: Switch terminal to cooked mode while asleep, to allow a SIGINT to
wake us up. But switch off echo, added TMODE_SLEEP.
Files: src/term.h, src/os_unix.c
Patch 5.5.005
Problem: When using <f-args> with a user command, an empty argument to the
command resulted in one empty string, while no string was
expected.
Solution: Catch an empty argument and pass no argument to the function.
(Paul Moore)
Files: src/ex_docmd.c
Patch 5.5.006
Problem: Python: When platform-dependent files are in another directory
than the platform-independent files it doesn't work.
Solution: Also check the executable directory, and add it to CFLAGS. (Tessa
Lau)
Files: src/configure.in, src/configure
Patch 5.5.007 (extra)
Problem: Win32 OLE: Occasional crash when exiting while still being used
via OLE.
Solution: Move OleUninitialize() to before deleting the application object.
(Vince Negri)
Files: src/if_ole.cpp
Patch 5.5.008
Problem: 10000@@ takes a long time and cannot be interrupted.
Solution: Check for CTRL-C typed while in the loop to push the register.
Files: src/normal.c
Patch 5.5.009
Problem: Recent Sequent machines don't link with "-linet". (Kurtis Rader)
Solution: Remove configure check for Sequent.
Files: src/configure.in, src/configure
Patch 5.5.010
Problem: Ctags freed a memory block twice when exiting. When out of
memory, a misleading error message was given.
Solution: Update to ctags 3.3.2. Also fixes a few other problems. (Darren
Hiebert)
Files: src/ctags/*
Patch 5.5.011
Problem: After "CTRL-V s", the cursor jumps back to the start, while all
other operators leave the cursor on the last changed character.
(Xiangjiang Ma)
Solution: Position cursor on last changed character, if possible.
Files: src/ops.c
Patch 5.5.012
Problem: Using CTRL-] in Visual mode doesn't work when the text includes a
space (just where it's useful). (Stefan Bittner)
Solution: Don't escape special characters in a tag name with a backslash.
Files: src/normal.c
Patch 5.5.013
Problem: The ":append" and ":insert" commands allow using a leading
backslash in a line. The ":source" command concatenates those
lines. (Heinlein)
Solution: Add the 'C' flag in 'cpoptions' to switch off concatenation.
Files: src/ex_docmd.c, src/option.h, runtime/doc/options.txt,
runtime/filetype.vim, runtime/scripts.vim
Patch 5.5.014
Problem: When executing a register with ":@", the ":append" command would
get text lines with a ':' prepended. (Heinlein)
Solution: Remove the ':' characters.
Files: src/ex_docmd.c, src/ex_getln.c, src/globals.h
Patch 5.5.015
Problem: When using ":g/pat/p", it's hard to see where the output starts,
the ":g" command is overwritten. Vi keeps the ":g" command.
Solution: Keep the ":g" command, but allow overwriting it with the report
for the number of changes.
Files: src/ex_cmds.c
Patch 5.5.016 (extra)
Problem: Win32: Using regedit to install Vim in the popup menu requires the
user to confirm this in a dialog.
Solution: Use "regedit /s" to avoid the dialog
Files: src/dosinst.c
Patch 5.5.017
Problem: If an error occurs when closing the current window, Vim could get
stuck in the error handling.
Solution: Don't set curwin to NULL when closing the current window.
Files: src/window.c
Patch 5.5.018
Problem: Absolute paths in shell scripts do not always work.
Solution: Use /usr/bin/env to find out the path.
Files: runtime/doc/vim2html.pl, runtime/tools/efm_filter.pl,
runtime/tools/shtags.pl
Patch 5.5.019
Problem: A function call in 'statusline' stops using ":q" twice from
exiting, when the last argument hasn't been edited.
Solution: Don't decrement quitmore when executing a function. (Madsen)
Files: src/ex_docmd.c
Patch 5.5.020
Problem: When the output of CTRL-D completion in the commandline goes all
the way to the last column, there is an empty line.
Solution: Don't add a newline when the cursor wrapped already. (Madsen)
Files: src/ex_getln.c
Patch 5.5.021
Problem: When checking if a file name in the tags file is relative,
environment variables were not expanded.
Solution: Expand the file name before checking if it is relative. (Madsen)
Files: src/tag.c
Patch 5.5.022
Problem: When setting or resetting 'paste' the ruler wasn't updated.
Solution: Update the status lines when 'ruler' changes because of 'paste'.
Files: src/option.c
Patch 5.5.023
Problem: When editing a new file and autocommands change the cursor
position, the cursor was moved back to the first non-white, unless
'startofline' was reset.
Solution: Keep the new column, just like the line number.
Files: src/ex_cmds.c
Patch 5.5.024 (extra)
Problem: Win32 GUI: When using confirm() to put up a dialog without a
default button, the dialog would not have keyboard focus.
(Krishna)
Solution: Always set focus to the dialog window. Only set focus to a button
when a default one is specified.
Files: src/gui_w32.c
Patch 5.5.025
Problem: When using "keepend" in a syntax region, a contained match that
includes the end-of-line could still force that region to
continue, if there is another contained match in between.
Solution: Check the keepend_level in check_state_ends().
Files: src/syntax.c
Patch 5.5.026
Problem: When starting Vim in a white-on-black xterm, with 'bg' set to
"dark", and then starting the GUI with ":gui", setting 'bg' to
"light" in the gvimrc, the highlighting isn't set. (Tsjokwing)
Solution: Set the highlighting when 'bg' is changed in the gvimrc, even
though full_screen isn't set.
Files: src/option.c
Patch 5.5.027
Problem: Unix: os_unix.c doesn't compile when XTERM_CLIP is used but
WANT_TITLE isn't. (Barnum)
Solution: Move a few functions that are used by the X11 title and clipboard
and put another "#if" around it.
Files: src/os_unix.c
Patch 5.5.028 (extra)
Problem: Win32 GUI: When a file is dropped on Win32 gvim while at the ":"
prompt, the file is edited but the command line is actually still
there, the cursor goes back to command line on the next command.
(Krishna)
Solution: When dropping a file or directory on gvim while at the ":" prompt,
insert the name of the file/directory. Allows using the
file/directory name for any Ex command.
Files: src/gui_w32.c
Patch 5.5.029
Problem: "das" at the end of the file didn't delete the last character of
the sentence.
Solution: When there is no character after the sentence, make the operation
inclusive in current_sent().
Files: src/search.c
Patch 5.5.030
Problem: Unix: in os_unix.c, "term_str" is used, which is also defined in
vim.h as a macro. (wuxin)
Solution: Renamed "term_str" to "buf" in do_xterm_trace().
Files: src/os_unix.c
Patch 5.5.031 (extra)
Problem: Win32 GUI: When exiting Windows, gvim will leave swap files behind
and will be killed ungracefully. (Krishna)
Solution: Catch the WM_QUERYENDSESSION and WM_ENDSESSION messages and try to
exit gracefully. Allow the user to cancel the shutdown if there
is a changed buffer.
Files: src/gui_w32.c
Patch 5.5.032
Problem: Patch 5.5.025 wasn't right. And C highlighting was still not
working correctly for a #define.
Solution: Added "excludenl" argument to ":syntax", to be able not to extend
a containing item when there is a match with the end-of-line.
Files: src/syntax.c, runtime/doc/syntax.txt, runtime/syntax/c.vim
Patch 5.5.033
Problem: When reading from stdin, a long line in viminfo would mess up the
file message. readfile() uses IObuff for keep_msg, which could be
overwritten by anyone.
Solution: Copy the message from IObuff to msg_buf and set keep_msg to that.
Also change vim fgets() to not use IObuff any longer.
Files: src/fileio.c
Patch 5.5.034
Problem: "gvim -rv" caused a crash. Using 't_Co' before it's set.
Solution: Don't try to initialize the highlighting before it has been
initialized from main().
Files: src/syntax.c
Patch 5.5.035
Problem: GTK with XIM: Resizing with status area was messy, and
":set guioptions+=b" didn't work.
Solution: Make status area a separate widget, but not a separate window.
(Chi-Deok Hwang)
Files: src/gui_gtk_f.c, src/gui_gtk_x11.c, src/multbyte.c
Patch 5.5.036
Problem: The GZIP_read() function in $VIMRUNTIME/vimrc_example.vim to
uncompress a file did not do detection for 'fileformat'. This is
because the filtering is done with 'binary' set.
Solution: Split the filtering into separate write, filter and read commands.
Files: runtime/vimrc_example.vim
Patch 5.5.037
Problem: The "U" command didn't mark the buffer as changed. (McCormack)
Solution: Set the 'modified' flag when using "U".
Files: src/undo.c
Patch 5.5.038
Problem: When typing a long ":" command, so that the screen scrolls up,
causes the hit-enter prompt, even though the user just typed
return to execute the command.
Solution: Reset need_wait_return if (part of) the command was typed in
getcmdline().
Files: src/ex_getln.c
Patch 5.5.039
Problem: When using a custom status line, "%a" (file # of #) reports the
index of the current window for all windows.
Solution: Pass a window pointer to append_arg_number(), and pass the window
being updated from build_stl_str_hl(). (Stephen P. Wall)
Files: src/buffer.c, src/screen.c, src/proto/buffer.pro
Patch 5.5.040
Problem: Multi-byte: When there is some error in xim_real_init(), it can
close XIM and return. After this there can be a segv.
Solution: Test "xic" for being non-NULL, don't set "xim" to NULL. Also try
to find more matches for supported styles. (Sung-Hyun Nam)
Files: src/multbyte.c
Patch 5.5.041
Problem: X11 GUI: CTRL-_ requires the SHIFT key only on some machines.
Solution: Translate CTRL-- to CTRL-_. (Robert Webb)
Files: src/gui_x11.c
Patch 5.5.042
Problem: X11 GUI: keys with ALT were assumed to be used for the menu, even
when the menu has been disabled by removing 'm' from 'guioptions'.
Solution: Ignore keys with ALT only when gui.menu_is_active is set. (Raf)
Files: src/gui_x11.c
Patch 5.5.043
Problem: GTK: Handling of fontset fonts was not right when 'guifontset'
contains exactly 14 times '-'.
Solution: Avoid setting fonts when working with a fontset. (Sung-Hyun Nam)
Files: src/gui_gtk_x11.c
Patch 5.5.044
Problem: pltags.pl contains an absolute path "/usr/local/bin/perl". That
might not work everywhere.
Solution: Use "/usr/bin/env perl" instead.
Files: runtime/tools/pltags.pl
Patch 5.5.045
Problem: Using "this_session" variable does not work, requires preceding it
with "v:". Default filename for ":mksession" isn't mentioned
in the docs. (Fisher)
Solution: Support using "this_session" to be backwards compatible.
Files: src/eval.c, runtime/doc/options.txt
Patch 5.5.046 (extra)
Problem: VMS: problems with path and filename.
Patch 5.5.059
Problem: GTK GUI: When $term is invalid, using "gvim" gives an error
message, even though $term isn't really used. (Robbins)
Solution: When the GUI is about to start, skip the error messages for a
wrong $term.
Files: src/term.c
Patch 5.5.060 (extra)
Problem: Dos 32 bit: When a directory in 'backupdir' doesn't exist, ":w"
causes the file to be renamed to "axlqwqhy.ba~". (Matzdorf)
Solution: The code to work around a LFN bug in Windows 95 doesn't handle a
non-existing target name correctly. When renaming fails, make
sure the file has its original name. Also do this for the Win32
version, although it's unlikely that it runs into this problem.
Files: src/os_msdos.c, src/os_win32.c
Patch 5.5.061
Problem: When using "\:" in a modeline, the backslash is included in the
option value. (Mohsin)
Solution: Remove one backslash before the ':' in a modeline.
Files: src/buffer.c, runtime/doc/options.txt
Patch 5.5.062 (extra)
Problem: Win32 console: Temp files are created in the root of the current
drive, which may be read-only. (Peterson)
Solution: Use the same mechanism of the GUI version: Use $TMP, $TEMP or the
current directory. Cleaned up vim_tempname() a bit.
Files: src/fileio.c, src/os_win32.h, runtime/doc/os_dos.txt
Patch 5.5.063
Problem: When using whole-line completion in Insert mode, 'cindent' is
applied, even after changing the indent of the line.
Solution: Don't reindent the completed line after inserting/removing indent.
(Robert Webb)
Files: src/edit.c
Patch 5.5.064
Problem: has("sniff") doesn't work correctly.
Solution: Return 1 when Vim was compiled with the +sniff feature. (Pruemmer)
Files: src/eval.c
Patch 5.5.065
Problem: When dropping a file on Vim, the 'shellslash' option is not
effective. (Krishna)
Solution: Fix the slashes in the dropped file names according to
'shellslash'.
Files: src/ex_docmd.c, runtime/doc/options.txt
Patch 5.5.066
Problem: For systems with backslash in file name: Setting a file name
option to a value starting with "\\machine" removed a backslash.
Solution: Keep the double backslash for "\\machine", but do change
"\\\\machine" to "\\machine" for backwards compatibility.
Files: src/option.c, runtime/doc/options.txt
Patch 5.5.067
Problem: With 'hlsearch' set, the pattern "\>" doesn't highlight the first
match in a line. (Benji Fisher)
Solution: Fix highlighting an empty match. Also highlight the first
character in an empty line for "$".
Files: src/screen.c
Patch 5.5.068
Problem: Crash when a ":while" is used with an argument that has an error.
(Sylvain Viart)
Solution: Was using an uninitialized index in the cs_line[] array. The
crash only happened when the index was far off. Made sure the
uninitialized index isn't used.
Files: src/ex_docmd.c
Patch 5.5.069
Problem: Shifting lines in blockwise Visual mode didn't set the 'modified'
flag.
Solution: Do set the 'modified' flag.
Files: src/ops.c
Patch 5.5.070
Problem: When editing a new file, creating that file outside of Vim, then
editing it again, ":w" still warns for overwriting an existing
file. (Nam)
Solution: The BF NEW flag in the "b flags" field wasn't cleared properly.
Patch 5.6a.010
Problem: In a function, ":startinsert!" does not append to the end of the
line if a ":normal" command was used to move the cursor. (Fisher)
Solution: Reset "w_set_curswant" to avoid that w_curswant is changed again.
Files: src/ex_docmd.c
Patch 5.6a.011 (depends on 5.6a.004)
Problem: A missing ":endif" or ":endwhile" in a function doesn't give an
error message.
Solution: Give that error message.
Files: src/ex_docmd.c
Patch 5.6a.012 (depends on 5.6a.008)
Problem: Some Syntax menu entries caused a hit-enter prompt.
Solution: Call a function to make the command shorter. Also rename a few
functions to avoid name clashes.
Files: runtime/menu.vim
Patch 5.6a.013
Problem: Command line completion works different when another completion
was done earlier. (Johannes Zellner)
Solution: Reset wim_index when starting a new completion.
Files: src/ex_getln.c
Patch 5.6a.014
Problem: Various warning messages when compiling and running lint with
different combinations of features.
Solution: Fix the warning messages.
Files: src/eval.c, src/ex_cmds.c, src/ex_docmd.c, src/gui_gtk_x11.c,
src/option.c, src/screen.c, src/search.c, src/syntax.c,
src/feature.h, src/globals.h
Patch 5.6a.015
Problem: The vimtutor command doesn't always know the value of $VIMRUNTIME.
Solution: Let Vim expand $VIMRUNTIME, instead of the shell.
Files: src/vimtutor
Patch 5.6a.016 (extra)
Problem: Mac: Window size is restricted when starting. Cannot drag the
window all over the desktop.
Solution: Get real screen size instead of assuming 640x400. Do not use a
fixed number for the drag limits. (Axel Kielhorn)
Files: src/gui_mac.c
Patch 5.6a.017
Problem: The "Paste" entry in popup menu for Visual, Insert and Cmdline
mode is in the wrong position. (Stol)
Solution: Add priority numbers for all Paste menu entries.
Files: runtime/menu.vim
Patch 5.6a.018
Problem: GTK GUI: submenu priority doesn't work.
Help dialog could be destroyed too soon.
When closing a dialog window (e.g. the "ATTENTION" one), Vim would
just hang.
When GTK theme is changed, Vim doesn't adjust to the new colors.
Argument for ":promptfind" isn't used.
Solution: Fixed the mentioned problems.
Made the dialogs look&feel nicer.
Moved functions to avoid the need for a forward declaration.
Fixed reentrancy of the file browser dialog.
Added drag&drop support for GNOME.
Init the text for the Find/replace dialog from the last used
search string. Set "match whole word" toggle button correctly.
Made repeat rate for drag outside of window depend on the
distance from the window. (Marcin Dalecki)
Made the drag in Visual mode actually work.
Removed recursiveness protection from gui_mch_get_rgb(), it might
cause more trouble than it solves.
Files: src/ex_docmd.c, src/gui_gtk.c, src/gui_gtk_x11.c, src/ui.c,
src/proto/ui.pro, src/misc2.c
Patch 5.6a.019
Problem: When trying to recover through NFS, which uses a large block size,
Vim might think the swap file is empty, because mf_blocknr_max is
zero. (Scott McDermott)
Solution: When computing the number of blocks of the file in mf_open(),
round up instead of down.
Files: src/memfile.c
Patch 5.6a.020
Changed *changed-5.7*
Renamed src/INSTALL.mac to INSTALL_mac.txt to avoid it being recognized with a
wrong file type. Also renamed src/INSTALL.amiga to INSTALL_ami.txt.
Added *added-5.7*
New syntax files:
stp Stored Procedures (Jeff Lanzarotta)
snnsnet, snnspat, snnsres SNNS (Davide Alberani)
mel MEL (Robert Minsk)
ruby Ruby (Mirko Nasato)
tli TealInfo (Kurt W. Andrews)
ora Oracle config file (Sandor Kopanyi)
abaqus Abaqus (Carl Osterwisch)
Fixed *fixed-5.7*
The 16 bit MS-DOS version is now compiled with Bcc 3.1 instead of 4.0. The
executable is smaller.
When a "make test" failed, the output file was lost. Rename it to
test99.failed to be able to see what went wrong.
After sourcing bugreport.vim, it's not clear that bugreport.txt has been
written in the current directory. Edit bugreport.txt to avoid that.
Adding IME support when using Makefile.w32 didn't work. (Taro Muraoka)
Win32 console: Mouse drags were passed on even when the mouse didn't move.
Perl interface: In Buffers(), type of argument to SvPV() was int, should be
STRLEN. (Tony Leneis)
Problem with prototype for index() on AIX 4.3.0. Added check for _AIX43 in
os_unix.h. (Jake Hamby)
Mappings in mswin.vim could break when some commands are mapped. Add "nore"
to most mappings to avoid re-mapping.
modify_fname() made a copy of a file name for ":p" when it already was a full
path name, which is a bit slow.
Win32 with Borland C++ 5.5: Pass the path to the compiler on to xxd and ctags,
to avoid depending on $PATH. Fixed "make clean".
Many fixes to Macintosh specific parts: (mostly by Dany StAmant)
- Only one Help menu.
- No more crash when removing a menu item.
- Support as External Editor for Codewarrior (still some little glitches).
- Popup menu support.
- Fixed crash when pasting after application switch.
- Color from rgb.txt properly displayed.
- 'isprint' default includes all chars above '~'. (Axel Kielhorn)
- mac_expandpath() was leaking memory.
- Add digraphs table. (Axel Kielhorn)
- Multi-byte support: (Kenichi Asai)
Switch keyscript when going in/out of Insert mode.
Draw multi-byte character correctly.
Don't use mblen() but highest bit of char to detect multi-byte char.
Display value of multi-byte in statusline (also for other systems).
- mouse button was not initialized properly to MOUSE_LEFT when
USE_CTRLCLICKMENU not defined.
- With Japanese SJIS characters: Make "w", "b", and "e" work
properly. (Kenichi Asai)
- Replaced old CodeWarrior file os_mac.CW9.hqx with os_mac.cw5.sit.hqx.
Fixes for VMS: (Zoltan Arpadffy) (also see patch 5.6.045 below)
- Added Makefile_vms.mms and vimrc.vms to src/testdir to be able to run the
tests.
- Various fixes.
Patch 5.6.025
Problem: GTK GUI: Starting the GUI could be interrupted by a SIGWINCH.
(Nils Lohner)
Solution: Repeat the read() call to get the gui_in_use value when
interrupted by a signal.
Files: src/gui.c
Patch 5.6.026 (extra)
Problem: Win32 GUI: Toolbar bitmaps are searched for in
$VIMRUNTIME/bitmaps, while GTK looks in $VIM/bitmaps. (Keith
Radebaugh)
Solution: Use $VIM/bitmaps for both, because these are not part of the
distribution but defined by the user.
Files: src/gui_w32.c, runtime/doc/gui.txt
Patch 5.6.027
Problem: TCL: Crash when using a Tcl script (reported for Win32).
Solution: Call Tcl_FindExecutable() in main(). (Brent Fulgham)
Files: src/main.c
Patch 5.6.028
Problem: Xterm patch level 126 sends codes for mouse scroll wheel.
Fully works with xterm patch level 131.
Solution: Recognize the codes for button 4 (0x60) and button 5 (0x61).
Files: src/term.c
Patch 5.6.029
Problem: GTK GUI: Shortcut keys cannot be used for a dialog. (Johannes
Zellner)
Solution: Add support for shortcut keys. (Marcin Dalecki)
Files: src/gui_gtk.c
Patch 5.6.030
Problem: When closing a window and 'ea' is set, Vim can crash. (Yasuhiro
Matsumoto)
Solution: Set "curbuf" to a valid value in win_close().
Files: src/window.c
Patch 5.6.031
Problem: Multi-byte: When a double-byte character ends in CSI, Vim waits
for another character to be typed.
Solution: Recognize the CSI as the second byte of a character and don't wait
for another one. (Yasuhiro Matsumoto)
Files: src/getchar.c
Patch 5.6.032
Problem: Functions with an argument that is a line number don't all accept
".", "$", etc. (Ralf Arens)
Solution: Add get_art_lnum() and use it for setline(), line2byte() and
synID().
Files: src/eval.c
Patch 5.6.033
Problem: Multi-byte: "f " sometimes skips to the second space. (Sung-Hyun
Nam)
Solution: Change logic in searchc() to skip trailing byte of a double-byte
character.
Also: Ask for second byte when searching for double-byte
character. (Park Chong-Dae)
Files: src/search.c
Patch 5.6.034 (extra)
Problem: Compiling with Borland C++ 5.5 fails on tolower() and toupper().
Solution: Use TO_LOWER() and TO_UPPER() instead. Also adjust the Makefile
to make using bcc 5.5 easier.
Files: src/edit.c, src/ex_docmd.c, src/misc1.c, src/Makefile.bor
Patch 5.6.035
Problem: Listing the"+comments" feature in the ":version" output depended
on the wrong ID. (Stephen P. Wall)
Solution: Change "CRYPTV" to "COMMENTS".
Files: src/version.c
Patch 5.6.036
Problem: GTK GUI: Copy/paste text doesn't work between gvim and Eterm.
Solution: Support TEXT and COMPOUND_TEXT selection targets. (ChiDeok Hwang)
Files: src/gui_gtk_x11.c
Patch 5.6.037
Problem: Multi-byte: Can't use "f" command with multi-byte character in GUI.
Solution: Enable XIM in Normal mode for the GUI. (Sung-Hyun Nam)
Patch 5.6.060
Problem: Some bold characters spill over to the cell on the left, that
spill-over can remain sometimes.
Solution: Redraw a character when the next character was bold and needs
redrawing. (Robert Webb)
Files: src/screen.c
Patch 5.6.061
Problem: When xterm sends 8-bit controls, recognizing the version response
doesn't work.
When using CSI instead of <Esc>[ for the termcap color codes,
using 16 colors doesn't work. (Neil Bird)
Solution: Also accept CSI in place of <Esc>[ for the version string.
Also check for CSI when handling colors 8-15 in term_color().
Use CSI for builtin xterm termcap entries when 'term' contains
"8bit".
Files: runtime/doc/term.txt, src/ex_cmds.c, src/option.c, src/term.c,
src/os_unix.c, src/proto/option.pro, src/proto/term.pro
Patch 5.6.062
Problem: The documentation says that setting 'smartindent' doesn't have an
effect when 'cindent' is set, but it does make a difference for
lines starting with "#". (Neil Bird)
Solution: Really ignore 'smartindent' when 'cindent' is set.
Files: src/misc1.c, src/ops.c
Patch 5.6.063
Problem: Using "I" in Visual-block mode doesn't accept a count. (Johannes
Zellner)
Solution: Pass the count on to do_insert() and edit(). (Allan Kelly)
Files: src/normal.c, src/ops.c, src/proto/ops.pro
Patch 5.6.064
Problem: MS-DOS and Win32 console: Mouse doesn't work correctly after
including patch 5.6.28. (Vince Negri)
Solution: Don't check for mouse scroll wheel when the mouse code contains
the number of clicks.
Files: src/term.c
Patch 5.6.065
Problem: After moving the cursor around in Insert mode, typing a space can
still trigger an abbreviation. (Benji Fisher)
Solution: Don't check for an abbreviation after moving around in Insert mode.
Files: src/edit.c
Patch 5.6.066
Problem: Still a few bold character spill-over remains after patch 60.
Solution: Clear character just in front of blanking out rest of the line.
(Robert Webb)
Files: src/screen.c
Patch 5.6.067
Problem: When a file name contains a NL, the viminfo file is corrupted.
Solution: Use viminfo_writestring() to convert the NL to CTRL-V n.
Also fix the Buffers menu and listing a menu name with a newline.
Files: runtime/menu.vim, src/buffer.c, src/mark.c, src/menu.c
Patch 5.6.068
Problem: Compiling the Perl interface doesn't work with Perl 5.6.0.
(Bernhard Rosenkraenzer)
Solution: Also check xs_apiversion for the version number when prepending
defines for PL_*.
Files: src/Makefile
Patch 5.6.069
Problem: "go" doesn't always end up at the right character when
'fileformat' is "dos". (Bruce DeVisser)
Solution: Correct computations in ml_find_line_or_offset().
Files: src/memline.
Patch 5.6.070 (depends on 5.6.068)
Problem: Compiling the Perl interface doesn't work with Perl 5.6.0.
(Bernhard Rosenkraenzer)
Solution: Simpler check instead of the one from patch 68.
Files: src/Makefile
Patch 5.6.071
Problem: "A" in Visual block mode on a Tab positions the cursor one char to
the right. (Michael Haumann)
Solution: Correct the column computation in op insert().
Files: src/ops.c
Patch 5.6.072
Problem: When starting Vim with "vim +startinsert", it enters Insert mode
only after typing the first command. (Andrew Pimlott)
Solution: Insert a dummy command in the stuff buffer.
Files: src/main.c
Patch 5.6.073 (extra) (depends on 5.6.034)
Problem: Win32 GUI: When compiled with Bcc 5.5 menus don't work.
In dosinst.c toupper() and tolower() give an "internal compiler
error" for Bcc 5.5.
Solution: Define WINVER to 4 to avoid compiling for Windows 2000. (Dan
Sharp) Also cleaned up compilation arguments.
Use our own implementation of toupper() in dosinst.c. Use
mytoupper() instead of tolower().
Files: src/Makefile.bor, src/dosinst.c
Patch 5.6.074 (extra)
Problem: Entering CSI directly doesn't always work, because it's recognized
as the start of a special key. Mostly a problem with multi-byte
in the GUI.
Solution: Use K_CSI for a typed CSI character. Use <CSI> for a normal CSI,
<xCSI> for a CSI typed in the GUI.
Files: runtime/doc/intro.txt, src/getchar.c, src/gui_amiga.c,
src/gui_gtk_x11.c, src/gui_mac.c, src/gui_riscos.c, src/gui_w32.c,
src/keymap.h, src/misc2.c
Patch 5.6.075
Problem: When using "I" or "A" in Visual block mode while 'sts' is set may
change spaces to a Tab the inserted text is not correct. (Mike
Steed) And some other problems when using "A" to append after the
end of the line.
Solution: Check for change in spaces/tabs after inserting the text. Append
spaces to fill the gap between the end-of-line and the right edge
of the block.
Files: src/ops.c
Patch 5.6.076
Problem: GTK GUI: Mapping <M-Space> doesn't work.
Solution: Don't use the "Alt" modifier twice in key_press_event().
Files: src/gui_gtk_x11.c
Patch 5.6.077
Problem: GUI: When interrupting an external program with CTRL-C, gvim might
crash. (Benjamin Korvemaker)
Solution: Avoid using a NULL pointer in ui_inchar_undo().
Files: src/ui.c
Patch 5.6.078
Problem: Locale doesn't always work on FreeBSD. (David O'Brien)
Solution: Link with the "xpg4" library when available.
Files: src/configure.in, src/configure
Patch 5.6.079
Problem: Vim could crash when several Tcl interpreters are created and
destroyed.
Solution: handle the "exit" command and nested ":tcl" commands better. (Ingo
Wilken)
Files: runtime/doc/if_tcl.txt, src/if_tcl.c
Patch 5.6.080
Problem: When jumping to a tag, generating the tags file and jumping to the
same tag again uses the old search pattern. (Sung-Hyun Nam)
Solution: Flush cached tag matches when executing an external command.
Files: src/misc2.c, src/proto/tag.pro, src/tag.c
Patch 5.6.081
Problem: ":syn include" uses a level for the included file, this confuses
contained items included at the same level.
Solution: Use a unique tag for each included file. Changed sp_syn_inc_lvl
to sp_syn_inc_tag. (Scott Bigham)
Files: src/syntax.c, src/structs.h
Patch 5.6.082
Problem: When using cscope, Vim can crash.
Solution: Initialize tag_fname in find_tags(). (Anton Blanchard)
Files: src/tag.c
Patch 5.6.083 (extra)
Problem: Win32: The visual beep can't be seen. (Eric Roesinger)
Solution: Flush the output before waiting with GdiFlush(). (Maurice S. Barnum)
Also: Allow specifying the delay in t_vb for the GUI.
Files: src/gui.c, src/gui_amiga.c, src/gui_gtk_x11.c, src/gui_mac.c,
src/gui_riscos.c, src/gui_w32.c, src/gui_x11.c, src/gui_beos.cc,
src/proto/gui_amiga.pro, src/proto/gui_gtk_x11.pro,
src/proto/gui_mac.pro, src/proto/gui_riscos.pro,
src/proto/gui_w32.pro, src/proto/gui_x11.pro,
src/proto/gui_beos.pro
Patch 5.6.084 (depends on 5.6.074)
Problem: GUI: Entering CSI doesn't always work for Athena and Motif.
Solution: Handle typed CSI as <xCSI> (forgot this bit in 5.6.074).
Files: src/gui_x11.c
Patch 5.6.085
Problem: Multi-byte: Using "r" to replace a double-byte char with a
single-byte char moved the cursor one character. (Matsumoto)
Also, using a count when replacing a single-byte char with a
double-byte char didn't work.
Solution: Don't use del_char() to delete the second byte.
Get "ptr" again after calling ins_char().
Files: src/normal.c
Patch 5.6.086 (extra)
Problem: Win32: When using libcall() and the returned value is not a valid
pointer, Vim crashes.
Solution: Use IsBadStringPtr() to check if the pointer is valid.
Files: src/os_win32.c
Patch 5.6.087
Problem: Multi-byte: Commands and messages with multi-byte characters are
displayed wrong.
Solution: Detect double-byte characters. (Yasuhiro Matsumoto)
Files: src/ex_getln.c, src/message.c, src/misc2.c, src/screen.c
Patch 5.6.088
Problem: Multi-byte with Motif or Athena: The message "XIM requires
fontset" is annoying when Vim was compiled with XIM support but it
is not being used.
Solution: Remove that message.
Files: src/multbyte.c
Patch 5.6.089
Problem: On non-Unix systems it's possible to overwrite a read-only file
without using "!".
Solution: Check if the file permissions allow overwriting before moving the
file to become the backup file.
Files: src/fileio.c
Patch 5.6.090
Problem: When editing a file in "/home/dir/home/dir" this was replaced with
"~~". (Andreas Jellinghaus)
Solution: Replace the home directory only once in home_replace().
Files: src/misc1.c
Patch 5.6.091
Problem: When editing many "no file" files, can't create swap file, because
.sw[a-p] have all been used. (Neil Bird)
Solution: Also use ".sv[a-z]", ".su[a-z]", etc.
Files: src/memline.c
Patch 5.6.092
Problem: FreeBSD: When setting $TERM to a non-valid terminal name, Vim
hangs in tputs().
Solution: After tgetent() returns an error code, call it again with the
terminal name "dumb". This apparently creates an environment in
which tputs() doesn't fail.
Files: src/term.c
Patch 5.6.093 (extra)
Problem: Win32 GUI: "ls | gvim -" will show a message box about reading
stdin when Vim exits. (Donohue)
Solution: Don't write a message about the file read from stdin until the GUI
has started.
Files: src/fileio.c
Patch 5.6.094
Problem: Problem with multi-byte string for ":echo var".
Solution: Check for length in msg_outtrans_len_attr(). (Sung-Hyun Nam)
Also make do_echo() aware of multi-byte characters.
Files: src/eval.c, src/message.c
Patch 5.6.095
Problem: With an Emacs TAGS file that include another a relative path
doesn't always work.
Solution: Use expand_tag_fname() on the name of the included file.
(Utz-Uwe Haus)
Files: src/tag.c
Patch 5.6.096
Problem: Unix: When editing many files, startup can be slow. (Paul
Ackersviller)
Solution: Halve the number of stat() calls used to add a file to the buffer
list.
Files: src/buffer.c
Patch 5.7a.001
Problem: GTK doesn't respond on drag&drop from ROX-Filer.
Solution: Add "text/uri-list" target. (Thomas Leonard)
Also: fix problem with checking for trash arguments.
Files: src/gui_gtk_x11.c
Patch 5.7a.002
Problem: Multi-byte: 'showmatch' is performed when second byte of an
inserted double-byte char is a paren or brace.
Solution: Check IsTrailByte() before calling showmatch(). (Taro Muraoka)
Files: src/misc1.c
Patch 5.7a.003
Problem: Multi-byte: After using CTRL-O in Insert mode with the cursor at
the end of the line on a multi-byte character the cursor moves to
the left.
Solution: Check for multi-byte character at end-of-line. (Taro Muraoka)
Also: fix cls() to detect a double-byte character. (Chong-Dae Park)
Files: src/edit.c, src/search.c
Patch 5.7a.004
Problem: When reporting the search pattern offset, the string could be
unterminated, which may cause a crash.
Solution: Terminate the string for the search offset. (Stephen P. Wall)
Files: src/search.c
Patch 5.7a.005
Problem: When ":s//~/" doesn't find a match it reports "[NULL]" for the
pattern.
Solution: Use get_search_pat() to obtain the actually used pattern.
Files: src/ex_cmds.c, src/proto/search.pro, src/search.c
Patch 5.7a.006 (extra)
Problem: VMS: Various problems, also with the VAXC compiler.
Solution: In many places use the Unix code for VMS too.
Added time, date and compiler version to version message.
(Zoltan Arpadffy)
Files: src/ex_cmds.c, src/ex_docmd.c, src/globals.h, src/gui_vms_conf.h,
src/main.c, src/message.c, src/misc1.c, src/os_vms.c,
src/os_vms.h, src/os_vms.mms, src/os_vms_conf.h,
src/proto/os_vms.pro, src/proto/version.pro, src/term.c,
src/version.c, src/xxd/os_vms.mms, src/xxd/xxd.c
Patch 5.7a.007
Problem: Motif and Athena GUI: CTRL-@ is interpreted as CTRL-C.
Solution: Only use "intr_char" when it has been set.
Files: src/gui_x11.c
Patch 5.7a.008
Problem: GTK GUI: When using CTRL-L the screen is redrawn twice, causing
trouble for bold characters. Also happens when moving with the
scrollbar. Best seen when 'writedelay' is non-zero.
When starting the GUI with ":gui" the screen is redrawn once with
the wrong colors.
Solution: Only set the geometry hints when the window size really changed.
This avoids setting it each time the scrollbar is forcefully
redrawn.
Don't redraw in expose_event() when gui.starting is still set.
Files: src/gui_gtk_x11.c
==============================================================================
VERSION 5.8 *version-5.8*
Changed *changed-5.8*
Ctags is no longer included with Vim. It has grown into a project of its own.
You can find it here: http://ctags.sf.net. It is highly recommended as a Vim
companion when you are writing programs.
Added *added-5.8*
New syntax files:
acedb AceDB (Stewart Morris)
aflex Aflex (Mathieu Clabaut)
antlr Antlr (Mathieu Clabaut)
asm68k 68000 Assembly (Steve Wall)
automake Automake (John Williams)
ayacc Ayacc (Mathieu Clabaut)
b B (Mathieu Clabaut)
bindzone BIND zone (glory hump)
blank Blank (Rafal Sulejman)
cfg Configure files (Igor Prischepoff)
changelog ChangeLog (Gediminas Paulauskas)
cl Clever (Phil Uren)
crontab Crontab (John Hoelzel)
csc Essbase script (Raul Segura Acevedo)
cynlib Cynlib(C++) (Phil Derrick)
cynpp Cyn++ (Phil Derrick)
debchangelog Debian Changelog (Wichert Akkerman)
debcontrol Debian Control (Wichert Akkerman)
dns DNS zone file (Jehsom)
dtml Zope's DTML (Jean Jordaan)
dylan Dylan, Dylan-intr and Dylan-lid (Brent Fulgham)
ecd Embedix Component Description (John Beppu)
fgl Informix 4GL (Rafal Sulejman)
foxpro FoxPro (Powing Tse)
gsp GNU Server Pages (Nathaniel Harward)
gtkrc GTK rc (David Necas)
hercules Hercules (Avant! Corporation) (Dana Edwards)
htmlos HTML/OS by Aestiva (Jason Rust)
inittab SysV process control (David Necas)
iss Inno Setup (Dominique Stephan)
jam Jam (Ralf Lemke)
jess Jess (Paul Baleme)
lprolog LambdaProlog (Markus Mottl)
ia64 Intel Itanium (parth malwankar)
kix Kixtart (Nigel Gibbs)
mgp MaGic Point (Gerfried Fuchs)
mason Mason (HTML with Perl) (Andrew Smith)
mma Mathematica (Wolfgang Waltenberger)
nqc Not Quite C (Stefan Scherer)
omnimark Omnimark (Paul Terray)
openroad OpenROAD (Luis Moreno Serrano)
named BIND configuration (glory hump)
papp PApp (Marc Lehmann)
pfmain Postfix main config (Peter Kelemen)
pic PIC assembly (Aleksandar Veselinovic)
ppwiz PPWizard (Stefan Schwarzer)
progress Progress (Phil Uren)
psf Product Specification File (Rex Barzee)
r R (Tom Payne)
registry MS-Windows registry (Dominique Stephan)
robots Robots.txt (Dominique Stephan)
rtf Rich Text Format (Dominique Stephan)
setl SETL (Alex Poylisher)
sgmldecl SGML Declarations (Daniel A. Molina W.)
sinda Sinda input (Adrian Nagle)
sindacmp Sinda compare (Adrian Nagle)
sindaout Sinda output (Adrian Nagle)
smith SMITH (Rafal Sulejman)
snobol4 Snobol 4 (Rafal Sulejman)
strace Strace (David Necas)
tak TAK input (Adrian Nagle)
takcmp TAK compare (Adrian Nagle)
takout TAK output (Adrian Nagle)
tasm Turbo assembly (FooLman)
texmf TeX configuration (David Necas)
Fixed *fixed-5.8*
Conversion of docs to HTML didn't convert "|tag|s" to a hyperlink.
Fixed compiling under NeXT. (Jeroen C.M. Goudswaard)
optwin.vim gave an error when used in Vi compatible mode ('cpo' contains 'C').
Tcl interpreter: "buffer" command didn't check for presence of an argument.
(Dave Bodenstab)
dosinst.c: Added checks for too long file name.
Amiga: a file name starting with a colon was considered absolute but it isn't.
Amiga: ":pwd" added a slash when in the root of a drive.
Macintosh: Warnings for unused variables. (Bernhard Pruemmer)
Unix: When catching a deadly signal, handle it in such a way that it's
unlikely that Vim will hang. Call _exit() instead of exit() in case of a
severe problem.
Setting the window title from nothing to something didn't work after patch 29.
Check for ownership of .exrc and .vimrc was done with stat(). Use lstat() as
well for extra security.
Win32 GUI: Printing a file with 'fileformat' "unix" didn't work. Set
'fileformat' to "dos" before writing the temp file.
Unix: Could start waiting for a character when checking for a CTRL-C typed
when an X event is received.
Could not use Perl and Python at the same time on FreeBSD, because Perl used
"-lc" and Python used the threaded C library.
Win32: The Mingw compiler gave a few warning messages.
When using "ZZ" and an autocommand for writing uses an abbreviation it didn't
work. Don't stuff the ":x" command but execute it directly. (Mikael Berthe)
VMS doesn't always have lstat(), added an #ifdef around it.
Added a few corrections for the Macintosh. (Axel Kielhorn)
Win32: Gvimext could not edit more than a few files at once, the length of the
argument was fixed.
Patch 5.7.002
Problem: When 'showmode' is set, using "CTRL-O :r file" waits three seconds
before displaying the read text. (Wichert Akkerman)
Solution: Set "keep_msg" to the file message so that the screen is redrawn
before the three seconds wait for displaying the mode message.
Files: src/fileio.c
Patch 5.7.003
Problem: Searching for "[[:cntrl:]]" doesn't work.
Solution: Exclude NUL from the matching characters, it terminates the list.
Files: src/regexp.c
Patch 5.7.004
Problem: GTK: When selecting a new font, Vim can crash.
Solution: In gui_mch_init_font() unreference the old font, not the new one.
Files: src/gui_gtk_x11.c
Patch 5.7.005
Problem: Multibyte: Inserting a wrapped line corrupts kterm screen.
Pasting TEXT/COMPOUND_TEXT into Vim does not work.
On Motif no XIM status line is displayed even though it is
available.
Solution: Don't use xterm trick for wrapping lines for multibyte mode.
Correct a missing "break", added TEXT/COMPOUND_TEXT selection
request.
Add XIMStatusArea fallback code.
(Katsuhito Nagano)
Files: src/gui_gtk_x11.c, src/multbyte.c, src/screen.c, src/ui.c
Patch 5.7.006
Problem: GUI: redrawing the non-Visual selection is wrong when the window
is unobscured. (Jean-Pierre Etienne)
Solution: Redraw the selection properly and don't clear it. Added "len"
argument to clip_may_redraw_selection().
Files: src/gui.c, src/ui.c, src/proto/ui.pro
Patch 5.7.007
Problem: Python: Crash when using the current buffer twice.
Solution: Increase the reference count for buffer and window objects.
(Johannes Zellner)
Files: src/if_python.c
Patch 5.7.008
Problem: In Ex mode, backspacing over the first TAB doesn't work properly.
(Wichert Akkerman)
Solution: Switch the cursor on before printing the newline.
Files: src/ex_getln.c
Patch 5.7.009 (extra)
Problem: Mac: Crash when using a long file.
Solution: Don't redefine malloc() and free(), because it will break using
realloc().
Files: src/os_mac.h
Patch 5.7.010
Problem: When using CTRL-A on a very long number Vim can crash. (Michael
Naumann)
Solution: Truncate the length of the new number to avoid a buffer overflow.
Files: src/ops.c
Patch 5.7.011 (extra)
Problem: Win32 GUI on NT 5 and Win98: Displaying Hebrew is reversed.
Solution: Output each character separately, to avoid that Windows reverses
the text for some fonts. (Ron Aaron)
Files: src/gui_w32.c
Patch 5.7.012
Problem: When using "-complete=buffer" for ":command" the user command
fails.
Solution: In a user command don't replace the buffer name with a count for
the buffer number.
Files: src/ex_docmd.c
Patch 5.7.013
Problem: "gD" didn't always find a match in the first line, depending on
the column the search started at.
Solution: Reset the column to zero before starting to search.
Files: src/normal.c
Patch 5.7.014
Scrolling *scrolling*
These commands move the contents of the window. If the cursor position is
moved off of the window, the cursor is moved onto the window (with
'scrolloff' screen lines around it). A page is the number of lines in the
window minus two. The mnemonics for these commands may be a bit confusing.
Remember that the commands refer to moving the window (the part of the buffer
that you see) upwards or downwards in the buffer. When the window moves
upwards in the buffer, the text in the window moves downwards on your screen.
See section |03.7| of the user manual for an introduction.
1. Scrolling downwards |scroll-down|
2. Scrolling upwards |scroll-up|
3. Scrolling relative to cursor |scroll-cursor|
4. Scrolling horizontally |scroll-horizontal|
5. Scrolling synchronously |scroll-binding|
6. Scrolling with a mouse wheel |scroll-mouse-wheel|
==============================================================================
1. Scrolling downwards *scroll-down*
The following commands move the edit window (the part of the buffer that you
see) downwards (this means that more lines downwards in the text buffer can be
seen):
*CTRL-E*
CTRL-E Scroll window [count] lines downwards in the buffer.
Mnemonic: Extra lines.
*CTRL-D*
CTRL-D Scroll window Downwards in the buffer. The number of
lines comes from the 'scroll' option (default: half a
screen). If [count] given, first set 'scroll' option
to [count]. The cursor is moved the same number of
lines down in the file (if possible; when lines wrap
and when hitting the end of the file there may be a
difference). When the cursor is on the last line of
the buffer nothing happens and a beep is produced.
See also 'startofline' option.
{difference from vi: Vim scrolls 'scroll' screen
lines, instead of file lines; makes a difference when
lines wrap}
*z+*
z+ Without [count]: Redraw with the line just below the
window at the top of the window. Put the cursor in
that line, at the first non-blank in the line.
With [count]: just like "z<CR>".
==============================================================================
2. Scrolling upwards *scroll-up*
The following commands move the edit window (the part of the buffer that you
see) upwards (this means that more lines upwards in the text buffer can be
seen):
*CTRL-Y*
CTRL-Y Scroll window [count] lines upwards in the buffer.
Note: When using the MS-Windows key bindings CTRL-Y is
remapped to redo.
*CTRL-U*
CTRL-U Scroll window Upwards in the buffer. The number of
lines comes from the 'scroll' option (default: half a
screen). If [count] given, first set the 'scroll'
option to [count]. The cursor is moved the same
number of lines up in the file (if possible; when
lines wrap and when hitting the end of the file there
may be a difference). When the cursor is on the first
line of the buffer nothing happens and a beep is
produced. See also 'startofline' option.
{difference from vi: Vim scrolls 'scroll' screen
lines, instead of file lines; makes a difference when
lines wrap}
*z^*
z^ Without [count]: Redraw with the line just above the
window at the bottom of the window. Put the cursor in
that line, at the first non-blank in the line.
With [count]: First scroll the text to put the [count]
line at the bottom of the window, then redraw with the
line which is now at the top of the window at the
bottom of the window. Put the cursor in that line, at
the first non-blank in the line.
==============================================================================
3. Scrolling relative to cursor *scroll-cursor*
The following commands reposition the edit window (the part of the buffer that
you see) while keeping the cursor on the same line:
*z<CR>*
z<CR> Redraw, line [count] at top of window (default
cursor line). Put cursor at first non-blank in the
line.
*zt*
zt Like "z<CR>", but leave the cursor in the same
column. {not in Vi}
*zN<CR>*
z{height}<CR> Redraw, make window {height} lines tall. This is
useful to make the number of lines small when screen
updating is very slow. Cannot make the height more
than the physical screen height.
*z.*
z. Redraw, line [count] at center of window (default
cursor line). Put cursor at first non-blank in the
line.
*zz*
zz Like "z.", but leave the cursor in the same column.
Careful: If caps-lock is on, this command becomes
"ZZ": write buffer and exit! {not in Vi}
*z-*
z- Redraw, line [count] at bottom of window (default
cursor line). Put cursor at first non-blank in the
line.
*zb*
zb Like "z-", but leave the cursor in the same column.
{not in Vi}
==============================================================================
4. Scrolling horizontally *scroll-horizontal*
For the following four commands the cursor follows the screen. If the
character that the cursor is on is moved off the screen, the cursor is moved
to the closest character that is on the screen. The value of 'sidescroll' is
not used.
*zL*
zL Move the view on the text half a screenwidth to the
right, thus scroll the text half a screenwidth to the
left. This only works when 'wrap' is off. {not in
Vi}
*zH*
zH Move the view on the text half a screenwidth to the
left, thus scroll the text half a screenwidth to the
right. This only works when 'wrap' is off. {not in
Vi}
For the following two commands the cursor is not moved in the text, only the
text scrolls on the screen.
*zs*
zs Scroll the text horizontally to position the cursor
at the start (left side) of the screen. This only
works when 'wrap' is off. {not in Vi}
*ze*
ze Scroll the text horizontally to position the cursor
at the end (right side) of the screen. This only
works when 'wrap' is off. {not in Vi}
==============================================================================
5. Scrolling synchronously *scroll-binding*
*scrollbind-relative*
Each 'scrollbind' window keeps track of its "relative offset," which can be
thought of as the difference between the current window's vertical scroll
position and the other window's vertical scroll position. When one of the
'scrollbind' windows is asked to vertically scroll past the beginning or end
limit of its text, the window no longer scrolls, but remembers how far past
the limit it wishes to be. The window keeps this information so that it can
maintain the same relative offset, regardless of its being asked to scroll
past its buffer's limits.
However, if a 'scrollbind' window that has a relative offset that is past its
buffer's limits is given the cursor focus, the other 'scrollbind' windows must
jump to a location where the current window's relative offset is valid. This
behavior can be changed by clearing the 'jump' flag from the 'scrollopt'
option.
*scrollbind-quickadj*
The 'scrollbind' flag is meaningful when using keyboard commands to vertically
scroll a window, and also meaningful when using the vertical scrollbar of the
window which has the cursor focus. However, when using the vertical scrollbar
of a window which doesn't have the cursor focus, 'scrollbind' is ignored.
This allows quick adjustment of the relative offset of 'scrollbind' windows.
==============================================================================
6. Scrolling with a mouse wheel *scroll-mouse-wheel*
When your mouse has a scroll wheel, it should work with Vim in the GUI. How
it works depends on your system. It might also work in an xterm
|xterm-mouse-wheel|. By default only vertical scroll wheels are supported,
but some GUIs also support horizontal scroll wheels.
For the Win32 GUI the scroll action is hard coded. It works just like
dragging the scrollbar of the current window. How many lines are scrolled
depends on your mouse driver. If the scroll action causes input focus
problems, see |intellimouse-wheel-problems|.
For the X11 GUIs (Motif, Athena and GTK) scrolling the wheel generates key
presses <ScrollWheelUp>, <ScrollWheelDown>, <ScrollWheelLeft> and
<ScrollWheelRight>. For example, if you push the scroll wheel upwards a
<ScrollWheelUp> key press is generated causing the window to scroll upwards
(while the text is actually moving downwards). The default action for these
keys are:
<ScrollWheelUp> scroll three lines up *<ScrollWheelUp>*
<S-ScrollWheelUp> scroll one page up *<S-ScrollWheelUp>*
<C-ScrollWheelUp> scroll one page up *<C-ScrollWheelUp>*
<ScrollWheelDown> scroll three lines down *<ScrollWheelDown>*
<S-ScrollWheelDown> scroll one page down *<S-ScrollWheelDown>*
<C-ScrollWheelDown> scroll one page down *<C-ScrollWheelDown>*
*<MouseDown>* *<MouseUp>*
The keys <MouseDown> and <MouseUp> have been deprecated. Use <ScrollWheelUp>
instead of <MouseDown> and use <ScrollWheelDown> instead of <MouseUp>.
*xterm-mouse-wheel*
To use the mouse wheel in a new xterm you only have to make the scroll wheel
work in your Xserver, as mentioned above.
To use the mouse wheel in an older xterm you must do this:
1. Make it work in your Xserver, as mentioned above.
2. Add translations for the xterm, so that the xterm will pass a scroll event
to Vim as an escape sequence.
3. Add mappings in Vim, to interpret the escape sequences as <ScrollWheelDown>
or <ScrollWheelUp> keys.
You can do the translations by adding this to your ~.Xdefaults file (or other
file where your X resources are kept):
XTerm*VT100.Translations: #override \n\
s<Btn4Down>: string("0x9b") string("[64~") \n\
s<Btn5Down>: string("0x9b") string("[65~") \n\
<Btn4Down>: string("0x9b") string("[62~") \n\
<Btn5Down>: string("0x9b") string("[63~") \n\
<Btn4Up>: \n\
<Btn5Up>:
Add these mappings to your vimrc file:
:map <M-Esc>[62~ <ScrollWheelUp>
:map! <M-Esc>[62~ <ScrollWheelUp>
:map <M-Esc>[63~ <ScrollWheelDown>
:map! <M-Esc>[63~ <ScrollWheelDown>
:map <M-Esc>[64~ <S-ScrollWheelUp>
:map! <M-Esc>[64~ <S-ScrollWheelUp>
:map <M-Esc>[65~ <S-ScrollWheelDown>
:map! <M-Esc>[65~ <S-ScrollWheelDown>
top - main help file
If the motion includes a count and the operator also had a count before it,
the two counts are multiplied. For example: "2d3w" deletes six words.
After applying the operator the cursor is mostly left at the start of the text
that was operated upon. For example, "yfe" doesn't move the cursor, but "yFe"
moves the cursor leftwards to the "e" where the yank started.
*linewise* *characterwise*
The operator either affects whole lines, or the characters between the start
and end position. Generally, motions that move between lines affect lines
(are linewise), and motions that move within a line affect characters (are
characterwise). However, there are some exceptions.
*exclusive* *inclusive*
A character motion is either inclusive or exclusive. When inclusive, the
start and end position of the motion are included in the operation. When
exclusive, the last character towards the end of the buffer is not included.
Linewise motions always include the start and end position.
Which motions are linewise, inclusive or exclusive is mentioned with the
command. There are however, two general exceptions:
1. If the motion is exclusive and the end of the motion is in column 1, the
end of the motion is moved to the end of the previous line and the motion
becomes inclusive. Example: "}" moves to the first line after a paragraph,
but "d}" will not include that line.
*exclusive-linewise*
2. If the motion is exclusive, the end of the motion is in column 1 and the
start of the motion was at or before the first non-blank in the line, the
motion becomes linewise. Example: If a paragraph begins with some blanks
and you do "d}" while standing on the first non-blank, all the lines of
the paragraph are deleted, including the blanks. If you do a put now, the
deleted lines will be inserted below the cursor position.
Note that when the operator is pending (the operator command is typed, but the
motion isn't yet), a special set of mappings can be used. See |:omap|.
Instead of first giving the operator and then a motion you can use Visual
mode: mark the start of the text with "v", move the cursor to the end of the
text that is to be affected and then hit the operator. The text between the
start and the cursor position is highlighted, so you can see what text will
be operated upon. This allows much more freedom, but requires more key
strokes and has limited redo functionality. See the chapter on Visual mode
|Visual-mode|.
You can use a ":" command for a motion. For example "d:call FindEnd()".
But this can't be redone with "." if the command is more than one line.
This can be repeated:
d:call search("f")<CR>
This cannot be repeated:
d:if 1<CR>
call search("f")<CR>
endif<CR>
*o_v*
v When used after an operator, before the motion command: Force
the operator to work characterwise, also when the motion is
linewise. If the motion was linewise, it will become
|exclusive|.
If the motion already was characterwise, toggle
inclusive/exclusive. This can be used to make an exclusive
*o_V*
V When used after an operator, before the motion command: Force
the operator to work linewise, also when the motion is
characterwise.
*o_CTRL-V*
CTRL-V When used after an operator, before the motion command: Force
the operator to work blockwise. This works like Visual block
mode selection, with the corners defined by the cursor
position before and after the motion.
==============================================================================
2. Left-right motions *left-right-motions*
These commands move the cursor to the specified column in the current line.
They stop at the first column and at the end of the line, except "$", which
may move to one of the next lines. See 'whichwrap' option to make some of the
commands move across line boundaries.
h or *h*
<Left> or *<Left>*
CTRL-H or *CTRL-H* *<BS>*
<BS> [count] characters to the left. |exclusive| motion.
Note: If you prefer <BS> to delete a character, use
the mapping:
:map CTRL-V<BS> X
(to enter "CTRL-V<BS>" type the CTRL-V key, followed
by the <BS> key)
See |:fixdel| if the <BS> key does not do what you
want.
l or *l*
<Right> or *<Right>* *<Space>*
<Space> [count] characters to the right. |exclusive| motion.
*0*
0 To the first character of the line. |exclusive|
motion.
*<Home>* *<kHome>*
<Home> To the first character of the line. |exclusive|
motion. When moving up or down next, stay in same
TEXT column (if possible). Most other commands stay
in the same SCREEN column. <Home> works like "1|",
which differs from "0" when the line starts with a
<Tab>. {not in Vi}
*^*
^ To the first non-blank character of the line.
|exclusive| motion.
*g_*
g_ To the last non-blank character of the line and
[count - 1] lines downward |inclusive|. {not in Vi}
*g0* *g<Home>*
g0 or g<Home> When lines wrap ('wrap' on): To the first character of
the screen line. |exclusive| motion. Differs from
"0" when a line is wider than the screen.
When lines don't wrap ('wrap' off): To the leftmost
character of the current line that is on the screen.
Differs from "0" when the first character of the line
is not on the screen. {not in Vi}
*g^*
g^ When lines wrap ('wrap' on): To the first non-blank
character of the screen line. |exclusive| motion.
Differs from "^" when a line is wider than the screen.
When lines don't wrap ('wrap' off): To the leftmost
non-blank character of the current line that is on the
screen. Differs from "^" when the first non-blank
character of the line is not on the screen. {not in
Vi}
*gm*
gm Like "g0", but half a screenwidth to the right (or as
much as possible). {not in Vi}
*g$* *g<End>*
g$ or g<End> When lines wrap ('wrap' on): To the last character of
the screen line and [count - 1] screen lines downward
|inclusive|. Differs from "$" when a line is wider
than the screen.
When lines don't wrap ('wrap' off): To the rightmost
character of the current line that is visible on the
screen. Differs from "$" when the last character of
the line is not on the screen or when a count is used.
Additionally, vertical movements keep the column,
instead of going to the end of the line.
{not in Vi}
*bar*
| To screen column [count] in the current line.
|exclusive| motion. Ceci n'est pas une pipe.
*f*
f{char} To [count]'th occurrence of {char} to the right. The
cursor is placed on {char} |inclusive|.
{char} can be entered as a digraph |digraph-arg|.
When 'encoding' is set to Unicode, composing
characters may be used, see |utf-8-char-arg|.
|:lmap| mappings apply to {char}. The CTRL-^ command
in Insert mode can be used to switch this on/off
|i_CTRL-^|.
*F*
F{char} To the [count]'th occurrence of {char} to the left.
The cursor is placed on {char} |exclusive|.
{char} can be entered like with the |f| command.
*t*
t{char} Till before [count]'th occurrence of {char} to the
right. The cursor is placed on the character left of
{char} |inclusive|.
{char} can be entered like with the |f| command.
*T*
T{char} Till after [count]'th occurrence of {char} to the
left. The cursor is placed on the character right of
{char} |exclusive|.
{char} can be entered like with the |f| command.
*;*
; Repeat latest f, t, F or T [count] times.
*,*
, Repeat latest f, t, F or T in opposite direction
[count] times.
==============================================================================
3. Up-down motions *up-down-motions*
k or *k*
<Up> or *<Up>* *CTRL-P*
CTRL-P [count] lines upward |linewise|.
j or *j*
<Down> or *<Down>*
CTRL-J or *CTRL-J*
<NL> or *<NL>* *CTRL-N*
CTRL-N [count] lines downward |linewise|.
gk or *gk* *g<Up>*
g<Up> [count] display lines upward. |exclusive| motion.
Differs from 'k' when lines wrap, and when used with
an operator, because it's not linewise. {not in Vi}
gj or *gj* *g<Down>*
g<Down> [count] display lines downward. |exclusive| motion.
Differs from 'j' when lines wrap, and when used with
an operator, because it's not linewise. {not in Vi}
*-*
- <minus> [count] lines upward, on the first non-blank
character |linewise|.
+ or *+*
CTRL-M or *CTRL-M* *<CR>*
<CR> [count] lines downward, on the first non-blank
character |linewise|.
*_*
_ <underscore> [count] - 1 lines downward, on the first non-blank
character |linewise|.
*G*
G Goto line [count], default last line, on the first
non-blank character |linewise|. If 'startofline' not
set, keep the same column.
G is a one of |jump-motions|.
*<C-End>*
<C-End> Goto line [count], default last line, on the last
character |inclusive|. {not in Vi}
*e*
e Forward to the end of word [count] |inclusive|.
Does not stop in an empty line.
*E*
E Forward to the end of WORD [count] |inclusive|.
Does not stop in an empty line.
*ge*
ge Backward to the end of word [count] |inclusive|.
*gE*
gE Backward to the end of WORD [count] |inclusive|.
These commands move over words or WORDS.
*word*
A word consists of a sequence of letters, digits and underscores, or a
sequence of other non-blank characters, separated with white space (spaces,
tabs, <EOL>). This can be changed with the 'iskeyword' option. An empty line
is also considered to be a word.
*WORD*
A WORD consists of a sequence of non-blank characters, separated with white
space. An empty line is also considered to be a WORD.
A sequence of folded lines is counted for one word of a single character.
"w" and "W", "e" and "E" move to the start/end of the first word or WORD after
a range of folded lines. "b" and "B" move to the start of the first word or
*(*
( [count] sentences backward. |exclusive| motion.
*)*
) [count] sentences forward. |exclusive| motion.
*{*
{ [count] paragraphs backward. |exclusive| motion.
*}*
} [count] paragraphs forward. |exclusive| motion.
*]]*
]] [count] sections forward or to the next '{' in the
first column. When used after an operator, then also
stops below a '}' in the first column. |exclusive|
Note that |exclusive-linewise| often applies.
*][*
][ [count] sections forward or to the next '}' in the
first column. |exclusive|
Note that |exclusive-linewise| often applies.
*[[*
[[ [count] sections backward or to the previous '{' in
the first column. |exclusive|
Note that |exclusive-linewise| often applies.
*[]*
[] [count] sections backward or to the previous '}' in
the first column. |exclusive|
Note that |exclusive-linewise| often applies.
These commands move over three kinds of text objects.
*sentence*
A sentence is defined as ending at a '.', '!' or '?' followed by either the
end of a line, or by a space or tab. Any number of closing ')', ']', '"''
and ''' characters may appear after the '.', '!' or '?' before the spaces,
tabs or end of line. A paragraph and section boundary is also a sentence
boundary.
If the 'J' flag is present in 'cpoptions', at least two spaces have to
follow the punctuation mark; <Tab>s are not recognized as white space.
The definition of a sentence cannot be changed.
*paragraph*
A paragraph begins after each empty line, and also at each of a set of
*section*
A section begins after a form-feed (<C-L>) in the first column and at each of
a set of section macros, specified by the pairs of characters in the
'sections' option. The default is "SHNHH HUnhsh", which defines a section to
start at the nroff macros ".SH", ".NH", ".H", ".HU", ".nh" and ".sh".
The "]" and "[" commands stop at the '{' or '}' in the first column. This is
useful to find the start or end of a function in a C program. Note that the
first character of the command determines the search direction and the
second character the type of brace found.
If your '{' or '}' are not in the first column, and you would like to use "[["
and "]]" anyway, try these mappings:
:map [[ ?{<CR>w99[{
:map ][ /}<CR>b99]}
:map ]] j0[[%/{<CR>
:map [] k$][%?}<CR>
[type these literally, see |<>|]
==============================================================================
6. Text object selection *object-select* *text-objects*
*v_a* *v_i*
This is a series of commands that can only be used while in Visual mode or
after an operator. The commands that start with "a" select "a"n object
including white space, the commands starting with "i" select an "inner" object
without white space, or just the white space. Thus the "inner" commands
always select less text than the "a" commands.
These commands are {not in Vi}.
These commands are not available when the |+textobjects| feature has been
disabled at compile time.
*v_aw* *aw*
aw "a word", select [count] words (see |word|).
Leading or trailing white space is included, but not
counted.
When used in Visual linewise mode "aw" switches to
Visual characterwise mode.
*v_iw* *iw*
iw "inner word", select [count] words (see |word|).
White space between words is counted too.
When used in Visual linewise mode "iw" switches to
Visual characterwise mode.
*v_aW* *aW*
aW "a WORD", select [count] WORDs (see |WORD|).
Leading or trailing white space is included, but not
counted.
When used in Visual linewise mode "aW" switches to
Visual characterwise mode.
*v_iW* *iW*
iW "inner WORD", select [count] WORDs (see |WORD|).
White space between words is counted too.
When used in Visual linewise mode "iW" switches to
Visual characterwise mode.
*v_as* *as*
as "a sentence", select [count] sentences (see
|sentence|).
When used in Visual mode it is made characterwise.
*v_is* *is*
is "inner sentence", select [count] sentences (see
|sentence|).
When used in Visual mode it is made characterwise.
*v_ap* *ap*
ap "a paragraph", select [count] paragraphs (see
|paragraph|).
Exception: a blank line (only containing white space)
is also a paragraph boundary.
When used in Visual mode it is made linewise.
*v_ip* *ip*
ip "inner paragraph", select [count] paragraphs (see
|paragraph|).
Exception: a blank line (only containing white space)
is also a paragraph boundary.
When used in Visual mode it is made linewise.
*v_at* *at*
at "a tag block", select [count] tag blocks, from the
[count]'th unmatched "<aaa>" backwards to the matching
"</aaa>", including the "<aaa>" and "</aaa>".
See |tag-blocks| about the details.
When used in Visual mode it is made characterwise.
*v_it* *it*
it "inner tag block", select [count] tag blocks, from the
[count]'th unmatched "<aaa>" backwards to the matching
"</aaa>", excluding the "<aaa>" and "</aaa>".
See |tag-blocks| about the details.
When used in Visual mode it is made characterwise.
For illustration, here is a list of delete commands, grouped from small to big
objects. Note that for a single character and a whole line the existing vi
movement commands are used.
"dl" delete character (alias: "x") |dl|
"diw" delete inner word *diw*
"daw" delete a word *daw*
"diW" delete inner WORD (see |WORD|) *diW*
"daW" delete a WORD (see |WORD|) *daW*
"dd" delete one line |dd|
"dis" delete inner sentence *dis*
"das" delete a sentence *das*
"dib" delete inner '(' ')' block *dib*
"dab" delete a '(' ')' block *dab*
"dip" delete inner paragraph *dip*
"dap" delete a paragraph *dap*
"diB" delete inner '{' '}' block *diB*
"daB" delete a '{' '}' block *daB*
Note the difference between using a movement command and an object. The
movement command operates from here (cursor position) to where the movement
takes us. When using an object the whole object is operated upon, no matter
where on the object the cursor is. For example, compare "dw" and "daw": "dw"
deletes from the cursor position to the start of the next word, "daw" deletes
the word under the cursor and the space after or before it.
*m'* *m`*
m' or m` Set the previous context mark. This can be jumped to
with the "''"' or "``" command (does not move the
*m[* *m]*
m[ or m] Set the |'[| or |']| mark. Useful when an operator is
to be simulated by multiple commands. (does not move
the cursor, this is not a motion command).
*:k*
:[range]k{a-zA-Z'} Same as :mark, but the space before the mark name can
be omitted.
*:marks*
:marks List all the current marks (not a motion command).
The |'(|, |')|, |'{| and |'}| marks are not listed.
The first column has number zero.
{not in Vi}
*E283*
:marks {arg} List the marks that are mentioned in {arg} (not a
motion command). For example:
:marks aB
to list marks 'a' and 'B'. {not in Vi}
*:delm* *:delmarks*
:delm[arks] {marks} Delete the specified marks. Marks that can be deleted
include A-Z and 0-9. You cannot delete the '' mark.
They can be specified by giving the list of mark
names, or with a range, separated with a dash. Spaces
are ignored. Examples:
:delmarks a deletes mark a
:delmarks a b 1 deletes marks a, b and 1
:delmarks Aa deletes marks A and a
:delmarks p-z deletes marks in the range p to z
:delmarks ^.[] deletes marks ^ . [ ]
:delmarks \" deletes mark "
{not in Vi}
:delm[arks]! Delete all marks for the current buffer, but not marks
A-Z or 0-9.
{not in Vi}
A mark is not visible in any way. It is just a position in the file that is
remembered. Do not confuse marks with named registers, they are totally
unrelated.
'a - 'z lowercase marks, valid within one file
'A - 'Z uppercase marks, also called file marks, valid between files
'0 - '9 numbered marks, set from .viminfo file
Lowercase marks 'a to 'z are remembered as long as the file remains in the
buffer list. If you remove the file from the buffer list, all its marks are
lost. If you delete a line that contains a mark, that mark is erased.
Lowercase marks can be used in combination with operators. For example: "d't"
deletes the lines from the cursor position to mark 't'. Hint: Use mark 't' for
Top, 'b' for Bottom, etc.. Lowercase marks are restored when using undo and
redo.
Uppercase marks 'A to 'Z include the file name. {Vi: no uppercase marks} You
can use them to jump from file to file. You can only use an uppercase mark
with an operator if the mark is in the current file. The line number of the
mark remains correct, even if you insert/delete lines or edit another file for
a moment. When the 'viminfo' option is not empty, uppercase marks are kept in
the .viminfo file. See |viminfo-file-marks|.
Numbered marks '0 to '9 are quite different. They can not be set directly.
They are only present when using a viminfo file |viminfo-file|. Basically '0
is the location of the cursor when you last exited Vim, '1 the last but one
time, etc. Use the "r" flag in 'viminfo' to specify files for which no
Numbered mark should be stored. See |viminfo-file-marks|.
*'[* *`[*
'[ `[ To the first character of the previously changed
or yanked text. {not in Vi}
*']* *`]*
'] `] To the last character of the previously changed or
yanked text. {not in Vi}
After executing an operator the Cursor is put at the beginning of the text
that was operated upon. After a put command ("p" or "P") the cursor is
sometimes placed at the first inserted line and sometimes on the last inserted
character. The four commands above put the cursor at either end. Example:
After yanking 10 lines you want to go to the last one of them: "10Y']". After
inserting several lines with the "p" command you want to jump to the lowest
inserted line: "p']". This also works for text that has been inserted.
Note: After deleting text, the start and end positions are the same, except
when using blockwise Visual mode. These commands do not work when no change
was made yet in the current file.
*'<* *`<*
'< `< To the first line or character of the last selected
Visual area in the current buffer. For block mode it
may also be the last character in the first line (to
be able to define the block). {not in Vi}.
*'>* *`>*
'> `> To the last line or character of the last selected
Visual area in the current buffer. For block mode it
may also be the first character of the last line (to
be able to define the block). Note that 'selection'
applies, the position may be just after the Visual
area. {not in Vi}.
*''* *``*
'' `` To the position before the latest jump, or where the
last "m'"' or "m`" command was given. Not set when the
|:keepjumps| command modifier was used.
Also see |restore-position|.
*'quote* *`quote*
'"' `" To the cursor position when last exiting the current
buffer. Defaults to the first character of the first
line. See |last-position-jump| for how to use this
for each opened file.
Only one position is remembered per buffer, not one
for each window. As long as the buffer is visible in
a window the position won't be changed.
{not in Vi}.
*'^* *`^*
'^ `^ To the position where the cursor was the last time
when Insert mode was stopped. This is used by the
|gi| command. Not set when the |:keepjumps| command
modifier was used. {not in Vi}
*'.* *`.*
'. `. To the position where the last change was made. The
position is at or near where the change started.
Sometimes a command is executed as several changes,
then the position can be near the end of what the
command changed. For example when inserting a word,
the position will be on the last character.
{not in Vi}
*'(* *`(*
'( `( To the start of the current sentence, like the |(|
command. {not in Vi}
*')* *`)*
') `) To the end of the current sentence, like the |)|
command. {not in Vi}
*'{* *`{*
'{ `{ To the start of the current paragraph, like the |{|
command. {not in Vi}
*'}* *`}*
'} `} To the end of the current paragraph, like the |}|
command. {not in Vi}
These commands are not marks themselves, but jump to a mark:
*]'*
]' [count] times to next line with a lowercase mark below
the cursor, on the first non-blank character in the
line. {not in Vi}
*]`*
]` [count] times to lowercase mark after the cursor. {not
in Vi}
*['*
[' [count] times to previous line with a lowercase mark
before the cursor, on the first non-blank character in
the line. {not in Vi}
*[`*
[` [count] times to lowercase mark before the cursor.
{not in Vi}
*:keepj* *:keepjumps*
:keepj[umps] {command}
Moving around in {command} does not change the |''|,
|'.| and |'^| marks, the |jumplist| or the
|changelist|.
Useful when making a change or inserting text
automatically and the user doesn't want to go to this
position. E.g., when updating a "Last change"
timestamp in the first line:
:let lnum = line(".")
:keepjumps normal gg
:call SetLastChange()
:keepjumps exe "normal " . lnum . "G"
Note that ":keepjumps" must be used for every command.
When invoking a function the commands in that function
can still change the jumplist. Also, for
":keepjumps exe 'command '"' the "command" won't keep
jumps. Instead use: ":exe 'keepjumps command'"'
==============================================================================
8. Jumps *jump-motions*
A "jump" is one of the following commands: "'"', "`", "G", "/", "?", "n",
"N", "%", "(", ")", "[[", "]]", "{", "}", ":s", ":tag", "L", "M", "H" and
the commands that start editing a new file. If you make the cursor "jump"
with one of these commands, the position of the cursor before the jump is
remembered. You can return to that position with the "''"' and "``" command,
unless the line containing that position was changed or deleted.
*CTRL-O*
CTRL-O Go to [count] Older cursor position in jump list
(not a motion command). {not in Vi}
{not available without the |+jumplist| feature}
*:ju* *:jumps*
:ju[mps] Print the jump list (not a motion command). {not in
Vi} {not available without the |+jumplist| feature}
*jumplist*
Jumps are remembered in a jump list. With the CTRL-O and CTRL-I command you
can go to cursor positions before older jumps, and back again. Thus you can
move up and down the list. There is a separate jump list for each window.
The maximum number of entries is fixed at 100.
{not available without the |+jumplist| feature}
For example, after three jump commands you have this jump list:
jump line col file/text
3 1 0 some text
2 70 0 another line
1 1154 23 end.
>
The "file/text" column shows the file name, or the text at the jump if it is
in the current file (an indent is removed and a long line is truncated to fit
in the window).
You are currently in line 1167. If you then use the CTRL-O command, the
cursor is put in line 1154. This results in:
jump line col file/text
2 1 0 some text
1 70 0 another line
> 0 1154 23 end.
1 1167 0 foo bar
The pointer will be set at the last used jump position. The next CTRL-O
command will use the entry above it, the next CTRL-I command will use the
entry below it. If the pointer is below the last entry, this indicates that
you did not use a CTRL-I or CTRL-O before. In this case the CTRL-O command
will cause the cursor position to be added to the jump list, so you can get
back to the position before the CTRL-O. In this case this is line 1167.
With more CTRL-O commands you will go to lines 70 and 1. If you use CTRL-I
you can go back to 1154 and 1167 again. Note that the number in the "jump"
column indicates the count for the CTRL-O or CTRL-I command that takes you to
this position.
If you use a jump command, the current line number is inserted at the end of
the jump list. If the same line was already in the jump list, it is removed.
The result is that when repeating CTRL-O you will get back to old positions
only once.
When the |:keepjumps| command modifier is used, jumps are not stored in the
jumplist. Jumps are also not stored in other cases, e.g., in a |:global|
command. You can explicitly add a jump by setting the '' mark.
After the CTRL-O command that got you into line 1154 you could give another
jump command (e.g., "G"). The jump list would then become:
jump line col file/text
4 1 0 some text
3 70 0 another line
2 1167 0 foo bar
1 1154 23 end.
>
The line numbers will be adjusted for deleted and inserted lines. This fails
if you stop editing a file without writing, like with ":n!".
When you split a window, the jumplist will be copied to the new window.
If you have included the '' item in the 'viminfo' option the jumplist will be
stored in the viminfo file and restored when starting Vim.
*g;* *E662*
g; Go to [count] older position in change list.
If [count] is larger than the number of older change
positions go to the oldest change.
If there is no older change an error message is given.
*g,* *E663*
g, Go to [count] newer cursor position in change list.
Just like |g;| but in the opposite direction.
(not a motion command)
{not in Vi}
{not available without the |+jumplist| feature}
When using a count you jump as far back or forward as possible. Thus you can
use "999g;" to go to the first change for which the position is still
remembered. The number of entries in the change list is fixed and is the same
as for the |jumplist|.
When two undo-able changes are in the same line and at a column position less
than 'textwidth' apart only the last one is remembered. This avoids that a
sequence of small changes in a line, for example "xxxxx", adds many positions
to the change list. When 'textwidth' is zero 'wrapmargin' is used. When that
also isn't set a fixed number of 79 is used. Detail: For the computations
bytes are used, not characters, to avoid a speed penalty (this only matters
for multi-byte encodings).
Note that when text has been inserted or deleted the cursor position might be
a bit different from the position of the change. Especially when lines have
been deleted.
When the |:keepjumps| command modifier is used the position of a change is not
remembered.
*:changes*
:changes Print the change list. A ">" character indicates the
current position. Just after a change it is below the
newest entry, indicating that "g;" takes you to the
newest entry position. The first column indicates the
count needed to take you to this position. Example:
change line col text
3 9 8 bla bla bla
2 11 57 foo is a bar
1 14 54 the latest changed line
>
The "3g;" command takes you to line 9. Then the
output of ":changes is:
change line col text
> 0 9 8 bla bla bla
1 11 57 foo is a bar
2 14 54 the latest changed line
Now you can use "g," to go to line 11 and "2g," to go
to line 14.
==============================================================================
9. Various motions *various-motions*
*%*
% Find the next item in this line after or under the
cursor and jump to its match. |inclusive| motion.
Items can be:
([{}]) parenthesis or (curly/square) brackets
(this can be changed with the
'matchpairs' option)
/* */ start or end of C-style comment
#if, #ifdef, #else, #elif, #endif
C preprocessor conditionals (when the
cursor is on the # or no ([{
following)
For other items the matchit plugin can be used, see
|matchit-install|. This plugin also helps to skip
matches in comments.
When 'cpoptions' contains "M" |cpo-M| backslashes
before parens and braces are ignored. Without "M" the
*[(*
[( go to [count] previous unmatched '('.
|exclusive| motion. {not in Vi}
*[{*
[{ go to [count] previous unmatched '{'.
|exclusive| motion. {not in Vi}
*])*
]) go to [count] next unmatched ')'.
|exclusive| motion. {not in Vi}
*]}*
]} go to [count] next unmatched '}'.
|exclusive| motion. {not in Vi}
The above four commands can be used to go to the start or end of the current
code block. It is like doing "%" on the '(', ')', '{' or '}' at the other
end of the code block, but you can do this from anywhere in the code block.
Very useful for C programs. Example: When standing on "case x:", "[{" will
bring you back to the switch statement.
*]m*
]m Go to [count] next start of a method (for Java or
similar structured language). When not before the
start of a method, jump to the start or end of the
class. When no '{' is found after the cursor, this is
an error. |exclusive| motion. {not in Vi}
*]M*
]M Go to [count] next end of a method (for Java or
similar structured language). When not before the end
of a method, jump to the start or end of the class.
When no '}' is found after the cursor, this is an
error. |exclusive| motion. {not in Vi}
*[m*
[m Go to [count] previous start of a method (for Java or
similar structured language). When not after the
start of a method, jump to the start or end of the
class. When no '{' is found before the cursor this is
an error. |exclusive| motion. {not in Vi}
*[M*
[M Go to [count] previous end of a method (for Java or
similar structured language). When not after the
end of a method, jump to the start or end of the
class. When no '}' is found before the cursor this is
an error. |exclusive| motion. {not in Vi}
The above two commands assume that the file contains a class with methods.
The class definition is surrounded in '{' and '}'. Each method in the class
is also surrounded with '{' and '}'. This applies to the Java language. The
file looks like this:
// comment
class foo {
int method_one() {
body_one();
}
int method_two() {
body_two();
}
}
Starting with the cursor on "body_two()", using "[m" will jump to the '{' at
the start of "method_two()" (obviously this is much more useful when the
method is long!). Using "2[m" will jump to the start of "method_one()".
Using "3[m" will jump to the start of the class.
*[#*
[# go to [count] previous unmatched "#if" or "#else".
|exclusive| motion. {not in Vi}
*]#*
]# go to [count] next unmatched "#else" or "#endif".
|exclusive| motion. {not in Vi}
These two commands work in C programs that contain #if/#else/#endif
constructs. It brings you to the start or end of the #if/#else/#endif where
the current line is included. You can then use "%" to go to the matching line.
*[star* *[/*
[* or [/ go to [count] previous start of a C comment "/*".
|exclusive| motion. {not in Vi}
*]star* *]/*
]* or ]/ go to [count] next end of a C comment "*/".
|exclusive| motion. {not in Vi}
*H*
H To line [count] from top (Home) of window (default:
first line on the window) on the first non-blank
character |linewise|. See also 'startofline' option.
Cursor is adjusted for 'scrolloff' option.
*M*
M To Middle line of window, on the first non-blank
character |linewise|. See also 'startofline' option.
*L*
L To line [count] from bottom of window (default: Last
line on the window) on the first non-blank character
|linewise|. See also 'startofline' option.
Cursor is adjusted for 'scrolloff' option.
<LeftMouse> Moves to the position on the screen where the mouse
click is |exclusive|. See also |<LeftMouse>|. If the
position is in a status line, that window is made the
active window and the cursor is not moved. {not in Vi}
top - main help file
*:dig* *:digraphs*
:dig[raphs] show currently defined digraphs.
*E104* *E39*
:dig[raphs] {char1}{char2} {number} ...
Add digraph {char1}{char2} to the list. {number} is
the decimal representation of the character. Normally
it is the Unicode character, see |digraph-encoding|.
Example:
:digr e: 235 a: 228
Avoid defining a digraph with '_' (underscore) as the
first character, it has a special meaning in the
future.
Vim is normally compiled with the |+digraphs| feature. If the feature is
disabled, the ":digraph" command will display an error message.
Example of the output of ":digraphs":
TH Þ 222 ss ß 223 a! à 224 a' á 225 a> â 226 a? ã 227 a: ä 228
The first two characters in each column are the characters you have to type to
enter the digraph.
In the middle of each column is the resulting character. This may be mangled
if you look at it on a system that does not support digraphs or if you print
this file.
*digraph-encoding*
The decimal number normally is the Unicode number of the character. Note that
the meaning doesn't change when 'encoding' changes. The character will be
converted from Unicode to 'encoding' when needed. This does require the
conversion to be available, it might fail. For the NUL character you will see
"10". That's because NUL characters are internally represented with a NL
character. When you write the file it will become a NUL character.
When Vim was compiled without the |+multi_byte| feature, you need to specify
the character in the encoding given with 'encoding'. You might want to use
something like this:
if has("multi_byte")
digraph oe 339
elseif &encoding == "iso-8859-15"
digraph oe 189
endif
This defines the "oe" digraph for a character that is number 339 in Unicode
and 189 in latin9 (iso-8859-15).
==============================================================================
2. Using digraphs *digraphs-use*
*digraph-table*
char digraph hex dec official name
^@ NU 0x00 0 NULL (NUL)
^A SH 0x01 1 START OF HEADING (SOH)
^B SX 0x02 2 START OF TEXT (STX)
^C EX 0x03 3 END OF TEXT (ETX)
^D ET 0x04 4 END OF TRANSMISSION (EOT)
^E EQ 0x05 5 ENQUIRY (ENQ)
^F AK 0x06 6 ACKNOWLEDGE (ACK)
^G BL 0x07 7 BELL (BEL)
^H BS 0x08 8 BACKSPACE (BS)
^I HT 0x09 9 CHARACTER TABULATION (HT)
^@ LF 0x0a 10 LINE FEED (LF)
^K VT 0x0b 11 LINE TABULATION (VT)
^L FF 0x0c 12 FORM FEED (FF)
^M CR 0x0d 13 CARRIAGE RETURN (CR)
^N SO 0x0e 14 SHIFT OUT (SO)
^O SI 0x0f 15 SHIFT IN (SI)
^P DL 0x10 16 DATALINK ESCAPE (DLE)
^Q D1 0x11 17 DEVICE CONTROL ONE (DC1)
^R D2 0x12 18 DEVICE CONTROL TWO (DC2)
^S D3 0x13 19 DEVICE CONTROL THREE (DC3)
^T D4 0x14 20 DEVICE CONTROL FOUR (DC4)
^U NK 0x15 21 NEGATIVE ACKNOWLEDGE (NAK)
^V SY 0x16 22 SYNCHRONOUS IDLE (SYN)
^W EB 0x17 23 END OF TRANSMISSION BLOCK (ETB)
^X CN 0x18 24 CANCEL (CAN)
^Y EM 0x19 25 END OF MEDIUM (EM)
^Z SB 0x1a 26 SUBSTITUTE (SUB)
^[ EC 0x1b 27 ESCAPE (ESC)
^\ FS 0x1c 28 FILE SEPARATOR (IS4)
^] GS 0x1d 29 GROUP SEPARATOR (IS3)
^^ RS 0x1e 30 RECORD SEPARATOR (IS2)
^_ US 0x1f 31 UNIT SEPARATOR (IS1)
SP 0x20 32 SPACE
# Nb 0x23 35 NUMBER SIGN
$ DO 0x24 36 DOLLAR SIGN
@ At 0x40 64 COMMERCIAL AT
[ <( 0x5b 91 LEFT SQUARE BRACKET
\ // 0x5c 92 REVERSE SOLIDUS
] )> 0x5d 93 RIGHT SQUARE BRACKET
*digraph-table-mbyte*
char digraph hex dec official name
Ä€ A- 0100 0256 LATIN CAPITAL LETTER A WITH MACRON
Ä a- 0101 0257 LATIN SMALL LETTER A WITH MACRON
Ä‚ A( 0102 0258 LATIN CAPITAL LETTER A WITH BREVE
ă a( 0103 0259 LATIN SMALL LETTER A WITH BREVE
Ä„ A; 0104 0260 LATIN CAPITAL LETTER A WITH OGONEK
Ä… a; 0105 0261 LATIN SMALL LETTER A WITH OGONEK
Ć C' 0106 0262 LATIN CAPITAL LETTER C WITH ACUTE
ć c' 0107 0263 LATIN SMALL LETTER C WITH ACUTE
Ĉ C> 0108 0264 LATIN CAPITAL LETTER C WITH CIRCUMFLEX
ĉ c> 0109 0265 LATIN SMALL LETTER C WITH CIRCUMFLEX
ÄŠ C. 010A 0266 LATIN CAPITAL LETTER C WITH DOT ABOVE
Ä‹ c. 010B 0267 LATIN SMALL LETTER C WITH DOT ABOVE
Č C< 010C 0268 LATIN CAPITAL LETTER C WITH CARON
Ä c< 010D 0269 LATIN SMALL LETTER C WITH CARON
ÄŽ D< 010E 0270 LATIN CAPITAL LETTER D WITH CARON
Ä d< 010F 0271 LATIN SMALL LETTER D WITH CARON
Ä D/ 0110 0272 LATIN CAPITAL LETTER D WITH STROKE
Ä‘ d/ 0111 0273 LATIN SMALL LETTER D WITH STROKE
Ä’ E- 0112 0274 LATIN CAPITAL LETTER E WITH MACRON
Credit card Through PayPal, see the PayPal site for information:
https://www.paypal.com/en_US/mrb/pal=XAC62PML3GF8Q
The e-mail address for sending sponsorship money is:
donate@vim.org
The e-mail address for Vim registration is:
register@vim.org
Using Euro is preferred, other currencies are also accepted.
In Euro countries a bank transfer is preferred, this has lower
costs.
Other methods See |iccf-donations|.
Include "Vim sponsor" or "Vim registration" in the comment of
your money transfer. Send me an e-mail that mentions the
amount you transferred if you want to vote for features and
show others you are a registered Vim user or sponsor.
Cash Small amounts can be sent with ordinary mail. Put something
around the money, so that it's not noticeable from the
outside. Mention your e-mail address if you want to vote for
features and show others you are a registered Vim user or
sponsor.
You can use this permanent address:
Bram Moolenaar
Finsterruetihof 1
8134 Adliswil
Switzerland
*-file* *---*
filename One or more file names. The first one will be the current
file and read into the buffer. The cursor will be positioned
on the first line of the buffer.
To avoid a file name starting with a '-' being interpreted as
an option, precede the arglist with "--", e.g.:
vim -- -filename
All arguments after the "--" will be interpreted as file names,
no other options or "+command" argument can follow.
*--*
- This argument can mean two things, depending on whether Ex
mode is to be used.
Starting in Normal mode:
vim -
ex -v -
Start editing a new buffer, which is filled with text
that is read from stdin. The commands that would normally be
read from stdin will now be read from stderr. Example:
*-t* *-tag*
-t {tag} A tag. "tag" is looked up in the tags file, the associated
file becomes the current file, and the associated command is
executed. Mostly this is used for C programs, in which case
"tag" often is a function name. The effect is that the file
containing that function becomes the current file and the
cursor is positioned on the start of the function (see
|tags|).
*-q* *-qf*
-q [errorfile] QuickFix mode. The file with the name [errorfile] is read
and the first error is displayed. See |quickfix|.
If [errorfile] is not given, the 'errorfile' option is used
for the file name. See 'errorfile' for the default value.
{not in Vi}
(nothing) Without one of the four items above, Vim will start editing a
new buffer. It's empty and doesn't have a file name.
The startup mode can be changed by using another name instead of "vim", which
is equal to giving options:
ex vim -e Start in Ex mode (see |Ex-mode|). *ex*
exim vim -E Start in improved Ex mode (see |Ex-mode|). *exim*
(normally not installed)
view vim -R Start in read-only mode (see |-R|). *view*
gvim vim -g Start the GUI (see |gui|). *gvim*
gex vim -eg Start the GUI in Ex mode. *gex*
gview vim -Rg Start the GUI in read-only mode. *gview*
rvim vim -Z Like "vim", but in restricted mode (see |-Z|) *rvim*
rview vim -RZ Like "view", but in restricted mode. *rview*
rgvim vim -gZ Like "gvim", but in restricted mode. *rgvim*
rgview vim -RgZ Like "gview", but in restricted mode. *rgview*
evim vim -y Easy Vim: set 'insertmode' (see |-y|) *evim*
eview vim -yR Like "evim" in read-only mode *eview*
vimdiff vim -d Start in diff mode |diff-mode|
gvimdiff vim -gd Start in diff mode |diff-mode|
Additional characters may follow, they are ignored. For example, you can have
"gvim-5" to start the GUI. You must have an executable by that name then, of
course.
On Unix, you would normally have one executable called Vim, and links from the
different startup-names to that executable. If your system does not support
links and you do not want to have several copies of the executable, you could
use an alias instead. For example:
alias view vim -R
alias gvim vim -g
*startup-options*
The option arguments may be given in any order. Single-letter options can be
combined after one dash. There can be no option arguments after the "--"
argument.
On VMS all option arguments are assumed to be lowercase, unless preceded with
a slash. Thus "-R" means recovery and "-/R" readonly.
*--version*
--version Print version information and exit. Same output as for
|:version| command. {not in Vi}
See |info-message| about capturing the text.
*--noplugin*
--noplugin Skip loading plugins. Resets the 'loadplugins' option.
{not in Vi}
Note that the |-u| argument may also disable loading plugins:
argument load vimrc files load plugins
(nothing) yes yes
-u NONE no no
-u NORC no yes
--noplugin yes no
*--literal*
--literal Take file names literally, don't expand wildcards. Not needed
for Unix, because Vim always takes file names literally (the
shell expands wildcards).
Applies to all the names, also the ones that come before this
argument.
*-+*
+[num] The cursor will be positioned on line "num" for the first
file being edited. If "num" is missing, the cursor will be
positioned on the last line.
*-+/*
+/{pat} The cursor will be positioned on the first line containing
"pat" in the first file being edited (see |pattern| for the
available search patterns).
{not in Vi}
*-S*
-S {file} The {file} will be sourced after the first file has been read.
This is an easy way to do the equivalent of:
-c "source {file}"
It can be mixed with "-c" arguments and repeated like "-c".
The limit of 10 "-c" arguments applies here as well.
{file} cannot start with a "-".
{not in Vi}
-S Works like "-S Session.vim". Only when used as the last
argument or when another "-" option follows.
*-r*
-r Recovery mode. Without a file name argument, a list of
existing swap files is given. With a file name, a swap file
is read to recover a crashed editing session. See
|crash-recovery|.
*-L*
-L Same as -r. {only in some versions of Vi: "List recoverable
edit sessions"}
*-R*
-R Readonly mode. The 'readonly' option will be set for all the
files being edited. You can still edit the buffer, but will
be prevented from accidentally overwriting a file. If you
forgot that you are in View mode and did make some changes,
you can overwrite a file by adding an exclamation mark to
the Ex command, as in ":w!". The 'readonly' option can be
reset with ":set noro" (see the options chapter, |options|).
Subsequent edits will not be done in readonly mode. Calling
the executable "view" has the same effect as the -R argument.
The 'updatecount' option will be set to 10000, meaning that
the swap file will not be updated automatically very often.
*-m*
-m Modifications not allowed to be written. The 'write' option
will be reset, so that writing files is disabled. However,
the 'write' option can be set to enable writing again.
{not in Vi}
*-M*
-M Modifications not allowed. The 'modifiable' option will be
reset, so that changes are not allowed. The 'write' option
will be reset, so that writing files is disabled. However,
the 'modifiable' and 'write' options can be set to enable
changes and writing.
{not in Vi}
*-g*
-g Start Vim in GUI mode. See |gui|. {not in Vi}
*-v*
-v Start Ex in Vi mode. Only makes a difference when the
executable is called "ex" or "gvim". For gvim the GUI is not
started if possible.
*-e*
-e Start Vim in Ex mode |Q|. Only makes a difference when the
executable is not called "ex".
*-E*
-E Start Vim in improved Ex mode |gQ|. Only makes a difference
when the executable is not called "exim".
{not in Vi}
*-s-ex*
-s Silent or batch mode. Only when Vim was started as "ex" or
when preceded with the "-e" argument. Otherwise see |-s|,
which does take an argument while this use of "-s" doesn't.
To be used when Vim is used to execute Ex commands from a file
instead of a terminal. Switches off most prompts and
informative messages. Also warnings and error messages.
The output of these commands is displayed (to stdout):
:print
:list
:number
:set to display option values.
When 'verbose' is non-zero messages are printed (for
debugging, to stderr).
'term' and $TERM are not used.
If Vim appears to be stuck try typing "qa!<Enter>". You don't
get a prompt thus you can't see Vim is waiting for you to type
something.
Initializations are skipped (except the ones given with the
"-u" argument).
Example:
vim -e -s < thefilter thefile
*-b*
-b Binary mode. File I/O will only recognize <NL> to separate
lines. The 'expandtab' option will be reset. The 'textwidth'
option is set to 0. 'modeline' is reset. The 'binary' option
is set. This is done after reading the vimrc/exrc files but
before reading any file in the arglist. See also
|edit-binary|. {not in Vi}
*-l*
-l Lisp mode. Sets the 'lisp' and 'showmatch' options on.
*-A*
-A Arabic mode. Sets the 'arabic' option on. (Only when
compiled with the |+arabic| features (which include
|+rightleft|), otherwise Vim gives an error message
and exits.) {not in Vi}
*-F*
-F Farsi mode. Sets the 'fkmap' and 'rightleft' options on.
(Only when compiled with |+rightleft| and |+farsi| features,
otherwise Vim gives an error message and exits.) {not in Vi}
*-H*
-H Hebrew mode. Sets the 'hkmap' and 'rightleft' options on.
(Only when compiled with the |+rightleft| feature, otherwise
Vim gives an error message and exits.) {not in Vi}
*-V* *verbose*
-V[N] Verbose. Sets the 'verbose' option to [N] (default: 10).
Messages will be given for each file that is ":source"d and
for reading or writing a viminfo file. Can be used to find
out what is happening upon startup and exit. {not in Vi}
Example:
vim -V8 foobar
-V[N]{filename}
Like -V and set 'verbosefile' to {filename}. The result is
that messages are not displayed but written to the file
{filename}. {filename} must not start with a digit.
Example:
vim -V20vimlog foobar
*-D*
*-C*
-C Compatible mode. Sets the 'compatible' option. You can use
this to get 'compatible', even though a .vimrc file exists.
Keep in mind that the command ":set nocompatible" in some
plugin or startup script overrules this, so you may end up
with 'nocompatible' anyway. To find out, use:
:verbose set compatible?
Several plugins won't work with 'compatible' set. You may
want to set it after startup this way:
vim "+set cp" filename
Also see |compatible-default|. {not in Vi}
*-N*
-N Not compatible mode. Resets the 'compatible' option. You can
use this to get 'nocompatible', when there is no .vimrc file
or when using "-u NONE".
Also see |compatible-default|. {not in Vi}
*-y* *easy*
-y Easy mode. Implied for |evim| and |eview|. Starts with
'insertmode' set and behaves like a click-and-type editor.
This sources the script $VIMRUNTIME/evim.vim. Mappings are
set up to work like most click-and-type editors, see
|evim-keys|. The GUI is started when available.
{not in Vi}
*-n*
-n No swap file will be used. Recovery after a crash will be
impossible. Handy if you want to view or edit a file on a
very slow medium (e.g., a floppy).
Can also be done with ":set updatecount=0". You can switch it
on again by setting the 'updatecount' option to some value,
e.g., ":set uc=100".
NOTE: Don't combine -n with -b, making -nb, because that has a
different meaning: |-nb|.
'updatecount' is set to 0 AFTER executing commands from a
vimrc file, but before the GUI initializations. Thus it
overrides a setting for 'updatecount' in a vimrc file, but not
in a gvimrc file. See |startup|.
When you want to reduce accesses to the disk (e.g., for a
laptop), don't use "-n", but set 'updatetime' and
'updatecount' to very big numbers, and type ":preserve" when
you want to save your work. This way you keep the possibility
for crash recovery.
{not in Vi}
*-o*
-o[N] Open N windows, split horizontally. If [N] is not given,
one window is opened for every file given as argument. If
there is not enough room, only the first few files get a
window. If there are more windows than arguments, the last
few windows will be editing an empty file.
{not in Vi}
*-O*
-O[N] Open N windows, split vertically. Otherwise it's like -o.
If both the -o and the -O option are given, the last one on
the command line determines how the windows will be split.
{not in Vi}
*-p*
-p[N] Open N tab pages. If [N] is not given, one tab page is opened
for every file given as argument. The maximum is set with
'tabpagemax' pages (default 10). If there are more tab pages
than arguments, the last few tab pages will be editing an
empty file. Also see |tabpage|.
{not in Vi}
*-T*
-T {terminal} Set the terminal type to "terminal". This influences the
codes that Vim will send to your terminal. This is normally
not needed, because Vim will be able to find out what type
of terminal you are using. (See |terminal-info|.) {not in Vi}
*-d*
-d Start in diff mode, like |vimdiff|.
{not in Vi} {not available when compiled without the |+diff|
feature}
-d {device} Only on the Amiga and when not compiled with the |+diff|
feature. Works like "-dev".
*-dev*
-dev {device} Only on the Amiga: The {device} is opened to be used for
editing.
Normally you would use this to set the window position and
size: "-d con:x/y/width/height", e.g.,
"-d con:30/10/600/150". But you can also use it to start
editing on another device, e.g., AUX:. {not in Vi}
*-f*
-f Amiga: Do not restart Vim to open a new window. This
option should be used when Vim is started by a program that
will wait for the edit session to finish (e.g., mail or
readnews). See |amiga-window|.
GUI: Do not disconnect from the program that started Vim.
'f' stands for "foreground". If omitted, the GUI forks a new
process and exits the current one. "-f" should be used when
gvim is started by a program that will wait for the edit
session to finish (e.g., mail or readnews). If you want gvim
never to fork, include 'f' in 'guioptions' in your |gvimrc|.
Careful: You can use "-gf" to start the GUI in the foreground,
but "-fg" is used to specify the foreground color. |gui-fork|
{not in Vi}
*--nofork*
--nofork GUI: Do not fork. Same as |-f|.
*-u* *E282*
-u {vimrc} The file {vimrc} is read for initializations. Most other
initializations are skipped; see |initialization|. This can
be used to start Vim in a special mode, with special
mappings and settings. A shell alias can be used to make
this easy to use. For example:
alias vimc vim -u ~/.c_vimrc !*
Also consider using autocommands; see |autocommand|.
When {vimrc} is equal to "NONE" (all uppercase), all
initializations from files and environment variables are
skipped, including reading the |gvimrc| file when the GUI
starts. Loading plugins is also skipped.
When {vimrc} is equal to "NORC" (all uppercase), this has the
same effect as "NONE", but loading plugins is not skipped.
Using the "-u" argument has the side effect that the
'compatible' option will be on by default. This can have
unexpected effects. See |'compatible'|.
{not in Vi}
*-U* *E230*
-U {gvimrc} The file {gvimrc} is read for initializations when the GUI
starts. Other GUI initializations are skipped. When {gvimrc}
is equal to "NONE", no file is read for GUI initializations at
all. |gui-init|
Exception: Reading the system-wide menu file is always done.
{not in Vi}
*-i*
-i {viminfo} The file "viminfo" is used instead of the default viminfo
file. If the name "NONE" is used (all uppercase), no viminfo
file is read or written, even if 'viminfo' is set or when
":rv" or ":wv" are used. See also |viminfo-file|.
{not in Vi}
*-x*
-x Use encryption to read/write files. Will prompt for a key,
which is then stored in the 'key' option. All writes will
then use this key to encrypt the text. The '-x' argument is
not needed when reading a file, because there is a check if
the file that is being read has been encrypted, and Vim asks
for a key automatically. |encryption|
*-X*
-X Do not try connecting to the X server to get the current
window title and copy/paste using the X clipboard. This
avoids a long startup time when running Vim in a terminal
emulator and the connection to the X server is slow.
See |--startuptime| to find out if affects you.
Only makes a difference on Unix or VMS, when compiled with the
|+X11| feature. Otherwise it's ignored.
To disable the connection only for specific terminals, see the
'clipboard' option.
When the X11 Session Management Protocol (XSMP) handler has
been built in, the -X option also disables that connection as
it, too, may have undesirable delays.
When the connection is desired later anyway (e.g., for
client-server messages), call the |serverlist()| function.
This does not enable the XSMP handler though.
{not in Vi}
*-s*
-s {scriptin} The script file "scriptin" is read. The characters in the
file are interpreted as if you had typed them. The same can
be done with the command ":source! {scriptin}". If the end
of the file is reached before the editor exits, further
characters are read from the keyboard. Only works when not
started in Ex mode, see |-s-ex|. See also |complex-repeat|.
{not in Vi}
*-w_nr*
-w {number}
-w{number} Set the 'window' option to {number}.
*-w*
-w {scriptout} All the characters that you type are recorded in the file
"scriptout", until you exit Vim. This is useful if you want
to create a script file to be used with "vim -s" or
":source!". When the "scriptout" file already exists, new
characters are appended. See also |complex-repeat|.
{scriptout} cannot start with a digit.
{not in Vi}
*-W*
-W {scriptout} Like -w, but do not append, overwrite an existing file.
{not in Vi}
--remote [+{cmd}] {file} ...
Open the {file} in another Vim that functions as a server.
Any non-file arguments must come before this.
See |--remote|. {not in Vi}
--remote-silent [+{cmd}] {file} ...
Like --remote, but don't complain if there is no server.
See |--remote-silent|. {not in Vi}
--remote-wait [+{cmd}] {file} ...
Like --remote, but wait for the server to finish editing the
file(s).
See |--remote-wait|. {not in Vi}
--remote-wait-silent [+{cmd}] {file} ...
Like --remote-wait, but don't complain if there is no server.
See |--remote-wait-silent|. {not in Vi}
--servername {name}
Specify the name of the Vim server to send to or to become.
See |--servername|. {not in Vi}
--remote-send {keys}
Send {keys} to a Vim server and exit.
See |--remote-send|. {not in Vi}
--remote-expr {expr}
Evaluate {expr} in another Vim that functions as a server.
The result is printed on stdout.
See |--remote-expr|. {not in Vi}
--serverlist Output a list of Vim server names and exit. See
|--serverlist|. {not in Vi}
--echo-wid *--echo-wid*
GTK+ GUI Vim only. Make gvim echo the Window ID on stdout,
which can be used to run gvim in a kpart widget. The format
of the output is:
WID: 12345\n
{not in Vi}
-nb *-nb*
-nb={fname}
-nb:{hostname}:{addr}:{password}
Attempt connecting to Netbeans and become an editor server for
it. The second form specifies a file to read connection info
from. The third form specifies the hostname, address and
password for connecting to Netbeans. |netbeans-run|
{only available when compiled with the |+netbeans_intg|
feature; if not then -nb will make Vim exit}
If the executable is called "view", Vim will start in Readonly mode. This is
useful if you can make a hard or symbolic link from "view" to "vim".
Starting in Readonly mode can also be done with "vim -R".
If the executable is called "ex", Vim will start in "Ex" mode. This means it
will accept only ":" commands. But when the "-v" argument is given, Vim will
start in Normal mode anyway.
Additional arguments are available on unix like systems when compiled with
X11 GUI support. See |gui-resources|.
==============================================================================
2. Vim on the Amiga *starting-amiga*
Vim can be started from the Workbench by clicking on its icon twice. It will
then start with an empty buffer.
Vim can be started to edit one or more files by using a "Project" icon. The
"Default Tool" of the icon must be the full pathname of the Vim executable.
The name of the ".info" file must be the same as the name of the text file.
By clicking on this icon twice, Vim will be started with the file name as
current file name, which will be read into the buffer (if it exists). You can
edit multiple files by pressing the shift key while clicking on icons, and
clicking twice on the last one. The "Default Tool" for all these icons must
be the same.
It is not possible to give arguments to Vim, other than file names, from the
workbench.
If the "-q" flag was given to Vim, the quickfix file is read. If this
fails, Vim exits.
11. Open all windows
When the |-o| flag was given, windows will be opened (but not
displayed yet).
When the |-p| flag was given, tab pages will be created (but not
displayed yet).
When switching screens, it happens now. Redrawing starts.
If the "-q" flag was given to Vim, the first error is jumped to.
Buffers for all windows will be loaded.
12. Execute startup commands
If a "-t" flag was given to Vim, the tag is jumped to.
The commands given with the |-c| and |+cmd| arguments are executed.
The starting flag is reset, has("vim_starting") will now return zero.
If the 'insertmode' option is set, Insert mode is entered.
The |VimEnter| autocommands are executed.
Some hints on using initializations:
Standard setup:
Create a vimrc file to set the default settings and mappings for all your edit
sessions. Put it in a place so that it will be found by 3b:
~/.vimrc (Unix and OS/2)
s:.vimrc (Amiga)
$VIM\_vimrc (MS-DOS and Win32)
Note that creating a vimrc file will cause the 'compatible' option to be off
by default. See |compatible-default|.
Local setup:
Put all commands that you need for editing a specific directory only into a
vimrc file and place it in that directory under the name ".vimrc" ("_vimrc"
for MS-DOS and Win32). NOTE: To make Vim look for these special files you
have to turn on the option 'exrc'. See |trojan-horse| too.
System setup:
This only applies if you are managing a Unix system with several users and
want to set the defaults for all users. Create a vimrc file with commands
for default settings and mappings and put it in the place that is given with
the ":version" command.
Saving the current state of Vim to a file:
Whenever you have changed values of options or when you have created a
mapping, then you may want to save them in a vimrc file for later use. See
|save-settings| about saving the current state of settings to a file.
Avoiding setup problems for Vi users:
Vi uses the variable EXINIT and the file "~/.exrc". So if you do not want to
interfere with Vi, then use the variable VIMINIT and the file "vimrc" instead.
Amiga environment variables:
On the Amiga, two types of environment variables exist. The ones set with the
DOS 1.3 (or later) setenv command are recognized. See the AmigaDos 1.3
manual. The environment variables set with the old Manx Set command (before
version 5.0) are not recognized.
MS-DOS line separators:
On MS-DOS-like systems (MS-DOS itself, Win32, and OS/2), Vim assumes that all
the vimrc files have <CR> <NL> pairs as line separators. This will give
problems if you have a file with only <NL>s and have a line like
":map xx yy^M". The trailing ^M will be ignored.
*compatible-default*
When Vim starts, the 'compatible' option is on. This will be used when Vim
starts its initializations. But as soon as a user vimrc file is found, or a
vimrc file in the current directory, or the "VIMINIT" environment variable is
set, it will be set to 'nocompatible'. This has the side effect of setting or
resetting other options (see 'compatible'). But only the options that have
not been set or reset will be changed. This has the same effect like the
value of 'compatible' had this value when starting Vim. Note that this
doesn't happen for the system-wide vimrc file nor when Vim was started with
the |-u| command line argument. It does also happen for gvimrc files. The
$MYVIMRC or $MYGVIMRC file will be set to the first found vimrc and/or gvimrc
file.
But there is a side effect of setting or resetting 'compatible' at the moment
a .vimrc file is found: Mappings are interpreted the moment they are
encountered. This makes a difference when using things like "<CR>". If the
*slow-start*
If Vim takes a long time to start up, use the |--startuptime| argument to find
out what happens. There are a few common causes:
- If the Unix version was compiled with the GUI and/or X11 (check the output
of ":version" for "+GUI" and "+X11"), it may need to load shared libraries
and connect to the X11 server. Try compiling a version with GUI and X11
disabled. This also should make the executable smaller.
Use the |-X| command line argument to avoid connecting to the X server when
running in a terminal.
- If you have "viminfo" enabled, the loading of the viminfo file may take a
while. You can find out if this is the problem by disabling viminfo for a
moment (use the Vim argument "-i NONE", |-i|). Try reducing the number of
lines stored in a register with ":set viminfo='20,<50,s10". |viminfo-file|.
*:intro*
When Vim starts without a file name, an introductory message is displayed (for
those who don't know what Vim is). It is removed as soon as the display is
redrawn in any way. To see the message again, use the ":intro" command (if
there is not enough room, you will see only part of it).
To avoid the intro message on startup, add the 'I' flag to 'shortmess'.
*info-message*
The |--help| and |--version| arguments cause Vim to print a message and then
exit. Normally the message is sent to stdout, thus can be redirected to a
file with:
vim --help >file
From inside Vim:
:read !vim --help
When using gvim, it detects that it might have been started from the desktop,
without a terminal to show messages on. This is detected when both stdout and
stderr are not a tty. This breaks the ":read" command, as used in the example
above. To make it work again, set 'shellredir' to ">" instead of the default
">&":
:set shellredir=>
*$VIMRUNTIME*
The environment variable "$VIMRUNTIME" is used to locate various support
files, such as the on-line documentation and files used for syntax
highlighting. For example, the main help file is normally
"$VIMRUNTIME/doc/help.txt".
You don't normally set $VIMRUNTIME yourself, but let Vim figure it out. This
is the order used to find the value of $VIMRUNTIME:
1. If the environment variable $VIMRUNTIME is set, it is used. You can use
this when the runtime files are in an unusual location.
2. If "$VIM/vim{version}" exists, it is used. {version} is the version
number of Vim, without any '-' or '.'. For example: "$VIM/vim54". This is
the normal value for $VIMRUNTIME.
3. If "$VIM/runtime" exists, it is used.
4. The value of $VIM is used. This is for backwards compatibility with older
versions.
5. When the 'helpfile' option is set and doesn't contain a '$', its value is
used, with "doc/help.txt" removed from the end.
For Unix, when there is a compiled-in default for $VIMRUNTIME (check the
output of ":version"), steps 2, 3 and 4 are skipped, and the compiled-in
default is used after step 5. This means that the compiled-in default
overrules the value of $VIM. This is useful if $VIM is "/etc" and the runtime
files are in "/usr/share/vim/vim54".
Once Vim has done this once, it will set the $VIMRUNTIME environment variable.
To change it later, use a ":let" command like this:
:let $VIMRUNTIME = "/home/piet/vim/vim54"
In case you need the value of $VIMRUNTIME in a shell (e.g., for a script that
greps in the help files) you might be able to use this:
VIMRUNTIME=`vim -e -T dumb --cmd 'exe "set t_cm=\<C-M>"|echo $VIMRUNTIME|quit' | tr -d
'\015' `
==============================================================================
6. Suspending *suspend*
mode.
Note: if CTRL-Z undoes a change see |mswin.vim|.
*:mk* *:mkexrc*
:mk[exrc] [file] Write current key mappings and changed options to
[file] (default ".exrc" in the current directory),
unless it already exists. {not in Vi}
:mk[exrc]! [file] Always write current key mappings and changed
options to [file] (default ".exrc" in the current
directory). {not in Vi}
*:mkv* *:mkvimrc*
:mkv[imrc][!] [file] Like ":mkexrc", but the default is ".vimrc" in the
current directory. The ":version" command is also
written to the file. {not in Vi}
These commands will write ":map" and ":set" commands to a file, in such a way
that when these commands are executed, the current key mappings and options
will be set to the same values. The options 'columns', 'endofline',
'fileformat', 'key', 'lines', 'modified', 'scroll', 'term', 'textmode',
'ttyfast' and 'ttymouse' are not included, because these are terminal or file
dependent. Note that the options 'binary', 'paste' and 'readonly' are
included, this might not always be what you want.
When special keys are used in mappings, The 'cpoptions' option will be
temporarily set to its Vim default, to avoid the mappings to be
misinterpreted. This makes the file incompatible with Vi, but makes sure it
can be used with different terminals.
Only global mappings are stored, not mappings local to a buffer.
A common method is to use a default ".vimrc" file, make some modifications
with ":map" and ":set" commands and write the modified file. First read the
default ".vimrc" in with a command like ":source ~piet/.vimrc.Cprogs", change
the settings and then save them in the current directory with ":mkvimrc!". If
you want to make this file your default .vimrc, move it to your home directory
(on Unix), s: (Amiga) or $VIM directory (MS-DOS). You could also use
autocommands |autocommand| and/or modelines |modeline|.
*vimrc-option-example*
If you only want to add a single option setting to your vimrc, you can use
these steps:
1. Edit your vimrc file with Vim.
2. Play with the option until it's right. E.g., try out different values for
'guifont'.
3. Append a line to set the value of the option, using the expression register
'=' to enter the value. E.g., for the 'guifont' option:
o:set guifont=<C-R>=&guifont<CR><Esc>
[<C-R> is a CTRL-R, <CR> is a return, <Esc> is the escape key]
You need to escape special characters, esp. spaces.
Note that when you create a .vimrc file, this can influence the 'compatible'
option, which has several side effects. See |'compatible'|.
":mkvimrc", ":mkexrc" and ":mksession" write the command to set or reset the
'compatible' option to the output file first, because of these side effects.
==============================================================================
8. Views and Sessions *views-sessions*
This is introduced in sections |21.4| and |21.5| of the user manual.
*View* *view-file*
A View is a collection of settings that apply to one window. You can save a
View and when you restore it later, the text is displayed in the same way.
The options and mappings in this window will also be restored, so that you can
continue editing like when the View was saved.
*Session* *session-file*
A Session keeps the Views for all windows, plus the global settings. You can
save a Session and when you restore it later the window layout looks the same.
You can use a Session to quickly switch between different projects,
automatically loading the files you were last working on in that project.
Views and Sessions are a nice addition to viminfo-files, which are used to
remember information for all Views and Sessions together |viminfo-file|.
You can quickly start editing with a previously saved View or Session with the
|-S| argument:
vim -S Session.vim
All this is {not in Vi} and {not available when compiled without the
|+mksession| feature}.
*:mks* *:mksession*
:mks[ession][!] [file] Write a Vim script that restores the current editing
session.
When [!] is included an existing file is overwritten.
When [file] is omitted "Session.vim" is used.
The output of ":mksession" is like ":mkvimrc", but additional commands are
added to the file. Which ones depends on the 'sessionoptions' option. The
resulting file, when executed with a ":source" command:
1. Restores global mappings and options, if 'sessionoptions' contains
"options". Script-local mappings will not be written.
2. Restores global variables that start with an uppercase letter and contain
at least one lowercase letter, if 'sessionoptions' contains "globals".
3. Unloads all currently loaded buffers.
4. Restores the current directory if 'sessionoptions' contains "curdir", or
sets the current directory to where the Session file is if 'sessionoptions'
contains "sesdir".
5. Restores GUI Vim window position, if 'sessionoptions' contains "winpos".
6. Restores screen size, if 'sessionoptions' contains "resize".
7. Reloads the buffer list, with the last cursor positions. If
'sessionoptions' contains "buffers" then all buffers are restored,
including hidden and unloaded buffers. Otherwise only buffers in windows
are restored.
8. Restores all windows with the same layout. If 'sessionoptions' contains
"help", help windows are restored. If 'sessionoptions' contains "blank",
windows editing a buffer without a name will be restored.
If 'sessionoptions' contains "winsize" and no (help/blank) windows were
left out, the window sizes are restored (relative to the screen size).
Otherwise, the windows are just given sensible sizes.
9. Restores the Views for all the windows, as with |:mkview|. But
'sessionoptions' is used instead of 'viewoptions'.
10. If a file exists with the same name as the Session file, but ending in
"x.vim" (for eXtra), executes that as well. You can use *x.vim files to
specify additional settings and actions associated with a given Session,
such as creating menu items in the GUI version.
After restoring the Session, the full filename of your current Session is
*:mkvie* *:mkview*
:mkvie[w][!] [file] Write a Vim script that restores the contents of the
current window.
When [!] is included an existing file is overwritten.
When [file] is omitted or is a number from 1 to 9, a
name is generated and 'viewdir' prepended. When the
last directory name in 'viewdir' does not exist, this
directory is created.
An existing file is always overwritten then. Use
|:loadview| to load this view again.
When [file] is the name of a file ('viewdir' is not
used), a command to edit the file is added to the
generated file.
The output of ":mkview" contains these items:
1. The argument list used in the window. When the global argument list is
used it is reset to the global list.
The index in the argument list is also restored.
2. The file being edited in the window. If there is no file, the window is
made empty.
3. Restore mappings, abbreviations and options local to the window if
'viewoptions' contains "options" or "localoptions". For the options it
restores only values that are local to the current buffer and values local
to the window.
When storing the view as part of a session and "options" is in
'sessionoptions', global values for local options will be stored too.
4. Restore folds when using manual folding and 'viewoptions' contains
"folds". Restore manually opened and closed folds.
5. The scroll position and the cursor position in the file. Doesn't work very
well when there are closed folds.
6. The local current directory, if it is different from the global current
directory.
Note that Views and Sessions are not perfect:
- They don't restore everything. For example, defined functions, autocommands
and ":syntax on" are not included. Things like register contents and
command line history are in viminfo, not in Sessions or Views.
- Global option values are only set when they differ from the default value.
When the current value is not the default value, loading a Session will not
set it back to the default value. Local options will be set back to the
default value though.
- Existing mappings will be overwritten without warning. An existing mapping
may cause an error for ambiguity.
- When storing manual folds and when storing manually opened/closed folds,
changes in the file between saving and loading the view will mess it up.
- The Vim script is not very efficient. But still faster than typing the
commands yourself!
*:lo* *:loadview*
:lo[adview] [nr] Load the view for the current file. When [nr] is
omitted, the view stored with ":mkview" is loaded.
When [nr] is specified, the view stored with ":mkview
[nr]" is loaded.
The combination of ":mkview" and ":loadview" can be used to store up to ten
different views of a file. These are remembered in the directory specified
with the 'viewdir' option. The views are stored using the file name. If a
file is renamed or accessed through a (symbolic) link the view will not be
found.
You might want to clean up your 'viewdir' directory now and then.
*viminfo-read*
When Vim is started and the 'viminfo' option is non-empty, the contents of
the viminfo file are read and the info can be used in the appropriate places.
The |v:oldfiles| variable is filled. The marks are not read in at startup
(but file marks are). See |initialization| for how to set the 'viminfo'
option upon startup.
*viminfo-write*
When Vim exits and 'viminfo' is non-empty, the info is stored in the viminfo
file (it's actually merged with the existing one, if one exists). The
'viminfo' option is a string containing information about what info should be
stored, and contains limits on how much should be stored (see 'viminfo').
Notes for Unix:
- The file protection for the viminfo file will be set to prevent other users
from being able to read it, because it may contain any text or commands that
you have worked with.
- If you want to share the viminfo file with other users (e.g. when you "su"
to another user), you can make the file writable for the group or everybody.
Vim will preserve this when writing new viminfo files. Be careful, don't
allow just anybody to read and write your viminfo file!
- Vim will not overwrite a viminfo file that is not writable by the current
"real" user. This helps for when you did "su" to become root, but your
$HOME is still set to a normal user's home directory. Otherwise Vim would
create a viminfo file owned by root that nobody else can read.
- The viminfo file cannot be a symbolic link. This is to avoid security
issues.
Marks are stored for each file separately. When a file is read and 'viminfo'
is non-empty, the marks for that file are read from the viminfo file. NOTE:
The marks are only written when exiting Vim, which is fine because marks are
remembered for all the files you have opened in the current editing session,
unless ":bdel" is used. If you want to save the marks for a file that you are
about to abandon with ":bdel", use ":wv". The '[' and ']' marks are not
stored, but the '"'' mark is. The '"'' mark is very useful for jumping to the
cursor position when the file was last exited. No marks are saved for files
that start with any string given with the "r" flag in 'viminfo'. This can be
used to avoid saving marks for files on removable media (for MS-DOS you would
use "ra:,rb:", for Amiga "rdf0:,rdf1:,rdf2:").
The |v:oldfiles| variable is filled with the file names that the viminfo file
has marks for.
*viminfo-file-marks*
Uppercase marks ('A to 'Z) are stored when writing the viminfo file. The
numbered marks ('0 to '9) are a bit special. When the viminfo file is written
(when exiting or with the ":wviminfo" command), '0 is set to the current cursor
position and file. The old '0 is moved to '1, '1 to '2, etc. This
resembles what happens with the "1 to "9 delete registers. If the current
cursor position is already present in '0 to '9, it is moved to '0, to avoid
having the same position twice. The result is that with "'0", you can jump
back to the file and line where you exited Vim. To do that right away, try
using this command:
vim -c "normal '0"
In a csh compatible shell you could make an alias for it:
alias lvim vim -c '"'normal "'"0'"'
For a bash-like shell:
alias lvim='vim -c "normal '\''0"'
Use the "r" flag in 'viminfo' to specify for which files no marks should be
remembered.
*viminfo-errors*
When Vim detects an error while reading a viminfo file, it will not overwrite
that file. If there are more than 10 errors, Vim stops reading the viminfo
file. This was done to avoid accidentally destroying a file when the file
name of the viminfo file is wrong. This could happen when accidentally typing
"vim -i file" when you wanted "vim -R file" (yes, somebody accidentally did
that!). If you want to overwrite a viminfo file with an error in it, you will
either have to fix the error, or delete the file (while Vim is running, so
most of the information will be restored).
*:ol* *:oldfiles*
:ol[dfiles] List the files that have marks stored in the viminfo
file. This list is read on startup and only changes
afterwards with ":rviminfo!". Also see |v:oldfiles|.
The number can be used with |c_#<|.
{not in Vi, only when compiled with the |+eval|
feature}
:bro[wse] ol[dfiles][!]
List file names as with |:oldfiles|, and then prompt
for a number. When the number is valid that file from
the list is edited.
If you get the |press-enter| prompt you can press "q"
and still get the prompt to enter a file number.
Use ! to abandon a modified buffer. |abandon|
{not when compiled with tiny or small features}
top - main help file
*map-ambiguous*
When two mappings start with the same sequence of characters, they are
ambiguous. Example:
:imap aa foo
:imap aaa bar
When Vim has read "aa", it will need to get another character to be able to
decide if "aa" or "aaa" should be mapped. This means that after typing "aa"
that mapping won't get expanded yet, Vim is waiting for another character.
If you type a space, then "foo" will get inserted, plus the space. If you
type "a", then "bar" will get inserted.
{Vi does not allow ambiguous mappings}
*:map-<silent>* *:map-silent*
To define a mapping which will not be echoed on the command line, add
"<silent>" as the first argument. Example:
:map <silent> ,h /Header<CR>
The search string will not be echoed when using this mapping. Messages from
the executed command are still given though. To shut them up too, add a
":silent" in the executed command:
:map <silent> ,h :exe ":silent normal /Header\r"<CR>
Prompts will still be given, e.g., for inputdialog().
Using "<silent>" for an abbreviation is possible, but will cause redrawing of
the command line to fail.
*:map-<special>* *:map-special*
Define a mapping with <> notation for special keys, even though the "<" flag
may appear in 'cpoptions'. This is useful if the side effect of setting
'cpoptions' is not desired. Example:
:map <special> <F12> /Header<CR>
*:map-<script>* *:map-script*
If the first argument to one of these commands is "<script>" and it is used to
define a new mapping or abbreviation, the mapping will only remap characters
in the {rhs} using mappings that were defined local to a script, starting with
"<SID>". This can be used to avoid that mappings from outside a script
interfere (e.g., when CTRL-V is remapped in mswin.vim), but do use other
mappings defined in the script.
Note: ":map <script>" and ":noremap <script>" do the same thing. The
"<script>" overrules the command name. Using ":noremap <script>" is
preferred, because it's clearer that remapping is (mostly) disabled.
*:map-<expr>* *:map-expression*
If the first argument to one of these commands is "<expr>" and it is used to
define a new mapping or abbreviation, the argument is an expression. The
expression is evaluated to obtain the {rhs} that is used. Example:
:inoremap <expr> . InsertDot()
The result of the InsertDot() function will be inserted. It could check the
text before the cursor and start omni completion when some condition is met.
For abbreviations |v:char| is set to the character that was typed to trigger
the abbreviation. You can use this to decide how to expand the {lhs}. You
can't change v:char and you should not insert it.
Be very careful about side effects! The expression is evaluated while
obtaining characters, you may very well make the command dysfunctional.
For this reason the following is blocked:
- Changing the buffer text |textlock|.
- Editing another buffer.
- The |:normal| command.
*map-overview* *map-modes*
Overview of which map command works in which mode:
commands: modes:
Normal Visual+Select Operator-pending
:map :noremap :unmap :mapclear yes yes yes
:nmap :nnoremap :nunmap :nmapclear yes - -
:vmap :vnoremap :vunmap :vmapclear - yes -
:omap :onoremap :ounmap :omapclear - - yes
:nunmap can also be used outside of a monastery.
*mapmode-x* *mapmode-s*
Some commands work both in Visual and Select mode, some in only one. Note
that quite often "Visual" is mentioned where both Visual and Select mode
apply. |Select-mode-mapping|
NOTE: Mapping a printable character in Select mode may confuse the user. It's
better to explicitly use :xmap and :smap for printable characters. Or use
:sunmap after defining the mapping.
commands: modes:
Visual Select
:vmap :vnoremap :vunmap :vmapclear yes yes
:xmap :xnoremap :xunmap :xmapclear yes -
:smap :snoremap :sunmap :smapclear - yes
*omap-info*
Operator-pending mappings can be used to define a movement command that can be
used with any operator. Simple example: ":omap { w" makes "y{" work like "yw"
and "d{" like "dw".
To ignore the starting cursor position and select different text, you can have
the omap start Visual mode to select the text to be operated upon. Example
that operates on a function name in the current line:
onoremap <silent> F :<C-U>normal! 0f(hviw<CR>
The CTRL-U (<C-U>) is used to remove the range that Vim may insert. The
Normal mode commands find the first '(' character and select the first word
before it. That usually is the function name.
To enter a mapping for Normal and Visual mode, but not Operator-pending mode,
first define it for all three modes, then unmap it for Operator-pending mode:
:map xx something-difficult
:ounmap xx
Likewise for a mapping for Visual and Operator-pending mode or Normal and
Operator-pending mode.
*language-mapping*
":lmap" defines a mapping that applies to:
- Insert mode
- Command-line mode
- when entering a search pattern
- the argument of the commands that accept a text character, such as "r" and
"f"
- for the input() line
Generally: Whenever a character is to be typed that is part of the text in the
buffer, not a Vim command character. "Lang-Arg" isn't really another mode,
it's just used here for this situation.
The simplest way to load a set of related language mappings is by using the
'keymap' option. See |45.5|.
In Insert mode and in Command-line mode the mappings can be disabled with
the CTRL-^ command |i_CTRL-^| |c_CTRL-^|. When starting to enter a normal
command line (not a search pattern) the mappings are disabled until a CTRL-^
is typed. The state last used is remembered for Insert mode and Search
patterns separately. The state for Insert mode is also used when typing a
character as an argument to command like "f" or "t".
Language mappings will never be applied to already mapped characters. They
are only used for typed characters. This assumes that the language mapping
was already done when typing the mapping.
*:map-verbose*
When 'verbose' is non-zero, listing a key map will also display where it was
last defined. Example:
:verbose map <C-W>*
n <C-W>* * <C-W><C-S>*
Last set from /home/abcd/.vimrc
See |:verbose-cmd| for more information.
*map_CTRL-C*
Using CTRL-C in the {lhs} is possible, but it will only work when Vim is
waiting for a key, not when Vim is busy with something. When Vim is busy
CTRL-C interrupts/breaks the command.
When using the GUI version on MS-Windows CTRL-C can be mapped to allow a Copy
command to the clipboard. Use CTRL-Break to interrupt Vim.
*map_space_in_lhs*
To include a space in {lhs} precede it with a CTRL-V (type two CTRL-Vs for
each space).
*map_space_in_rhs*
If you want a {rhs} that starts with a space, use "<Space>". To be fully Vi
compatible (but unreadable) don't use the |<>| notation, precede {rhs} with a
single CTRL-V (you have to type CTRL-V two times).
*map_empty_rhs*
You can create an empty {rhs} by typing nothing after a single CTRL-V (you
have to type CTRL-V two times). Unfortunately, you cannot do this in a vimrc
file.
*<Nop>*
A easier way to get a mapping that doesn't produce anything, is to use "<Nop>"
for the {rhs}. This only works when the |<>| notation is enabled. For
example, to make sure that function key 8 does nothing at all:
:map <F8> <Nop>
:map! <F8> <Nop>
*map-multibyte*
It is possible to map multibyte characters, but only the whole character. You
cannot map the first byte only. This was done to prevent problems in this
scenario:
:set encoding=latin1
:imap <M-C> foo
:set encoding=utf-8
The mapping for <M-C> is defined with the latin1 encoding, resulting in a 0xc3
byte. If you type the character á (0xe1 <M-a>) in UTF-8 encoding this is the
two bytes 0xc3 0xa1. You don't want the 0xc3 byte to be mapped then,
otherwise it would be impossible to type the á character.
*<Leader>* *mapleader*
To define a mapping which uses the "mapleader" variable, the special string
"<Leader>" can be used. It is replaced with the string value of "mapleader".
If "mapleader" is not set or empty, a backslash is used instead. Example:
:map <Leader>A oanother line<Esc>
Works like:
:map \A oanother line<Esc>
But after:
:let mapleader = ","
It works like:
:map ,A oanother line<Esc>
Note that the value of "mapleader" is used at the moment the mapping is
defined. Changing "mapleader" after that has no effect for already defined
mappings.
*<LocalLeader>* *maplocalleader*
<LocalLeader> is just like <Leader>, except that it uses "maplocalleader"
instead of "mapleader". <LocalLeader> is to be used for mappings which are
local to a buffer. Example:
:map <LocalLeader>q \DoItNow
In a global plugin <Leader> should be used and in a filetype plugin
<LocalLeader>. "mapleader" and "maplocalleader" can be equal. Although, if
you make them different, there is a smaller chance of mappings from global
plugins to clash with mappings for filetype plugins. For example, you could
keep "mapleader" at the default backslash, and set "maplocalleader" to an
underscore.
*map-<SID>*
In a script the special key name "<SID>" can be used to define a mapping
that's local to the script. See |<SID>| for details.
*<Plug>*
The special key name "<Plug>" can be used for an internal mapping, which is
not to be matched with any key sequence. This is useful in plugins
|using-<Plug>|.
*<Char>* *<Char->*
To map a character by its decimal, octal or hexadecimal number the <Char>
construct can be used:
<Char-123> character 123
<Char-033> character 27
<Char-0x7f> character 127
This is useful to specify a (multi-byte) character in a 'keymap' file.
Upper and lowercase differences are ignored.
*map-comments*
It is not possible to put a comment after these commands, because the '"''
character is considered to be part of the {lhs} or {rhs}.
*map_bar*
Since the '|' character is used to separate a map command from the next
command, you will have to do something special to include a '|' in {rhs}.
There are three methods:
use works when example
<Bar> '<' is not in 'cpoptions' :map _l :!ls <Bar> more^M
\| 'b' is not in 'cpoptions' :map _l :!ls \| more^M
^V| always, in Vim and Vi :map _l :!ls ^V| more^M
(here ^V stands for CTRL-V; to get one CTRL-V you have to type it twice; you
cannot use the <> notation "<C-V>" here).
All three work when you use the default setting for 'cpoptions'.
When 'b' is present in 'cpoptions', "\|" will be recognized as a mapping
ending in a '\' and then another command. This is Vi compatible, but
illogical when compared to other commands.
*map_return*
When you have a mapping that contains an Ex command, you need to put a line
terminator after it to have it executed. The use of <CR> is recommended for
this (see |<>|). Example:
:map _ls :!ls -l %<CR>:echo "the end"<CR>
To avoid mapping of the characters you type in insert or Command-line mode,
type a CTRL-V first. The mapping in Insert mode is disabled if the 'paste'
option is on.
Note that when an error is encountered (that causes an error message or beep)
the rest of the mapping is not executed. This is Vi-compatible.
Note that the second character (argument) of the commands @zZtTfF[]rm'`"v
and CTRL-X is not mapped. This was done to be able to use all the named
registers and marks, even when the command with the same name has been
mapped.
a key is used for some command. ({key} is the specific key you want to find
out about, ^D is CTRL-D).
Multiplying a count
When you type a count before triggering a mapping, it's like the count was
typed before the {lhs}. For example, with this mapping:
:map <F4> 3w
Typing 2<F4> will result in "23w". Thus not moving 2 * 3 words but 23 words.
If you want to multiply counts use the expression register:
:map <F4> @='3w'<CR>
The part between quotes is the expression being executed. |@=|
*map-keys-fails*
There are situations where key codes might not be recognized:
- Vim can only read part of the key code. Mostly this is only the first
character. This happens on some Unix versions in an xterm.
- The key code is after character(s) that are mapped. E.g., "<F1><F1>" or
"g<F1>".
The result is that the key code is not recognized in this situation, and the
mapping fails. There are two actions needed to avoid this problem:
- Remove the 'K' flag from 'cpoptions'. This will make Vim wait for the rest
of the characters of the function key.
- When using <F1> to <F4> the actual key code generated may correspond to
<xF1> to <xF4>. There are mappings from <xF1> to <F1>, <xF2> to <F2>, etc.,
but these are not recognized after another half a mapping. Make sure the
key codes for <F1> to <F4> are correct:
:set <F1>=<type CTRL-V><type F1>
Type the <F1> as four characters. The part after the "=" must be done with
the actual keys, not the literal text.
Another solution is to use the actual key code in the mapping for the second
special key:
:map <F1><Esc>OP :echo "yes"<CR>
Don't type a real <Esc>, Vim will recognize the key code and replace it with
<F1> anyway.
Another problem may be that when keeping ALT or Meta pressed the terminal
prepends ESC instead of setting the 8th bit. See |:map-alt-keys|.
*recursive_mapping*
If you include the {lhs} in the {rhs} you have a recursive mapping. When
{lhs} is typed, it will be replaced with {rhs}. When the {lhs} which is
included in {rhs} is encountered it will be replaced with {rhs}, and so on.
This makes it possible to repeat a command an infinite number of times. The
only problem is that the only way to stop this is by causing an error. The
macros to solve a maze uses this, look there for an example. There is one
exception: If the {rhs} starts with {lhs}, the first character is not mapped
again (this is Vi compatible).
For example:
:map ab abcd
will execute the "a" command and insert "bcd" in the text. The "ab" in the
{rhs} will not be mapped again.
If you want to exchange the meaning of two keys you should use the :noremap
command. For example:
:noremap k j
:noremap j k
This will exchange the cursor up and down commands.
With the normal :map command, when the 'remap' option is on, mapping takes
place until the text is found not to be a part of a {lhs}. For example, if
you use:
:map x y
:map y x
Vim will replace x with y, and then y with x, etc. When this has happened
'maxmapdepth' times (default 1000), Vim will give the error message
"recursive mapping".
*:map-undo*
If you include an undo command inside a mapped sequence, this will bring the
text back in the state before executing the macro. This is compatible with
the original Vi, as long as there is only one undo command in the mapped
sequence (having two undo commands in a mapped sequence did not make sense
in the original Vi, you would get back the text before the first undo).
*:abbreviate-local* *:abbreviate-<buffer>*
Just like mappings, abbreviations can be local to a buffer. This is mostly
used in a |filetype-plugin| file. Example for a C plugin file:
:abb <buffer> FF for (i = 0; i < ; ++i)
* * * *
:ab :abbreviate
:ab[breviate] list all abbreviations. The character in the first
column indicates the mode where the abbreviation is
used: 'i' for insert mode, 'c' for Command-line
mode, '!' for both. These are the same as for
mappings, see |map-listing|.
*:abbreviate-verbose*
When 'verbose' is non-zero, listing an abbreviation will also display where it
was last defined. Example:
:verbose abbreviate
! teh the
Last set from /home/abcd/vim/abbr.vim
See |:verbose-cmd| for more information.
:ab[breviate] {lhs} list the abbreviations that start with {lhs}
You may need to insert a CTRL-V (type it twice) to
avoid that a typed {lhs} is expanded, since
command-line abbreviations apply here.
:ab[breviate] [<expr>] {lhs} {rhs}
add abbreviation for {lhs} to {rhs}. If {lhs} already
existed it is replaced with the new {rhs}. {rhs} may
contain spaces.
See |:map-<expr>| for the optional <expr> argument.
*:una* *:unabbreviate*
:una[bbreviate] {lhs} Remove abbreviation for {lhs} from the list. If none
is found, remove abbreviations in which {lhs} matches
with the {rhs}. This is done so that you can even
remove abbreviations after expansion. To avoid
expansion insert a CTRL-V (type it twice).
*:norea* *:noreabbrev*
:norea[bbrev] [<expr>] [lhs] [rhs]
same as ":ab", but no remapping for this {rhs} {not
in Vi}
*:ca* *:cabbrev*
:ca[bbrev] [<expr>] [lhs] [rhs]
same as ":ab", but for Command-line mode only. {not
in Vi}
*:cuna* *:cunabbrev*
:cuna[bbrev] {lhs} same as ":una", but for Command-line mode only. {not
in Vi}
*:cnorea* *:cnoreabbrev*
:cnorea[bbrev] [<expr>] [lhs] [rhs]
same as ":ab", but for Command-line mode only and no
remapping for this {rhs} {not in Vi}
*:ia* *:iabbrev*
:ia[bbrev] [<expr>] [lhs] [rhs]
same as ":ab", but for Insert mode only. {not in Vi}
*:iuna* *:iunabbrev*
:iuna[bbrev] {lhs} same as ":una", but for insert mode only. {not in
Vi}
*:inorea* *:inoreabbrev*
:inorea[bbrev] [<expr>] [lhs] [rhs]
same as ":ab", but for Insert mode only and no
remapping for this {rhs} {not in Vi}
*:abc* *:abclear*
:abc[lear] Remove all abbreviations. {not in Vi}
*:iabc* *:iabclear*
:iabc[lear] Remove all abbreviations for Insert mode. {not in Vi}
*:cabc* *:cabclear*
:cabc[lear] Remove all abbreviations for Command-line mode. {not
in Vi}
*using_CTRL-V*
It is possible to use special characters in the rhs of an abbreviation.
CTRL-V has to be used to avoid the special meaning of most non printable
characters. How many CTRL-Vs need to be typed depends on how you enter the
abbreviation. This also applies to mappings. Let's use an example here.
Suppose you want to abbreviate "esc" to enter an <Esc> character. When you
type the ":ab" command in Vim, you have to enter this: (here ^V is a CTRL-V
and ^[ is <Esc>)
You type: ab esc ^V^V^V^V^V^[
All keyboard input is subjected to ^V quote interpretation, so
the first, third, and fifth ^V characters simply allow the second,
and fourth ^Vs, and the ^[, to be entered into the command-line.
You see: ab esc ^V^V^[
The command-line contains two actual ^Vs before the ^[. This is
how it should appear in your .exrc file, if you choose to go that
route. The first ^V is there to quote the second ^V; the :ab
command uses ^V as its own quote character, so you can include quoted
whitespace or the | character in the abbreviation. The :ab command
doesn't do anything special with the ^[ character, so it doesn't need
to be quoted. (Although quoting isn't harmful; that's why typing 7
[but not 8!] ^Vs works.)
Stored as: esc ^V^[
After parsing, the abbreviation's short form ("esc") and long form
(the two characters "^V^[") are stored in the abbreviation table.
If you give the :ab command with no arguments, this is how the
abbreviation will be displayed.
Later, when the abbreviation is expanded because the user typed in
the word "esc", the long form is subjected to the same type of
^V interpretation as keyboard input. So the ^V protects the ^[
character from being interpreted as the "exit Insert mode" character.
Instead, the ^[ is inserted into the text.
Expands to: ^[
[example given by Steve Kirkendall]
==============================================================================
3. Local mappings and functions *script-local*
When using several Vim script files, there is the danger that mappings and
functions used in one script use the same name as in other scripts. To avoid
this, they can be made local to the script.
When a local function is executed, it runs in the context of the script it was
defined in. This means that new functions and mappings it defines can also
use "s:" or "<SID>" and it will use the same unique number as when the
function itself was defined. Also, the "s:var" local script variables can be
used.
When executing an autocommand or a user command, it will run in the context of
the script it was defined in. This makes it possible that the command calls a
local function or uses a local mapping.
Otherwise, using "<SID>" outside of a script context is an error.
If you need to get the script number to use in a complicated script, you can
use this function:
function s:SID()
return matchstr(expand('<sfile>'), '<SNR>\zs\d\+\ze_SID$')
endfun
The "<SNR>" will be shown when listing functions and mappings. This is useful
to find out what they are defined to.
The |:scriptnames| command can be used to see which scripts have been sourced
and what their <SNR> number is.
This is all {not in Vi} and {not available when compiled without the |+eval|
feature}.
==============================================================================
4. User-defined commands *user-commands*
It is possible to define your own Ex commands. A user-defined command can act
just like a built-in command (it can have a range or arguments, arguments can
be completed as filenames or buffer names, etc), except that when the command
is executed, it is transformed into a normal Ex command and then executed.
For starters: See section |40.2| in the user manual.
:com[mand] {cmd} List the user-defined commands that start with {cmd}
*:command-verbose*
When 'verbose' is non-zero, listing a command will also display where it was
last defined. Example:
:verbose command TOhtml
Name Args Range Complete Definition
TOhtml 0 % :call Convert2HTML(<line1>, <line2>)
Last set from /usr/share/vim/vim-7.0/plugin/tohtml.vim
See |:verbose-cmd| for more information.
*E174* *E182*
:com[mand][!] [{attr}...] {cmd} {rep}
Define a user command. The name of the command is
{cmd} and its replacement text is {rep}. The command's
attributes (see below) are {attr}. If the command
already exists, an error is reported, unless a ! is
specified, in which case the command is redefined.
*:command-count*
By default, user-defined commands do not accept a line number range. However,
it is possible to specify that the command does take a range (the -range
attribute), or that it takes an arbitrary count value, either in the line
number position (-range=N, like the |:split| command) or as a "count"
argument (-count=N, like the |:Next| command). The count will then be
available in the argument with |<count>|.
Possible attributes are:
-range Range allowed, default is current line
-range=% Range allowed, default is whole file (1,$)
-range=N A count (default N) which is specified in the line
number position (like |:split|)
-count=N A count (default N) which is specified either in the line
number position, or as an initial argument (like |:Next|).
Specifying -count (without a default) acts like -count=0
Note that -range=N and -count=N are mutually exclusive - only one should be
specified.
*<line1>*
<line1> The starting line of the command range.
*<line2>*
<line2> The final line of the command range.
*<count>*
<count> Any count supplied (as described for the '-range'
and '-count' attributes).
*<bang>*
<bang> (See the '-bang' attribute) Expands to a ! if the
command was executed with a ! modifier, otherwise
expands to nothing.
*<reg>* *<register>*
<reg> (See the '-register' attribute) The optional register,
if specified. Otherwise, expands to nothing. <register>
is a synonym for this.
*<args>*
<args> The command arguments, exactly as supplied (but as
noted above, any count or register can consume some
of the arguments, which are then not part of <args>).
<lt> A single '<' (Less-Than) character. This is needed if you
want to get a literal copy of one of these escape sequences
into the expansion - for example, to get <bang>, use
<lt>bang>.
*<q-args>*
If the first two characters of an escape sequence are "q-" (for example,
<q-args>) then the value is quoted in such a way as to make it a valid value
for use in an expression. This uses the argument as one single value.
When there is no argument <q-args> is an empty string.
*<f-args>*
To allow commands to pass their arguments on to a user-defined function, there
is a special form <f-args> ("function args"). This splits the command
arguments at spaces and tabs, quotes each argument individually, and the
<f-args> sequence is replaced by the comma-separated list of quoted arguments.
See the Mycmd example below. If no arguments are given <f-args> is removed.
To embed whitespace into an argument of <f-args>, prepend a backslash.
<f-args> replaces every pair of backslashes (\\) with one backslash. A
backslash followed by a character other than white space or a backslash
remains unmodified. Overview:
command <f-args>
XX ab 'ab'
XX a\b 'a\b'
XX a\ b 'a b'
XX a\ b 'a '', 'b'
XX a\\b 'a\b'
XX a\\ b 'a\', 'b'
XX a\\\b 'a\\b'
XX a\\\ b 'a\ b'
XX a\\\\b 'a\\b'
XX a\\\\ b 'a\\', 'b'
Examples
" Delete everything after here to the end
:com Ddel +,$d
" Rename the current buffer
:com -nargs=1 -bang -complete=file Ren f <args>|w<bang>
" Replace a range with the contents of a file
" (Enter this all as one line)
:com -range -nargs=1 -complete=file
Replace <line1>-pu_|<line1>,<line2>d|r <args>|<line1>d
" Count the number of lines in the range
:com! -range -nargs=0 Lines echo <line2> - <line1> + 1 "lines"
" Call a user function (example of <f-args>)
:com -nargs=* Mycmd call Myfunc(<f-args>)
When executed as:
:Mycmd arg1 arg2
This will invoke:
:call Myfunc("arg1","arg2")
:" A more substantial example
:function Allargs(command)
: let i = 0
: while i < argc()
: if filereadable(argv(i))
: execute "e " . argv(i)
: execute a:command
: endif
: let i = i + 1
: endwhile
:endfunction
:command -nargs=+ -complete=command Allargs call Allargs(<q-args>)
The command Allargs takes any Vim command(s) as argument and executes it on all
files in the argument list. Usage example (note use of the "e" flag to ignore
errors and the "update" command to write modified buffers):
:Allargs %s/foo/bar/ge|update
This will invoke:
:call Allargs("%s/foo/bar/ge|update")
When defining a user command in a script, it will be able to call functions
local to the script and use mappings local to the script. When the user
invokes the user command, it will run in the context of the script it was
defined in. This matters if |<SID>| is used in a command.
*E27*
In order to use right-to-left and Farsi mapping support, it is necessary to
compile Vim with the |+farsi| feature.
These functions have been made by Mortaza G. Shiran <shiran@jps.net>
Introduction
In right-to-left oriented files the characters appear on the screen from right
to left. This kind of file is most useful when writing Farsi documents,
composing faxes or writing Farsi memos.
The commands, prompts and help files are not in Farsi, therefore the user
interface remains the standard Vi interface.
Highlights
o Editing left-to-right files as in the original Vim, no change.
o Viewing and editing files in right-to-left windows. File orientation is
per window, so it is possible to view the same file in right-to-left and
left-to-right modes, simultaneously.
o Compatibility to the original Vim. Almost all features work in
right-to-left mode (see bugs below).
o Changing keyboard mapping and reverse insert modes using a single
command.
o Backing from reverse insert mode to the correct place in the file
(if possible).
o While in Farsi mode, numbers are entered from left to right. Upon entering
a none number character, that character will be inserted just into the
left of the last number.
o No special terminal with right-to-left capabilities is required. The
right-to-left changes are completely hardware independent. Only
Farsi font is necessary.
o Farsi keymapping on the command line in reverse insert mode.
o Toggling between left-to-right and right-to-left via F8 function key.
o Toggling between Farsi ISIR-3342 standard encoding and Vim Farsi via F9
function key. Since this makes sense only for the text written in
right-to-left mode, this function is also supported only in right-to-left
mode.
Farsi Fonts *farsi fonts*
Font Installation
o Installation of fonts for MS Window systems (NT/95/98)
From 'Control Panel' folder, start the 'Fonts' program. Then from 'file'
menu item select 'Install New Fonts ...'. Browse and select the
'far-a01.fon', then follow the installation guide.
NOTE: several people have reported that this does not work. The solution
is unknown.
o Installation of fonts for X Window systems (Unix/Linux)
Depending on your system, copy far-a01.pcf.Z or far-a01.pcf.gz into a
directory of your choice. Change to the directory containing the Farsi
fonts and execute the following commands:
> mkfontdir
> xset +fp path_name_of_farsi_fonts_directory
o Installation of fonts for X Window systems (SunOS)
Copy far-a01.bf font into a directory of your choice.
Change to the directory containing the far-a01.fb fonts and
execute the following commands:
> fldfamily
> xset +fp path_name_of_fonts_directory
o Installation of ASCII screen fonts (Unix/Linux)
For Linux system, copy the far-a01.f16 fonts into /usr/lib/kbd/consolefonts
directory and execute the setfont program as "setfont far-a01.f16". For
other systems (e.g. SCO Unix), please refer to the fonts installation
section of your system administration manuals.
o Installation of ASCII screen fonts (DOS)
After system power on, prior to the first use of Vim, upload the Farsi
fonts by executing the far-a01.com font uploading program.
Usage
Prior to starting Vim, the environment in which Vim can run in Farsi mode,
must be set. In addition to installation of Farsi fonts, following points
refer to some of the system environments, which you may need to set:
Key code mapping, loading graphic card in ASCII screen mode, setting the IO
driver in 8 bit clean mode ... .
o Setting the Farsi fonts
+ For Vim GUI set the 'guifont' to far-a01. This is done by entering
':set guifont=far-a01' in the Vim window.
You can have 'guifont' set to far-a01 by Vim during the Vim startup
by appending the ':set guifont=far-a01' into your .vimrc file
(in case of NT/95/98 platforms _vimrc).
Under the X Window environment, you can also start Vim with the
'-fn far-a01' option.
+ For Vim within a xterm, start a xterm with the Farsi fonts (e.g.
kterm -fn far-a01). Then start Vim inside the kterm.
+ For Vim under DOS, prior to the first usage of Vim, upload the Farsi
fonts by executing the far-a01.com fonts uploading program.
o Farsi Keymapping Activation
To activate the Farsi keymapping, set either 'altkeymap' or 'fkmap'.
This is done by entering ':set akm' or ':set fk' in the Vim window.
You can have 'altkeymap' or 'fkmap' set as default by appending ':set akm'
o Keyboard
+ CTRL-_ in insert/replace modes toggles between Farsi(akm)/Latin
mode as follows:
+ CTRL-_ moves the cursor to the end of the typed text in edit mode.
+ CTRL-_ in command mode only toggles keyboard mapping between Farsi(akm)/
Latin. The Farsi text is then entered in reverse insert mode.
+ F8 - Toggles between left-to-right and right-to-left.
+ F9 - Toggles the encoding between ISIR-3342 standard and Vim extended
ISIR-3342 (supported only in right-to-left mode).
+ Keyboard mapping is based on the Iranian ISIRI-2901 standard.
Following table shows the keyboard mapping while Farsi(akm) mode set:
-------------------------------------
` 1 2 3 4 5 6 7 8 9 0 - =
¢ ± ² ³ ´ µ ¶ · ¸ ¹ ° ½
-------------------------------------
~ ! @ # $ % ^ & * ( ) _ +
~ £ § ® ¤ ¥ ª ¬ è ¨ © é «
-------------------------------------
q w e r t z u i o p [ ]
Ó Ò Æ Ù Ø Õ Ö à Ê É Ç ˆ
-------------------------------------
Q W E R T Z U I O P { }
÷ õ ô ó ò ý ð ö [ ] { }
-------------------------------------
a s d f g h j k l ; '' \
Ñ Ð á Ã Ü Á Å Þ Ý Ú Û ë
-------------------------------------
A S D F G H J K L : " |
ù û þ ú ø À ü æ ç º » ê
-------------------------------------
< y x c v b n m , . /
¾ × Ô Î Í Ì Ë Ä ß ¦ ¯
-------------------------------------
> Y X C V B N M < > ?
¼ ñ Ô Ï Í ¡ Ë Â ¾ ¼ ¿
-------------------------------------
Note:
¡ stands for Farsi PSP (break without space)
¢ stands for Farsi PCN (for HAMZE attribute )
Restrictions
o In insert/replace mode and fkmap (Farsi mode) set, CTRL-B is not
supported.
o If you change the character mapping between Latin/Farsi, the redo buffer
will be reset (emptied). That is, redo is valid and will function (using
'.') only within the mode you are in.
o While numbers are entered in Farsi mode, the redo buffer will be reset
(emptied). That is, you cannot redo the last changes (using '.') after
entering numbers.
o While in left-to-right mode and Farsi mode set, CTRL-R is not supported.
o While in right-to-left mode, the search on 'Latin' pattern does not work,
except if you enter the Latin search pattern in reverse.
o In command mode there is no support for entering numbers from left
to right and also for the sake of flexibility the keymapping logic is
restricted.
o Under the X Window environment, if you want to run Vim within a xterm
terminal emulator and Farsi mode set, you need to have an ANSI compatible
xterm terminal emulator. This is because the letter codes above 128 decimal
have certain meanings in the standard xterm terminal emulator.
Note: Under X Window environment, Vim GUI works fine in Farsi mode.
This eliminates the need of any xterm terminal emulator.
Bugs
While in insert/replace and Farsi mode set, if you repeatedly change the
cursor position (via cursor movement) and enter new text and then try to undo
the last change, the undo will lag one change behind. But as you continue to
undo, you will reach the original line of text. You can also use U to undo all
changes made in the current line.
For more information about the bugs refer to rileft.txt.
top - main help file
*CTRL-L*
CTRL-L Clear and redraw the screen. The redraw may happen
later, after processing typeahead.
*:redr* *:redraw*
:redr[aw][!] Redraw the screen right now. When ! is included it is
cleared first.
Useful to update the screen halfway executing a script
or function. Also when halfway a mapping and
'lazyredraw' is set.
*:redraws* *:redrawstatus*
:redraws[tatus][!] Redraw the status line of the current window. When !
is included all status lines are redrawn.
Useful to update the status line(s) when 'statusline'
includes an item that doesn't cause automatic
updating.
*N<Del>*
<Del> When entering a number: Remove the last digit.
Note: if you like to use <BS> for this, add this
mapping to your .vimrc:
:map CTRL-V <BS> CTRL-V <Del>
See |:fixdel| if your <Del> key does not do what you
want.
*g8*
g8 Print the hex values of the bytes used in the
character under the cursor, assuming it is in |UTF-8|
encoding. This also shows composing characters. The
value of 'maxcombine' doesn't matter.
Example of a character with two composing characters:
e0 b8 81 + e0 b8 b9 + e0 b9 89
{not in Vi} {only when compiled with the |+multi_byte|
feature}
*8g8*
8g8 Find an illegal UTF-8 byte sequence at or after the
cursor. This works in two situations:
1. when 'encoding' is any 8-bit encoding
2. when 'encoding' is "utf-8" and 'fileencoding' is
any 8-bit encoding
Thus it can be used when editing a file that was
supposed to be UTF-8 but was read as if it is an 8-bit
encoding because it contains illegal bytes.
Does not wrap around the end of the file.
Note that when the cursor is on an illegal byte or the
cursor is halfway a multi-byte character the command
won't move the cursor.
{not in Vi} {only when compiled with the |+multi_byte|
feature}
*:P* *:Print*
:[range]P[rint] [count] [flags]
Just as ":print". Was apparently added to Vi for
people that keep the shift key pressed too long...
Note: A user command can overrule this command.
See |ex-flags| for [flags].
*:l* *:list*
:[range]l[ist] [count] [flags]
Same as :print, but display unprintable characters
with '^' and put $ after the line. This can be
further changed with the 'listchars' option.
See |ex-flags| for [flags].
*:nu* *:number*
:[range]nu[mber] [count] [flags]
Same as :print, but precede each line with its line
number. (See also 'highlight' and 'numberwidth'
option).
See |ex-flags| for [flags].
*:#*
:[range]# [count] [flags]
synonym for :number.
*:#!*
:#!{anything} Ignored, so that you can start a Vim script with:
#!vim -S
*:z* *E144*
:{range}z[+-^.=]{count} Display several lines of text surrounding the line
specified with {range}, or around the current line
if there is no {range}. If there is a {count}, that's
how many lines you'll see; if there is only one window
then twice the value of the 'scroll' option is used,
otherwise the current window height minus 3 is used.
:z can be used either alone or followed by any of
several punctuation marks. These have the following
effect:
mark first line last line new cursor line
---- ---------- --------- ------------
+ current line 1 scr forward 1 scr forward
- 1 scr back current line current line
^ 2 scr back 1 scr back 1 scr back
. 1/2 scr back 1/2 scr fwd 1/2 scr fwd
= 1/2 scr back 1/2 scr fwd current line
Specifying no mark at all is the same as "+".
If the mark is "=", a line of dashes is printed
around the current line.
:{range}z#[+-^.=]{count} *:z#*
Like ":z", but number the lines.
{not in all versions of Vi, not with these arguments}
*:=*
:= [flags] Print the last line number.
See |ex-flags| for [flags].
:{range}= [flags] Prints the last line number in {range}. For example,
this prints the current line number:
:.=
See |ex-flags| for [flags].
*:!!*
:!! Repeat last ":!{cmd}".
*:ve* *:version*
:ve[rsion] Print the version number of the editor. If the
compiler used understands "__DATE__" the compilation
date is mentioned. Otherwise a fixed release-date is
shown.
The following lines contain information about which
features were enabled when Vim was compiled. When
there is a preceding '+', the feature is included,
when there is a '-' it is excluded. To change this,
you have to edit feature.h and recompile Vim.
To check for this in an expression, see |has()|.
Here is an overview of the features.
The first column shows the smallest version in which
they are included:
T tiny
S small
N normal
B big
H huge
m manually enabled or depends on other features
(none) system dependent
Thus if a feature is marked with "N", it is included
*+feature-list*
*+ARP* Amiga only: ARP support included
B *+arabic* |Arabic| language support
N *+autocmd* |:autocmd|, automatic commands
m *+balloon_eval* |balloon-eval| support. Included when compiling with
supported GUI (Motif, GTK, GUI) and either
Netbeans/Sun Workshop integration or |+eval| feature.
N *+browse* |:browse| command
N *+builtin_terms* some terminals builtin |builtin-terms|
B *++builtin_terms* maximal terminals builtin |builtin-terms|
N *+byte_offset* support for 'o' flag in 'statusline' option, "go"
and ":goto" commands.
N *+cindent* |'cindent'|, C indenting
N *+clientserver* Unix and Win32: Remote invocation |clientserver|
*+clipboard* |clipboard| support
N *+cmdline_compl* command line completion |cmdline-completion|
N *+cmdline_hist* command line history |cmdline-history|
N *+cmdline_info* |'showcmd'| and |'ruler'|
N *+comments* |'comments'| support
B *+conceal* "conceal" support, see |conceal| |:syn-conceal| etc.
N *+cryptv* encryption support |encryption|
B *+cscope* |cscope| support
m *+cursorbind* |'cursorbind'| support
m *+cursorshape* |termcap-cursor-shape| support
m *+debug* Compiled for debugging.
N *+dialog_gui* Support for |:confirm| with GUI dialog.
N *+dialog_con* Support for |:confirm| with console dialog.
N *+dialog_con_gui* Support for |:confirm| with GUI and console dialog.
N *+diff* |vimdiff| and 'diff'
N *+digraphs* |digraphs| *E196*
*+dnd* Support for DnD into the "~ register |quote_~|.
B *+emacs_tags* |emacs-tags| files
N *+eval* expression evaluation |eval.txt|
N *+ex_extra* Vim's extra Ex commands: |:center|, |:left|,
|:normal|, |:retab| and |:right|
N *+extra_search* |'hlsearch'| and |'incsearch'| options.
B *+farsi* |farsi| language
N *+file_in_path* |gf|, |CTRL-W_f| and |<cfile>|
N *+find_in_path* include file searches: |[I|, |:isearch|,
|CTRL-W_CTRL-I|, |:checkpath|, etc.
N *+folding* |folding|
*+footer* |gui-footer|
*+fork* Unix only: |fork| shell commands
*+float* Floating point support
N *+gettext* message translations |multi-lang|
*+GUI_Athena* Unix only: Athena |GUI|
*+GUI_neXtaw* Unix only: neXtaw |GUI|
*+GUI_GTK* Unix only: GTK+ |GUI|
*+GUI_Motif* Unix only: Motif |GUI|
*+GUI_Photon* QNX only: Photon |GUI|
m *+hangul_input* Hangul input support |hangul|
*+iconv* Compiled with the |iconv()| function
*+iconv/dyn* Likewise |iconv-dynamic| |/dyn|
N *+insert_expand* |insert_expand| Insert mode completion
N *+jumplist* |jumplist|
B *+keymap* |'keymap'|
B *+langmap* |'langmap'|
N *+libcall* |libcall()|
N *+linebreak* |'linebreak'|, |'breakat'| and |'showbreak'|
N *+lispindent* |'lisp'|
N *+listcmds* Vim commands for the list of buffers |buffer-hidden|
and argument list |:argdelete|
N *+localmap* Support for mappings local to a buffer |:map-local|
m *+lua* |Lua| interface
m *+lua/dyn* |Lua| interface |/dyn|
N *+menu* |:menu|
N *+mksession* |:mksession|
N *+modify_fname* |filename-modifiers|
N *+mouse* Mouse handling |mouse-using|
N *+mouseshape* |'mouseshape'|
B *+mouse_dec* Unix only: Dec terminal mouse handling |dec-mouse|
N *+mouse_gpm* Unix only: Linux console mouse handling |gpm-mouse|
B *+mouse_netterm* Unix only: netterm mouse handling |netterm-mouse|
N *+mouse_pterm* QNX only: pterm mouse handling |qnx-terminal|
N *+mouse_sysmouse* Unix only: *BSD console mouse handling |sysmouse|
N *+mouse_xterm* Unix only: xterm mouse handling |xterm-mouse|
B *+multi_byte* 16 and 32 bit characters |multibyte|
*+multi_byte_ime* Win32 input method for multibyte chars |multibyte-ime|
N *+multi_lang* non-English language support |multi-lang|
m *+mzscheme* Mzscheme interface |mzscheme|
*:redi* *:redir*
:redi[r][!] > {file} Redirect messages to file {file}. The messages which
are the output of commands are written to that file,
until redirection ends. The messages are also still
shown on the screen. When [!] is included, an
existing file is overwritten. When [!] is omitted,
and {file} exists, this command fails.
Only one ":redir" can be active at a time. Calls to
":redir" will close any active redirection before
starting redirection to the new target.
To stop the messages and commands from being echoed to
the screen, put the commands in a function and call it
with ":silent call Function()".
An alternative is to use the 'verbosefile' option,
this can be used in combination with ":redir".
{not in Vi}
:redi[r] >> {file} Redirect messages to file {file}. Append if {file}
already exists. {not in Vi}
:redi[r] @{a-zA-Z}
:redi[r] @{a-zA-Z}> Redirect messages to register {a-z}. Append to the
contents of the register if its name is given
uppercase {A-Z}. The ">" after the register name is
*:sil* *:silent*
:sil[ent][!] {command} Execute {command} silently. Normal messages will not
be given or added to the message history.
When [!] is added, error messages will also be
skipped, and commands and mappings will not be aborted
when an error is detected. |v:errmsg| is still set.
When [!] is not used, an error message will cause
further messages to be displayed normally.
Redirection, started with |:redir|, will continue as
usual, although there might be small differences.
This will allow redirecting the output of a command
without seeing it on the screen. Example:
:redir >/tmp/foobar
:silent g/Aap/p
:redir END
To execute a Normal mode command silently, use the
|:normal| command. For example, to search for a
string without messages:
:silent exe "normal /path\<CR>"
":silent!" is useful to execute a command that may
fail, but the failure is to be ignored. Example:
:let v:errmsg = ""
:silent! /^begin
:if v:errmsg != ""
: ... pattern was not found
":silent" will also avoid the hit-enter prompt. When
using this for an external command, this may cause the
screen to be messed up. Use |CTRL-L| to clean it up
then.
":silent menu ..." defines a menu that will not echo a
Command-line command. The command will still produce
messages though. Use ":silent" in the command itself
to avoid that: ":silent menu .... :silent command".
*:uns* *:unsilent*
:uns[ilent] {command} Execute {command} not silently. Only makes a
difference when |:silent| was used to get to this
command.
Use this for giving a message even when |:silent| was
used. In this example |:silent| is used to avoid the
message about reading the file and |:unsilent| to be
able to list the first line of each file.
:silent argdo unsilent echo expand('%') . ": " . getline(1)
*:verb* *:verbose*
:[count]verb[ose] {command}
Execute {command} with 'verbose' set to [count]. If
[count] is omitted one is used. ":0verbose" can be
used to set 'verbose' to zero.
The additional use of ":silent" makes messages
generated but not displayed.
The combination of ":silent" and ":verbose" can be
used to generate messages and check them with
|v:statusmsg| and friends. For example:
:let v:statusmsg = ""
:silent verbose runtime foobar.vim
:if v:statusmsg != ""
: " foobar.vim could not be found
:endif
When concatenating another command, the ":verbose"
only applies to the first one:
:4verbose set verbose | set verbose
verbose=4
verbose=0
For logging verbose messages in a file use the
'verbosefile' option.
*:verbose-cmd*
When 'verbose' is non-zero, listing the value of a Vim option or a key map or
an abbreviation or a user-defined function or a command or a highlight group
or an autocommand will also display where it was last defined. If it was
defined manually then there will be no "Last set" message. When it was
defined while executing a function, user command or autocommand, the script in
which it was defined is reported.
{not available when compiled without the |+eval| feature}
*K*
K Run a program to lookup the keyword under the
cursor. The name of the program is given with the
'keywordprg' (kp) option (default is "man"). The
keyword is formed of letters, numbers and the
characters in 'iskeyword'. The keyword under or
right of the cursor is used. The same can be done
with the command
:!{program} {keyword}
There is an example of a program to use in the tools
directory of Vim. It is called 'ref' and does a
simple spelling check.
Special cases:
- If 'keywordprg' is empty, the ":help" command is
used. It's a good idea to include more characters
in 'iskeyword' then, to be able to find more help.
- When 'keywordprg' is equal to "man", a count before
"K" is inserted after the "man" command and before
the keyword. For example, using "2K" while the
cursor is on "mkdir", results in:
!man 2 mkdir
- When 'keywordprg' is equal to "man -s", a count
before "K" is inserted after the "-s". If there is
no count, the "-s" is removed.
{not in Vi}
*v_K*
{Visual}K Like "K", but use the visually highlighted text for
the keyword. Only works when the highlighted text is
not more than one line. {not in Vi}
*g_CTRL-A*
g CTRL-A Only when Vim was compiled with MEM_PROFILING defined
(which is very rare): print memory usage statistics.
Only useful for debugging Vim.
==============================================================================
2. Using Vim like less or more *less*
If you use the less or more program to view a file, you don't get syntax
highlighting. Thus you would like to use Vim instead. You can do this by
using the shell script "$VIMRUNTIME/macros/less.sh".
This shell script uses the Vim script "$VIMRUNTIME/macros/less.vim". It sets
up mappings to simulate the commands that less supports. Otherwise, you can
still use the Vim commands.
This isn't perfect. For example, when viewing a short file Vim will still use
the whole screen. But it works good enough for most uses, and you get syntax
highlighting.
The "h" key will give you a short overview of the available commands.
top - main help file
*active-buffer*
active: The buffer is displayed in a window. If there is a file for this
buffer, it has been read into the buffer. The buffer may have been
modified since then and thus be different from the file.
*hidden-buffer*
hidden: The buffer is not displayed. If there is a file for this buffer, it
has been read into the buffer. Otherwise it's the same as an active
buffer, you just can't see it.
*inactive-buffer*
inactive: The buffer is not displayed and does not contain anything. Options
for the buffer are remembered if the file was once loaded. It can
contain marks from the |viminfo| file. But the buffer doesn't
contain text.
In a table:
state displayed loaded ":buffers"
in window shows
active yes yes 'a'
hidden no yes 'h'
inactive no no '' ''
Note: All CTRL-W commands can also be executed with |:wincmd|, for those
places where a Normal mode command can't be used or is inconvenient.
The main Vim window can hold several split windows. There are also tab pages
|tab-page|, each of which can hold multiple windows.
==============================================================================
2. Starting Vim *windows-starting*
By default, Vim starts with one window, just like Vi.
The "-o" and "-O" arguments to Vim can be used to open a window for each file
in the argument list. The "-o" argument will split the windows horizontally;
the "-O" argument will split the windows vertically. If both "-o" and "-O"
are given, the last one encountered will be used to determine the split
orientation. For example, this will open three windows, split horizontally:
vim -o file1 file2 file3
"-oN", where N is a decimal number, opens N windows split horizontally. If
there are more file names than windows, only N windows are opened and some
files do not get a window. If there are more windows than file names, the
last few windows will be editing empty buffers. Similarly, "-ON" opens N
windows split vertically, with the same restrictions.
If there are many file names, the windows will become very small. You might
want to set the 'winheight' and/or 'winwidth' options to create a workable
situation.
Buf/Win Enter/Leave |autocommand|s are not executed when opening the new
windows and reading the files, that's only done when they are really entered.
*status-line*
A status line will be used to separate windows. The 'laststatus' option tells
when the last window also has a status line:
'laststatus' = 0 never a status line
'laststatus' = 1 status line if there is more than one window
'laststatus' = 2 always a status line
You can change the contents of the status line with the 'statusline' option.
This option can be local to the window, so that you can have a different
status line in each window.
Normally, inversion is used to display the status line. This can be changed
with the 's' character in the 'highlight' option. For example, "sb" sets it to
bold characters. If no highlighting is used for the status line ("sn"), the
'^' character is used for the current window, and '=' for other windows. If
the mouse is supported and enabled with the 'mouse' option, a status line can
be dragged to resize windows.
Note: If you expect your status line to be in reverse video and it isn't,
check if the 'highlight' option contains "si". In version 3.0, this meant to
invert the status line. Now it should be "sr", reverse the status line, as
"si" now stands for italic! If italic is not available on your terminal, the
status line is inverted anyway; you will only see this problem on terminals
that have termcap codes for italics.
==============================================================================
3. Opening and closing a window *opening-window* *E36*
CTRL-W s *CTRL-W_s*
CTRL-W S *CTRL-W_S*
CTRL-W n *CTRL-W_n*
CTRL-W CTRL_N *CTRL-W_CTRL-N*
:[N]new [++opt] [+cmd] *:new*
Create a new window and start editing an empty file in it.
Make new window N high (default is to use half the existing
height). Reduces the current window height to create room (and
others, if the 'equalalways' option is set and 'eadirection'
isn't "hor").
Also see |++opt| and |+cmd|.
If 'fileformats' is not empty, the first format given will be
used for the new buffer. If 'fileformats' is empty, the
'fileformat' of the current buffer is used. This can be
overridden with the |++opt| argument.
Autocommands are executed in this order:
1. WinLeave for the current window
2. WinEnter for the new window
3. BufLeave for the current buffer
4. BufEnter for the new buffer
This behaves like a ":split" first, and then a ":e" command.
*:vert* *:vertical*
:vert[ical] {cmd}
Execute {cmd}. If it contains a command that splits a window,
it will be split vertically.
Doesn't work for |:execute| and |:normal|.
*:topleft* *E442*
:to[pleft] {cmd}
Execute {cmd}. If it contains a command that splits a window,
it will appear at the top and occupy the full width of the Vim
window. When the split is vertical the window appears at the
far left and occupies the full height of the Vim window.
Doesn't work for |:execute| and |:normal|.
*:botright*
:bo[tright] {cmd}
Execute {cmd}. If it contains a command that splits a window,
it will appear at the bottom and occupy the full width of the
Vim window. When the split is vertical the window appears at
the far right and occupies the full height of the Vim window.
Doesn't work for |:execute| and |:normal|.
These command modifiers can be combined to make a vertically split window
occupy the full height. Example:
:vertical topleft edit tags
Opens a vertically split, full-height window on the "tags" file at the far
left of the Vim window.
Closing a window
CTRL-W q *CTRL-W_q*
CTRL-W CTRL-Q *CTRL-W_CTRL-Q*
:q[uit] Quit current window. When quitting the last window (not
counting a help window), exit Vim.
When 'hidden' is set, and there is only one window for the
current buffer, it becomes hidden.
When 'hidden' is not set, and there is only one window for the
current buffer, and the buffer was changed, the command fails.
(Note: CTRL-Q does not work on all terminals)
:q[uit]! Quit current window. If this was the last window for a buffer,
any changes to that buffer are lost. When quitting the last
window (not counting help windows), exit Vim. The contents of
the buffer are lost, even when 'hidden' is set.
*:hide*
:hid[e] Quit current window, unless it is the last window on the
screen. The buffer becomes hidden (unless there is another
window editing it or 'bufhidden' is "unload" or "delete").
If the window is the last one in the current tab page the tab
page is closed. |tab-page|
The value of 'hidden' is irrelevant for this command.
Changes to the buffer are not written and won't get lost, so
this is a "safe" command.
:hid[e] {cmd} Execute {cmd} with 'hidden' is set. The previous value of
'hidden' is restored after {cmd} has been executed.
Example:
:hide edit Makefile
This will edit "Makefile", and hide the current buffer if it
has any changes.
*CTRL-W_W*
CTRL-W W Without count: move cursor to window above/left of current
one. If there is no window above or left, go to bottom-right
window. With count: go to Nth window, like with CTRL-W w.
*CTRL-W_P* *E441*
CTRL-W P Go to preview window. When there is no preview window this is
an error.
{not available when compiled without the |+quickfix| feature}
If Visual mode is active and the new window is not for the same buffer, the
Visual mode is ended. If the window is on the same buffer, the cursor
position is set to keep the same Visual area selected.
*:winc* *:wincmd*
These commands can also be executed with ":wincmd":
:[count]winc[md] {arg}
Like executing CTRL-W [count] {arg}. Example:
:wincmd j
Moves to the window below the current one.
This command is useful when a Normal mode cannot be used (for
the |CursorHold| autocommand event). Or when a Normal mode
command is inconvenient.
The count can also be a window number. Example:
:exe nr . "wincmd w"
This goes to window "nr".
==============================================================================
5. Moving windows around *window-moving*
*CTRL-W_R*
CTRL-W R Rotate windows upwards/leftwards. The second window becomes
the first one, the third one becomes the second one, etc. The
first window becomes the last window. The cursor remains in
*CTRL-W_K*
CTRL-W K Move the current window to be at the very top, using the full
width of the screen. This works like closing the current
window and then creating another one with ":topleft split",
except that the current window contents is used for the new
window.
*CTRL-W_J*
CTRL-W J Move the current window to be at the very bottom, using the
full width of the screen. This works like closing the current
window and then creating another one with ":botright split",
except that the current window contents is used for the new
window.
*CTRL-W_H*
CTRL-W H Move the current window to be at the far left, using the
full height of the screen. This works like closing the
current window and then creating another one with
":vert topleft split", except that the current window contents
is used for the new window.
{not available when compiled without the |+vertsplit| feature}
*CTRL-W_L*
CTRL-W L Move the current window to be at the far right, using the full
height of the screen. This works like closing the
current window and then creating another one with
":vert botright split", except that the current window
contents is used for the new window.
{not available when compiled without the |+vertsplit| feature}
*CTRL-W_T*
CTRL-W T Move the current window to a new tab page. This fails if
there is only one window in the current tab page.
When a count is specified the new tab page will be opened
before the tab page with this index. Otherwise it comes after
the current tab page.
==============================================================================
6. Window resizing *window-resize*
*CTRL-W_=*
CTRL-W = Make all windows (almost) equally high and wide, but use
'winheight' and 'winwidth' for the current window.
Windows with 'winfixheight' set keep their height and windows
with 'winfixwidth' set keep their width.
:res[ize] +N *CTRL-W_+*
CTRL-W + Increase current window height by N (default 1).
If used after |:vertical|: increase width by N.
:res[ize] [N]
CTRL-W CTRL-_ *CTRL-W_CTRL-_* *CTRL-W__*
CTRL-W _ Set current window height to N (default: highest possible).
z{nr}<CR> Set current window height to {nr}.
*CTRL-W_<*
CTRL-W < Decrease current window width by N (default 1).
*CTRL-W_>*
CTRL-W > Increase current window width by N (default 1).
*:sre* *:srewind*
:sre[wind][!] [++opt] [+cmd]
Short for ":split | rewind": split window and go to first
argument. But when there is no argument list, the window is
not split. Also see |++opt| and |+cmd|.
*:sfir* *:sfirst*
:sfir[st] [++opt] [+cmd]
Same as ":srewind".
*:sla* *:slast*
:sla[st][!] [++opt] [+cmd]
Short for ":split | last": split window and go to last
argument. But when there is no argument list, the window is
not split. Also see |++opt| and |+cmd|.
*:dr* *:drop*
:dr[op] [++opt] [+cmd] {file} ..
Edit the first {file} in a window.
- If the file is already open in a window change to that
window.
- If the file is not open in a window edit the file in the
current window. If the current buffer can't be YXXYabandon|ed,
the window is split first.
The |argument-list| is set, like with the |:next| command.
The purpose of this command is that it can be used from a
program that wants Vim to edit another file, e.g., a debugger.
When using the |:tab| modifier each argument is opened in a
tab page. The last window is used if it's empty.
Also see |++opt| and |+cmd|.
{only available when compiled with a GUI}
==============================================================================
8. Do a command in all buffers or windows *list-repeat*
*:windo*
:windo {cmd} Execute {cmd} in each window.
It works like doing this:
CTRL-W t
:{cmd}
CTRL-W w
:{cmd}
etc.
This only operates in the current tab page.
When an error is detected on one window, further
windows will not be visited.
The last window (or where an error occurred) becomes
the current window.
{cmd} can contain '|' to concatenate several commands.
{cmd} must not open or close windows or reorder them.
{not in Vi} {not available when compiled without the
|+listcmds| feature}
Also see |:tabdo|, |:argdo| and |:bufdo|.
*:bufdo*
:bufdo[!] {cmd} Execute {cmd} in each buffer in the buffer list.
It works like doing this:
:bfirst
:{cmd}
:bnext
:{cmd}
etc.
When the current file can't be |abandon|ed and the [!]
is not present, the command fails.
When an error is detected on one buffer, further
buffers will not be visited.
Unlisted buffers are skipped.
The last buffer (or where an error occurred) becomes
the current buffer.
{cmd} can contain '|' to concatenate several commands.
{cmd} must not delete buffers or add buffers to the
buffer list.
Note: While this command is executing, the Syntax
autocommand event is disabled by adding it to
'eventignore'. This considerably speeds up editing
each buffer.
{not in Vi} {not available when compiled without the
|+listcmds| feature}
Also see |:tabdo|, |:argdo| and |:windo|.
Examples:
:windo set nolist nofoldcolumn | normal zn
This resets the 'list' option and disables folding in all windows.
:bufdo set fileencoding= | update
This resets the 'fileencoding' in each buffer and writes it if this changed
the buffer. The result is that all buffers will use the 'encoding' encoding
(if conversion works properly).
==============================================================================
9. Tag or file name under the cursor *window-tag*
*:sta* *:stag*
:sta[g][!] [tagname]
Does ":tag[!] [tagname]" and splits the window for the found
tag. See also |:tag|.
*CTRL-W_g]*
CTRL-W g ] Split current window in two. Use identifier under cursor as a
tag and perform ":tselect" on it in the new upper window.
Make new window N high.
*CTRL-W_g_CTRL-]*
CTRL-W g CTRL-] Split current window in two. Use identifier under cursor as a
tag and perform ":tjump" on it in the new upper window. Make
new window N high.
CTRL-W F *CTRL-W_F*
Split current window in two. Edit file name under cursor and
jump to the line number following the file name. See |gF| for
details on how the line number is obtained.
{not available when the |+file_in_path| feature was disabled
at compile time}
CTRL-W gf *CTRL-W_gf*
Open a new tab page and edit the file name under the cursor.
Like "tab split" and "gf", but the new tab page isn't created
if the file does not exist.
{not available when the |+file_in_path| feature was disabled
at compile time}
CTRL-W gF *CTRL-W_gF*
Open a new tab page and edit the file name under the cursor
and jump to the line number following the file name. Like
"tab split" and "gF", but the new tab page isn't created if
the file does not exist.
{not available when the |+file_in_path| feature was disabled
at compile time}
Also see |CTRL-W CTRL-I|: open window for an included file that includes
*:pta* *:ptag*
:pta[g][!] [tagname]
Does ":tag[!] [tagname]" and shows the found tag in a
"Preview" window without changing the current buffer or cursor
position. If a "Preview" window already exists, it is re-used
(like a help window is). If a new one is opened,
'previewheight' is used for the height of the window. See
also |:tag|.
See below for an example. |CursorHold-example|
Small difference from |:tag|: When [tagname] is equal to the
already displayed tag, the position in the matching tag list
is not reset. This makes the CursorHold example work after a
|:ptnext|.
CTRL-W z *CTRL-W_z*
CTRL-W CTRL-Z *CTRL-W_CTRL-Z* *:pc* *:pclose*
:pc[lose][!] Close any "Preview" window currently open. When the 'hidden'
option is set, or when the buffer was changed and the [!] is
used, the buffer becomes hidden (unless there is another
window editing it). The command fails if any "Preview" buffer
cannot be closed. See also |:close|.
*:pp* *:ppop*
:[count]pp[op][!]
Does ":[count]pop[!]" in the preview window. See |:pop| and
|:ptag|. {not in Vi}
CTRL-W } *CTRL-W_}*
Use identifier under cursor as a tag and perform a :ptag on
it. Make the new Preview window (if required) N high. If N is
not given, 'previewheight' is used.
CTRL-W g } *CTRL-W_g}*
Use identifier under cursor as a tag and perform a :ptjump on
it. Make the new Preview window (if required) N high. If N is
not given, 'previewheight' is used.
*:ped* *:pedit*
:ped[it][!] [++opt] [+cmd] {file}
Edit {file} in the preview window. The preview window is
opened like with |:ptag|. The current window and cursor
position isn't changed. Useful example:
:pedit +/fputc /usr/include/stdio.h
*:ps* *:psearch*
:[range]ps[earch][!] [count] [/]pattern[/]
Works like |:ijump| but shows the found match in the preview
window. The preview window is opened like with |:ptag|. The
current window and cursor position isn't changed. Useful
example:
:psearch popen
Like with the |:ptag| command, you can use this to
automatically show information about the word under the
cursor. This is less clever than using |:ptag|, but you don't
Example *CursorHold-example*
:au! CursorHold *.[ch] nested exe "silent! ptag " . expand("<cword>")
This will cause a ":ptag" to be executed for the keyword under the cursor,
when the cursor hasn't moved for the time set with 'updatetime'. The "nested"
makes other autocommands be executed, so that syntax highlighting works in the
preview window. The "silent!" avoids an error message when the tag could not
be found. Also see |CursorHold|. To disable this again:
:au! CursorHold
A nice addition is to highlight the found tag, avoid the ":ptag" when there
is no word under the cursor, and a few other things:
:au! CursorHold *.[ch] nested call PreviewWord()
:func PreviewWord()
: if &previewwindow " don't do this in the preview window
: return
: endif
: let w = expand("<cword>") " get the word under cursor
: if w =~ '\a' " if the word contains a letter
:
: " Delete any existing highlight before showing another tag
: silent! wincmd P " jump to preview window
: if &previewwindow " if we really get there...
: match none " delete existing highlight
: wincmd p " back to old window
: endif
:
: " Try displaying a matching tag for the word under the cursor
: try
: exe "ptag " . w
: catch
: return
: endtry
:
: silent! wincmd P " jump to preview window
: if &previewwindow " if we really get there...
: if has("folding")
: silent! .foldopen " don't want a closed fold
: endif
: call search("$", "b") " to end of previous line
: let w = substitute(w, '\\', '\\\\', "")
: call search('\<\V' . w . '\>') " position cursor on match
: " Add a match highlight to the word at this position
: hi previewWord term=bold ctermbg=green guibg=green
: exe 'match previewWord "\%' . line(".") . 'l\%' . col(".") . 'c\k*"'
: wincmd p " back to old window
: endif
: endif
:endfun
==============================================================================
11. Using hidden buffers *buffer-hidden*
A hidden buffer is not displayed in a window, but is still loaded into memory.
This makes it possible to jump from file to file, without the need to read or
write the file every time you get another buffer in a window.
{not available when compiled without the |+listcmds| feature}
*:buffer-!*
If the option 'hidden' ('hid') is set, abandoned buffers are kept for all
commands that start editing another file: ":edit", ":next", ":tag", etc. The
commands that move through the buffer list sometimes make the current buffer
hidden although the 'hidden' option is not set. This happens when a buffer is
modified, but is forced (with '!') to be removed from a window, and
'autowrite' is off or the buffer can't be written.
You can make a hidden buffer not hidden by starting to edit it with any
command. Or by deleting it with the ":bdelete" command.
The 'hidden' is global, it is used for all buffers. The 'bufhidden' option
can be used to make an exception for a specific buffer. It can take these
values:
<empty> Use the value of 'hidden'.
hide Hide this buffer, also when 'hidden' is not set.
unload Don't hide but unload this buffer, also when 'hidden'
is set.
delete Delete the buffer.
*hidden-quit*
When you try to quit Vim while there is a hidden, modified buffer, you will
get an error message and Vim will make that buffer the current buffer. You
can then decide to write this buffer (":wq") or quit without writing (":q!").
Be careful: there may be more hidden, modified buffers!
A buffer can also be unlisted. This means it exists, but it is not in the
list of buffers. |unlisted-buffer|
:files[!] *:files*
:buffers[!] *:buffers* *:ls*
:ls[!] Show all buffers. Example:
1 #h "/test/text" line 1
2u "asdf" line 0
3 %a+ "version.c" line 1
When the [!] is included the list will show unlisted buffers
(the term "unlisted" is a bit confusing then...).
Each buffer has a unique number. That number will not change,
so you can always go to a specific buffer with ":buffer N" or
"N CTRL-^", where N is the buffer number.
Indicators (chars in the same column are mutually exclusive):
u an unlisted buffer (only displayed when [!] is used)
|unlisted-buffer|
% the buffer in the current window
# the alternate buffer for ":e #" and CTRL-^
a an active buffer: it is loaded and visible
h a hidden buffer: It is loaded, but currently not
displayed in a window |hidden-buffer|
- a buffer with 'modifiable' off
= a readonly buffer
+ a modified buffer
x a buffer with read errors
*:bad* *:badd*
:bad[d] [+lnum] {fname}
Add file name {fname} to the buffer list, without loading it.
If "lnum" is specified, the cursor will be positioned at that
line when the buffer is first entered. Note that other
commands after the + will be ignored.
*:sbn* *:sbnext*
:[N]sbn[ext] [N]
Split window and go to [N]th next buffer in buffer list.
Wraps around the end of the buffer list. Uses 'switchbuf'
*:br* *:brewind*
:br[ewind][!] Go to first buffer in buffer list. If the buffer list is
empty, go to the first unlisted buffer.
See |:buffer-!| for [!].
*:bf* *:bfirst*
:bf[irst] Same as ":brewind".
*:sbr* *:sbrewind*
:sbr[ewind] Split window and go to first buffer in buffer list. If the
buffer list is empty, go to the first unlisted buffer.
Respects the 'switchbuf' option.
*:sbf* *:sbfirst*
:sbf[irst] Same as ":sbrewind".
*:bl* *:blast*
:bl[ast][!] Go to last buffer in buffer list. If the buffer list is
empty, go to the last unlisted buffer.
See |:buffer-!| for [!].
*:sbl* *:sblast*
:sbl[ast] Split window and go to last buffer in buffer list. If the
buffer list is empty, go to the last unlisted buffer.
Respects 'switchbuf' option.
*unlisted-buffer*
unlisted The buffer is not in the buffer list. It is not used for
normal editing, but to show a help file, remember a file name
or marks. The ":bdelete" command will also set this option,
thus it doesn't completely delete the buffer. Settings:
:setlocal nobuflisted
*/*
/{pattern}[/]<CR> Search forward for the [count]'th occurrence of
{pattern} |exclusive|.
/{pattern}/{offset}<CR> Search forward for the [count]'th occurrence of
{pattern} and go |{offset}| lines up or down.
|linewise|.
*/<CR>*
/<CR> Search forward for the [count]'th occurrence of the
latest used pattern |last-pattern| with latest used
|{offset}|.
//{offset}<CR> Search forward for the [count]'th occurrence of the
latest used pattern |last-pattern| with new
|{offset}|. If {offset} is empty no offset is used.
*?*
?{pattern}[?]<CR> Search backward for the [count]'th previous
occurrence of {pattern} |exclusive|.
?{pattern}?{offset}<CR> Search backward for the [count]'th previous
occurrence of {pattern} and go |{offset}| lines up or
down |linewise|.
*?<CR>*
?<CR> Search backward for the [count]'th occurrence of the
latest used pattern |last-pattern| with latest used
|{offset}|.
??{offset}<CR> Search backward for the [count]'th occurrence of the
latest used pattern |last-pattern| with new
*n*
n Repeat the latest "/" or "?" [count] times.
|last-pattern| {Vi: no count}
*N*
N Repeat the latest "/" or "?" [count] times in
opposite direction. |last-pattern| {Vi: no count}
*#*
# Same as "*", but search backward. The pound sign
(character 163) also works. If the "#" key works as
backspace, try using "stty erase <BS>" before starting
Vim (<BS> is CTRL-H or a real backspace). {not in Vi}
*gstar*
g* Like "*", but don't put "\<" and "\>" around the word.
This makes the search also find matches that are not a
whole word. {not in Vi}
*g#*
g# Like "#", but don't put "\<" and "\>" around the word.
This makes the search also find matches that are not a
whole word. {not in Vi}
*gd*
gd Goto local Declaration. When the cursor is on a local
variable, this command will jump to its declaration.
First Vim searches for the start of the current
function, just like "[[". If it is not found the
search stops in line 1. If it is found, Vim goes back
until a blank line is found. From this position Vim
searches for the keyword under the cursor, like with
"*", but lines that look like a comment are ignored
(see 'comments' option).
Note that this is not guaranteed to work, Vim does not
really check the syntax, it only searches for a match
with the keyword. If included files also need to be
searched use the commands listed in |include-search|.
After this command |n| searches forward for the next
match (not backward).
{not in Vi}
*gD*
gD Goto global Declaration. When the cursor is on a
global variable that is defined in the file, this
command will jump to its declaration. This works just
like "gd", except that the search for the keyword
always starts in line 1. {not in Vi}
*1gd*
1gd Like "gd", but ignore matches inside a {} block that
ends before the cursor position. {not in Vi}
*1gD*
*CTRL-C*
CTRL-C Interrupt current (search) command. Use CTRL-Break on
MS-DOS |dos-CTRL-Break|.
In Normal mode, any pending command is aborted.
*:noh* *:nohlsearch*
:noh[lsearch] Stop the highlighting for the 'hlsearch' option. It
is automatically turned back on when using a search
command, or setting the 'hlsearch' option.
This command doesn't work in an autocommand, because
the highlighting state is saved and restored when
executing autocommands |autocmd-searchpat|.
Same thing for when invoking a user function.
While typing the search pattern the current match will be shown if the
'incsearch' option is on. Remember that you still have to finish the search
command with <CR> to actually position the cursor at the displayed match. Or
use <Esc> to abandon the search.
All matches for the last used search pattern will be highlighted if you set
the 'hlsearch' option. This can be suspended with the |:nohlsearch| command.
*search-offset* *{offset}*
These commands search for the specified pattern. With "/" and "?" an
additional offset may be given. There are two types of offsets: line offsets
and character offsets. {the character offsets are not in Vi}
The offset gives the cursor position relative to the found match:
[num] [num] lines downwards, in column 1
+[num] [num] lines downwards, in column 1
-[num] [num] lines upwards, in column 1
e[+num] [num] characters to the right of the end of the match
e[-num] [num] characters to the left of the end of the match
s[+num] [num] characters to the right of the start of the match
s[-num] [num] characters to the left of the start of the match
b[+num] [num] identical to s[+num] above (mnemonic: begin)
b[-num] [num] identical to s[-num] above (mnemonic: begin)
;{pattern} perform another search, see |//;|
If a '-' or '+' is given but [num] is omitted, a count of one will be used.
When including an offset with 'e', the search becomes inclusive (the
character the cursor lands on is included in operations).
Examples:
pattern cursor position
/test/+1 one line below "test", in column 1
/test/e on the last t of "test"
/test/s+2 on the 's' of "test"
/test/b-3 three characters before "test"
If one of these commands is used after an operator, the characters between
the cursor position before and after the search is affected. However, if a
line offset is given, the whole lines between the two cursor positions are
affected.
An example of how to search for matches with a pattern and change the match
with another word:
/foo<CR> find "foo"
c//e change until end of match
bar<Esc> type replacement
//<CR> go to start of next match
c//e change until end of match
beep<Esc> type another replacement
etc.
*//;* *E386*
A very special offset is ';' followed by another search command. For example:
/test 1/;/test
/test.*/+1;?ing?
The first one first finds the next occurrence of "test 1", and then the first
occurrence of "test" after that.
This is like executing two search commands after each other, except that:
- It can be used as a single motion command after an operator.
- The direction for a following "n" or "N" command comes from the first
search command.
- When an error occurs the cursor is not moved at all.
*last-pattern*
The last used pattern and offset are remembered. They can be used to repeat
the search, possibly in another direction or with another count. Note that
two patterns are remembered: One for 'normal' search commands and one for the
substitute command ":s". Each time an empty pattern is given, the previously
used pattern is used. However, if there is no previous search command, a
previous substitute pattern is used, if possible.
The 'magic' option sticks with the last used pattern. If you change 'magic',
this will not change how the last used pattern will be interpreted.
The 'ignorecase' option does not do this. When 'ignorecase' is changed, it
will result in the pattern to match other text.
All matches for the last used search pattern will be highlighted if you set
the 'hlsearch' option.
To clear the last used search pattern:
:let @/ = ""
This will not set the pattern to an empty string, because that would match
everywhere. The pattern is really cleared, like when starting Vim.
The search usually skips matches that don't move the cursor. Whether the next
match is found at the next character or after the skipped match depends on the
'c' flag in 'cpoptions'. See |cpo-c|.
with 'c' flag: "/..." advances 1 to 3 characters
without 'c' flag: "/..." advances 1 character
The unpredictability with the 'c' flag is caused by starting the search in the
first column, skipping matches until one is found past the cursor position.
When searching backwards, searching starts at the start of the line, using the
'c' flag in 'cpoptions' as described above. Then the last match before the
cursor position is used.
In Vi the ":tag" command sets the last search pattern when the tag is searched
for. In Vim this is not done, the previous search pattern is still remembered,
unless the 't' flag is present in 'cpoptions'. The search pattern is always
put in the search history.
If the 'wrapscan' option is on (which is the default), searches wrap around
the end of the buffer. If 'wrapscan' is not set, the backward search stops
at the beginning and the forward search stops at the end of the buffer. If
'wrapscan' is set and the pattern was not found the error message "pattern
not found" is given, and the cursor will not be moved. If 'wrapscan' is not
set the message becomes "search hit BOTTOM without match" when searching
forward, or "search hit TOP without match" when searching backward. If
wrapscan is set and the search wraps around the end of the file the message
"search hit TOP, continuing at BOTTOM" or "search hit BOTTOM, continuing at
TOP" is given when searching backwards or forwards respectively. This can be
switched off by setting the 's' flag in the 'shortmess' option. The highlight
method 'w' is used for this message (default: standout).
*search-range*
You can limit the search command "/" to a certain range of lines by including
\%>l items. For example, to match the word "limit" below line 199 and above
line 300:
/\%>199l\%<300llimit
Also see |/\%>l|.
Another way is to use the ":substitute" command with the 'c' flag. Example:
:.,300s/Pattern//gc
This command will search from the cursor position until line 300 for
"Pattern". At the match, you will be asked to type a character. Type 'q' to
stop at this match, type 'n' to find the next match.
The "*", "#", "g*" and "g#" commands look for a word near the cursor in this
order, the first one that is found is used:
- The keyword currently under the cursor.
- The first keyword to the right of the cursor, in the same line.
- The WORD currently under the cursor.
- The first WORD to the right of the cursor, in the same line.
The keyword may only contain letters and characters in 'iskeyword'.
The WORD may contain any non-blanks (<Tab>s and/or <Space>s).
Note that if you type with ten fingers, the characters are easy to remember:
the "#" is under your left hand middle finger (search to the left and up) and
the "*" is under your right hand middle finger (search to the right and down).
(this depends on your keyboard layout though).
==============================================================================
2. The definition of a pattern *search-pattern* *pattern* *[pattern]*
*regular-expression* *regexp* *Pattern*
*E76* *E383* *E476*
For starters, read chapter 27 of the user manual |usr_27.txt|.
*/branch* */\&*
2. A branch is one or more concats, separated by "\&". It matches the last
concat, but only if all the preceding concats also match at the same
position. Examples:
"foobeep\&..." matches "foo" in "foobeep".
".*Peter\&.*Bob" matches in a line containing both "Peter" and "Bob"
branch ::= concat
or concat \& concat
or concat \& concat \& concat
etc.
*/concat*
3. A concat is one or more pieces, concatenated. It matches a match for the
first piece, followed by a match for the second piece, etc. Example:
"f[0-9]b", first matches "f", then a digit and then "b".
concat ::= piece
or piece piece
or piece piece piece
etc.
*/piece*
4. A piece is an atom, possibly followed by a multi, an indication of how many
times the atom can be matched. Example: "a*" matches any sequence of "a"
characters: "", "a", "aa", etc. See |/multi|.
piece ::= atom
or atom multi
*/atom*
5. An atom can be one of a long list of items. Many atoms match one character
in the text. It is often an ordinary character or a character class.
Braces can be used to make a pattern into an atom. The "\z(\)" construct
is only for syntax highlighting.
atom ::= ordinary-atom |/ordinary-atom|
or \( pattern \) |/\(|
or \%( pattern \) |/\%(|
or \z( pattern \) |/\z(|
==============================================================================
3. Magic */magic*
Some characters in the pattern are taken literally. They match with the same
*E59*
|/\@>| \@> \@> 1, like matching a whole pattern (*)
|/\@=| \@= \@= nothing, requires a match |/zero-width| (*)
|/\@!| \@! \@! nothing, requires NO match |/zero-width| (*)
|/\@<=| \@<= \@<= nothing, requires a match behind |/zero-width| (*)
|/\@<!| \@<! \@<! nothing, requires NO match behind |/zero-width| (*)
(*) {not in Vi}
==============================================================================
5. Multi items *pattern-multi-items*
An atom can be followed by an indication of how many times the atom can be
matched and in what way. This is called a multi. See |/multi| for an
overview.
*/\+* *E57*
\+ Matches 1 or more of the preceding atom, as many as possible. {not in
Vi}
Example matches
^.\+$ any non-empty line
\s\+ white space of at least one character
*/\=*
\= Matches 0 or 1 of the preceding atom, as many as possible. {not in Vi}
Example matches
foo\= "fo" and "foo"
*/\?*
\? Just like \=. Cannot be used when searching backwards with the "?"
*/\@=*
\@= Matches the preceding atom with zero width. {not in Vi}
Like "(?=pattern)" in Perl.
Example matches
foo\(bar\)\@= "foo" in "foobar"
foo\(bar\)\@=foo nothing
*/zero-width*
When using "\@=" (or "^", "$", "\<", "\>") no characters are included
in the match. These items are only used to check if a match can be
made. This can be tricky, because a match with following items will
be done in the same position. The last example above will not match
"foobarfoo", because it tries match "foo" in the same position where
"bar" matched.
Note that using "\&" works the same as using "\@=": "foo\&.." is the
same as "\(foo\)\@=..". But using "\&" is easier, you don't need the
braces.
*/\@!*
\@! Matches with zero width if the preceding atom does NOT match at the
current position. |/zero-width| {not in Vi}
Like '(?!pattern)" in Perl.
Example matches
foo\(bar\)\@! any "foo" not followed by "bar"
a.\{-}p\@! "a", "ap", "app", etc. not followed by a "p"
if \(\(then\)\@!.\)*$ "if " not followed by "then"
Using "\@!" is tricky, because there are many places where a pattern
does not match. "a.*p\@!" will match from an "a" to the end of the
line, because ".*" can match all characters in the line and the "p"
doesn't match at the end of the line. "a.\{-}p\@!" will match any
"a", "ap", "aap", etc. that isn't followed by a "p", because the "."
can match a "p" and "p\@!" doesn't match after that.
You can't use "\@!" to look for a non-match before the matching
position: "\(foo\)\@!bar" will match "bar" in "foobar", because at the
position where "bar" matches, "foo" does not match. To avoid matching
*/\@<=*
\@<= Matches with zero width if the preceding atom matches just before what
follows. |/zero-width| {not in Vi}
Like '(?<=pattern)" in Perl, but Vim allows non-fixed-width patterns.
Example matches
\(an\_s\+\)\@<=file "file" after "an" and white space or an
end-of-line
For speed it's often much better to avoid this multi. Try using "\zs"
instead |/\zs|. To match the same as the above example:
an\_s\+\zsfile
"\@<=" and "\@<!" check for matches just before what follows.
Theoretically these matches could start anywhere before this position.
But to limit the time needed, only the line where what follows matches
is searched, and one line before that (if there is one). This should
be sufficient to match most things and not be too slow.
The part of the pattern after "\@<=" and "\@<!" are checked for a
match first, thus things like "\1" don't work to reference \(\) inside
the preceding atom. It does work the other way around:
Example matches
\1\@<=,\([a-z]\+\) ",abc" in "abc,abc"
*/\@<!*
\@<! Matches with zero width if the preceding atom does NOT match just
before what follows. Thus this matches if there is no position in the
current or previous line where the atom matches such that it ends just
before what follows. |/zero-width| {not in Vi}
Like '(?<!pattern)" in Perl, but Vim allows non-fixed-width patterns.
The match with the preceding atom is made to end just before the match
with what follows, thus an atom that ends in ".*" will work.
Warning: This can be slow (because many positions need to be checked
for a match).
Example matches
\(foo\)\@<!bar any "bar" that's not in "foobar"
\(\/\/.*\)\@<!in "in" which is not after "//"
*/\@>*
\@> Matches the preceding atom like matching a whole pattern. {not in Vi}
Like "(?>pattern)" in Perl.
Example matches
\(a*\)\@>a nothing (the "a*" takes all the "a"'s, there can't be
another one following)
This matches the preceding atom as if it was a pattern by itself. If
it doesn't match, there is no retry with shorter sub-matches or
anything. Observe this difference: "a*b" and "a*ab" both match
"aaab", but in the second case the "a*" matches only the first two
"a"s. "\(a*\)\@>ab" will not match "aaab", because the "a*" matches
the "aaa" (as many "a"s as possible), thus the "ab" can't match.
==============================================================================
6. Ordinary atoms *pattern-atoms*
An ordinary atom can be:
*/^*
^ At beginning of pattern or after "\|", "\(", "\%(" or "\n": matches
start-of-line; at other positions, matches literal '^'. |/zero-width|
Example matches
^beep( the start of the C function "beep" (probably).
*/\^*
\^ Matches literal '^'. Can be used at any position in the pattern.
*/\_^*
\_^ Matches start-of-line. |/zero-width| Can be used at any position in
the pattern.
Example matches
*/$*
$ At end of pattern or in front of "\|", "\)" or "\n" ('magic' on):
matches end-of-line <EOL>; at other positions, matches literal '$'.
|/zero-width|
*/\$*
\$ Matches literal '$'. Can be used at any position in the pattern.
*/\_$*
\_$ Matches end-of-line. |/zero-width| Can be used at any position in the
pattern. Note that "a\_$b" never matches, since "b" cannot match an
end-of-line. Use "a\nb" instead |/\n|.
Example matches
foo\_$\_s* "foo" at end-of-line and following white space and
blank lines
*/\_.*
\_. Matches any single character or end-of-line.
Careful: "\_.*" matches all text to the end of the buffer!
*/\<*
\< Matches the beginning of a word: The next char is the first char of a
word. The 'iskeyword' option specifies what is a word character.
|/zero-width|
*/\>*
\> Matches the end of a word: The previous char is the last char of a
word. The 'iskeyword' option specifies what is a word character.
|/zero-width|
*/\zs*
\zs Matches at any position, and sets the start of the match there: The
next char is the first char of the whole match. |/zero-width|
Example:
/^\s*\zsif
matches an "if" at the start of a line, ignoring white space.
Can be used multiple times, the last one encountered in a matching
branch is used. Example:
/\(.\{-}\zsFab\)\{3}
Finds the third occurrence of "Fab".
{not in Vi} {not available when compiled without the |+syntax| feature}
*/\ze*
\ze Matches at any position, and sets the end of the match there: The
previous char is the last char of the whole match. |/zero-width|
Can be used multiple times, the last one encountered in a matching
branch is used.
Example: "end\ze\(if\|for\)" matches the "end" in "endif" and
"endfor".
{not in Vi} {not available when compiled without the |+syntax| feature}
*/\%^* *start-of-file*
\%^ Matches start of the file. When matching with a string, matches the
start of the string. {not in Vi}
For example, to find the first "VIM" in a file:
/\%^\_.\{-}\zsVIM
*/\%$* *end-of-file*
\%$ Matches end of the file. When matching with a string, matches the
end of the string. {not in Vi}
Note that this does NOT find the last "VIM" in a file:
/VIM\_.\{-}\%$
It will find the next VIM, because the part after it will always
match. This one will find the last "VIM" in the file:
/VIM\ze\(\(VIM\)\@!\_.\)*\%$
This uses |/\@!| to ascertain that "VIM" does NOT match in any
position after the first "VIM".
Searching from the end of the file backwards is easier!
*/\%V*
\%V Match inside the Visual area. When Visual mode has already been
stopped match in the area that |gv| would reselect.
This is a |/zero-width| match. To make sure the whole pattern is
inside the Visual area put it at the start and end of the pattern,
e.g.:
/\%Vfoo.*bar\%V
Only works for the current buffer.
*/\%#* *cursor-position*
\%# Matches with the cursor position. Only works when matching in a
buffer displayed in a window. {not in Vi}
WARNING: When the cursor is moved after the pattern was used, the
result becomes invalid. Vim doesn't automatically update the matches.
This is especially relevant for syntax highlighting and 'hlsearch'.
In other words: When the cursor moves the display isn't updated for
this change. An update is done for lines which are changed (the whole
line is updated) or when using the |CTRL-L| command (the whole screen
is updated). Example, to highlight the word under the cursor:
/\k*\%#\k*
When 'hlsearch' is set and you move the cursor around and make changes
this will clearly show when the match is updated or not.
column 44.
*/\%v* */\%>v* */\%<v*
\%23v Matches in a specific virtual column.
\%<23v Matches before a specific virtual column.
\%>23v Matches after a specific virtual column.
These three can be used to match specific virtual columns in a buffer
or string. When not matching with a buffer in a window, the option
values of the current window are used (e.g., 'tabstop').
The "23" can be any column number. The first column is 1.
Note that some virtual column positions will never match, because they
are halfway through a tab or other character that occupies more than
one screen character. {not in Vi}
WARNING: When inserting or deleting text Vim does not automatically
update highlighted matches. This means Syntax highlighting quickly
becomes wrong.
Example, to highlight all the characters after virtual column 72:
/\%>72v.*
When 'hlsearch' is set and you move the cursor around and make changes
this will clearly show when the match is updated or not.
To match the text up to column 17:
/.*\%17v
Column 17 is included, because that's where the "\%17v" matches,
even though this is a |/zero-width| match. Adding a dot to match the
next character has the same result:
/.*\%17v.
This command does the same thing, but also matches when there is no
character in column 17:
/.*\%<18v.
*whitespace* *white-space*
\s whitespace character: <Space> and <Tab> */\s*
\S non-whitespace character; opposite of \s */\S*
\d digit: [0-9] */\d*
\D non-digit: [^0-9] */\D*
\x hex digit: [0-9A-Fa-f] */\x*
\X non-hex digit: [^0-9A-Fa-f] */\X*
\o octal digit: [0-7] */\o*
\O non-octal digit: [^0-7] */\O*
\w word character: [0-9A-Za-z_] */\w*
\W non-word character: [^0-9A-Za-z_] */\W*
\h head of word character: [A-Za-z_] */\h*
\H non-head of word character: [^A-Za-z_] */\H*
*/\* */\\*
\x A backslash followed by a single character, with no special meaning,
is reserved for future expansions
*/\c* */\C*
When "\c" appears anywhere in the pattern, the whole pattern is handled like
'ignorecase' is on. The actual value of 'ignorecase' and 'smartcase' is
ignored. "\C" does the opposite: Force matching case for the whole pattern.
{only Vim supports \c and \C}
Note that 'ignorecase', "\c" and "\C" are not used for the character classes.
Examples:
pattern 'ignorecase' 'smartcase' matches
foo off - foo
foo on - foo Foo FOO
Foo on off foo Foo FOO
Foo on on Foo
\cfoo - - foo Foo FOO
foo\C - - foo
*CR-used-for-NL*
When 'fileformat' is "mac", <NL> characters in the file are stored as <CR>
characters internally. In the text they are shown as "^J". Otherwise this
works similar to the usage of <NL> for a <Nul>.
When working with expression evaluation, a <NL> character in the pattern
matches a <NL> in the string. The use of "\n" (backslash n) to match a <NL>
doesn't work there, it only works to match text in the buffer.
*pattern-multi-byte*
Patterns will also work with multi-byte characters, mostly as you would
expect. But invalid bytes may cause trouble, a pattern with an invalid byte
will probably never match.
==============================================================================
8. Composing characters *patterns-composing*
*/\Z*
When "\Z" appears anywhere in the pattern, composing characters are ignored.
Thus only the base characters need to match, the composing characters may be
different and the number of composing characters may differ. Only relevant
when 'encoding' is "utf-8".
When a composing character appears at the start of the pattern of after an
item that doesn't include the composing character, a match is found at any
character that includes this composing character.
When using a dot and a composing character, this works the same as the
composing character by itself, except that it doesn't matter what comes before
this.
The order of composing characters matters, even though changing the order
doesn't change what a character looks like. This may change in the future.
==============================================================================
9. Compare with Perl patterns *perl-patterns*
Vim's regexes are most similar to Perl's, in terms of what you can do. The
difference between them is mostly just notation; here's a summary of where
they differ:
Capability in Vimspeak in Perlspeak
force case insensitivity \c (?i)
force case sensitivity \C (?-i)
backref-less grouping \%(atom\) (?:atom)
conservative quantifiers \{-n,m} *?, +?, ??, {}?
0-width match atom\@= (?=atom)
0-width non-match atom\@! (?!atom)
0-width preceding match atom\@<= (?<=atom)
*:mat* *:match*
:mat[ch] {group} /{pattern}/
Define a pattern to highlight in the current window. It will
be highlighted with {group}. Example:
:highlight MyGroup ctermbg=green guibg=green
:match MyGroup /TODO/
Instead of // any character can be used to mark the start and
end of the {pattern}. Watch out for using special characters,
such as '"'' and '|'.
{group} must exist at the moment this command is executed.
The {group} highlighting still applies when a character is
to be highlighted for 'hlsearch', as the highlighting for
matches is given higher priority than that of 'hlsearch'.
Syntax highlighting (see 'syntax') is also overruled by
matches.
Note that highlighting the last used search pattern with
'hlsearch' is used in all windows, while the pattern defined
with ":match" only exists in the current window. It is kept
when switching to another buffer.
'ignorecase' does not apply, use |/\c| in the pattern to
ignore case. Otherwise case is not ignored.
'redrawtime' defines the maximum time searched for pattern
matches.
When matching end-of-line and Vim redraws only part of the
display you may get unexpected results. That is because Vim
looks for a match in the line where redrawing starts.
Also see |matcharg()| and |getmatches()|. The former returns
the highlight group and pattern of a previous |:match|
command. The latter returns a list with highlight groups and
patterns defined by both |matchadd()| and |:match|.
Highlighting matches using |:match| are limited to three
matches (aside from |:match|, |:2match| and |:3match|are
available). |matchadd()| does not have this limitation and in
addition makes it possible to prioritize matches.
Another example, which highlights all characters in virtual
column 72 and more:
*current-file*
As long as you don't write the buffer, the original file remains unchanged.
If you start editing a file (read a file into the buffer), the file name is
remembered as the "current file name". This is also known as the name of the
current buffer. It can be used with "%" on the command line |:_%|.
*alternate-file*
If there already was a current file name, then that one becomes the alternate
file name. It can be used with "#" on the command line |:_#| and you can use
the |CTRL-^| command to toggle between the current and the alternate file.
However, the alternate file name is not changed when |:keepalt| is used.
*:keepalt* *:keepa*
:keepalt {cmd} Execute {cmd} while keeping the current alternate file
name. Note that commands invoked indirectly (e.g.,
with a function) may still set the alternate file
name. {not in Vi}
All file names are remembered in the buffer list. When you enter a file name,
for editing (e.g., with ":e filename") or writing (e.g., with ":w filename"),
the file name is added to the list. You can use the buffer list to remember
which files you edited and to quickly switch from one file to another (e.g.,
to copy text) with the |CTRL-^| command. First type the number of the file
and then hit CTRL-^. {Vi: only one alternate file name is remembered}
*v_g_CTRL-G*
{Visual}g CTRL-G Similar to "g CTRL-G", but Word, Character, Line, and
Byte counts for the visually selected region are
displayed.
In Blockwise mode, Column count is also shown. (For
{Visual} see |Visual-mode|.)
{not in VI}
*:file_f*
:f[ile][!] {name} Sets the current file name to {name}. The optional !
avoids truncating the message, as with |:file|.
If the buffer did have a name, that name becomes the
|alternate-file| name. An unlisted buffer is created
to hold the old name.
*:0file*
:0f[ile][!] Remove the name of the current buffer. The optional !
avoids truncating the message, as with |:file|. {not
in Vi}
:buffers
:files
:ls List all the currently known file names. See
'windows.txt' |:files| |:buffers| |:ls|. {not in
Vi}
Vim will remember the full path name of a file name that you enter. In most
cases when the file name is displayed only the name you typed is shown, but
the full path name is being used if you used the ":cd" command |:cd|.
*home-replace*
If the environment variable $HOME is set, and the file name starts with that
string, it is often displayed with HOME replaced with "~". This was done to
keep file names short. When reading or writing files the full name is still
used, the "~" is only used when displaying file names. When replacing the
file name would result in just "~", "~/" is used instead (to avoid confusion
between options set to $HOME with 'backupext' set to "~").
When writing the buffer, the default is to use the current file name. Thus
when you give the "ZZ" or ":wq" command, the original file will be
overwritten. If you do not want this, the buffer can be written into another
file by giving a file name argument to the ":write" command. For example:
vim testfile
[change the buffer with editor commands]
:w newfile
:q
This will create a file "newfile", that is a modified copy of "testfile".
The file "testfile" will remain unchanged. Anyway, if the 'backup' option is
set, Vim renames or copies the original file before it will be overwritten.
You can use this file if you discover that you need the original file. See
also the 'patchmode' option. The name of the backup file is normally the same
as the original file with 'backupext' appended. The default "~" is a bit
strange to avoid accidentally overwriting existing files. If you prefer ".bak"
change the 'backupext' option. Extra dots are replaced with '_' on MS-DOS
machines, when Vim has detected that an MS-DOS-like filesystem is being used
(e.g., messydos or crossdos) or when the 'shortname' option is on. The
backup file can be placed in another directory by setting 'backupdir'.
*auto-shortname*
Technical: On the Amiga you can use 30 characters for a file name. But on an
MS-DOS-compatible filesystem only 8 plus 3 characters are
available. Vim tries to detect the type of filesystem when it is
creating the .swp file. If an MS-DOS-like filesystem is suspected,
a flag is set that has the same effect as setting the 'shortname'
option. This flag will be reset as soon as you start editing a
new file. The flag will be used when making the file name for the
".swp" and ".~" files for the current file. But when you are
editing a file in a normal filesystem and write to an MS-DOS-like
filesystem the flag will not have been set. In that case the
creation of the ".~" file may fail and you will get an error
message. Use the 'shortname' option in this case.
When you started editing without giving a file name, "No File" is displayed in
messages. If the ":write" command is used with a file name argument, the file
name for the current file is set to that file name. This only happens when
the 'F' flag is included in 'cpoptions' (by default it is included) |cpo-F|.
This is useful when entering text in an empty buffer and then writing it to a
file. If 'cpoptions' contains the 'f' flag (by default it is NOT included)
|cpo-f| the file name is set for the ":read file" command. This is useful
when starting Vim without an argument and then doing ":read file" to start
editing a file.
When the file name was set and 'filetype' is empty the filetype detection
autocommands will be triggered.
*not-edited*
Because the file name was set without really starting to edit that file, you
are protected from overwriting that file. This is done by setting the
"notedited" flag. You can see if this flag is set with the CTRL-G or ":file"
command. It will include "[Not edited]" when the "notedited" flag is set.
When writing the buffer to the current file name (with ":w!"), the "notedited"
flag is reset.
*abandon*
Vim remembers whether you have changed the buffer. You are protected from
losing the changes you made. If you try to quit without writing, or want to
start editing another file, Vim will refuse this. In order to overrule this
protection, add a '!' to the command. The changes will then be lost. For
example: ":q" will not work if the buffer was changed, but ":q!" will. To see
whether the buffer was changed use the "CTRL-G" command. The message includes
the string "[Modified]" if the buffer has been changed.
If you want to automatically save the changes without asking, switch on the
'autowriteall' option. 'autowrite' is the associated Vi-compatible option
that does not work for all commands.
If you want to keep the changed buffer without saving it, switch on the
'hidden' option. See |hidden-buffer|.
==============================================================================
2. Editing a file *edit-a-file*
*:e* *:edit*
:e[dit] [++opt] [+cmd] Edit the current file. This is useful to re-edit the
current file, when it has been changed outside of Vim.
This fails when changes have been made to the current
buffer and 'autowriteall' isn't set or the file can't
be written.
Also see |++opt| and |+cmd|.
{Vi: no ++opt}
*:edit!*
:e[dit]! [++opt] [+cmd]
Edit the current file always. Discard any changes to
the current buffer. This is useful if you want to
start all over again.
*:edit_f*
:e[dit] [++opt] [+cmd] {file}
Edit {file}.
This fails when changes have been made to the current
buffer, unless 'hidden' is set or 'autowriteall' is
set and the file can be written.
Also see |++opt| and |+cmd|.
{Vi: no ++opt}
*:edit!_f*
:e[dit]! [++opt] [+cmd] {file}
Edit {file} always. Discard any changes to the
current buffer.
Also see |++opt| and |+cmd|.
{Vi: no ++opt}
:e[dit] [++opt] [+cmd] #[count]
Edit the [count]th buffer (as shown by |:files|).
This command does the same as [count] CTRL-^. But ":e
#" doesn't work if the alternate buffer doesn't have a
file name, while CTRL-^ still works then.
Also see |++opt| and |+cmd|.
{Vi: no ++opt}
*:ene* *:enew*
:ene[w] Edit a new, unnamed buffer. This fails when changes
have been made to the current buffer, unless 'hidden'
is set or 'autowriteall' is set and the file can be
written.
If 'fileformats' is not empty, the first format given
will be used for the new buffer. If 'fileformats' is
empty, the 'fileformat' of the current buffer is used.
{not in Vi}
*:ene!* *:enew!*
:ene[w]! Edit a new, unnamed buffer. Discard any changes to
the current buffer.
Set 'fileformat' like |:enew|.
{not in Vi}
*:fin* *:find*
:fin[d][!] [++opt] [+cmd] {file}
Find {file} in 'path' and then |:edit| it.
{not in Vi} {not available when the |+file_in_path|
feature was disabled at compile time}
:{count}fin[d][!] [++opt] [+cmd] {file}
Just like ":find", but use the {count} match in
'path'. Thus ":2find file" will find the second
"file" found in 'path'. When there are fewer matches
for the file in 'path' than asked for, you get an
error message.
*:ex*
:ex [++opt] [+cmd] [file]
Same as |:edit|.
*:vi* *:visual*
:vi[sual][!] [++opt] [+cmd] [file]
When used in Ex mode: Leave |Ex-mode|, go back to
Normal mode. Otherwise same as |:edit|.
*:vie* *:view*
:vie[w][!] [++opt] [+cmd] file
When used in Ex mode: Leave |Ex mode|, go back to
Normal mode. Otherwise same as |:edit|, but set
'readonly' option for this buffer. {not in Vi}
*CTRL-^* *CTRL-6*
CTRL-^ Edit the alternate file. Mostly the alternate file is
the previously edited file. This is a quick way to
toggle between two files. It is equivalent to ":e #",
except that it also works when there is no file name.
If the 'autowrite' or 'autowriteall' option is on and
the buffer was changed, write it.
Mostly the ^ character is positioned on the 6 key,
pressing CTRL and 6 then gets you what we call CTRL-^.
But on some non-US keyboards CTRL-^ is produced in
another way.
{count}CTRL-^ Edit [count]th file in the buffer list (equivalent to
":e #[count]"). This is a quick way to switch between
files.
See |CTRL-^| above for further details.
{not in Vi}
*v_gf*
{Visual}[count]gf Same as "gf", but the highlighted text is used as the
name of the file to edit. 'isfname' is ignored.
Leading blanks are skipped, otherwise all blanks and
special characters are included in the file name.
(For {Visual} see |Visual-mode|.)
{not in VI}
*gF*
[count]gF Same as "gf", except if a number follows the file
name, then the cursor is positioned on that line in
the file. The file name and the number must be
separated by a non-filename (see 'isfname') and
non-numeric character. White space between the
filename, the separator and the number are ignored.
Examples:
eval.c:10
eval.c @ 20
eval.c (30)
eval.c 40
*v_gF*
{Visual}[count]gF Same as "v_gf".
These commands are used to start editing a single file. This means that the
file is read into the buffer and the current file name is set. The file that
is opened depends on the current directory, see |:cd|.
See |read-messages| for an explanation of the message that is given after the
file has been read.
You can use the ":e!" command if you messed up the buffer and want to start
all over again. The ":e" command is only useful if you have changed the
current file name.
*:filename* *{file}*
Besides the things mentioned here, more special items for where a filename is
expected are mentioned at |cmdline-special|.
Note for systems other than Unix: When using a command that accepts a single
file name (like ":edit file") spaces in the file name are allowed, but
trailing spaces are ignored. This is useful on systems that regularly embed
spaces in file names (like MS-Windows and the Amiga). Example: The command
":e Long File Name " will edit the file "Long File Name". When using a
command that accepts more than one file name (like ":next file1 file2")
embedded spaces must be escaped with a backslash.
*wildcard* *wildcards*
Wildcards in {file} are expanded. Which wildcards are supported depends on
the system. These are the common ones:
? matches one character
* matches anything, including nothing
** matches anything, including nothing, recurses into directories
[abc] match 'a', 'b' or 'c'
To avoid the special meaning of the wildcards prepend a backslash. However,
on MS-Windows the backslash is a path separator and "path\[abc]" is still seen
as a wildcard when "[" is in the 'isfname' option. A simple way to avoid this
is to use "path\[[]abc]". Then the file "path[abc]" literally.
*starstar-wildcard*
Expanding "**" is possible on Unix, Win32, Mac OS/X and a few other systems.
This allows searching a directory tree. This goes up to 100 directories deep.
Note there are some commands where this works slightly different, see
|file-searching|.
Example:
:n **/*.txt
Finds files:
ttt.txt
subdir/ttt.txt
a/b/c/d/ttt.txt
When non-wildcard characters are used these are only matched in the first
directory. Example:
:n /usr/inc**/*.h
Finds files:
/usr/include/types.h
/usr/include/sys/types.h
/usr/inc_old/types.h
*backtick-expansion* *`-expansion*
On Unix and a few other systems you can also use backticks in the file name,
for example:
:e `find . -name ver\\*.c -print`
The backslashes before the star are required to prevent "ver*.c" to be
expanded by the shell before executing the find program.
This also works for most other systems, with the restriction that the
backticks must be around the whole item. It is not possible to have text
directly before the first or just after the last backtick.
*`=*
You can have the backticks expanded as a Vim expression, instead of an
external command, by using the syntax `={expr}` e.g.:
:e `=tempname()`
The expression can contain just about anything, thus this can also be used to
avoid the special meaning of '"'', '|', '%' and '#'. Names are to be separated
with line breaks. When the result is a |List| then each item is used as a
*++opt* *[++opt]*
The [++opt] argument can be used to force the value of 'fileformat',
'fileencoding' or 'binary' to a value for one command, and to specify the
behavior for bad characters. The form is:
++{optname}
Or:
++{optname}={value}
*++bad*
The argument of "++bad=" specifies what happens with characters that can't be
converted and illegal bytes. It can be one of three things:
++bad=X A single-byte character that replaces each bad character.
++bad=keep Keep bad characters without conversion. Note that this may
result in illegal bytes in your text!
++bad=drop Remove the bad characters.
The default is like "++bad=?": Replace each bad character with a question
mark. In some places an inverted question mark is used (0xBF).
Note that not all commands use the ++bad argument, even though they do not
give an error when you add it. E.g. |:write|.
Note that when reading, the 'fileformat' and 'fileencoding' options will be
set to the used format. When writing this doesn't happen, thus a next write
will use the old value of the option. Same for the 'binary' option.
*+cmd* *[+cmd]*
The [+cmd] argument can be used to position the cursor in the newly opened
file, or execute any other command:
+ Start at the last line.
+{num} Start at line {num}.
+/{pat} Start at first line containing {pat}.
+{command} Execute {command} after opening the new file.
{command} is any Ex command.
To include a white space in the {pat} or {command}, precede it with a
backslash. Double the number of backslashes.
:edit +/The\ book file
:edit +/dir\ dirname\\ file
:edit +set\ dir=c:\\\\temp file
Note that in the last example the number of backslashes is halved twice: Once
for the "+cmd" argument and once for the ":set" command.
*file-formats*
The 'fileformat' option sets the <EOL> style for a file:
'fileformat' characters name
"dos" <CR><NL> or <NL> DOS format *DOS-format*
"unix" <NL> Unix format *Unix-format*
"mac" <CR> Mac format *Mac-format*
==============================================================================
3. The argument list *argument-list* *arglist*
If you give more than one file name when starting Vim, this list is remembered
as the argument list. You can jump to each file in this list.
Do not confuse this with the buffer list, which you can see with the
|:buffers| command. The argument list was already present in Vi, the buffer
list is new in Vim. Every file name in the argument list will also be present
in the buffer list (unless it was deleted with |:bdel| or |:bwipe|). But it's
common that names in the buffer list are not in the argument list.
This subject is introduced in section |07.2| of the user manual.
There is one global argument list, which is used for all windows by default.
It is possible to create a new argument list local to a window, see
|:arglocal|.
You can use the argument list with the following commands, and with the
expression functions |argc()| and |argv()|. These all work on the argument
list of the current window.
*:ar* *:args*
*:argu* *:argument*
:[count]argu[ment] [count] [++opt] [+cmd]
Edit file [count] in the argument list. When [count]
*:rew* *:rewind*
:rew[ind] [++opt] [+cmd]
Start editing the first file in the argument list.
This fails when changes have been made and Vim does
not want to |abandon| the current buffer.
Also see |++opt| and |+cmd|. {Vi: no ++opt}
:rew[ind]! [++opt] [+cmd]
Start editing the first file in the argument list.
Discard any changes to the buffer. Also see |++opt|
and |+cmd|. {Vi: no ++opt}
*:fir* *:first*
:fir[st][!] [++opt] [+cmd]
Other name for ":rewind". {not in Vi}
*:la* *:last*
:la[st] [++opt] [+cmd]
Start editing the last file in the argument list.
This fails when changes have been made and Vim does
not want to |abandon| the current buffer.
Also see |++opt| and |+cmd|. {not in Vi}
:la[st]! [++opt] [+cmd]
Start editing the last file in the argument list.
Discard any changes to the buffer. Also see |++opt|
*:wn* *:wnext*
:[count]wn[ext] [++opt]
Write current file and start editing the [count]
next file. Also see |++opt| and |+cmd|. {not in Vi}
:[count]wn[ext] [++opt] {file}
Write current file to {file} and start editing the
[count] next file, unless {file} already exists and
the 'writeany' option is off. Also see |++opt| and
|+cmd|. {not in Vi}
:[count]wn[ext]! [++opt] {file}
Write current file to {file} and start editing the
[count] next file. Also see |++opt| and |+cmd|. {not
in Vi}
*{arglist}*
The wildcards in the argument list are expanded and the file names are sorted.
Thus you can use the command "vim *.c" to edit all the C files. From within
Vim the command ":n *.c" does the same.
White space is used to separate file names. Put a backslash before a space or
tab to include it in a file name. E.g., to edit the single file "foo bar":
:next foo\ bar
On Unix and a few other systems you can also use backticks, for example:
:next `find . -name \\*.c -print`
The backslashes before the star are required to prevent "*.c" to be expanded
by the shell before executing the find program.
*arglist-position*
When there is an argument list you can see which file you are editing in the
title of the window (if there is one and 'title' is on) and with the file
message you get with the "CTRL-G" command. You will see something like
(file 4 of 11)
If 'shortmess' contains 'f' it will be
(4 of 11)
If you are not really editing the file at the current position in the argument
list it will be
(file (4) of 11)
This means that you are position 4 in the argument list, but not editing the
fourth file in the argument list. This happens when you do ":e file".
*:arglocal*
:argl[ocal] Make a local copy of the global argument list.
Doesn't start editing another file.
:argl[ocal][!] [++opt] [+cmd] {arglist}
Define a new argument list, which is local to the
current window. Works like |:args_f| otherwise.
*:argglobal*
:argg[lobal] Use the global argument list for the current window.
Doesn't start editing another file.
:argg[lobal][!] [++opt] [+cmd] {arglist}
Use the global argument list for the current window.
Define a new global argument list like |:args_f|.
All windows using the global argument list will see
this new list.
There can be several argument lists. They can be shared between windows.
When they are shared, changing the argument list in one window will also
change it in the other window.
When a window is split the new window inherits the argument list from the
current window. The two windows then share this list, until one of them uses
|:arglocal| or |:argglobal| to use another argument list.
*:argdo*
:argdo[!] {cmd} Execute {cmd} for each file in the argument list.
It works like doing this:
:rewind
:{cmd}
:next
:{cmd}
etc.
When the current file can't be |abandon|ed and the [!]
is not present, the command fails.
When an error is detected on one file, further files
in the argument list will not be visited.
The last file in the argument list (or where an error
occurred) becomes the current file.
{cmd} can contain '|' to concatenate several commands.
{cmd} must not change the argument list.
Note: While this command is executing, the Syntax
autocommand event is disabled by adding it to
'eventignore'. This considerably speeds up editing
each file.
{not in Vi} {not available when compiled without the
|+listcmds| feature}
Also see |:windo|, |:tabdo| and |:bufdo|.
Example:
:args *.c
:argdo set ff=unix | update
This sets the 'fileformat' option to "unix" and writes the file if it is now
changed. This is done for all *.c files.
Example:
:args *.[ch]
:argdo %s/\<my_foo\>/My_Foo/ge | update
This changes the word "my_foo" to "My_Foo" in all *.c and *.h files. The "e"
flag is used for the ":substitute" command to avoid an error for files where
"my_foo" isn't used. ":update" writes the file only if changes were made.
==============================================================================
4. Writing *writing* *save-file*
Note: When the 'write' option is off, you are not able to write any file.
*:w* *:write*
*E502* *E503* *E504* *E505*
*E512* *E514* *E667* *E796*
:w[rite] [++opt] Write the whole buffer to the current file. This is
the normal way to save changes to a file. It fails
when the 'readonly' option is set or when there is
another reason why the file can't be written.
For ++opt see |++opt|, but only ++bin, ++nobin, ++ff
and ++enc are effective.
:w[rite]! [++opt] Like ":write", but forcefully write when 'readonly' is
*:w_f* *:write_f*
:[range]w[rite] [++opt] {file}
Write the specified lines to {file}, unless it
already exists and the 'writeany' option is off.
*:w!*
:[range]w[rite]! [++opt] {file}
Write the specified lines to {file}. Overwrite an
existing file.
*:w_c* *:write_c*
:[range]w[rite] [++opt] !{cmd}
Execute {cmd} with [range] lines as standard input
(note the space in front of the '!'). {cmd} is
executed like with ":!{cmd}", any '!' is replaced with
the previous command |:!|.
The default [range] for the ":w" command is the whole buffer (1,$). If you
write the whole buffer, it is no longer considered changed. When you
write it to a different file with ":w somefile" it depends on the "+" flag in
'cpoptions'. When included, the write command will reset the 'modified' flag,
even though the buffer itself may still be different from its file.
If a file name is given with ":w" it becomes the alternate file. This can be
used, for example, when the write fails and you want to try again later with
":w #". This can be switched off by removing the 'A' flag from the
'cpoptions' option.
*:sav* *:saveas*
:sav[eas][!] [++opt] {file}
Save the current buffer under the name {file} and set
the filename of the current buffer to {file}. The
previous name is used for the alternate file name.
The [!] is needed to overwrite an existing file.
When 'filetype' is empty filetype detection is done
with the new name, before the file is written.
When the write was successful 'readonly' is reset.
{not in Vi}
*:up* *:update*
:[range]up[date][!] [++opt] [>>] [file]
Like ":write", but only write when the buffer has been
modified. {not in Vi}
*:wa* *:wall*
:wa[ll] Write all changed buffers. Buffers without a file
name or which are readonly are not written. {not in
Vi}
:wa[ll]! Write all changed buffers, even the ones that are
Vim will warn you if you try to overwrite a file that has been changed
elsewhere. See |timestamp|.
*backup-table*
'backup' 'writebackup' action
off off no backup made
off on backup current file, deleted afterwards (default)
on off delete old backup, backup current file
on on delete old backup, backup current file
When the 'backupskip' pattern matches with the name of the file which is
written, no backup file is made. The values of 'backup' and 'writebackup' are
ignored then.
When the 'backup' option is on, an old backup file (with the same name as the
new backup file) will be deleted. If 'backup' is not set, but 'writebackup'
is set, an existing backup file will not be deleted. The backup file that is
made while the file is being written will have a different name.
On some filesystems it's possible that in a crash you lose both the backup and
the newly written file (it might be there but contain bogus data). In that
case try recovery, because the swap file is synced to disk and might still be
there. |:recover|
The directories given with the 'backupdir' option is used to put the backup
file in. (default: same directory as the written file).
Whether the backup is a new file, which is a copy of the original file, or the
original file renamed depends on the 'backupcopy' option. See there for an
explanation of when the copy is made and when the file is renamed.
If the creation of a backup file fails, the write is not done. If you want
to write anyway add a '!' to the command.
*write-permissions*
When writing a new file the permissions are read-write. For unix the mask is
0666 with additionally umask applied. When writing a file that was read Vim
will preserve the permissions, but clear the s-bit.
*write-readonly*
When the 'cpoptions' option contains 'W', Vim will refuse to overwrite a
readonly file. When 'W' is not present, ":w!" will overwrite a readonly file,
if the system allows it (the directory must be writable).
*write-fail*
If the writing of the new file fails, you have to be careful not to lose
your changes AND the original file. If there is no backup file and writing
the new file failed, you have already lost the original file! DON'T EXIT VIM
UNTIL YOU WRITE OUT THE FILE! If a backup was made, it is put back in place
of the original file (if possible). If you exit Vim, and lose the changes
you made, the original file will mostly still be there. If putting back the
original file fails, there will be an error message telling you that you
lost the original file.
*DOS-format-write*
If the 'fileformat' is "dos", <CR> <NL> is used for <EOL>. This is default
for MS-DOS, Win32 and OS/2. On other systems the message "[dos format]" is
shown to remind you that an unusual <EOL> was used.
*Unix-format-write*
If the 'fileformat' is "unix", <NL> is used for <EOL>. On MS-DOS, Win32 and
OS/2 the message "[unix format]" is shown.
*Mac-format-write*
If the 'fileformat' is "mac", <CR> is used for <EOL>. On non-Mac systems the
message "[mac format]" is shown.
See also |file-formats| and the 'fileformat' and 'fileformats' options.
*ACL*
ACL stands for Access Control List. It is an advanced way to control access
rights for a file. It is used on new MS-Windows and Unix systems, but only
when the filesystem supports it.
Vim attempts to preserve the ACL info when writing a file. The backup file
will get the ACL info of the original file.
The ACL info is also used to check if a file is read-only (when opening the
file).
*read-only-share*
When MS-Windows shares a drive on the network it can be marked as read-only.
This means that even if the file read-only attribute is absent, and the ACL
settings on NT network shared drives allow writing to the file, you can still
not write to the file. Vim on Win32 platforms will detect read-only network
drives and will mark the file as read-only. You will not be able to override
it with |:write|.
*write-device*
When the file name is actually a device name, Vim will not make a backup (that
would be impossible). You need to use "!", since the device already exists.
Example for Unix:
:w! /dev/lpt0
and for MS-DOS or MS-Windows:
:w! lpt0
For Unix a device is detected when the name doesn't refer to a normal file or
a directory. A fifo or named pipe also looks like a device to Vim.
For MS-DOS and MS-Windows the device is detected by its name:
AUX
CON
CLOCK$
NUL
PRN
COMn n=1,2,3... etc
LPTn n=1,2,3... etc
The names can be in upper- or lowercase.
==============================================================================
5. Writing and quitting *write-quit*
*:q* *:quit*
:q[uit] Quit the current window. Quit Vim if this is the last
window. This fails when changes have been made and
Vim refuses to |abandon| the current buffer, and when
the last file in the argument list has not been
edited.
If there are other tab pages and quitting the last
window in the current tab page the current tab page is
closed |tab-page|.
:conf[irm] q[uit] Quit, but give prompt when changes have been made, or
the last file in the argument list has not been
edited. See |:confirm| and 'confirm'. {not in Vi}
:q[uit]! Quit without writing, also when visible buffers have
changes. Does not exit when there are changed hidden
buffers. Use ":qall!" to exit always.
:cq[uit] Quit always, without writing, and return an error
code. See |:cq|. Used for Manx's QuickFix mode (see
|quickfix|). {not in Vi}
*:wq*
:wq [++opt] Write the current file and quit. Writing fails when
the file is read-only or the buffer does not have a
name. Quitting fails when the last file in the
argument list has not been edited.
:wq! [++opt] Write the current file and quit. Writing fails when
the current buffer does not have a name.
:wq [++opt] {file} Write to {file} and quit. Quitting fails when the
last file in the argument list has not been edited.
:wq! [++opt] {file} Write to {file} and quit.
:[range]wq[!] [++opt] [file]
Same as above, but only write the lines in [range].
*:x* *:xit*
:[range]x[it][!] [++opt] [file]
Like ":wq", but write only when changes have been
made.
When 'hidden' is set and there are more windows, the
current buffer becomes hidden, after writing the file.
*:exi* *:exit*
:[range]exi[t][!] [++opt] [file]
Same as :xit.
*ZZ*
ZZ Write current file, if modified, and quit (same as
":x"). (Note: If there are several windows for the
current file, the file is written if it was modified
and the window is closed).
*ZQ*
ZQ Quit without checking for changes (same as ":q!").
{not in Vi}
*:qa* *:qall*
:qa[ll] Exit Vim, unless there are some buffers which have been
changed. (Use ":bmod" to go to the next modified buffer).
When 'autowriteall' is set all changed buffers will be
written, like |:wqall|. {not in Vi}
:conf[irm] qa[ll]
Exit Vim. Bring up a prompt when some buffers have been
changed. See |:confirm|. {not in Vi}
:qa[ll]! Exit Vim. Any changes to buffers are lost. {not in Vi}
Also see |:cquit|, it does the same but exits with a non-zero
value.
*:quita* *:quitall*
:quita[ll][!] Same as ":qall". {not in Vi}
*:confirm* *:conf*
:conf[irm] {command} Execute {command}, and use a dialog when an
operation has to be confirmed. Can be used on the
":q", ":qa" and ":w" commands (the latter to over-ride
a read-only setting).
Examples:
:confirm w foo
Will ask for confirmation when "foo" already exists.
:confirm q
Will ask for confirmation when there are changes.
:confirm qa
If any modified, unsaved buffers exist, you will be prompted to save
or abandon each one. There are also choices to "save all" or "abandon
all".
If you want to always use ":confirm", set the 'confirm' option.
*browsefilter*
For MS Windows, you can modify the filters that are used in the browse dialog.
By setting the g:browsefilter or b:browsefilter variables, you can change the
filters globally or locally to the buffer. The variable is set to a string in
the format "{filter label}\t{pattern};{pattern}\n" where {filter label} is the
text that appears in the "Files of Type" comboBox, and {pattern} is the
pattern which filters the filenames. Several patterns can be given, separated
by ';'.
For Motif the same format is used, but only the very first pattern is actually
used (Motif only offers one pattern, but you can edit it).
For example, to have only Vim files in the dialog, you could use the following
command:
let g:browsefilter="Vim Scripts\t*.vim\nVim Startup Files\t*vimrc\n"
You can override the filter setting on a per-buffer basis by setting the
b:browsefilter variable. You would most likely set b:browsefilter in a
filetype plugin, so that the browse dialog would contain entries related to
the type of file you are currently editing. Disadvantage: This makes it
*:cd-* *E186*
:cd[!] - Change to the previous current directory (before the
previous ":cd {path}" command). {not in Vi}
*:chd* *:chdir*
:chd[ir][!] [path] Same as |:cd|.
*:lc* *:lcd*
:lc[d][!] {path} Like |:cd|, but only set the current directory for the
current window. The current directory for other
windows is not changed. {not in Vi}
*:lch* *:lchdir*
:lch[dir][!] Same as |:lcd|. {not in Vi}
Although Vim was made to edit text files, it is possible to edit binary
files. The |-b| Vim argument (b for binary) makes Vim do file I/O in binary
mode, and sets some options for editing binary files ('binary' on, 'textwidth'
to 0, 'modeline' off, 'expandtab' off). Setting the 'binary' option has the
same effect. Don't forget to do this before reading the file.
There are a few things to remember when editing binary files:
- When editing executable files the number of characters must not change.
Use only the "R" or "r" command to change text. Do not delete characters
with "x" or by backspacing.
- Set the 'textwidth' option to 0. Otherwise lines will unexpectedly be
split in two.
- When there are not many <EOL>s, the lines will become very long. If you
want to edit a line that does not fit on the screen reset the 'wrap' option.
Horizontal scrolling is used then. If a line becomes too long (more than
about 32767 characters on the Amiga, much more on 32-bit systems, see
|limits|) you cannot edit that line. The line will be split when reading
the file. It is also possible that you get an "out of memory" error when
reading the file.
- Make sure the 'binary' option is set BEFORE loading the
file. Otherwise both <CR> <NL> and <NL> are considered to end a line
and when the file is written the <NL> will be replaced with <CR> <NL>.
- <Nul> characters are shown on the screen as ^@. You can enter them with
"CTRL-V CTRL-@" or "CTRL-V 000" {Vi cannot handle <Nul> characters in the
file}
- To insert a <NL> character in the file split up a line. When writing the
buffer to a file a <NL> will be written for the <EOL>.
- Vim normally appends an <EOL> at the end of the file if there is none.
Setting the 'binary' option prevents this. If you want to add the final
<EOL>, set the 'endofline' option. You can also read the value of this
option to see if there was an <EOL> for the last line (you cannot see this
in the text).
==============================================================================
9. Encryption *encryption*
Vim is able to write files encrypted, and read them back. The encrypted text
cannot be read without the right key.
{only available when compiled with the |+cryptv| feature} *E833*
The text in the swap file and the undo file is also encrypted. *E843*
Note: The text in memory is not encrypted. A system administrator may be able
to see your text while you are editing it. When filtering text with
":!filter" or using ":w !command" the text is not encrypted, this may reveal
it to others. The 'viminfo' file is not encrypted.
WARNING: If you make a typo when entering the key and then write the file and
exit, the text will be lost!
The normal way to work with encryption, is to use the ":X" command, which will
ask you to enter a key. A following write command will use that key to
encrypt the file. If you later edit the same file, Vim will ask you to enter
a key. If you type the same key as that was used for writing, the text will
be readable again. If you use a wrong key, it will be a mess.
*:X*
:X Prompt for an encryption key. The typing is done without showing the
actual text, so that someone looking at the display won't see it.
The typed key is stored in the 'key' option, which is used to encrypt
the file when it is written. The file will remain unchanged until you
write it. See also |-x|.
The value of the 'key' options is used when text is written. When the option
is not empty, the written file will be encrypted, using the value as the
encryption key. A magic number is prepended, so that Vim can recognize that
the file is encrypted.
To disable the encryption, reset the 'key' option to an empty value:
:set key=
You can use the 'cryptmethod' option to select the type of encryption, use one
of these two:
:setlocal cm=zip " weak method, backwards compatible
:setlocal cm=blowfish " strong method
Do this before writing the file. When reading an encrypted file it will be
set automatically to the method used when that file was written. You can
change 'cryptmethod' before writing that file to change the method.
To set the default method, used for new files, use one of these in your
|vimrc| file:
set cm=zip
set cm=blowfish
The message given for reading and writing a file will show "[crypted]" when
using zip, "[blowfish]" when using blowfish.
When writing an undo file, the same key and method will be used for the text
in the undo file. |persistent-undo|.
*E831* This is an internal error, "cannot happen". If you can reproduce it,
please report to the developers.
When reading a file that has been encrypted and the 'key' option is not empty,
it will be used for decryption. If the value is empty, you will be prompted
to enter the key. If you don't enter a key, or you enter the wrong key, the
file is edited without being decrypted. There is no warning about using the
wrong key (this makes brute force methods to find the key more difficult).
If want to start reading a file that uses a different key, set the 'key'
option to an empty string, so that Vim will prompt for a new one. Don't use
the ":set" command to enter the value, other people can read the command over
your shoulder.
Since the value of the 'key' option is supposed to be a secret, its value can
never be viewed. You should not set this option in a vimrc file.
An encrypted file can be recognized by the "file" command, if you add these
lines to "/etc/magic", "/usr/share/misc/magic" or wherever your system has the
"magic" file:
0 string VimCrypt~ Vim encrypted file
>9 string 01 - "zip" cryptmethod
>9 string 02 - "blowfish" cryptmethod
Notes:
- Encryption is not possible when doing conversion with 'charconvert'.
- Text you copy or delete goes to the numbered registers. The registers can
be saved in the .viminfo file, where they could be read. Change your
'viminfo' option to be safe.
- Someone can type commands in Vim when you walk away for a moment, he should
not be able to get the key.
- If you make a typing mistake when entering the key, you might not be able to
get your text back!
- If you type the key with a ":set key=value" command, it can be kept in the
history, showing the 'key' value in a viminfo file.
- There is never 100% safety. The encryption in Vim has not been tested for
robustness.
- The algorithm used for 'cryptmethod' "zip" is breakable. A 4 character key
in about one hour, a 6 character key in one day (on a Pentium 133 PC). This
requires that you know some text that must appear in the file. An expert
can break it for any key. When the text has been decrypted, this also means
that the key can be revealed, and other files encrypted with the same key
can be decrypted.
- Pkzip uses the same encryption as 'cryptmethod' "zip", and US Govt has no
objection to its export. Pkzip's public file APPNOTE.TXT describes this
algorithm in detail.
- Vim originates from the Netherlands. That is where the sources come from.
Thus the encryption code is not exported from the USA.
==============================================================================
10. Timestamps *timestamp* *timestamps*
Vim remembers the modification timestamp of a file when you begin editing it.
This is used to avoid that you have two different versions of the same file
(without you knowing this).
After a shell command is run (|:!cmd| |suspend| |:read!| |K|) timestamps are
compared for all buffers in a window. Vim will run any associated
|FileChangedShell| autocommands or display a warning for any files that have
changed. In the GUI this happens when Vim regains input focus.
*E321* *E462*
If you want to automatically reload a file when it has been changed outside of
Vim, set the 'autoread' option. This doesn't work at the moment you write the
file though, only when the file wasn't changed inside of Vim.
Note that if a FileChangedShell autocommand is defined you will not get a
warning message or prompt. The autocommand is expected to handle this.
There is no warning for a directory (e.g., with |netrw-browse|). But you do
get warned if you started editing a new file and it was created as a directory
later.
When Vim notices the timestamp of a file has changed, and the file is being
edited in a buffer but has not changed, Vim checks if the contents of the file
is equal. This is done by reading the file again (into a hidden buffer, which
is immediately deleted again) and comparing the text. If the text is equal,
you will get no warning.
If you don't get warned often enough you can use the following command.
*:checkt* *:checktime*
:checkt[ime] Check if any buffers were changed outside of Vim.
This checks and warns you if you would end up with two
versions of a file.
If this is called from an autocommand, a ":global"
command or is not typed the actual check is postponed
until a moment the side effects (reloading the file)
would be harmless.
Each loaded buffer is checked for its associated file
being changed. If the file was changed Vim will take
action. If there are no changes in the buffer and
'autoread' is set, the buffer is reloaded. Otherwise,
you are offered the choice of reloading the file. If
the file was deleted you get an error message.
If the file previously didn't exist you get a warning
if it exists now.
Once a file has been checked the timestamp is reset,
you will not be warned again.
:[N]checkt[ime] {filename}
:[N]checkt[ime] [N]
Check the timestamp of a specific buffer. The buffer
may be specified by name, number or with a pattern.
*E813* *E814*
Vim will reload the buffer if you chose to. If a window is visible that
contains this buffer, the reloading will happen in the context of this window.
Otherwise a special window is used, so that most autocommands will work. You
can't close this window. A few other restrictions apply. Best is to make
sure nothing happens outside of the current buffer. E.g., setting
window-local options may end up in the wrong window. Splitting the window,
doing something there and closing it should be OK (if there are no side
effects from other autocommands). Closing unrelated windows and buffers will
get you into trouble.
Before writing a file the timestamp is checked. If it has changed, Vim will
ask if you really want to overwrite the file:
WARNING: The file has been changed since reading it!!!
Do you really want to write to it (y/n)?
If you hit 'y' Vim will continue writing the file. If you hit 'n' the write is
aborted. If you used ":wq" or "ZZ" Vim will not exit, you will get another
chance to write the file.
The message would normally mean that somebody has written to the file after
the edit session started. This could be another person, in which case you
probably want to check if your changes to the file and the changes from the
other person should be merged. Write the file under another name and check for
differences (the "diff" program can be used for this).
It is also possible that you modified the file yourself, from another edit
session or with another command (e.g., a filter command). Then you will know
which version of the file you want to keep.
There is one situation where you get the message while there is nothing wrong:
On a Win32 system on the day daylight saving time starts. There is something
in the Win32 libraries that confuses Vim about the hour time difference. The
problem goes away the next day.
==============================================================================
11. File Searching *file-searching*
{not available when compiled without the |+path_extra| feature}
The file searching is currently used for the 'path', 'cdpath' and 'tags'
options, for |finddir()| and |findfile()|. Other commands use |wildcards|
which is slightly different.
There are three different types of searching:
and then search for a file with |gf| the file is searched in:
/u/user_x/work/release/include
/u/user_x/work/include
/u/user_x/include
3) Combined up/downward search:
If Vim's current path is /u/user_x/work/release and you do
set path=**;/u/user_x
and then search for a file with |gf| the file is searched in:
/u/user_x/work/release/**
/u/user_x/work/**
/u/user_x/**
BE CAREFUL! This might consume a lot of time, as the search of
'/u/user_x/**' includes '/u/user_x/work/**' and
'/u/user_x/work/release/**'. So '/u/user_x/work/release/**' is searched
three times and '/u/user_x/work/**' is searched twice.
In the above example you might want to set path to:
:set path=**,/u/user_x/**
This searches:
/u/user_x/work/release/**
/u/user_x/**
This searches the same directories, but in a different order.
Note that completion for ":find", ":sfind", and ":tabfind" commands do not
currently work with 'path' items that contain a url or use the double star
(/usr/**2) or upward search (;) notations.
vim:tw=78:ts=8:ft=help:norl:
top - main help file
*gui-win32-maximized*
If you want Vim to start with a maximized window, add this command to your
vimrc or gvimrc file:
au GUIEnter * simalt ~x
*gui-w32s*
There is a specific version of gvim.exe that runs under the Win32s subsystem
of Windows 3.1 or 3.11. See |win32s|.
When gvim starts up normally, it creates its own top level window. If you
pass Vim the command-line option |--windowid| with a decimal or hexadecimal
value, Vim will create a window that is a child of the window with the given
ID. This enables Vim to act as a plugin in another application. This really
is a programmer's interface, and is of no use without a supporting application
to spawn Vim correctly.
==============================================================================
2. Vim as default editor *vim-default-editor*
To set Vim as the default editor for a file type:
1. Start a Windows Explorer
2. Choose View/Options -> File Types
3. Select the path to gvim for every file type that you want to use it for.
(you can also use three spaces in the file type field, for files without an
extension).
In the "open" action, use:
gvim "%1"
The quotes are required for using file names with embedded spaces.
You can also use this:
gvim "%L"
This should avoid short (8.3 character) file names in some situations. But
I'm not sure if this works everywhere.
When you open a file in Vim by double clicking it, Vim changes to that
file's directory.
If you want Vim to start full-screen, use this for the Open action:
gvim -c "simalt ~x" "%1"
Another method, which also works when you put Vim in another directory (e.g.,
when you have got a new version):
1. select a file you want to use Vim with
2. <Shift-F10>
3. select "Open With..." menu entry
4. click "Other..."
5. browse to the (new) location of Vim and click "Open"
6. make "Always Use this program..." checked
7. <OK>
*send-to-menu* *sendto*
You can also install Vim in the "Send To" menu:
1. Start a Windows Explorer
2. Navigate to your sendto directory:
Windows 95: %windir%\sendto (e.g. "c:\windows\sendto")
Windows NT: %windir%\profiles\%user%\sendto (e.g.
"c:\winnt\profiles\mattha\sendto").
3. Right-click in the file pane and select New->Shortcut
4. Follow the shortcut wizard, using the full path to VIM/GVIM.
When you 'send a file to Vim', Vim changes to that file's directory. Note,
however, that any long directory names will appear in their short (MS-DOS)
form. This is a limitation of the Windows "Send To" mechanism.
*notepad*
You could replace notepad.exe with gvim.exe, but that has a few side effects.
Some programs rely on notepad arguments, which are not recognized by Vim. For
example "notepad -p" is used by some applications to print a file. It's
better to leave notepad where it is and use another way to start Vim.
*win32-popup-menu*
A more drastic approach is to install an "Edit with Vim" entry in the popup
menu for the right mouse button. With this you can edit any file with Vim.
This can co-exist with the file associations mentioned above. The difference
is that the file associations will make starting Vim the default action. With
the "Edit with Vim" menu entry you can keep the existing file association for
double clicking on the file, and edit the file with Vim when you want. For
example, you can associate "*.mak" with your make program. You can execute
the makefile by double clicking it and use the "Edit with Vim" entry to edit
the makefile.
You can select any files and right-click to see a menu option called "Edit
with gvim". Choosing this menu option will invoke gvim with the file you have
selected. If you select multiple files, you will find two gvim-related menu
options:
"Edit with multiple gvims" -- one gvim for each file in the selection
"Edit with single gvim" -- one gvim for all the files in the selection
And if there already is a gvim running:
"Edit with existing gvim" -- edit the file with the running gvim
*install-registry*
You can add the "Edit with Vim" menu entry in an easy way by using the
"install.exe" program. It will add several registry entries for you.
You can also do this by hand. This is complicated! Use the install.exe if
you can.
1. Start the registry editor with "regedit".
2. Add these keys:
key value name value
HKEY_CLASSES_ROOT\CLSID\{51EEE242-AD87-11d3-9C1E-0090278BBD99}
{default} Vim Shell Extension
HKEY_CLASSES_ROOT\CLSID\{51EEE242-AD87-11d3-9C1E-0090278BBD99}\InProcServer32
{default} {path}\gvimext.dll
ThreadingModel Apartment
HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\gvim
{default} {51EEE242-AD87-11d3-9C1E-0090278BBD99}
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved
{51EEE242-AD87-11d3-9C1E-0090278BBD99}
Vim Shell Extension
HKEY_LOCAL_MACHINE\Software\Vim\Gvim
path {path}\gvim.exe
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\vim 5.6
DisplayName Vim 5.6: Edit with Vim popup menu entry
UninstallString {path}\uninstal.exe
Replace {path} with the path that leads to the executable.
Don't type {default}, this is the value for the key itself.
To remove "Edit with Vim" from the popup menu, just remove the registry
entries mentioned above. The "uninstal.exe" program can do this for you. You
can also use the entry in the Windows standard "Add/Remove Programs" list.
If you notice that this entry overrules other file type associations, set
those associations again by hand (using Windows Explorer, see above). This
only seems to happen on some Windows NT versions (Windows bug?). Procedure:
1. Find the name of the file type. This can be done by starting the registry
editor, and searching for the extension in \\HKEY_CLASSES_ROOT
2. In a Windows Explorer, use View/Options/File Types. Search for the file
type in the list and click "Edit". In the actions list, you can select on
to be used as the default (normally the "open" action) and click on the
"Set Default" button.
*mswin.vim*
To use the standard MS-Windows way of CTRL-X, CTRL-C and CTRL-V, use the
$VIMRUNTIME/mswin.vim script. You could add this line to your _vimrc file:
source $VIMRUNTIME/mswin.vim
Since CTRL-C is used to copy the text to the clipboard, it can't be used to
cancel an operation. Use CTRL-Break for that.
CTRL-Z is used for undo. This means you can't suspend Vim with this key, use
|:suspend| instead (if it's supported at all).
*CTRL-V-alternative* *CTRL-Q*
Since CTRL-V is used to paste, you can't use it to start a blockwise Visual
selection. You can use CTRL-Q instead. You can also use CTRL-Q in Insert
mode and Command-line mode to get the old meaning of CTRL-V. But CTRL-Q
doesn't work for terminals when it's used for control flow.
NOTE: The clipboard support still has a number of bugs. See |todo|.
==============================================================================
4. Shell Commands *gui-shell-win32*
Vim uses another window for external commands, to make it possible to run any
command. The external command gets its own environment for running, just like
it was started from a DOS prompt.
*win32-vimrun*
Executing an external command is done indirectly by the "vimrun" command. The
"vimrun.exe" must be in the path for this to work. Or it must be in the same
directory as the Vim executable. If "vimrun" cannot be found, the command is
executed directly, but then the DOS window closes immediately after the
external command has finished.
WARNING: If you close this window with the "X" button, and confirm the
question if you really want to kill the application, Vim may be killed too!
(This does not apply to commands run asynchronously with ":!start".)
In Windows 95, the window in which the commands are executed is always 25x80
characters, to be as DOS compatible as possible (this matters!). The default
system font is used. On NT, the window will be the default you have set up for
"Console" in Control Panel. On Win32s, the properties of the DOS box are
determined by _default.pif in the windows directory.
*msdos-mode*
If you get a dialog that says "This program is set to run in MS-DOS mode..."
when you run an external program, you can solve this by changing the
properties of the associated shortcut:
- Use a Windows Explorer to find the command.com that is used. It can be
c:\command.com, c:\dos\command.com, c:\windows\command.com, etc.
- With the right mouse button, select properties of this command.com.
- In the Program tab select "Advanced".
- Unselect "MS-DOS mode".
*win32-!start*
Normally, Vim waits for a command to complete before continuing (this makes
sense for most shell commands which produce output for Vim to use). If you
want Vim to start a program and return immediately, you can use the following
syntax on W95 & NT:
:!start [/min] {command}
The optional "/min" causes the window to be minimized.
On Win32s, you will have to go to another window instead. Don't forget that
you must tell Windows 3.1x to keep executing a DOS command in the background
while you switch back to Vim.
==============================================================================
5. Special colors *win32-colors*
On Win32, the normal DOS colors can be used. See |dos-colors|.
Additionally the system configured colors can also be used. These are known
by the names Sys_XXX, where XXX is the appropriate system color name, from the
following list (see the Win32 documentation for full descriptions). Case is
ignored. Note: On Win32s not all of these colors are supported.
Sys_3DDKShadow Sys_3DFace Sys_BTNFace
Sys_3DHilight Sys_3DHighlight Sys_BTNHilight
Sys_BTNHighlight Sys_3DLight Sys_3DShadow
Sys_BTNShadow Sys_ActiveBorder Sys_ActiveCaption
Sys_AppWorkspace Sys_Background Sys_Desktop
Sys_BTNText Sys_CaptionText Sys_GrayText
Sys_Highlight Sys_HighlightText Sys_InactiveBorder
Sys_InactiveCaption Sys_InactiveCaptionText Sys_InfoBK
Sys_InfoText Sys_Menu Sys_MenuText
Sys_ScrollBar Sys_Window Sys_WindowFrame
Sys_WindowText
Probably the most useful values are
Sys_Window Normal window background
Sys_WindowText Normal window text
Sys_Highlight Highlighted background
Sys_HighlightText Highlighted text
These extra colors are also available:
Gray, Grey, LightYellow, SeaGreen, Orange, Purple, SlateBlue, Violet,
*rgb.txt*
Additionally, colors defined by a "rgb.txt" file can be used. This file is
well known from X11. A few lines from it:
255 218 185 peach puff
205 133 63 peru
255 181 197 pink
This shows the layout of the file: First the R, G and B value as a decimal
number, followed by the name of the color. The four fields are separated by
spaces.
You can get an rgb.txt file from any X11 distribution. It is located in a
directory like "/usr/X11R6/lib/X11/". For Vim it must be located in the
$VIMRUNTIME directory. Thus the file can be found with "$VIMRUNTIME/rgb.txt".
==============================================================================
*gui-w32-dialogs* *dialog*
6. Windows dialogs & browsers
The Win32 GUI can use familiar Windows components for some operations, as well
as the traditional interface shared with the console version.
6.1 Dialogs
The dialogs displayed by the "confirm" family (i.e. the 'confirm' option,
|:confirm| command and |confirm()| function) are GUI-based rather than the
console-based ones used by other versions. The 'c' flag in 'guioptions'
changes this.
*:tearoff* *:te*
:te[aroff] {name} Tear-off the menu {name}. The menu named must have at
least one subentry, but need not appear on the
menu-bar (see |win32-hidden-menus|).
Example:
:tearoff File
will make the "File" menu (if there is one) appear as a tearoff menu.
:amenu ]Toolbar.Make :make<CR>
:tearoff ]Toolbar
This creates a floating menu that doesn't exist on the main menu-bar.
Note that a menu that starts with ']' will not be displayed.
==============================================================================
7. Command line arguments *gui-w32-cmdargs*
Analysis of a command line into parameters is not standardised in MS Windows.
Gvim has to provide logic to analyse a command line. This logic is likely to
be different from the default logic provided by a compilation system used to
build vim. The differences relate to unusual double quote (") usage.
The arguments "C:\My Music\freude.txt" and "+/Sch\"iller" are handled in the
same way. The argument "+/Sch""iller" may be handled different by gvim and
vim, depending what it was compiled with.
The rules are:
a) A parameter is a sequence of graphic characters.
b) Parameters are separated by white space.
c) A parameter can be enclosed in double quotes to include white space.
d) A sequence of zero or more backslashes (\) and a double quote (")
is special. The effective number of backslashes is halved, rounded
down. An even number of backslashes reverses the acceptability of
spaces and tabs, an odd number of backslashes produces a literal
double quote.
So:
" is a special double quote
\" is a literal double quote
\\" is a literal backslash and a special double quote
\\\" is a literal backslash and a literal double quote
\\\\" is 2 literal backslashes and a special double quote
\\\\\" is 2 literal backslashes and a literal double quote
etc.
Example:
gvim "C:\My Music\freude" +"set ignorecase" +/"\"foo\\" +\"bar\\\"
opens "C:\My Music\freude" and executes the line mode commands:
set ignorecase; /"foo\ and /bar\"
==============================================================================
8. Various *gui-w32-various*
*gui-w32-printing*
The "File/Print" menu prints the text with syntax highlighting, see
|:hardcopy|. If you just want to print the raw text and have a default
printer installed this should also work:
:w >>prn
Vim supports a number of standard MS Windows features. Some of these are
detailed elsewhere: see |'mouse'|, |win32-hidden-menus|.
*drag-n-drop-win32*
You can drag and drop one or more files into the Vim window, where they will
be opened as normal. See |drag-n-drop|.
*:simalt* *:si*
:sim[alt] {key} simulate pressing {key} while holding Alt pressed.
{not in Vi} {only for Win32 versions}
Normally, Vim takes control of all Alt-<Key> combinations, to increase the
number of possible mappings. This clashes with the standard use of Alt as the
key for accessing menus.
The quick way of getting standard behavior is to set the 'winaltkeys' option
to "yes". This however prevents you from mapping Alt keys at all.
Another way is to set 'winaltkeys' to "menu". Menu shortcut keys are then
handled by windows, other ALT keys can be mapped. This doesn't allow a
dependency on the current state though.
To get round this, the :simalt command allows Vim (when 'winaltkeys' is not
"yes") to fake a Windows-style Alt keypress. You can use this to map Alt key
combinations (or anything else for that matter) to produce standard Windows
actions. Here are some examples:
:map <M-f> :simalt f<CR>
This makes Alt-F pop down the 'File' menu (with the stock Menu.vim) by
simulating the keystrokes Alt, F.
:map <M-Space> :simalt ~<CR>
This maps Alt-Space to pop down the system menu for the Vim window. Note that
~ is used by simalt to represent the <Space> character.
:map <C-n> :simalt ~n<CR>
Maps Control-N to produce the keys Alt-Space followed by N. This minimizes the
Vim window via the system menu.
Note that the key changes depending on the language you are using.
*intellimouse-wheel-problems*
When using the Intellimouse mouse wheel causes Vim to stop accepting input, go
to:
ControlPanel - Mouse - Wheel - UniversalScrolling - Exceptions
And add gvim to the list of applications. This problem only appears to happen
with the Intellimouse driver 2.2 and when "Universal Scrolling" is turned on.
top - main help file
*CTRL-R*
CTRL-R Redo [count] changes which were undone. {Vi: redraw
screen}
*U*
U Undo all latest changes on one line. {Vi: while not
moved off of it}
The last changes are remembered. You can use the undo and redo commands above
to revert the text to how it was before each change. You can also apply the
changes again, getting back the text before the undo.
The "U" command is treated by undo/redo just like any other command. Thus a
"u" command undoes a "U" command and a 'CTRL-R' command redoes it again. When
mixing "U", "u" and 'CTRL-R' you will notice that the "U" command will
restore the situation of a line to before the previous "U" command. This may
be confusing. Try it out to get used to it.
The "U" command will always mark the buffer as changed. When "U" changes the
buffer back to how it was without changes, it is still considered changed.
Use "u" to undo changes until the buffer becomes unchanged.
==============================================================================
*:undol* *:undolist*
:undol[ist] List the leafs in the tree of changes. Example:
number changes when saved
88 88 2010/01/04 14:25:53
108 107 08/07 12:47:51
136 46 13:33:01 7
166 164 3 seconds ago
The "number" column is the change number. This number
continuously increases and can be used to identify a
specific undo-able change, see |:undo|.
The "changes" column is the number of changes to this
leaf from the root of the tree.
The "when" column is the date and time when this
change was made. The four possible formats are:
N seconds ago
HH:MM:SS hour, minute, seconds
MM/DD HH:MM:SS idem, with month and day
YYYY/MM/DD HH:MM:SS idem, with year
The "saved" column specifies, if this change was
written to disk and which file write it was. This can
be used with the |:later| and |:earlier| commands.
For more details use the |undotree()| function.
*g-*
g- Go to older text state. With a count repeat that many
times. {not in Vi}
*:ea* *:earlier*
:earlier {count} Go to older text state {count} times.
:earlier {N}s Go to older text state about {N} seconds before.
:earlier {N}m Go to older text state about {N} minutes before.
:earlier {N}h Go to older text state about {N} hours before.
:earlier {N}d Go to older text state about {N} days before.
:earlier {N}f Go to older text state {N} file writes before.
When changes were made since the last write
":earlier 1f" will revert the text to the state when
it was written. Otherwise it will go to the write
before that.
When at the state of the first file write, or when
the file was not written, ":earlier 1f" will go to
before the first change.
*g+*
g+ Go to newer text state. With a count repeat that many
times. {not in Vi}
*:lat* *:later*
:later {count} Go to newer text state {count} times.
:later {N}s Go to newer text state about {N} seconds later.
:later {N}m Go to newer text state about {N} minutes later.
:later {N}h Go to newer text state about {N} hours later.
:later {N}d Go to newer text state about {N} days later.
:later {N}f Go to newer text state {N} file writes later.
When at the state of the last file write, ":later 1f"
will go to the newest text state.
Note that text states will become unreachable when undo information is cleared
for 'undolevels'.
Don't be surprised when moving through time shows multiple changes to take
place at a time. This happens when moving through the undo tree and then
making a new change.
EXAMPLE
Start with this text:
one two three
Delete the first word by pressing "x" three times:
ne two three
e two three
two three
Now undo that by pressing "u" three times:
e two three
ne two three
one two three
Delete the second word by pressing "x" three times:
one wo three
one o three
one three
Now undo that by using "g-" three times:
one o three
one wo three
two three
You are now back in the first undo branch, after deleting "one". Repeating
"g-" will now bring you back to the original text:
e two three
ne two three
one two three
Jump to the last change with ":later 1h":
one three
And back to the start again with ":earlier 1h":
one two three
Note that using "u" and CTRL-R will not get you to all possible text states
while repeating "g-" and "g+" does.
==============================================================================
5. Undo persistence *undo-persistence* *persistent-undo*
When unloading a buffer Vim normally destroys the tree of undos created for
that buffer. By setting the 'undofile' option, Vim will automatically save
your undo history when you write a file and restore undo history when you edit
the file again.
The 'undofile' option is checked after writing a file, before the BufWritePost
autocommands. If you want to control what files to write undo information
for, you can use a BufWritePre autocommand:
au BufWritePre /tmp/* setlocal noundofile
Vim saves undo trees in a separate undo file, one for each edited file, using
a simple scheme that maps filesystem paths directly to undo files. Vim will
detect if an undo file is no longer synchronized with the file it was written
for (with a hash of the file contents) and ignore it when the file was changed
after the undo file was written, to prevent corruption. An undo file is also
ignored if its owner differs from the owner of the edited file. Set 'verbose'
to get a message about that.
Undo files are normally saved in the same directory as the file. This can be
changed with the 'undodir' option.
When the file is encrypted, the text in the undo file is also crypted. The
same key and method is used. |encryption|
You can also save and restore undo histories by using ":wundo" and ":rundo"
respectively:
*:wundo* *:rundo*
:wundo[!] {file}
Write undo history to {file}.
When {file} exists and it does not look like an undo file
(the magic number at the start of the file is wrong), then
this fails, unless the ! was added.
If it exists and does look like an undo file it is
overwritten.
{not in Vi}
:rundo {file} Read undo history from {file}.
{not in Vi}
You can use these in autocommands to explicitly specify the name of the
history file. E.g.:
au BufReadPost * call ReadUndo()
au BufWritePost * call WriteUndo()
func ReadUndo()
if filereadable(expand('%:h'). '/UNDO/' . expand('%:t'))
rundo %:h/UNDO/%:t
endif
endfunc
func WriteUndo()
let dirname = expand('%:h') . '/UNDO'
if !isdirectory(dirname)
call mkdir(dirname)
endif
wundo %:h/UNDO/%:t
endfunc
You should keep 'undofile' off, otherwise you end up with two undo files for
every write.
You can use the |undofile()| function to find out the file name that Vim would
use.
Note that while reading/writing files and 'undofile' is set most errors will
be silent, unless 'verbose' is set. With :wundo and :rundo you will get more
error messages, e.g., when the file cannot be read or written.
NOTE: undo files are never deleted by Vim. You need to delete them yourself.
Reading an existing undo file may fail for several reasons:
*E822* It cannot be opened, because the file permissions don't allow it.
*E823* The magic number at the start of the file doesn't match. This usually
means it is not an undo file.
*E824* The version number of the undo file indicates that it's written by a
newer version of Vim. You need that newer version to open it. Don't
write the buffer if you want to keep the undo info in the file.
"File contents changed, cannot use undo info"
The file text differs from when the undo file was written. This means
the undo file cannot be used, it would corrupt the text. This also
happens when 'encoding' differs from when the undo file was written.
*E825* The undo file does not contain valid contents and cannot be used.
*E826* The undo file is encrypted but decryption failed.
*E827* The undo file is encrypted but this version of Vim does not support
encryption. Open the file with another Vim.
*E832* The undo file is encrypted but 'key' is not set, the text file is not
encrypted. This would happen if the text file was written by Vim
encrypted at first, and later overwritten by not encrypted text.
You probably want to delete this undo file.
"Not reading undo file, owner differs"
The undo file is owned by someone else than the owner of the text
file. For safety the undo file is not used.
Writing an undo file may fail for these reasons:
*E828* The file to be written cannot be created. Perhaps you do not have
write permissions in the directory.
"Cannot write undo file in any directory in 'undodir'"'
None of the directories in 'undodir' can be used.
"Will not overwrite with undo file, cannot read"
A file exists with the name of the undo file to be written, but it
cannot be read. You may want to delete this file or rename it.
"Will not overwrite, this is not an undo file"
A file exists with the name of the undo file to be written, but it
does not start with the right magic number. You may want to delete
this file or rename it.
"Skipping undo file write, nothing to undo"
There is no undo information to be written, nothing has been changed
or 'undolevels' is negative.
*E829* An error occurred while writing the undo file. You may want to try
again.
==============================================================================
6. Remarks about undo *undo-remarks*
The number of changes that are remembered is set with the 'undolevels' option.
If it is zero, the Vi-compatible way is always used. If it is negative no
undo is possible. Use this if you are running out of memory.
*clear-undo*
When you set 'undolevels' to -1 the undo information is not immediately
cleared, this happens at the next change. To force clearing the undo
information you can use these commands:
:let old_undolevels = &undolevels
:set undolevels=-1
:exe "normal a \<BS>\<Esc>"
:let &undolevels = old_undolevels
:unlet old_undolevels
Marks for the buffer ('a to 'z) are also saved and restored, together with the
text. {Vi does this a little bit different}
When all changes have been undone, the buffer is not considered to be changed.
It is then possible to exit Vim with ":q" instead of ":q!" {not in Vi}. Note
that this is relative to the last write of the file. Typing "u" after ":w"
actually changes the buffer, compared to what was written, so the buffer is
considered changed then.
When manual |folding| is being used, the folds are not saved and restored.
Only changes completely within a fold will keep the fold as it was, because
the first and last line of the fold don't change.
The numbered registers can also be used for undoing deletes. Each time you
delete text, it is put into register "1. The contents of register "1 are
shifted to "2, etc. The contents of register "9 are lost. You can now get
back the most recent deleted text with the put command: '"'1P'. (also, if the
deleted text was the result of the last delete or copy operation, 'P' or 'p'
also works as this puts the contents of the unnamed register). You can get
back the text of three deletes ago with '"'3P'.
*redo-register*
If you want to get back more than one part of deleted text, you can use a
special feature of the repeat command ".". It will increase the number of the
register used. So if you first do ""1P", the following "." will result in a
'"'2P'. Repeating this will result in all numbered registers being inserted.
Example: If you deleted text with 'dd....' it can be restored with
'"'1P....'.
If you don't know in which register the deleted text is, you can use the
:display command. An alternative is to try the first register with '"'1P', and
if it is not what you want do 'u.'. This will remove the contents of the
first put, and repeat the put command for the second register. Repeat the
'u.' until you got what you want.
top - main help file
*.*
. Repeat last change, with count replaced with [count].
Also repeat a yank command, when the 'y' flag is
included in 'cpoptions'. Does not repeat a
command-line command.
Simple changes can be repeated with the "." command. Without a count, the
count of the last change is used. If you enter a count, it will replace the
last one. If the last change included a specification of a numbered register,
the register number will be incremented. See |redo-register| for an example
how to use this. Note that when repeating a command that used a Visual
selection, the same SIZE of area is used, see |visual-repeat|.
*@:*
@: Repeat last command-line [count] times.
{not available when compiled without the
|+cmdline_hist| feature}
==============================================================================
2. Multiple repeats *multi-repeat*
*:v* *:vglobal*
:[range]v[global]/{pattern}/[cmd]
Same as :g!.
Instead of the '/' which surrounds the {pattern}, you can use any other
single byte character, but not an alphanumeric character, '\', '"'' or '|'.
This is useful if you want to include a '/' in the search pattern or
replacement string.
For the definition of a pattern, see |pattern|.
The global commands work by first scanning through the [range] lines and
marking each line where a match occurs (for a multi-line pattern, only the
start of the match matters).
In a second scan the [cmd] is executed for each marked line with its line
number prepended. For ":v" and ":g!" the command is executed for each not
marked line. If a line is deleted its mark disappears.
The default for [range] is the whole buffer (1,$). Use "CTRL-C" to interrupt
the command. If an error message is given for a line, the command for that
line is aborted and the global command continues with the next marked or
unmarked line.
To repeat a non-Ex command, you can use the ":normal" command:
:g/pat/normal {commands}
Make sure that {commands} ends with a whole command, otherwise Vim will wait
for you to type the rest of the command for each match. The screen will not
have been updated, so you don't know what you are doing. See |:normal|.
The undo/redo command will undo/redo the whole global command at once.
The previous context mark will only be set once (with "''"' you go back to
where the cursor was before the global command).
The global command sets both the last used search pattern and the last used
substitute pattern (this is vi compatible). This makes it easy to globally
replace a string:
:g/pat/s//PAT/g
This replaces all occurrences of "pat" with "PAT". The same can be done with:
:%s/pat/PAT/g
Which is two characters shorter!
When using "global" in Ex mode, a special case is using ":visual" as a
command. This will move to a matching line, go to Normal mode to let you
execute commands there until you use |Q| to return to Ex mode. This will be
repeated for each matching line. While doing this you cannot use ":global".
To abort this type CTRL-C twice.
==============================================================================
3. Complex repeats *complex-repeat*
*q* *recording*
q{0-9a-zA-Z"} Record typed characters into register {0-9a-zA-Z"}
(uppercase to append). The 'q' command is disabled
while executing a register, and it doesn't work inside
a mapping and |:normal|. {Vi: no recording}
q Stops recording. (Implementation note: The 'q' that
stops recording is not stored in the register, unless
it was the result of a mapping) {Vi: no recording}
*@*
@{0-9a-z".=*} Execute the contents of register {0-9a-z".=*} [count]
times. Note that register '%' (name of the current
file) and '#' (name of the alternate file) cannot be
used.
The register is executed like a mapping, that means
that the difference between 'wildchar' and 'wildcharm'
applies.
For "@=" you are prompted to enter an expression. The
result of the expression is then executed.
See also |@:|. {Vi: only named registers}
*@@* *E748*
@@ Repeat the previous @{0-9a-z":*} [count] times.
:[addr]*{0-9a-z".=} *:@* *:star*
:[addr]@{0-9a-z".=*} Execute the contents of register {0-9a-z".=*} as an Ex
command. First set cursor at line [addr] (default is
current line). When the last line in the register does
not have a <CR> it will be added automatically when
the 'e' flag is present in 'cpoptions'.
Note that the ":*" command is only recognized when the
*:@:*
:[addr]@: Repeat last command-line. First set cursor at line
[addr] (default is current line). {not in Vi}
*:@@*
:[addr]@@ Repeat the previous :@{0-9a-z"}. First set cursor at
line [addr] (default is current line). {Vi: only in
some versions}
==============================================================================
4. Using Vim scripts *using-scripts*
For writing a Vim script, see chapter 41 of the user manual |usr_41.txt|.
*:ru* *:runtime*
:ru[ntime][!] {file} ..
Read Ex commands from {file} in each directory given
by 'runtimepath'. There is no error for non-existing
files. Example:
:runtime syntax/c.vim
There can be multiple {file} arguments, separated by
spaces. Each {file} is searched for in the first
directory from 'runtimepath', then in the second
directory, etc. Use a backslash to include a space
inside {file} (although it's better not to use spaces
in file names, it causes trouble).
When [!] is included, all found files are sourced.
When it is not included only the first found file is
sourced.
When {file} contains wildcards it is expanded to all
matching files. Example:
:runtime! plugin/*.vim
This is what Vim uses to load the plugin files when
starting up. This similar command:
:runtime plugin/*.vim
would source the first file only.
When 'verbose' is one or higher, there is a message
when no file could be found.
When 'verbose' is two or higher, there is a message
about each searched file.
{not in Vi}
scriptencoding iso-8859-5
scriptencoding cp932
When [encoding] is empty, no conversion is done. This
can be used to restrict conversion to a sequence of
lines:
scriptencoding euc-jp
... lines to be converted ...
scriptencoding
... not converted ...
When conversion isn't supported by the system, there
is no error message and no conversion is done.
Don't use "ucs-2" or "ucs-4", scripts cannot be in
these encodings (they would contain NUL bytes).
When a sourced script starts with a BOM (Byte Order
Mark) in utf-8 format Vim will recognize it, no need
to use ":scriptencoding utf-8" then.
When compiled without the |+multi_byte| feature this
command is ignored.
{not in Vi}
*:scrip* *:scriptnames*
:scrip[tnames] List all sourced script names, in the order they were
first sourced. The number is used for the script ID
|<SID>|.
{not in Vi} {not available when compiled without the
|+eval| feature}
"other.vimrc" file in the same directory as your ".vimrc" file, you can source
it from your ".vimrc" file with this command:
:source <sfile>:h/other.vimrc
In script files terminal-dependent key codes are represented by
terminal-independent two character codes. This means that they can be used
in the same way on different kinds of terminals. The first character of a
key code is 0x80 or 128, shown on the screen as "~@". The second one can be
found in the list |key-notation|. Any of these codes can also be entered
with CTRL-V followed by the three digit decimal code. This does NOT work for
the <t_xx> termcap codes, these can only be used in mappings.
*:source_crnl* *W15*
MS-DOS, Win32 and OS/2: Files that are read with ":source" normally have
<CR><NL> <EOL>s. These always work. If you are using a file with <NL> <EOL>s
(for example, a file made on Unix), this will be recognized if 'fileformats'
is not empty and the first line does not end in a <CR>. This fails if the
first line has something like ":map <F1> :help^M", where "^M" is a <CR>. If
the first line ends in a <CR>, but following ones don't, you will get an error
message, because the <CR> from the first lines will be lost.
Mac Classic: Files that are read with ":source" normally have <CR> <EOL>s.
These always work. If you are using a file with <NL> <EOL>s (for example, a
file made on Unix), this will be recognized if 'fileformats' is not empty and
the first line does not end in a <CR>. Be careful not to use a file with <NL>
linebreaks which has a <CR> in first line.
On other systems, Vim expects ":source"ed files to end in a <NL>. These
always work. If you are using a file with <CR><NL> <EOL>s (for example, a
file made on MS-DOS), all lines will have a trailing <CR>. This may cause
problems for some commands (e.g., mappings). There is no automatic <EOL>
detection, because it's common to start with a line that defines a mapping
that ends in a <CR>, which will confuse the automaton.
*line-continuation*
Long lines in a ":source"d Ex command script file can be split by inserting
a line continuation symbol "\" (backslash) at the start of the next line.
There can be white space before the backslash, which is ignored.
Example: the lines
:set comments=sr:/*,mb:*,el:*/,
\://,
\b:#,
\:%,
\n:>,
\fb:-
are interpreted as if they were given in one line:
:set comments=sr:/*,mb:*,el:*/,://,b:#,:%,n:>,fb:-
All leading whitespace characters in the line before a backslash are ignored.
Note however that trailing whitespace in the line before it cannot be
inserted freely; it depends on the position where a command is split up
whether additional whitespace is allowed or not.
When a space is required it's best to put it right after the backslash. A
space at the end of a line is hard to see and may be accidentally deleted.
:syn match Comment
\ "very long regexp"
\ keepend
There is a problem with the ":append" and ":insert" commands:
:1append
\asdf
.
The backslash is seen as a line-continuation symbol, thus this results in the
command:
:1appendasdf
.
To avoid this, add the 'C' flag to the 'cpoptions' option:
:set cpo+=C
:1append
\asdf
.
:set cpo-=C
Note that when the commands are inside a function, you need to add the 'C'
flag when defining the function, it is not relevant when executing it.
:set cpo+=C
:function Foo()
:1append
\asdf
.
:endfunction
:set cpo-=C
Rationale:
Most programs work with a trailing backslash to indicate line
continuation. Using this in Vim would cause incompatibility with Vi.
For example for this Vi mapping:
:map xx asdf\
Therefore the unusual leading backslash is used.
==============================================================================
5. Debugging scripts *debug-scripts*
Besides the obvious messages that you can add to your scripts to find out what
they are doing, Vim offers a debug mode. This allows you to step through a
sourced file or user function and set breakpoints.
NOTE: The debugging mode is far from perfect. Debugging will have side
effects on how Vim works. You cannot use it to debug everything. For
example, the display is messed up by the debugging messages.
{Vi does not have a debug mode}
An alternative to debug mode is setting the 'verbose' option. With a bigger
number it will give more verbose messages about what Vim is doing.
DEBUG MODE
Once in debugging mode, the usual Ex commands can be used. For example, to
inspect the value of a variable:
echo idx
When inside a user function, this will print the value of the local variable
"idx". Prepend "g:" to get the value of a global variable:
echo g:idx
All commands are executed in the context of the current function or script.
You can also set options, for example setting or resetting 'verbose' will show
what happens, but you might want to set it just before executing the lines you
are interested in:
:set verbose=20
Commands that require updating the screen should be avoided, because their
effect won't be noticed until after leaving debug mode. For example:
:help
won't be very helpful.
There is a separate command-line history for debug mode.
The line number for a function line is relative to the start of the function.
If you have trouble figuring out where you are, edit the file that defines
the function in another Vim, search for the start of the function and do
"99j". Replace "99" with the line number.
Additionally, these commands can be used:
*>cont*
cont Continue execution until the next breakpoint is hit.
*>quit*
quit Abort execution. This is like using CTRL-C, some
things might still be executed, doesn't abort
everything. Still stops at the next breakpoint.
*>next*
next Execute the command and come back to debug mode when
it's finished. This steps over user function calls
and sourced files.
*>step*
step Execute the command and come back to debug mode for
the next command. This steps into called user
functions and sourced files.
*>interrupt*
interrupt This is like using CTRL-C, but unlike ">quit" comes
back to debug mode for the next command that is
executed. Useful for testing |:finally| and |:catch|
on interrupt exceptions.
*>finish*
finish Finish the current script or user function and come
back to debug mode for the command after the one that
sourced or called it.
About the additional commands in debug mode:
- There is no command-line completion for them, you get the completion for the
normal Ex commands only.
- You can shorten them, up to a single character: "c", "n", "s" and "f".
- Hitting <CR> will repeat the previous one. When doing another command, this
is reset (because it's not clear what you want to repeat).
- When you want to use the Ex command with the same name, prepend a colon:
":cont", ":next", ":finish" (or shorter).
DEFINING BREAKPOINTS
*:breaka* *:breakadd*
:breaka[dd] func [lnum] {name}
Set a breakpoint in a function. Example:
:breakadd func Explore
Doesn't check for a valid function name, thus the breakpoint
can be set before the function is defined.
:breaka[dd] file [lnum] {name}
Set a breakpoint in a sourced file. Example:
:breakadd file 43 .vimrc
:breaka[dd] here
Set a breakpoint in the current line of the current file.
Like doing:
:breakadd file <cursor-line> <current-file>
Note that this only works for commands that are executed when
sourcing the file, not for a function defined in that file.
The [lnum] is the line number of the breakpoint. Vim will stop at or after
this line. When omitted line 1 is used.
*:debug-name*
{name} is a pattern that is matched with the file or function name. The
pattern is like what is used for autocommands. There must be a full match (as
if the pattern starts with "^" and ends in "$"). A "*" matches any sequence
of characters. 'ignorecase' is not used, but "\c" can be used in the pattern
to ignore case |/\c|. Don't include the () for the function name!
The match for sourced scripts is done against the full file name. If no path
is specified the current directory is used. Examples:
breakadd file explorer.vim
matches "explorer.vim" in the current directory.
breakadd file *explorer.vim
matches ".../plugin/explorer.vim", ".../plugin/iexplorer.vim", etc.
breakadd file */explorer.vim
matches ".../plugin/explorer.vim" and "explorer.vim" in any other directory.
The match for functions is done against the name as it's shown in the output
of ":function". For local functions this means that something like "<SNR>99_"
is prepended.
Note that functions are first loaded and later executed. When they are loaded
the "file" breakpoints are checked, when they are executed the "func"
breakpoints.
DELETING BREAKPOINTS
*:breakd* *:breakdel* *E161*
:breakd[el] {nr}
Delete breakpoint {nr}. Use |:breaklist| to see the number of
each breakpoint.
:breakd[el] *
Delete all breakpoints.
:breakd[el] func [lnum] {name}
Delete a breakpoint in a function.
:breakd[el] file [lnum] {name}
Delete a breakpoint in a sourced file.
:breakd[el] here
Delete a breakpoint at the current line of the current file.
When [lnum] is omitted, the first breakpoint in the function or file is
deleted.
The {name} must be exactly the same as what was typed for the ":breakadd"
command. "explorer", "*explorer.vim" and "*explorer*" are different.
LISTING BREAKPOINTS
*:breakl* *:breaklist*
:breakl[ist]
List all breakpoints.
OBSCURE
*:debugg* *:debuggreedy*
:debugg[reedy]
Read debug mode commands from the normal input stream, instead
of getting them directly from the user. Only useful for test
scripts. Example:
echo 'q^Mq' | vim -e -s -c debuggreedy -c 'breakadd file script.vim' -S
script.vim
:0debugg[reedy]
Undo ":debuggreedy": get debug mode commands directly from the
user, don't use typeahead for debug commands.
==============================================================================
6. Profiling *profile* *profiling*
Profiling means that Vim measures the time that is spent on executing
functions and/or scripts. The |+profile| feature is required for this.
It is only included when Vim was compiled with "huge" features.
{Vi does not have profiling}
You can also use the |reltime()| function to measure time. This only requires
the |+reltime| feature, which is present more often.
You must always start with a ":profile start fname" command. The resulting
file is written when Vim exits. Here is an example of the output, with line
numbers prepended for the explanation:
1 FUNCTION Test2()
2 Called 1 time
3 Total time: 0.155251
4 Self time: 0.002006
5
6 count total (s) self (s)
7 9 0.000096 for i in range(8)
8 8 0.153655 0.000410 call Test3()
9 8 0.000070 endfor
10 " Ask a question
11 1 0.001341 echo input("give me an answer: ")
The header (lines 1-4) gives the time for the whole function. The "Total"
time is the time passed while the function was executing. The "Self" time is
the "Total" time reduced by time spent in:
- other user defined functions
- sourced scripts
- executed autocommands
- external (shell) commands
Lines 7-11 show the time spent in each executed line. Lines that are not
executed do not count. Thus a comment line is never counted.
The Count column shows how many times a line was executed. Note that the
"for" command in line 7 is executed one more time as the following lines.
That is because the line is also executed to detect the end of the loop.
The time Vim spends waiting for user input isn't counted at all. Thus how
long you take to respond to the input() prompt is irrelevant.
Profiling should give a good indication of where time is spent, but keep in
mind there are various things that may clobber the results:
- The accuracy of the time measured depends on the gettimeofday() system
function. It may only be as accurate as 1/100 second, even though the times
are displayed in micro seconds.
- Real elapsed time is measured, if other processes are busy they may cause
delays at unpredictable moments. You may want to run the profiling several
times and use the lowest results.
- If you have several commands in one line you only get one time. Split the
line to see the time for the individual commands.
- The time of the lines added up is mostly less than the time of the whole
function. There is some overhead in between.
- Functions that are deleted before Vim exits will not produce profiling
information. You can check the |v:profiling| variable if needed:
:if !v:profiling
: delfunc MyFunc
:endif
- Profiling may give weird results on multi-processor systems, when sleep
mode kicks in or the processor frequency is reduced to save power.
- The "self" time is wrong when a function is used recursively.
'foldmethod' "diff"
'foldcolumn' value from 'diffopt', default is 2
These options are set local to the window. When editing another file they are
reset to the global value.
The options can still be overruled from a modeline when re-editing the file.
However, 'foldmethod' and 'wrap' won't be set from a modeline when 'diff' is
set.
The differences shown are actually the differences in the buffer. Thus if you
make changes after loading a file, these will be included in the displayed
diffs. You might have to do ":diffupdate" now and then, not all changes are
immediately taken into account.
In your .vimrc file you could do something special when Vim was started in
diff mode. You could use a construct like this:
if &diff
setup for diff mode
else
setup for non-diff mode
endif
While already in Vim you can start diff mode in three ways.
*E98*
:diffsplit {filename} *:diffs* *:diffsplit*
Open a new window on the file {filename}. The options are set
as for "vimdiff" for the current and the newly opened window.
Also see 'diffexpr'.
*:difft* *:diffthis*
:diffthis Make the current window part of the diff windows. This sets
the options like for "vimdiff".
*E96*
There can be up to four buffers with 'diff' set.
Since the option values are remembered with the buffer, you can edit another
file for a moment and come back to the same file and be in diff mode again.
*:diffo* *:diffoff*
:diffoff Switch off diff mode for the current window.
:diffoff! Switch off diff mode for the current window and in all windows
in the current tab page where 'diff' is set.
The ":diffoff" command resets the relevant options to their default value.
This may be different from what the values were before diff mode was started,
the old values are not remembered.
'diff' off
'scrollbind' off
'cursorbind' off
'scrollopt' without "hor"
'wrap' on
'foldmethod' "manual"
'foldcolumn' 0
==============================================================================
2. Viewing diffs *view-diffs*
The effect is that the diff windows show the same text, with the differences
highlighted. When scrolling the text, the 'scrollbind' option will make the
text in other windows to be scrolled as well. With vertical splits the text
should be aligned properly.
The alignment of text will go wrong when:
- 'wrap' is on, some lines will be wrapped and occupy two or more screen
lines
- folds are open in one window but not another
- 'scrollbind' is off
- changes have been made to the text
- "filler" is not present in 'diffopt', deleted/inserted lines makes the
alignment go wrong
All the buffers edited in a window where the 'diff' option is set will join in
the diff. This is also possible for hidden buffers. They must have been
edited in a window first for this to be possible.
*:DiffOrig* *diff-original-file*
Since 'diff' is a window-local option, it's possible to view the same buffer
in diff mode in one window and "normal" in another window. It is also
possible to view the changes you have made to a buffer since the file was
loaded. Since Vim doesn't allow having two buffers for the same file, you
need another buffer. This command is useful:
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
(this is in |vimrc_example.vim|). Use ":DiffOrig" to see the differences
between the current buffer and the file it was loaded from.
A buffer that is unloaded cannot be used for the diff. But it does work for
hidden buffers. You can use ":hide" to close a window without unloading the
buffer. If you don't want a buffer to remain used for the diff do ":set
nodiff" before hiding it.
*:diffu* *:diffupdate*
:diffu[pdate] Update the diff highlighting and folds.
Vim attempts to keep the differences updated when you make changes to the
text. This mostly takes care of inserted and deleted lines. Changes within a
line and more complicated changes do not cause the differences to be updated.
To force the differences to be updated use:
:diffupdate
Vim will show filler lines for lines that are missing in one window but are
present in another. These lines were inserted in another file or deleted in
this file. Removing "filler" from the 'diffopt' option will make Vim not
display these filler lines.
Folds are used to hide the text that wasn't changed. See |folding| for all
the commands that can be used with folds.
The context of lines above a difference that are not included in the fold can
be set with the 'diffopt' option. For example, to set the context to three
lines:
:set diffopt=filler,context:3
*:diffg* *:diffget*
:[range]diffg[et] [bufspec]
Modify the current buffer to undo difference with another
buffer. If [bufspec] is given, that buffer is used. If
[bufspec] refers to the current buffer then nothing happens.
Otherwise this only works if there is one other buffer in diff
mode.
See below for [range].
*do*
do Same as ":diffget" without argument or range. The "o" stands
for "obtain" ("dg" can't be used, it could be the start of
"dgg"!). Note: this doesn't work in Visual mode.
*dp*
dp Same as ":diffput" without argument or range.
Note: this doesn't work in Visual mode.
When no [range] is given, the diff at the cursor position or just above it is
affected. When [range] is used, Vim tries to only put or get the specified
lines. When there are deleted lines, this may not always be possible.
There can be deleted lines below the last line of the buffer. When the cursor
is on the last line in the buffer and there is no diff above this line, the
":diffget" and "do" commands will obtain lines from the other buffer.
To be able to get those lines from another buffer in a [range] it's allowed to
use the last line number plus one. This command gets all diffs from the other
buffer:
:1,$+1diffget
Note that deleted lines are displayed, but not counted as text lines. You
can't move the cursor into them. To fill the deleted lines with the lines
from another buffer use ":diffget" on the line below them.
*E787*
When the buffer that is about to be modified is read-only and the autocommand
that is triggered by |FileChangedRO| changes buffers the command will fail.
The autocommand must not change buffers.
The [bufspec] argument above can be a buffer number, a pattern for a buffer
name or a part of a buffer name. Examples:
:diffget Use the other buffer which is in diff mode
:diffget 3 Use buffer 3
:diffget v2 Use the buffer which matches "v2" and is in
diff mode (e.g., "file.c.v2")
==============================================================================
5. Diff options *diff-options*
Also see |'diffopt'| and the "diff" item of |'fillchars'|.
The "-a" argument is used to force comparing the files as text, comparing as
binaries isn't useful. The "--binary" argument makes the files read in binary
mode, so that a CTRL-Z doesn't end the text on DOS.
*E810* *E97*
Vim will do a test if the diff output looks alright. If it doesn't, you will
get an error message. Possible causes:
- The "diff" program cannot be executed.
- The "diff" program doesn't produce normal "ed" style diffs (see above).
- The 'shell' and associated options are not set correctly. Try if filtering
works with a command like ":!sort".
- You are using 'diffexpr' and it doesn't work.
If it's not clear what the problem is set the 'verbose' option to one or more
to see more messages.
The self-installing Vim for MS-Windows includes a diff program. If you don't
have it you might want to download a diff.exe. For example from
http://gnuwin32.sourceforge.net/packages/diffutils.htm.
*quotes*
Here are some nice quotes about Vim that I collected from news and mail.
vim (vim) noun - Ebullient vitality and energy. [Latin, accusative of vis,
strength] (Dictionary)
Vim is so much better than vi that a great many of my old vi :map's became
immediately obsolete! (Tony Nugent, Australia)
Coming with a very GUI mindset from Windows, I always thought of people using
Vi as some kind of outer space alien in human clothes. Once I tried I really
got addicted by its power and now I found myself typing Vim keypresses in the
oddest places! That's why I would like to see Vim embedded in every
application which deals with text editing. (José Fonseca)
I was a 12-year emacs user who switched to Vim about a year ago after finally
giving up on the multiple incompatible versions, flaky contributed packages,
disorganized keystrokes, etc. And it was one of the best moves I ever made.
(Joel Burton)
Although all of the programs were used during the preparation of the new and
revised material, most of the editing was done with Vim versions 4.5 and 5.0
under GNU-Linux (Redhat 4.2). (Arnold Robbins, Israel, author of "Learning
the Vi editor")
Out of all the open software i've ever seen and used, and i've seen a lot, Vim
is the best, most useful and highest quality to work with, second only to the
linux kernel itself. (Peter Jay Salzman)
It's well worth noting that the _entirety_ of SourceForge was written using
Vim and its nifty PHP syntax highlighting. I think the entire SF.net tech
staff uses Vim and we're all excited to have you aboard! (Tim Perdue)
Vim is one of a select bunch of tools for which I have no substitute. It is
a brilliant piece of work! (Biju Chacko)
A previous girlfriend of mine switched to emacs. Needless to say, the
relationship went nowhere. (Geoffrey Mann)
I rarely think about Vim, in the same way that I guess a fish rarely thinks
about water. It's the environment in which everything else happens. I'm a
fairly busy system administrator working on a lot of different platforms. Vim
is the only thing that's consistent across all my systems, and it's just about
the only thing that doesn't break from time to time. When a new system comes
in the door without Vim, I install it right away. Great to have a tool that's
the same everywhere, that's completely reliable, so I can ignore it and think
about other things. (Pete Schaeffer)
Having recently succeeded in running Vim via telnet through a Nokia
Communicator, I can now report that it works nicely on a Palm Pilot too.
(Allan Kelly, Scotland)
You've done a tremendous job with 'VIM', Bram! The more I use it, the more
impressed I get (I am an old 'vi' die hard who once started out with early
versions of 'emacs' in the late 1970's and was relieved by finding 'vi' in the
first UNIX I came across in 1983). In my opinion, it's about time 'VIM'
replace 'emacs' as the standard for top editors. (Bo Thide', Sweden)
I love and use VIM heavily too. (Larry Wall)
Vi is like a Ferrari, if you're a beginner, it handles like a bitch, but once
you get the hang of it, it's small, powerful and FAST! (Unknown)
VIM is like a new model Ferrari, and sounds like one too - "VIIIIIIMMM!"
(Stephen Riehm, Germany)
Schon bei Nutzung eines Bruchteils der VIM-Funktionen wird der Benutzer recht
schnell die Vorzuege dieses Editors kennen- und schaetzenlernen.
Translated: Even when only using a fraction of VIM-functions, the user will
quickly get used to and appreciate the advantages of this editor. (Garry
Glendown, conclusion of an article on VIM in iX magazine 9/1998)
I've recently acquired the O'Reilly book on VI (it also discusses VIM
in-depth), and I'm amazed at just how powerful this application is. (Jeffrey
Rankin)
This guide was written using the Windows 9.x distribution of GVIM, which is
quite possibly the greatest thing to come along since God created the naked
girl. (Michael DiBernardo)
Boy, I thought I knew almost everything about VIM, but every time I browse the
online documentation, I hit upon a minor but cool aspect of a VIM feature that
I didn't know before! I must say the documentation is one the finest I've
ever seen in a product -- even better than most commercial products.
(Gautam Mudunuri)
VIM 4.5 is really a fantastic editor. It has sooooo many features and more
importantly, the defaults are so well thought out that you really don't have
to change anything!! Words cannot express my amazement and gratitude to the
creators of VIM. Keep it up. (Vikas, USA)
I wonder how long it will be before people will refer to other Vi editors as
VIM clones? (Darren Hiebert)
I read about [auto-positioning-in-file-based-on-the-errors-from-make] in one
of those "Perfect Programmer's Editor" threads and was delighted to discover
that VIM already supports it. (Brendan Macmillan, Australia)
I just discovered VIM (5.0) and I'm telling everyone I know about it!
I tell them VIM stands for VI for the new (M)illenium. Thanks so much!
(Matt F. Valentine)
I think from now on "vi" should be called "Vim Imitation", not the other way
around. (Rungun Ramanathan)
The Law of VIM:
For each member b of the possible behaviour space B of program P, there exists
a finite time t before which at least one user u in the total user space U of
program P will request b becomes a member of the allowed behaviour space B'
(B' <= B).
In other words: Sooner or later everyone wants everything as an option.
(Negri)
Whenever I move to a new computing platform, the first thing I do is to port
VIM. Lately, I am simply stunned by its ease of compilation using the
configure facility. (A.M. Sabuncu, Turkey)
The options are really excellent and very powerful. (Anish Maharaj)
The Spring user-interface designs are in, and word from the boutiques is that
80x24 text-only mode is back with a *vengeance! Vi editor clone VIM burst onto
March desk-tops with a dazzling show of pastel syntax highlights for its 5.0
look. Strident and customizable, VIM raises eyebrows with its interpretation
of the classic Vi single-key macro collection.
http://www.ntk.net/index.cgi?back=archive98/now0327.txt&line=179#l
I just wanted to take this opportunity to let you know that VIM 5 ROCKS!
Syntax highlighting: how did I survive without it?! Thank you for creating
mankind's best editor! (Mun Johl, USA)
Thanks again for VIM. I use it every day on Linux. (Eric Foster-Johnson,
author of the book "UNIX Programming Tools")
The BEST EDITOR EVER (Stuart Woolford)
I have used most of VIM's fancy features at least once, many frequently, and I
can honestly say that I couldn't live with anything less anymore. My
productivity has easily doubled compared to what it was when I used vi.
(Sitaram Chamarty)
I luv VIM. It is incredible. I'm naming my first-born Vimberly. (Jose
Unpingco, USA)
Hint: "VIM" is "vi improved" - much better! (Sven Guckes, Germany)
I use VIM every day. I spend more time in VIM than in any other program...
It's the best vi clone there is. I think it's great. (Craig Sanders,
Australia)
I strongly advise using VIM--its infinite undo/redo saved me much grief.
(Terry Brown)
Thanks very much for writing what in my opinion is the finest text editor on
the planet. If I were to get another cat, I would name it "Vim".
(Bob Sheehan, USA)
I typed :set all and the screen FILLED up with options. A whole screen of
things to be set and unset. I saw some of my old friends like wrapmargin,
modelines and showmode, but the screen was FILLED with new friends! I love
them all! I love VIM! I'm so happy that I've found this editor! I feel
like how I once felt when I started using vi after a couple of years of using
ed. I never thought I'd forsake my beloved ed, but vi ... oh god, vi was
great. And now, VIM. (Peter Jay Salzman, USA)
I am really happy with such a wonderful software package. Much better than
almost any expensive, off the shelf program. (Jeff Walker)
Whenever I reread the VIM documentation I'm overcome with excitement at the
power of the editor. (William Edward Webber, Australia)
Hurrah for VIM!! It is "at your fingertips" like vi, and has the extensions
that vi sorely needs: highlighting for executing commands on blocks, an easily
navigable and digestible help screen, and more. (Paul Pax)
The reason WHY I don't have this amazingly useful macro any more, is that I
now use VIM - and this is built in!! (Stephen Riehm, Germany)
I am a user of VIM and I love it. I use it to do all my programming, C,
C++, HTML what ever. (Tim Allwine)
I discovered VIM after years of struggling with the original vi, and I just
can't live without it any more. (Emmanuel Mogenet, USA)
Emacs has not a bit of chance to survive so long as VIM is around. Besides,
it also has the most detailed software documentation I have ever seen---much
better than most commercial software! (Leiming Qian)
This version of VIM will just blow people apart when they discover just how
fantastic it is! (Tony Nugent, Australia)
I took your advice & finally got VIM & I'm really impressed. Instant convert.
(Patrick Killelea, USA)
VIM is by far my favorite piece of shareware and I have been particularly
pleased with version 3.0. This is really a solid piece of work. (Robert
Colon, USA)
VIM is a joy to use, it is so well thought and practical that I wonder why
anybody would use visual development tools. VIM is powerful and elegant, it
looks deceptively simple but is almost as complex as a 747 (especially when I
look at my growing .vimrc), keep up that wonderful job, VIM is a centerpiece
of the free software world. (Louis-David Mitterand, USA)
I cannot believe how great it is to use VIM. I think the guys at work are
getting tired of hearing me bragging about it. Others eyes are lighting up.
(Rick Croote)
Emacs takes way too much time to start up and run, it is too big and bulky for
effective use and the interface is more confusing than it is of any help. VIM
however is short, it is fast, it is powerful, it has a good interface and it
is all purpose. (Paal Ditlefsen Ekran)
From the first time I got VIM3.0, I was very enthusiastic. It has almost no
problems. The swapfile handling and the backup possibilities are robust, also
the protection against editing one file twice. It is very compatible to the
real VI (and that is a MUST, because my brain is trained over years in using
it). (Gert van Antwerpen, Holland)
In summary:
__ ___ _ _ _ ___ _____ `
\ \ / (_)_ __ ___ (_)___ | | | |/ _ \_ _| `
\ \ / /| | '_ ` _ \ | / __| | |_| | | | || | `
\ V / | | | | | | | | \__ \ | _ | |_| || | `
\_/ |_|_| |_| |_| |_|___/ |_| |_|\___/ |_| `
____ _____ _ _ _____ _____ _ _ `
/ ___|_ _| | | | ___| ___| | | `
\___ \ | | | | | | |_ | |_ | | | `
___) || | | |_| | _| | _| |_|_| `
|____/ |_| \___/|_| |_| (_|_) (Tony Nugent, Australia) `
*]s*
]s Move to next misspelled word after the cursor.
A count before the command can be used to repeat.
'wrapscan' applies.
*[s*
[s Like "]s" but search backwards, find the misspelled
word before the cursor. Doesn't recognize words
split over two lines, thus may stop at words that are
not highlighted as bad. Does not stop at word with
missing capital at the start of a line.
*]S*
]S Like "]s" but only stop at bad words, not at rare
words or words for another region.
*[S*
[S Like "]S" but search backwards.
*zg*
zg Add word under the cursor as a good word to the first
name in 'spellfile'. A count may precede the command
to indicate the entry in 'spellfile' to be used. A
count of two uses the second entry.
In Visual mode the selected characters are added as a
word (including white space!).
When the cursor is on text that is marked as badly
spelled then the marked text is used.
Otherwise the word under the cursor, separated by
non-word characters, is used.
If the word is explicitly marked as bad word in
another spell file the result is unpredictable.
*zG*
zG Like "zg" but add the word to the internal word list
|internal-wordlist|.
*zw*
zw Like "zg" but mark the word as a wrong (bad) word.
If the word already appears in 'spellfile' it is
turned into a comment line. See |spellfile-cleanup|
for getting rid of those.
*zW*
zW Like "zw" but add the word to the internal word list
|internal-wordlist|.
*:spe* *:spellgood*
:[count]spe[llgood] {word}
Add {word} as a good word to 'spellfile', like with
|zg|. Without count the first name is used, with a
count of two the second entry, etc.
:spe[llgood]! {word} Add {word} as a good word to the internal word list,
like with |zG|.
*:spellw* *:spellwrong*
:[count]spellw[rong] {word}
Add {word} as a wrong (bad) word to 'spellfile', as
with |zw|. Without count the first name is used, with
a count of two the second entry, etc.
:spellw[rong]! {word} Add {word} as a wrong (bad) word to the internal word
list, like with |zW|.
After adding a word to 'spellfile' with the above commands its associated
".spl" file will automatically be updated and reloaded. If you change
'spellfile' manually you need to use the |:mkspell| command. This sequence of
commands mostly works well:
:edit <file in 'spellfile'>
(make changes to the spell file)
:mkspell! %
More details about the 'spellfile' format below |spell-wordlist-format|.
*internal-wordlist*
The internal word list is used for all buffers where 'spell' is set. It is
not stored, it is lost when you exit Vim. It is also cleared when 'encoding'
is set.
words that have been seen often get a bigger bonus. The COMMON item in the
affix file can be used to define common words, so that this mechanism also
works in a new or short file |spell-COMMON|.
==============================================================================
2. Remarks on spell checking *spell-remarks*
PERFORMANCE
Vim does on-the-fly spell checking. To make this work fast the word list is
loaded in memory. Thus this uses a lot of memory (1 Mbyte or more). There
might also be a noticeable delay when the word list is loaded, which happens
when 'spell' is set and when 'spelllang' is set while 'spell' was already set.
To minimize the delay each word list is only loaded once, it is not deleted
when 'spelllang' is made empty or 'spell' is reset. When 'encoding' is set
all the word lists are reloaded, thus you may notice a delay then too.
REGIONS
A word may be spelled differently in various regions. For example, English
comes in (at least) these variants:
en all regions
en_au Australia
en_ca Canada
en_gb Great Britain
en_nz New Zealand
en_us USA
Words that are not used in one region but are used in another region are
highlighted with SpellLocal |hl-SpellLocal|.
Always use lowercase letters for the language and region names.
When adding a word with |zg| or another command it's always added for all
regions. You can change that by manually editing the 'spellfile'. See
|spell-wordlist-format|. Note that the regions as specified in the files in
'spellfile' are only used when all entries in 'spelllang' specify the same
region (not counting files specified by their .spl name).
*spell-german*
Specific exception: For German these special regions are used:
de all German words accepted
de_de old and new spelling
de_19 old spelling
de_20 new spelling
de_at Austria
de_ch Switzerland
*spell-russian*
Specific exception: For Russian these special regions are used:
ru all Russian words accepted
ru_ru "IE" letter spelling
ru_yo "YO" letter spelling
*spell-yiddish*
Yiddish requires using "utf-8" encoding, because of the special characters
used. If you are using latin1 Vim will use transliterated (romanized) Yiddish
instead. If you want to use transliterated Yiddish with utf-8 use "yi-tr".
In a table:
'encoding' 'spelllang'
utf-8 yi Yiddish
latin1 yi transliterated Yiddish
utf-8 yi-tr transliterated Yiddish
Examples:
'spelllang' LL
en_us en
en-rare en-rare
medical_ca medical
Only the first file is loaded, the one that is first in 'runtimepath'. If
this succeeds then additionally files with the name LL.EEE.add.spl are loaded.
All the ones that are found are used.
If no spell file is found the |SpellFileMissing| autocommand event is
triggered. This may trigger the |spellfile.vim| plugin to offer you
downloading the spell file.
Additionally, the files related to the names in 'spellfile' are loaded. These
are the files that |zg| and |zw| add good and wrong words to.
Exceptions:
- Vim uses "latin1" when 'encoding' is "iso-8859-15". The euro sign doesn't
matter for spelling.
- When no spell file for 'encoding' is found "ascii" is tried. This only
works for languages where nearly all words are ASCII, such as English. It
helps when 'encoding' is not "latin1", such as iso-8859-2, and English text
is being edited. For the ".add" files the same name as the found main
spell file is used.
For example, with these values:
'runtimepath' is "~/.vim,/usr/share/vim70,~/.vim/after"
'encoding' is "iso-8859-2"
'spelllang' is "pl"
Vim will look for:
1. ~/.vim/spell/pl.iso-8859-2.spl
2. /usr/share/vim70/spell/pl.iso-8859-2.spl
3. ~/.vim/spell/pl.iso-8859-2.add.spl
4. /usr/share/vim70/spell/pl.iso-8859-2.add.spl
5. ~/.vim/after/spell/pl.iso-8859-2.add.spl
This assumes 1. is not found and 2. is found.
If 'encoding' is "latin1" Vim will look for:
1. ~/.vim/spell/pl.latin1.spl
2. /usr/share/vim70/spell/pl.latin1.spl
3. ~/.vim/after/spell/pl.latin1.spl
4. ~/.vim/spell/pl.ascii.spl
5. /usr/share/vim70/spell/pl.ascii.spl
6. ~/.vim/after/spell/pl.ascii.spl
This assumes none of them are found (Polish doesn't make sense when leaving
out the non-ASCII characters).
Spelling for EBCDIC is currently not supported.
A spell file might not be available in the current 'encoding'. See
|spell-mkspell| about how to create a spell file. Converting a spell file
with "iconv" will NOT work!
Note: on VMS ".{enc}.spl" is changed to "_{enc}.spl" to avoid trouble with
filenames.
*spell-sug-file* *E781*
If there is a file with exactly the same name as the ".spl" file but ending in
".sug", that file will be used for giving better suggestions. It isn't loaded
before suggestions are made to reduce memory use.
:runtime spell/cleanadd.vim
This deletes all comment lines, except the ones that start with "##". Use
"##" lines to add comments that you want to keep.
You can invoke this script as often as you like. A variable is provided to
skip updating files that have been changed recently. Set it to the number of
seconds that has passed since a file was changed before it will be cleaned.
For example, to clean only files that were not changed in the last hour:
let g:spell_clean_limit = 60 * 60
The default is one second.
WORDS
Vim uses a fixed method to recognize a word. This is independent of
'iskeyword', so that it also works in help files and for languages that
include characters like '-' in 'iskeyword'. The word characters do depend on
'encoding'.
The table with word characters is stored in the main .spl file. Therefore it
matters what the current locale is when generating it! A .add.spl file does
not contain a word table though.
For a word that starts with a digit the digit is ignored, unless the word as a
whole is recognized. Thus if "3D" is a word and "D" is not then "3D" is
recognized as a word, but if "3D" is not a word then only the "D" is marked as
bad. Hex numbers in the form 0x12ab and 0X12AB are recognized.
WORD COMBINATIONS
It is possible to spell-check words that include a space. This is used to
recognize words that are invalid when used by themselves, e.g. for "et al.".
It can also be used to recognize "the the" and highlight it.
The number of spaces is irrelevant. In most cases a line break may also
appear. However, this makes it difficult to find out where to start checking
for spelling mistakes. When you make a change to one line and only that line
is redrawn Vim won't look in the previous line, thus when "et" is at the end
of the previous line "al." will be flagged as an error. And when you type
"the<CR>the" the highlighting doesn't appear until the first line is redrawn.
Use |CTRL-L| to redraw right away. "[s" will also stop at a word combination
with a line break.
When encountering a line break Vim skips characters such as '*', '>' and '"'',
so that comments in C, shell and Vim code can be spell checked.
VIM SCRIPTS
If you want to write a Vim script that does something with spelling, you may
find these functions useful:
spellbadword() find badly spelled word at the cursor
spellsuggest() get list of spelling suggestions
soundfold() get the sound-a-like version of a word
up to the first comma, dot or underscore. This can be used to set options
specifically for the language, especially 'spellcapcheck'.
The distribution includes a few of these files. Use this command to see what
they do:
:next $VIMRUNTIME/spell/*.vim
Note that the default scripts don't set 'spellcapcheck' if it was changed from
the default value. This assumes the user prefers another value then.
*:mksp* *:mkspell*
:mksp[ell][!] [-ascii] {outname} {inname} ...
Generate a Vim spell file from word lists. Example:
:mkspell /tmp/nl nl_NL.words
*E751*
When {outname} ends in ".spl" it is used as the output
file name. Otherwise it should be a language name,
such as "en", without the region name. The file
written will be "{outname}.{encoding}.spl", where
{encoding} is the value of the 'encoding' option.
When the output file already exists [!] must be used
to overwrite it.
When the [-ascii] argument is present, words with
non-ascii characters are skipped. The resulting file
ends in "ascii.spl".
*:spelldump* *:spelld*
:spelld[ump] Open a new window and fill it with all currently valid
words. Compound words are not included.
Note: For some languages the result may be enormous,
causing Vim to run out of memory.
:spelld[ump]! Like ":spelldump" and include the word count. This is
the number of times the word was found while
updating the screen. Words that are in COMMON items
get a starting count of 10.
The format of the word list is used |spell-wordlist-format|. You should be
able to read it with ":mkspell" to generate one .spl file that includes all
the words.
When all entries to 'spelllang' use the same regions or no regions at all then
the region information is included in the dumped words. Otherwise only words
for the current region are included and no "/regions" line is generated.
Comment lines with the name of the .spl file are used as a header above the
words that were generated from that .spl file.
Note that the SpellFileMissing autocommand must not change or destroy the
buffer the user was editing.
==============================================================================
4. Spell file format *spell-file-format*
This is the format of the files that are used by the person who creates and
maintains a word list.
Note that we avoid the word "dictionary" here. That is because the goal of
spell checking differs from writing a dictionary (as in the book). For
spelling we need a list of words that are OK, thus should not be highlighted.
Person and company names will not appear in a dictionary, but do appear in a
word list. And some old words are rarely used while they are common
misspellings. These do appear in a dictionary but not in a word list.
There are two formats: A straight list of words and a list using affix
compression. The files with affix compression are used by Myspell (Mozilla
and OpenOffice.org). This requires two files, one with .aff and one with .dic
extension.
used to modify the basic words to get the full word list. This significantly
reduces the number of words, especially for a language like Polish. This is
called affix compression.
The basic word list and the affix file are combined with the ":mkspell"
command and results in a binary spell file. All the preprocessing has been
done, thus this file loads fast. The binary spell file format is described in
the source code (src/spell.c). But only developers need to know about it.
The preprocessing also allows us to take the Myspell language files and modify
them before the Vim word list is made. The tools for this can be found in the
"src/spell" directory.
The format for the affix and word list files is based on what Myspell uses
(the spell checker of Mozilla and OpenOffice.org). A description can be found
here:
http://lingucomponent.openoffice.org/affix.readme
Note that affixes are case sensitive, this isn't obvious from the description.
Vim supports quite a few extras. They are described below |spell-affix-vim|.
Attempts have been made to keep this compatible with other spell checkers, so
that the same files can often be used. One other project that offers more
than Myspell is Hunspell http://hunspell.sf.net .
The KEEPCASE affix ID can be used to specifically match a word with identical
case only, see below |spell-KEEPCASE|.
Note: in line 5 to 7 non-word characters are used. You can include any
character in a word. When checking the text a word still only matches when it
appears with a non-word character before and after it. For Myspell a word
starting with a non-word character probably won't work.
In line 12 the word "TCP/IP" is defined. Since the slash has a special
meaning the comma is used instead. This is defined with the SLASH item in the
affix file, see |spell-SLASH|. Note that without this SLASH item the word
will be "TCP,IP".
*spell-affix-comment*
Comment lines in the .aff file start with a '#':
# comment line
Items with a fixed number of arguments can be followed by a comment. But only
if none of the arguments can contain white space. The comment must start with
a "#" character. Example:
KEEPCASE = # fix case for words with this flag
ENCODING *spell-SET*
The affix file can be in any encoding that is supported by "iconv". However,
in some cases the current locale should also be set properly at the time
|:mkspell| is invoked. Adding FOL/LOW/UPP lines removes this requirement
|spell-FOL|.
The encoding should be specified before anything where the encoding matters.
The encoding applies both to the affix file and the dictionary file. It is
done with a SET line:
SET utf-8
The encoding can be different from the value of the 'encoding' option at the
time ":mkspell" is used. Vim will then convert everything to 'encoding' and
generate a spell file for 'encoding'. If some of the used characters to not
fit in 'encoding' you will get an error message.
*spell-affix-mbyte*
When using a multi-byte encoding it's possible to use more different affix
flags. But Myspell doesn't support that, thus you may not want to use it
anyway. For compatibility use an 8-bit encoding.
INFORMATION
These entries in the affix file can be used to add information to the spell
file. There are no restrictions on the format, but they should be in the
right encoding.
*:spellinfo* *:spelli*
:spelli[nfo] Display the information for the spell file(s) used for
the current buffer.
CHARACTER TABLES
*spell-affix-chars*
When using an 8-bit encoding the affix file should define what characters are
word characters. This is because the system where ":mkspell" is used may not
support a locale with this encoding and isalpha() won't work. For example
when using "cp1250" on Unix.
*E761* *E762* *spell-FOL*
*spell-LOW* *spell-UPP*
Three lines in the affix file are needed. Simplistic example:
FOL áëñ
LOW áëñ
UPP ÁËÑ
All three lines must have exactly the same number of characters.
The "FOL" line specifies the case-folded characters. These are used to
compare words while ignoring case. For most encodings this is identical to
the lower case line.
The "LOW" line specifies the characters in lower-case. Mostly it's equal to
the "FOL" line.
The "UPP" line specifies the characters with upper-case. That is, a character
is upper-case where it's different from the character at the same position in
"FOL".
An exception is made for the German sharp s ß. The upper-case version is
"SS". In the FOL/LOW/UPP lines it should be included, so that it's recognized
as a word character, but use the ß character in all three.
ASCII characters should be omitted, Vim always handles these in the same way.
When the encoding is UTF-8 no word characters need to be specified.
*E763*
Vim allows you to use spell checking for several languages in the same file.
You can list them in the 'spelllang' option. As a consequence all spell files
for the same encoding must use the same word characters, otherwise they can't
be combined without errors. If you get a warning that the word tables differ
you may need to generate the .spl file again with |:mkspell|. Check the FOL,
LOW and UPP lines in the used .aff file.
The XX.ascii.spl spell file generated with the "-ascii" argument will not
contain the table with characters, so that it can be combine with spell files
for any encoding. The .add.spl files also do not contain the table.
MID-WORD CHARACTERS
*spell-midword*
Some characters are only to be considered word characters if they are used in
between two ordinary word characters. An example is the single quote: It is
often used to put text in quotes, thus it can't be recognized as a word
character, but when it appears in between word characters it must be part of
the word. This is needed to detect a spelling error such as they'are. That
should be they're, but since "they" and "are" are words themselves that would
go unnoticed.
These characters are defined with MIDWORD in the .aff file. Example:
MIDWORD '-
With "FLAG num" the numbers in a list of affixes need to be separated with a
comma: "234,2143,1435". This method is inefficient, but useful if the file is
generated with a program.
When using "caplong" the two-character flags all start with a capital: "Aa",
"B1", "BB", etc. This is useful to use one-character flags for the most
common items and two-character flags for uncommon items.
Note: When using utf-8 only characters up to 65000 may be used for flags.
Note: even when using "num" or "long" the number of flags available to
compounding and prefixes is limited to about 250.
AFFIXES
*spell-PFX* *spell-SFX*
The usual PFX (prefix) and SFX (suffix) lines are supported (see the Myspell
documentation or the Aspell manual:
http://aspell.net/man-html/Affix-Compression.html.
Summary:
SFX L Y 2
SFX L 0 re [^x]
SFX L 0 ro x
The first line is a header and has four fields:
SFX {flag} {combine} {count}
{flag} The name used for the suffix. Mostly it's a single letter,
but other characters can be used, see |spell-FLAG|.
{combine} Can be 'Y' or 'N'. When 'Y' then the word plus suffix can
also have a prefix. When 'N' then a prefix is not allowed.
{count} The number of lines following. If this is wrong you will get
an error message.
For PFX the fields are exactly the same.
The basic format for the following lines is:
SFX {flag} {strip} {add} {condition} {extra}
{flag} Must be the same as the {flag} used in the first line.
{strip} Characters removed from the basic word. There is no check if
the characters are actually there, only the length is used (in
bytes). This better match the {condition}, otherwise strange
things may happen. If the {strip} length is equal to or
longer than the basic word the suffix won't be used.
When {strip} is 0 (zero) then nothing is stripped.
{add} Characters added to the basic word, after removing {strip}.
Optionally there is a '/' followed by flags. The flags apply
to the word plus affix. See |spell-affix-flags|
{condition} A simplistic pattern. Only when this matches with a basic
word will the suffix be used for that word. This is normally
for using one suffix letter with different {add} and {strip}
fields for words with different endings.
When {condition} is a . (dot) there is no condition.
The pattern may contain:
- Literal characters.
- A set of characters in []. [abc] matches a, b and c.
A dash is allowed for a range [a-c], but this is
Vim-specific.
- A set of characters that starts with a ^, meaning the
complement of the specified characters. [^abc] matches any
character but a, b and c.
{extra} Optional extra text:
# comment Comment is ignored
- Hunspell uses this, ignored
For PFX the fields are the same, but the {strip}, {add} and {condition} apply
to the start of the word.
Note: Myspell ignores any extra text after the relevant info. Vim requires
this text to start with a "#" so that mistakes don't go unnoticed. Example:
CIRCUMFIX *spell-CIRCUMFIX*
The CIRCUMFIX flag means a prefix and suffix must be added at the same time.
If a prefix has the CIRCUMFIX flag than only suffixes with the CIRCUMFIX flag
can be added, and the other way around.
An alternative is to only specify the suffix, and give the that suffix two
flags: The required prefix and the NEEDAFFIX flag. |spell-NEEDAFFIX|
PFXPOSTPONE *spell-PFXPOSTPONE*
When an affix file has very many prefixes that apply to many words it's not
possible to build the whole word list in memory. This applies to Hebrew (a
list with all words is over a Gbyte). In that case applying prefixes must be
postponed. This makes spell checking slower. It is indicated by this keyword
in the .aff file:
PFXPOSTPONE
Only prefixes without a chop string and without flags can be postponed.
Prefixes with a chop string or with flags will still be included in the word
list. An exception if the chop string is one character and equal to the last
character of the added string, but in lower case. Thus when the chop string
is used to allow the following word to start with an upper case letter.
*spell-FORBIDDENWORD*
FORBIDDENWORD can be used just like BAD. For compatibility with Hunspell.
*spell-NEEDAFFIX*
The NEEDAFFIX flag is used to require that a word is used with an affix. The
word itself is not a good word (unless there is an empty affix). Example:
NEEDAFFIX +
*spell-COMPOUNDFLAG*
The Myspell compatible method uses one flag, specified with COMPOUNDFLAG. All
words with this flag combine in any order. This means there is no control
over which word comes first. Example:
COMPOUNDFLAG c
*spell-COMPOUNDRULE*
A more advanced method to specify how compound words can be formed uses
multiple items with multiple flags. This is not compatible with Myspell 3.0.
Let's start with an example:
COMPOUNDRULE c+
COMPOUNDRULE se
The first line defines that words with the "c" flag can be concatenated in any
order. The second line defines compound words that are made of one word with
the "s" flag and one word with the "e" flag. With this dictionary:
bork/c
onion/s
soup/e
You can make these words:
bork
borkbork
borkborkbork
(etc.)
onion
soup
onionsoup
The COMPOUNDRULE item may appear multiple times. The argument is made out of
one or more groups, where each group can be:
one flag e.g., c
alternate flags inside [] e.g., [abc]
Optionally this may be followed by:
* the group appears zero or more times, e.g., sm*e
+ the group appears one or more times, e.g., c+
This is similar to the regexp pattern syntax (but not the same!). A few
examples with the sequence of word flags they require:
COMPOUNDRULE x+ x xx xxx etc.
COMPOUNDRULE yz yz
COMPOUNDRULE x+z xz xxz xxxz etc.
COMPOUNDRULE yx+ yx yxx yxxx etc.
COMPOUNDRULE [abc]z az bz cz
COMPOUNDRULE [abc]+z az aaz abaz bz baz bcbz cz caz cbaz etc.
COMPOUNDRULE a[xyz]+ ax axx axyz ay ayx ayzz az azy azxy etc.
COMPOUNDRULE sm*e se sme smme smmme etc.
COMPOUNDRULE s[xyz]*e se sxe sxye sxyxe sye syze sze szye szyxe etc.
A specific example: Allow a compound to be made of two words and a dash:
In the .aff file:
COMPOUNDRULE sde
NEEDAFFIX x
COMPOUNDWORDMAX 3
COMPOUNDMIN 1
In the .dic file:
start/s
end/e
-/xd
*spell-NEEDCOMPOUND*
The NEEDCOMPOUND flag is used to require that a word is used as part of a
compound word. The word itself is not a good word. Example:
NEEDCOMPOUND &
*spell-ONLYINCOMPOUND*
The ONLYINCOMPOUND does exactly the same as NEEDCOMPOUND. Supported for
compatibility with Hunspell.
*spell-COMPOUNDMIN*
The minimal character length of a word used for compounding is specified with
COMPOUNDMIN. Example:
COMPOUNDMIN 5
When omitted there is no minimal length. Obviously you could just leave out
the compound flag from short words instead, this feature is present for
compatibility with Myspell.
*spell-COMPOUNDWORDMAX*
The maximum number of words that can be concatenated into a compound word is
specified with COMPOUNDWORDMAX. Example:
COMPOUNDWORDMAX 3
When omitted there is no maximum. It applies to all compound words.
To set a limit for words with specific flags make sure the items in
COMPOUNDRULE where they appear don't allow too many words.
*spell-COMPOUNDSYLMAX*
The maximum number of syllables that a compound word may contain is specified
with COMPOUNDSYLMAX. Example:
COMPOUNDSYLMAX 6
This has no effect if there is no SYLLABLE item. Without COMPOUNDSYLMAX there
is no limit on the number of syllables.
If both COMPOUNDWORDMAX and COMPOUNDSYLMAX are defined, a compound word is
accepted if it fits one of the criteria, thus is either made from up to
COMPOUNDWORDMAX words or contains up to COMPOUNDSYLMAX syllables.
*spell-COMPOUNDFORBIDFLAG*
The COMPOUNDFORBIDFLAG specifies a flag that can be used on an affix. It
means that the word plus affix cannot be used in a compound word. Example:
affix file:
COMPOUNDFLAG c
COMPOUNDFORBIDFLAG x
SFX a Y 2
SFX a 0 s .
SFX a 0 ize/x .
dictionary:
word/c
util/ac
This allows for "wordutil" and "wordutils" but not "wordutilize".
Note: this doesn't work for postponed prefixes yet.
*spell-COMPOUNDPERMITFLAG*
The COMPOUNDPERMITFLAG specifies a flag that can be used on an affix. It
means that the word plus affix can also be used in a compound word in a way
where the affix ends up halfway the word. Without this flag that is not
allowed.
Note: this doesn't work for postponed prefixes yet.
*spell-COMPOUNDROOT*
The COMPOUNDROOT flag is used for words in the dictionary that are already a
compound. This means it counts for two words when checking the compounding
rules. Can also be used for an affix to count the affix as a compounding
word.
*spell-CHECKCOMPOUNDPATTERN*
CHECKCOMPOUNDPATTERN is used to define patterns that, when matching at the
position where two words are compounded together forbids the compound.
For example:
CHECKCOMPOUNDPATTERN o e
This forbids compounding if the first word ends in "o" and the second word
starts with "e".
The arguments must be plain text, no patterns are actually supported, despite
the item name. Case is always ignored.
The Hunspell feature to use three arguments and flags is not supported.
*spell-SYLLABLE*
The SYLLABLE item defines characters or character sequences that are used to
count the number of syllables in a word. Example:
SYLLABLE aáeéiíoóöõuúüûy/aa/au/ea/ee/ei/ie/oa/oe/oo/ou/uu/ui
Before the first slash is the set of characters that are counted for one
syllable, also when repeated and mixed, until the next character that is not
in this set. After the slash come sequences of characters that are counted
for one syllable. These are preferred over using characters from the set.
With the example "ideeen" has three syllables, counted by "i", "ee" and "e".
Only case-folded letters need to be included.
Another way to restrict compounding was mentioned above: Adding the
|spell-COMPOUNDFORBIDFLAG| flag to an affix causes all words that are made
with that affix not be be used for compounding.
*spell-COMMON*
Common words can be specified with the COMMON item. This will give better
suggestions when editing a short file. Example:
COMMON the of to and a in is it you that he was for on are
The words must be separated by white space, up to 25 per line.
When multiple regions are specified in a ":mkspell" command the common words
for all regions are combined and used for all regions.
*spell-NOSPLITSUGS*
This item indicates that splitting a word to make suggestions is not a good
idea. Split-word suggestions will appear only when there are few similar
words.
NOSPLITSUGS
*spell-NOSUGGEST*
The flag specified with NOSUGGEST can be used for words that will not be
suggested. Can be used for obscene words.
NOSUGGEST %
REPLACEMENTS *spell-REP*
In the affix file REP items can be used to define common mistakes. This is
used to make spelling suggestions. The items define the "from" text and the
"to" replacement. Example:
REP 4
REP f ph
REP ph f
REP k ch
REP ch k
The first line specifies the number of REP lines following. Vim ignores the
number, but it must be there (for compatibility with Myspell).
Don't include simple one-character replacements or swaps. Vim will try these
anyway. You can include whole words if you want to, but you might want to use
the "file:" item in 'spellsuggest' instead.
You can include a space by using an underscore:
REP the_the the
SOUND-A-LIKE *spell-SAL*
In the affix file SAL items can be used to define the sounds-a-like mechanism
to be used. The main items define the "from" text and the "to" replacement.
Simplistic example:
SAL CIA X
SAL CH X
SAL C K
SAL K K
There are a few rules and this can become quite complicated. An explanation
how it works can be found in the Aspell manual:
http://aspell.net/man-html/Phonetic-Code.html.
There are a few special items:
MANUAL *fold-manual*
Use commands to manually define the fold regions. This can also be used by a
script that parses text to find folds.
The level of a fold is only defined by its nesting. To increase the fold
level of a fold for a range of lines, define a fold inside it that has the
same lines.
The manual folds are lost when you abandon the file. To save the folds use
the |:mkview| command. The view can be restored later with |:loadview|.
INDENT *fold-indent*
The folds are automatically defined by the indent of the lines.
The foldlevel is computed from the indent of the line, divided by the
'shiftwidth' (rounded down). A sequence of lines with the same or higher fold
level form a fold, with the lines with a higher level forming a nested fold.
EXPR *fold-expr*
The folds are automatically defined by their foldlevel, like with the "indent"
method. The value of the 'foldexpr' option is evaluated to get the foldlevel
of a line. Examples:
This will create a fold for all consecutive lines that start with a tab:
:set foldexpr=getline(v:lnum)[0]==\"\\t\"
This will call a function to compute the fold level:
:set foldexpr=MyFoldLevel(v:lnum)
This will make a fold out of paragraphs separated by blank lines:
:set foldexpr=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1
this does the same:
:set foldexpr=getline(v:lnum-1)=~'^\\s*$'&&getline(v:lnum)=~'\\S'?'>1':1
Note that backslashes must be used to escape characters that ":set" handles
differently (space, backslash, double quote, etc., see |option-backslash|).
These are the conditions with which the expression is evaluated:
- The current buffer and window are set for the line.
- The variable "v:lnum" is set to the line number.
- The result is used for the fold level in this way:
value meaning
0 the line is not in a fold
1, 2, .. the line is in a fold with this level
-1 the fold level is undefined, use the fold level of a
line before or after this line, whichever is the
lowest.
"=" use fold level from the previous line
"a1", "a2", .. add one, two, .. to the fold level of the previous
line
"s1", "s2", .. subtract one, two, .. from the fold level of the
previous line
"<1", "<2", .. a fold with this level ends at this line
">1", ">2", .. a fold with this level starts at this line
It is not required to mark the start (end) of a fold with ">1" ("<1"), a fold
will also start (end) when the fold level is higher (lower) than the fold
level of the previous line.
There must be no side effects from the expression. The text in the buffer,
cursor position, the search patterns, options etc. must not be changed.
You can change and restore them if you are careful.
If there is some error in the expression, or the resulting value isn't
recognized, there is no error message and the fold level will be zero.
For debugging the 'debug' option can be set to "msg", the error messages will
be visible then.
Note: Since the expression has to be evaluated for every line, this fold
method can be very slow!
Try to avoid the "=", "a" and "s" return values, since Vim often has to search
backwards for a line for which the fold level is defined. This can be slow.
|foldlevel()| can be useful to compute a fold level relative to a previous
fold level. But note that foldlevel() may return -1 if the level is not known
yet. And it returns the level at the start of the line, while a fold might
end in that line.
It may happened that folds are not updated properly. You can use |zx| or |zX|
to force updating folds.
SYNTAX *fold-syntax*
A fold is defined by syntax items that have the "fold" argument. |:syn-fold|
The fold level is defined by nesting folds. The nesting of folds is limited
with 'foldnestmax'.
Be careful to specify proper syntax syncing. If this is not done right, folds
may differ from the displayed highlighting. This is especially relevant when
using patterns that match more than one line. In case of doubt, try using
brute-force syncing:
:syn sync fromstart
DIFF *fold-diff*
The folds are automatically defined for text that is not part of a change or
close to a change.
This method only works properly when the 'diff' option is set for the current
window and changes are being displayed. Otherwise the whole buffer will be
one big fold.
The 'diffopt' option can be used to specify the context. That is, the number
of lines between the fold and a change that are not included in the fold. For
example, to use a context of 8 lines:
:set diffopt=filler,context:8
The default context is six lines.
When 'scrollbind' is also set, Vim will attempt to keep the same folds open in
other diff windows, so that the same text is visible.
MARKER *fold-marker*
Markers in the text tell where folds start and end. This allows you to
precisely specify the folds. This will allow deleting and putting a fold,
without the risk of including the wrong lines. The 'foldtext' option is
normally set such that the text before the marker shows up in the folded line.
This makes it possible to give a name to the fold.
Markers can have a level included, or can use matching pairs. Including a
level is easier, you don't have to add end markers and avoid problems with
non-matching marker pairs. Example:
/* global variables {{{1 */
int varA, varB;
/* functions {{{1 */
/* funcA() {{{2 */
void funcA() {}
/* funcB() {{{2 */
void funcB() {}
A fold starts at a "{{{" marker. The following number specifies the fold
level. What happens depends on the difference between the current fold level
and the level given by the marker:
1. If a marker with the same fold level is encountered, the previous fold
ends and another fold with the same level starts.
2. If a marker with a higher fold level is found, a nested fold is started.
3. if a marker with a lower fold level is found, all folds up to and including
this level end and a fold with the specified level starts.
The number indicates the fold level. A zero cannot be used (a marker with
level zero is ignored). You can use "}}}" with a digit to indicate the level
of the fold that ends. The fold level of the following line will be one less
than the indicated level. Note that Vim doesn't look back to the level of the
matching marker (that would take too much time). Example:
{{{1
fold level here is 1
{{{3
fold level here is 3
}}}3
fold level here is 2
You can also use matching pairs of "{{{" and "}}}" markers to define folds.
Each "{{{" increases the fold level by one, each "}}}" decreases the fold
level by one. Be careful to keep the markers matching! Example:
{{{
*fold-create-marker*
"zf" can be used to create a fold defined by markers. Vim will insert the
markers for you. Vim will append the start and end marker, as specified with
'foldmarker'. The markers are appended to the end of the line.
'commentstring' is used if it isn't empty.
This does not work properly when:
- The line already contains a marker with a level number. Vim then doesn't
know what to do.
- Folds nearby use a level number in their marker which gets in the way.
- The line is inside a comment, 'commentstring' isn't empty and nested
comments don't work. For example with C: adding /* {{{ */ inside a comment
will truncate the existing comment. Either put the marker before or after
the comment, or add the marker manually.
Generally it's not a good idea to let Vim create markers when you already have
markers with a level number.
*fold-delete-marker*
"zd" can be used to delete a fold defined by markers. Vim will delete the
markers for you. Vim will search for the start and end markers, as specified
with 'foldmarker', at the start and end of the fold. When the text around the
marker matches with 'commentstring', that text is deleted as well.
This does not work properly when:
- A line contains more than one marker and one of them specifies a level.
Only the first one is removed, without checking if this will have the
desired effect of deleting the fold.
- The marker contains a level number and is used to start or end several folds
at the same time.
==============================================================================
2. Fold commands *fold-commands* *E490*
All folding commands start with "z". Hint: the "z" looks like a folded piece
of paper, if you look at it from the side.
*zF*
zF Create a fold for [count] lines. Works like "zf".
*zd* *E351*
zd Delete one fold at the cursor. When the cursor is on a folded
line, that fold is deleted. Nested folds are moved one level
up. In Visual mode all folds (partially) in the selected area
are deleted. Careful: This easily deletes more folds than you
expect and there is no undo.
This only works when 'foldmethod' is "manual" or "marker".
Also see |fold-delete-marker|.
*zD*
zD Delete folds recursively at the cursor. In Visual mode all
folds (partially) in the selected area and all nested folds in
them are deleted.
This only works when 'foldmethod' is "manual" or "marker".
Also see |fold-delete-marker|.
*zE* *E352*
zE Eliminate all folds in the window.
This only works when 'foldmethod' is "manual" or "marker".
Also see |fold-delete-marker|.
*zo*
zo Open one fold under the cursor. When a count is given, that
many folds deep will be opened. In Visual mode one level of
folds is opened for all lines in the selected area.
*zO*
zO Open all folds under the cursor recursively. Folds that don't
contain the cursor line are unchanged.
In Visual mode it opens all folds that are in the selected
area, also those that are only partly selected.
*zc*
zc Close one fold under the cursor. When a count is given, that
many folds deep are closed. In Visual mode one level of folds
is closed for all lines in the selected area.
'foldenable' will be set.
*zC*
zC Close all folds under the cursor recursively. Folds that
don't contain the cursor line are unchanged.
In Visual mode it closes all folds that are in the selected
area, also those that are only partly selected.
'foldenable' will be set.
*za*
za When on a closed fold: open it. When folds are nested, you
may have to use "za" several times. When a count is given,
that many closed folds are opened.
When on an open fold: close it and set 'foldenable'. This
will only close one level, since using "za" again will open
the fold. When a count is given that many folds will be
closed (that's not the same as repeating "za" that many
times).
*zA*
zA When on a closed fold: open it recursively.
When on an open fold: close it recursively and set
'foldenable'.
*zv*
zv View cursor line: Open just enough folds to make the line in
which the cursor is located not folded.
*zx*
zx Update folds: Undo manually opened and closed folds: re-apply
*zX*
zX Undo manually opened and closed folds: re-apply 'foldlevel'.
Also forces recomputing folds, like |zx|.
*zm*
zm Fold more: Subtract one from 'foldlevel'. If 'foldlevel' was
already zero nothing happens.
'foldenable' will be set.
*zM*
zM Close all folds: set 'foldlevel' to 0.
'foldenable' will be set.
*zr*
zr Reduce folding: Add one to 'foldlevel'.
*zR*
zR Open all folds. This sets 'foldlevel' to highest fold level.
*:foldo* *:foldopen*
:{range}foldo[pen][!]
Open folds in {range}. When [!] is added all folds are
opened. Useful to see all the text in {range}. Without [!]
one level of folds is opened.
*:foldc* *:foldclose*
:{range}foldc[lose][!]
Close folds in {range}. When [!] is added all folds are
closed. Useful to hide all the text in {range}. Without [!]
one level of folds is closed.
*zn*
zn Fold none: reset 'foldenable'. All folds will be open.
*zN*
zN Fold normal: set 'foldenable'. All folds will be as they
were before.
*zi*
zi Invert 'foldenable'.
*]z*
]z Move to the end of the current open fold. If already at the
end, move to the end of the fold that contains it. If there
is no containing fold, the command fails.
When a count is used, repeats the command [count] times.
*zj*
zj Move downwards to the start of the next fold. A closed fold
is counted as one fold.
When a count is used, repeats the command [count] times.
This command can be used after an |operator|.
*zk*
zk Move upwards to the end of the previous fold. A closed fold
is counted as one fold.
When a count is used, repeats the command [count] times.
This command can be used after an |operator|.
COLORS *fold-colors*
The colors of a closed fold are set with the Folded group |hl-Folded|. The
colors of the fold column are set with the FoldColumn group |hl-FoldColumn|.
Example to set the colors:
:highlight Folded guibg=grey guifg=blue
:highlight FoldColumn guibg=darkgrey guifg=white
FOLDLEVEL *fold-foldlevel*
'foldlevel' is a number option: The higher the more folded regions are open.
When 'foldlevel' is 0, all folds are closed.
When 'foldlevel' is positive, some folds are closed.
When 'foldlevel' is very high, all folds are open.
'foldlevel' is applied when it is changed. After that manually folds can be
opened and closed.
When increased, folds above the new level are opened. No manually opened
folds will be closed.
When decreased, folds above the new level are closed. No manually closed
folds will be opened.
FOLDTEXT *fold-foldtext*
'foldtext' is a string option that specifies an expression. This expression
is evaluated to obtain the text displayed for a closed fold. Example:
:set foldtext=v:folddashes.substitute(getline(v:foldstart),'/\\*\\\|\\*/\\\|{{{\\d\\=','','g')
This shows the first line of the fold, with "/*", "*/" and "{{{" removed.
Note the use of backslashes to avoid some characters to be interpreted by the
":set" command. It's simpler to define a function and call that:
:set foldtext=MyFoldText()
:function MyFoldText()
: let line = getline(v:foldstart)
: let sub = substitute(line, '/\*\|\*/\|{{{\d\=', '', 'g')
: return v:folddashes . sub
:endfunction
FOLDCOLUMN *fold-foldcolumn*
'foldcolumn' is a number, which sets the width for a column on the side of the
window to indicate folds. When it is zero, there is no foldcolumn. A normal
value is 4 or 5. The minimal useful value is 2, although 1 still provides
some information. The maximum is 12.
An open fold is indicated with a column that has a '-' at the top and '|'
characters below it. This column stops where the open fold stops. When folds
nest, the nested fold is one character right of the fold it's contained in.
A closed fold is indicated with a '+'.
Where the fold column is too narrow to display all nested folds, digits are
shown to indicate the nesting level.
The mouse can also be used to open and close folds by clicking in the
fold column:
- Click on a '+' to open the closed fold at this row.
- Click on any other non-blank character to close the open fold at this row.
OTHER OPTIONS
'foldenable' 'fen': Open all folds while not set.
'foldexpr' 'fde': Expression used for "expr" folding.
'foldignore' 'fdi': Characters used for "indent" folding.
'foldmarker' 'fmr': Defined markers used for "marker" folding.
'foldmethod' 'fdm': Name of the current folding method.
'foldminlines' 'fml': Minimum number of screen lines for a fold to be
displayed closed.
'foldnestmax' 'fdn': Maximum nesting for "indent" and "syntax" folding.
'foldopen' 'fdo': Which kinds of commands open closed folds.
'foldclose' 'fcl': When the folds not under the cursor are closed.
==============================================================================
4. Behavior of folds *fold-behavior*
When moving the cursor upwards or downwards and when scrolling, the cursor
will move to the first line of a sequence of folded lines. When the cursor is
already on a folded line, it moves to the next unfolded line or the next
closed fold.
While the cursor is on folded lines, the cursor is always displayed in the
first column. The ruler does show the actual cursor position, but since the
line is folded, it cannot be displayed there.
Many movement commands handle a sequence of folded lines like an empty line.
For example, the "w" command stops once in the first column.
When in Insert mode, the cursor line is never folded. That allows you to see
what you type!
When using an operator, a closed fold is included as a whole. Thus "dl"
COMPILING
If you already have a compiled Vim program, check if the |+multi_byte| feature
is included. The |:version| command can be used for this.
If +multi_byte is not included, you should compile Vim with "big" features.
You can further tune what features are included. See the INSTALL files in the
source directory.
LOCALE
First of all, you must make sure your current locale is set correctly. If
your system has been installed to use the language, it probably works right
away. If not, you can often make it work by setting the $LANG environment
ENCODING
If your locale works properly, Vim will try to set the 'encoding' option
accordingly. If this doesn't work you can overrule its value:
:set encoding=utf-8
See |encoding-values| for a list of acceptable values.
The result is that all the text that is used inside Vim will be in this
encoding. Not only the text in the buffers, but also in registers, variables,
etc. This also means that changing the value of 'encoding' makes the existing
text invalid! The text doesn't change, but it will be displayed wrong.
You can edit files in another encoding than what 'encoding' is set to. Vim
will convert the file when you read it and convert it back when you write it.
See 'fileencoding', 'fileencodings' and |++enc|.
INPUT
There are several ways to enter multi-byte characters:
- For X11 XIM can be used. See |XIM|.
- For MS-Windows IME can be used. See |IME|.
*locale-name*
The (simplified) format of |locale| name is:
language
or language_territory
or language_territory.codeset
Territory means the country (or part of it), codeset means the |charset|. For
example, the locale name "ja_JP.eucJP" means:
ja the language is Japanese
JP the country is Japan
eucJP the codeset is EUC-JP
But it also could be "ja", "ja_JP.EUC", "ja_JP.ujis", etc. And unfortunately,
the locale name for a specific language, territory and codeset is not unified
and depends on your system.
Examples of locale name:
charset language locale name
GB2312 Chinese (simplified) zh_CN.EUC, zh_CN.GB2312
Big5 Chinese (traditional) zh_TW.BIG5, zh_TW.Big5
CNS-11643 Chinese (traditional) zh_TW
EUC-JP Japanese ja, ja_JP.EUC, ja_JP.ujis, ja_JP.eucJP
Shift_JIS Japanese ja_JP.SJIS, ja_JP.Shift_JIS
EUC-KR Korean ko, ko_KR.EUC
USING A LOCALE
To start using a locale for the whole system, see the documentation of your
system. Mostly you need to set it in a configuration file in "/etc".
To use a locale in a shell, set the $LANG environment value. When you want to
use Korean and the |locale| name is "ko", do this:
sh: export LANG=ko
*charset* *codeset*
Charset is another name for encoding. There are subtle differences, but these
don't matter when using Vim. "codeset" is another similar name.
Each character is encoded as one or more bytes. When all characters are
encoded with one byte, we call this a single-byte encoding. The most often
used one is called "latin1". This limits the number of characters to 256.
Some of these are control characters, thus even fewer can be used for text.
When some characters use two or more bytes, we call this a multi-byte
encoding. This allows using much more than 256 characters, which is required
for most East Asian languages.
Most multi-byte encodings use one byte for the first 127 characters. These
are equal to ASCII, which makes it easy to exchange plain-ASCII text, no
matter what language is used. Thus you might see the right text even when the
encoding was set wrong.
*encoding-names*
Vim can use many different character encodings. There are three major groups:
1 8bit Single-byte encodings, 256 different characters. Mostly used
in USA and Europe. Example: ISO-8859-1 (Latin1). All
characters occupy one screen cell only.
2 2byte Double-byte encodings, over 10000 different characters.
Mostly used in Asian countries. Example: euc-kr (Korean)
The number of screen cells is equal to the number of bytes
(except for euc-jp when the first byte is 0x8e).
u Unicode Universal encoding, can replace all others. ISO 10646.
Millions of different characters. Example: UTF-8. The
relation between bytes and screen cells is complex.
Other encodings cannot be used by Vim internally. But files in other
encodings can be edited by using conversion, see 'fileencoding'.
Note that all encodings must use ASCII for the characters up to 128 (except
when compiled for EBCDIC).
There are a few encodings which are similar, but not exactly the same. Vim
treats them as if they were different encodings, so that conversion will be
done when needed. You might want to use the similar name to avoid conversion
or when conversion is not possible:
cp932, shift-jis, sjis
cp936, euc-cn
*encoding-table*
Normally 'encoding' is equal to your current locale and 'termencoding' is
empty. This means that your keyboard and display work with characters encoded
in your current locale, and Vim uses the same characters internally.
You can make Vim use characters in a different encoding by setting the
'encoding' option to a different value. Since the keyboard and display still
use the current locale, conversion needs to be done. The 'termencoding' then
takes over the value of the current locale, so Vim converts between 'encoding'
and 'termencoding'. Example:
:let &termencoding = &encoding
:set encoding=utf-8
However, not all combinations of values are possible. The table below tells
you how each of the nine combinations works. This is further restricted by
not all conversions being possible, iconv() being present, etc. Since this
depends on the system used, no detailed list can be given.
('tenc' is the short name for 'termencoding' and 'enc' short for 'encoding')
'tenc' 'enc' remark
8bit 8bit Works. When 'termencoding' is different from
'encoding' typing and displaying may be wrong for some
characters, Vim does NOT perform conversion (set
'encoding' to "utf-8" to get this).
8bit 2byte MS-Windows: works for all codepages installed on your
system; you can only type 8bit characters;
Other systems: does NOT work.
8bit Unicode Works, but only 8bit characters can be typed directly
(others through digraphs, keymaps, etc.); in a
terminal you can only see 8bit characters; the GUI can
show all characters that the 'guifont' supports.
2byte 8bit Works, but typing non-ASCII characters might
be a problem.
2byte 2byte MS-Windows: works for all codepages installed on your
system; typing characters might be a problem when
locale is different from 'encoding'.
Other systems: Only works when 'termencoding' is equal
to 'encoding', you might as well leave it empty.
2byte Unicode works, Vim will translate typed characters.
Unicode 8bit works (unusual)
Unicode 2byte does NOT work
Unicode Unicode works very well (leaving 'termencoding' empty works
the same way, because all Unicode is handled
internally as UTF-8)
CONVERSION *charset-conversion*
Vim will automatically convert from one to another encoding in several places:
- When reading a file and 'fileencoding' is different from 'encoding'
- When writing a file and 'fileencoding' is different from 'encoding'
- When displaying characters and 'termencoding' is different from 'encoding'
- When reading input and 'termencoding' is different from 'encoding'
- When displaying messages and the encoding used for LC_MESSAGES differs from
'encoding' (requires a gettext version that supports this).
- When reading a Vim script where |:scriptencoding| is different from
'encoding'.
- When reading or writing a |viminfo| file.
Most of these require the |+iconv| feature. Conversion for reading and
writing files may also be specified with the 'charconvert' option.
Useful utilities for converting the charset:
All: iconv
GNU iconv can convert most encodings. Unicode is used as the
intermediate encoding, which allows conversion from and to all other
encodings. See http://www.gnu.org/directory/libiconv.html.
Japanese: nkf
Nkf is "Network Kanji code conversion Filter". One of the most unique
facility of nkf is the guess of the input Kanji code. So, you don't
need to know what the inputting file's |charset| is. When convert to
EUC-JP from ISO-2022-JP or Shift_JIS, simply do the following command
in Vim:
:%!nkf -e
Nkf can be found at:
http://www.sfc.wide.ad.jp/~max/FreeBSD/ports/distfiles/nkf-1.62.tar.gz
Chinese: hc
Hc is "Hanzi Converter". Hc convert a GB file to a Big5 file, or Big5
file to GB file. Hc can be found at:
ftp://ftp.cuhk.hk/pub/chinese/ifcss/software/unix/convert/hc-30.tar.gz
Korean: hmconv
Hmconv is Korean code conversion utility especially for E-mail. It can
convert between EUC-KR and ISO-2022-KR. Hmconv can be found at:
ftp://ftp.kaist.ac.kr/pub/hangul/code/hmconv/
Multilingual: lv
Lv is a Powerful Multilingual File Viewer. And it can be worked as
|charset| converter. Supported |charset|: ISO-2022-CN, ISO-2022-JP,
ISO-2022-KR, EUC-CN, EUC-JP, EUC-KR, EUC-TW, UTF-7, UTF-8, ISO-8859
series, Shift_JIS, Big5 and HZ. Lv can be found at:
http://www.ff.iij4u.or.jp/~nrt/freeware/lv4495.tar.gz
*mbyte-conversion*
When reading and writing files in an encoding different from 'encoding',
conversion needs to be done. These conversions are supported:
- All conversions between Latin-1 (ISO-8859-1), UTF-8, UCS-2 and UCS-4 are
handled internally.
- For MS-Windows, when 'encoding' is a Unicode encoding, conversion from and
to any codepage should work.
- Conversion specified with 'charconvert'
- Conversion with the iconv library, if it is available.
Old versions of GNU iconv() may cause the conversion to fail (they
request a very large buffer, more than Vim is willing to provide).
Try getting another iconv() implementation.
*iconv-dynamic*
On MS-Windows Vim can be compiled with the |+iconv/dyn| feature. This means
Vim will search for the "iconv.dll" and "libiconv.dll" libraries. When
neither of them can be found Vim will still work but some conversions won't be
possible.
==============================================================================
4. Using a terminal *mbyte-terminal*
The GUI fully supports multi-byte characters. It is also possible in a
terminal, if the terminal supports the same encoding that Vim uses. Thus this
is less flexible.
For example, you can run Vim in a xterm with added multi-byte support and/or
|XIM|. Examples are kterm (Kanji term) and hanterm (for Korean), Eterm
(Enlightened terminal) and rxvt.
If your terminal does not support the right encoding, you can set the
'termencoding' option. Vim will then convert the typed characters from
'termencoding' to 'encoding'. And displayed text will be converted from
'encoding' to 'termencoding'. If the encoding supported by the terminal
doesn't include all the characters that Vim uses, this leads to lost
characters. This may mess up the display. If you use a terminal that
supports Unicode, such as the xterm mentioned below, it should work just fine,
since nearly every character set can be converted to Unicode without loss of
information.
http://invisible-island.net/xterm/xterm.html
Compile it with "./configure --enable-wide-chars ; make"
Also get the ISO 10646-1 version of various fonts, which is available on
http://www.cl.cam.ac.uk/~mgk25/download/ucs-fonts.tar.gz
and install the font as described in the README file.
Now start xterm with
xterm -u8 -fn -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646-1
or, for bigger character:
xterm -u8 -fn -misc-fixed-medium-r-normal--15-140-75-75-c-90-iso10646-1
and you will have a working UTF-8 terminal emulator. Try both
cat utf-8-demo.txt
vim utf-8-demo.txt
with the demo text that comes with ucs-fonts.tar.gz in order to see
whether there are any problems with UTF-8 in your xterm.
For Vim you may need to set 'encoding' to "utf-8".
==============================================================================
5. Fonts on X11 *mbyte-fonts-X11*
Unfortunately, using fonts in X11 is complicated. The name of a single-byte
font is a long string. For multi-byte fonts we need several of these...
Note: Most of this is no longer relevant for GTK+ 2. Selecting a font via
its XLFD is not supported; see 'guifont' for an example of how to
set the font. Do yourself a favor and ignore the |XLFD| and |xfontset|
sections below.
First of all, Vim only accepts fixed-width fonts for displaying text. You
cannot use proportionally spaced fonts. This excludes many of the available
(and nicer looking) fonts. However, for menus and tooltips any font can be
used.
Note that Display and Input are independent. It is possible to see your
language even though you have no input method for it.
You should get a default font for menus and tooltips that works, but it might
be ugly. Read the following to find out how to select a better font.
X FONTSET
*fontset* *xfontset*
A single-byte charset is typically associated with one font. For multi-byte
charsets a combination of fonts is often used. This means that one group of
characters are used from one font and another group from another font (which
might be double wide). This collection of fonts is called a fontset.
Which fonts are required in a fontset depends on the current locale. X
windows maintains a table of which groups of characters are required for a
locale. You have to specify all the fonts that a locale requires in the
'guifontset' option.
NOTE: The fontset always uses the current locale, even though 'encoding' may
be set to use a different charset. In that situation you might want to use
'guifont' and 'guifontwide' instead of 'guifontset'.
Example:
|charset| language "groups of characters"
GB2312 Chinese (simplified) ISO-8859-1 and GB 2312
Big5 Chinese (traditional) ISO-8859-1 and Big5
CNS-11643 Chinese (traditional) ISO-8859-1, CNS 11643-1 and CNS 11643-2
EUC-JP Japanese JIS X 0201 and JIS X 0208
EUC-KR Korean ISO-8859-1 and KS C 5601 (KS X 1001)
You can search for fonts using the xlsfonts command. For example, when you're
searching for a font for KS C 5601:
xlsfonts | grep ksc5601
This is complicated and confusing. You might want to consult the X-Windows
documentation if there is something you don't understand.
*base_font_name_list*
When you have found the names of the fonts you want to use, you need to set
the 'guifontset' option. You specify the list by concatenating the font names
and putting a comma in between them.
For example, when you use the ja_JP.eucJP locale, this requires JIS X 0201
and JIS X 0208. You could supply a list of fonts that explicitly specifies
the charsets, like:
:set guifontset=-misc-fixed-medium-r-normal--14-130-75-75-c-140-jisx0208.1983-0,
\-misc-fixed-medium-r-normal--14-130-75-75-c-70-jisx0201.1976-0
Alternatively, you can supply a base font name list that omits the charset
name, letting X-Windows select font characters required for the locale. For
example:
:set guifontset=-misc-fixed-medium-r-normal--14-130-75-75-c-140,
\-misc-fixed-medium-r-normal--14-130-75-75-c-70
Alternatively, you can supply a single base font name that allows X-Windows to
select from all available fonts. For example:
:set guifontset=-misc-fixed-medium-r-normal--14-*
Alternatively, you can specify alias names. See the fonts.alias file in the
fonts directory (e.g., /usr/X11R6/lib/X11/fonts/). For example:
:set guifontset=k14,r14
*E253*
Note that in East Asian fonts, the standard character cell is square. When
mixing a Latin font and an East Asian font, the East Asian font width should
be twice the Latin font width.
If 'guifontset' is not empty, the "font" argument of the |:highlight| command
is also interpreted as a fontset. For example, you should use for
highlighting:
:hi Comment font=english_font,your_font
If you use a wrong "font" argument you will get an error message.
Also make sure that you set 'guifontset' before setting fonts for highlight
groups.
The GTK+ version of GUI Vim does not use .Xdefaults, use ~/.gtkrc instead.
The default mostly works OK. But for the menus you might have to change
it. Example:
style "default"
{
fontset="-*-*-medium-r-normal--14-*-*-*-c-*-*-*"
}
widget_class "*" style "default"
==============================================================================
6. Fonts on MS-Windows *mbyte-fonts-MSwin*
The simplest is to use the font dialog to select fonts and try them out. You
can find this at the "Edit/Select Font..." menu. Once you find a font name
that works well you can use this command to see its name:
:set guifont
Then add a command to your |gvimrc| file to set 'guifont':
:set guifont=courier_new:h12
==============================================================================
7. Input on X11 *mbyte-XIM*
XIM is an international input module for X. There are two kinds of structures,
Xlib unit type and |IM-server| (Input-Method server) type. |IM-server| type
is suitable for complex input, such as CJK.
- IM-server
*IM-server*
In |IM-server| type input structures, the input event is handled by either
of the two ways: FrontEnd system and BackEnd system. In the FrontEnd
system, input events are snatched by the |IM-server| first, then |IM-server|
give the application the result of input. On the other hand, the BackEnd
system works reverse order. MS Windows adopt BackEnd system. In X, most of
|IM-server|s adopt FrontEnd system. The demerit of BackEnd system is the
large overhead in communication, but it provides safe synchronization with
no restrictions on applications.
For example, there are xwnmo and kinput2 Japanese |IM-server|, both are
FrontEnd system. Xwnmo is distributed with Wnn (see below), kinput2 can be
found at: ftp://ftp.sra.co.jp/pub/x11/kinput2/
For Chinese, there's a great XIM server named "xcin", you can input both
Traditional and Simplified Chinese characters. And it can accept other
locale if you make a correct input table. Xcin can be found at:
http://cle.linux.org.tw/xcin/
Others are scim: http://scim.freedesktop.org/ and fcitx:
http://www.fcitx.org/
- Conversion Server
*conversion-server*
Some system needs additional server: conversion server. Most of Japanese
|IM-server|s need it, Kana-Kanji conversion server. For Chinese inputting,
it depends on the method of inputting, in some methods, PinYin or ZhuYin to
HanZi conversion server is needed. For Korean inputting, if you want to
input Hanja, Hangul-Hanja conversion server is needed.
For example, the Japanese inputting process is divided into 2 steps. First
we pre-input Hira-gana, second Kana-Kanji conversion. There are so many
Kanji characters (6349 Kanji characters are defined in JIS X 0208) and the
number of Hira-gana characters are 76. So, first, we pre-input text as
pronounced in Hira-gana, second, we convert Hira-gana to Kanji or Kata-Kana,
if needed. There are some Kana-Kanji conversion server: jserver
(distributed with Wnn, see below) and canna. Canna could be found at:
ftp://ftp.nec.co.jp/pub/Canna/ no longer works.
There is a good input system: Wnn4.2. Wnn 4.2 contains,
xwnmo (|IM-server|)
jserver (Japanese Kana-Kanji conversion server)
cserver (Chinese PinYin or ZhuYin to simplified HanZi conversion server)
tserver (Chinese PinYin or ZhuYin to traditional HanZi conversion server)
kserver (Hangul-Hanja conversion server)
Wnn 4.2 for several systems can be found at various places on the internet.
Use the RPM or port for your system.
- Input Style
*xim-input-style*
When inputting CJK, there are four areas:
1. The area to display of the input while it is being composed
2. The area to display the currently active input mode.
3. The area to display the next candidate for the selection.
4. The area to display other tools.
The third area is needed when converting. For example, in Japanese
inputting, multiple Kanji characters could have the same pronunciation, so
a sequence of Hira-gana characters could map to a distinct sequence of Kanji
characters.
The first and second areas are defined in international input of X with the
names of "Preedit Area", "Status Area" respectively. The third and fourth
areas are not defined and are left to be managed by the |IM-server|. In the
international input, four input styles have been defined using combinations
of Preedit Area and Status Area: |OnTheSpot|, |OffTheSpot|, |OverTheSpot|
and |Root|.
Currently, GUI Vim supports three styles, |OverTheSpot|, |OffTheSpot| and
|Root|.
*. on-the-spot *OnTheSpot*
Preedit Area and Status Area are performed by the client application in
the area of application. The client application is directed by the
|IM-server| to display all pre-edit data at the location of text
insertion. The client registers callbacks invoked by the input method
during pre-editing.
*. over-the-spot *OverTheSpot*
Status Area is created in a fixed position within the area of application,
in case of Vim, the position is the additional status line. Preedit Area
is made at present input position of application. The input method
displays pre-edit data in a window which it brings up directly over the
text insertion position.
*. off-the-spot *OffTheSpot*
Preedit Area and Status Area are performed in the area of application, in
case of Vim, the area is additional status line. The client application
provides display windows for the pre-edit data to the input method which
displays into them directly.
*. root-window *Root*
Preedit Area and Status Area are outside of the application. The input
method displays all pre-edit data in a separate area of the screen in a
window specific to the input method.
The actual mappings are in the lines below "loadkeymap". In the example "a"
is mapped to "A" and "b" to "B". Thus the first item is mapped to the second
item. This is done for each line, until the end of the file.
These items are exactly the same as what can be used in a |:lnoremap| command,
using "<buffer>" to make the mappings local to the buffer..
You can check the result with this command:
:lmap
The two items must be separated by white space. You cannot include white
space inside an item, use the special names "<Tab>" and "<Space>" instead.
The length of the two items together must not exceed 200 bytes.
It's possible to have more than one character in the first column. This works
like a dead key. Example:
'a á
Since Vim doesn't know if the next character after a quote is really an "a",
it will wait for the next character. To be able to insert a single quote,
also add this line:
'' '
Since the mapping is defined with |:lnoremap| the resulting quote will not be
used for the start of another character.
The "accents" keymap uses this. *keymap-accents*
Although it's possible to have more than one character in the second column,
this is unusual. But you can use various ways to specify the character:
A a literal character
A <char-97> decimal value
A <char-0x61> hexadecimal value
A <char-0141> octal value
x <Space> special key name
The characters are assumed to be encoded for the current value of 'encoding'.
It's possible to use ":scriptencoding" when all characters are given
literally. That doesn't work when using the <char-> construct, because the
conversion is done on the keymap file, not on the resulting character.
The lines after "loadkeymap" are interpreted with 'cpoptions' set to "C".
This means that continuation lines are not used and a backslash has a special
meaning in the mappings. Examples:
" a comment line
\" x maps " to x
\\ y maps \ to y
If you write a keymap file that will be useful for others, consider submitting
it to the Vim maintainer for inclusion in the distribution:
<maintainer@vim.org>
*bom-bytes*
When reading a file a BOM (Byte Order Mark) can be used to recognize the
Unicode encoding:
EF BB BF utf-8
FE FF utf-16 big endian
FF FE utf-16 little endian
00 00 FE FF utf-32 big endian
FF FE 00 00 utf-32 little endian
Utf-8 is the recommended encoding. Note that it's difficult to tell utf-16
and utf-32 apart. Utf-16 is often used on MS-Windows, utf-32 is not
widespread as file format.
*mbyte-combining* *mbyte-composing*
A composing or combining character is used to change the meaning of the
character before it. The combining characters are drawn on top of the
preceding character.
Up to two combining characters can be used by default. This can be changed
with the 'maxcombine' option.
When editing text a composing character is mostly considered part of the
preceding character. For example "x" will delete a character and its
following composing characters by default.
If the 'delcombine' option is on, then pressing 'x' will delete the combining
characters, one at a time, then the base character. But when inserting, you
type the first character and the following composing characters separately,
after which they will be joined. The "r" command will not allow you to type a
combining character, because it doesn't know one is coming. Use "R" instead.
Bytes which are not part of a valid UTF-8 byte sequence are handled like a
single character and displayed as <xx>, where "xx" is the hex value of the
byte.
Overlong sequences are not handled specially and displayed like a valid
character. However, search patterns may not match on an overlong sequence.
(an overlong sequence is where more bytes are used than required for the
character.) An exception is NUL (zero) which is displayed as "<00>".
In the file and buffer the full range of Unicode characters can be used (31
bits). However, displaying only works for 16 bit characters, and only for the
characters present in the selected font.
Useful commands:
- "ga" shows the decimal, hexadecimal and octal value of the character under
the cursor. If there are composing characters these are shown too. (If the
message is truncated, use ":messages").
- "g8" shows the bytes used in a UTF-8 character, also the composing
characters, as hex numbers.
- ":set encoding=utf-8 fileencodings=" forces using UTF-8 for all files. The
default is to use the current locale for 'encoding' and set 'fileencodings'
to automatically detect the encoding of a file.
STARTING VIM
If your current locale is in an utf-8 encoding, Vim will automatically start
in utf-8 mode.
If you are using another locale:
set encoding=utf-8
You might also want to select the font used for the menus. Unfortunately this
doesn't always work. See the system specific remarks below, and 'langmenu'.
==============================================================================
11. Overview of options *mbyte-options*
These options are relevant for editing multi-byte files. Check the help in
options.txt for detailed information.
'encoding' Encoding used for the keyboard and display. It is also the
default encoding for files.
'fileencoding' Encoding of a file. When it's different from 'encoding'
conversion is done when reading or writing the file.
'fileencodings' List of possible encodings of a file. When opening a file
these will be tried and the first one that doesn't cause an
error is used for 'fileencoding'.
'charconvert' Expression used to convert files from one encoding to another.
'formatoptions' The 'm' flag can be included to have formatting break a line
at a multibyte character of 256 or higher. Thus is useful for
languages where a sequence of characters can be broken
anywhere.
'guifontset' The list of font names used for a multi-byte encoding. When
this option is not empty, it replaces 'guifont'.
'keymap' Specify the name of a keyboard mapping.
==============================================================================
Contributions specifically for the multi-byte features by:
Chi-Deok Hwang <hwang@mizi.co.kr>
SungHyun Nam <goweol@gmail.com>
K.Nagano <nagano@atese.advantest.co.jp>
Taro Muraoka <koron@tka.att.ne.jp>
Yasuhiro Matsumoto <mattn@mail.goo.ne.jp>
top - main help file
==============================================================================
3. Netrw Reference *netrw-ref* {{{1
Netrw supports several protocols in addition to scp and ftp as mentioned
in |netrw-start|. These include dav, fetch, http,... well, just look
at the list in |netrw-externapp|. Each protocol is associated with a
variable which holds the default command supporting that protocol.
curl : "-o"
wget : "-q -O"
fetch : "-o"
For example, if your system has elinks, and you'd rather see the
page using an attempt at rendering the text, you may wish to have
let g:netrw_http_xcmd= "-dump >"
in your .vimrc.
:e scp://[user]@hostname/path/
:e ftp://[user]@hostname/path/
For remote directories (ie. those using scp or ftp), that trailing
"/" is necessary (the slash tells netrw to treat the argument as a
directory to browse instead of a file to download).
However, the Nread command can also be used to accomplish this:
:Nread [protocol]://[user]@hostname/path/
*netrw-login* *netrw-password*
CHANGING USERID AND PASSWORD *netrw-chgup* *netrw-userpass* {{{2
Attempts to use ftp will prompt you for a user-id and a password.
These will be saved in global variables g:netrw_uid and
s:netrw_passwd; subsequent uses of ftp will re-use those two items to
simplify the further use of ftp. However, if you need to use a
different user id and/or password, you'll want to call NetUserPass()
first. To work around the need to enter passwords, check if your ftp
supports a <.netrc> file in your home directory. Also see
|netrw-passwd| (and if you're using ssh/scp hoping to figure out how
to not need to use passwords, look at |netrw-ssh-hack|).
:NetUserPass [uid [password]] -- prompts as needed
:call NetUserPass() -- prompts for uid and password
:call NetUserPass("uid") -- prompts for password
:call NetUserPass("uid","password") -- sets global uid and password
client. As an example:
="passive"
*g:netrw_nogx* if this variable exists, then the "gx" map will not
be available (see |netrw-gx|)
*g:netrw_sepchr* =\0xff
=\0x01 for enc == euc-jp (and perhaps it should be for
others, too, please let me
know)
Separates priority codes from filenames internally.
See |netrw-p12|.
==============================================================================
4. Network-Oriented File Transfer *netrw-xfer* {{{1
Network-oriented file transfer under Vim is implemented by a VimL-based script
(<netrw.vim>) using plugin techniques. It currently supports both reading and
writing across networks using rcp, scp, ftp or ftp+<.netrc>, scp, fetch,
dav/cadaver, rsync, or sftp.
http is currently supported read-only via use of wget or fetch.
<netrw.vim> is a standard plugin which acts as glue between Vim and the
various file transfer programs. It uses autocommand events (BufReadCmd,
FileReadCmd, BufWriteCmd) to intercept reads/writes with url-like filenames.
ex. vim ftp://hostname/path/to/file
The characters preceding the colon specify the protocol to use; in the
example, it's ftp. The <netrw.vim> script then formulates a command or a
series of commands (typically ftp) which it issues to an external program
(ftp, scp, etc) which does the actual file transfer/protocol. Files are read
from/written to a temporary file (under Unix/Linux, /tmp/...) which the
<netrw.vim> script will clean up.
Now, a word about Jan Minář's "FTP User Name and Password Disclosure"; first,
ftp is not a secure protocol. User names and passwords are transmitted "in
the clear" over the internet; any snooper tool can pick these up; this is not
a netrw thing, this is a ftp thing. If you're concerned about this, please
try to use scp or sftp instead.
Netrw re-uses the user id and password during the same vim session and so long
as the remote hostname remains the same.
Jan seems to be a bit confused about how netrw handles ftp; normally multiple
commands are performed in a "ftp session", and he seems to feel that the
uid/password should only be retained over one ftp session. However, netrw
does every ftp operation in a separate "ftp session"; so remembering the
uid/password for just one "ftp session" would be the same as not remembering
the uid/password at all. IMHO this would rapidly grow tiresome as one
browsed remote directories, for example.
On the other hand, thanks go to Jan M. for pointing out the many
vulnerabilities that netrw (and vim itself) had had in handling "crafted"
filenames. The |shellescape()| and |fnameescape()| functions were written in
response by Bram Moolenaar to handle these sort of problems, and netrw has
been modified to use them. Still, my advice is, if the "filename" looks like
a vim command that you aren't comfortable with having executed, don't open it.
For rcp, scp, sftp, and http, one may use network-oriented file transfers
transparently; ie.
vim rcp://[user@]machine/path
vim scp://[user@]machine/path
If your ftp supports <.netrc>, then it too can be transparently used
if the needed triad of machine name, user id, and password are present in
that file. Your ftp must be able to use the <.netrc> file on its own, however.
vim ftp://[user@]machine[[:#]portnumber]/path
Windows provides an ftp (typically c:\Windows\System32\ftp.exe) which uses
an option, -s:filename (filename can and probably should be a full path)
which contains ftp commands which will be automatically run whenever ftp
starts. You may use this feature to enter a user and password for one site:
userid
password
If |g:netrw_ftp_cmd| contains -s:[path/]MACHINE, then (on Windows machines only)
netrw will substitute the current machine name requested for ftp connection
for MACHINE. Hence one can have multiple machine.ftp files containing login
and password for ftp. Example:
g:netrw_ftp_cmd= 'c:\Windows\System32\ftp -s:C:\Users\Myself\MACHINE'
vim ftp://myhost.somewhere.net/
will use a file
C:\Users\Myself\myhost.ftp
Often, ftp will need to query the user for the userid and password.
The latter will be done "silently"; ie. asterisks will show up instead of
the actually-typed-in password. Netrw will retain the userid and password
for subsequent read/writes from the most recent transfer so subsequent
transfers (read/write) to or from that machine will take place without
additional prompting.
*netrw-urls*
+=================================+============================+============+
| Reading | Writing | Uses |
+=================================+============================+============+
| DAV: | | |
| dav://host/path | | cadaver |
| :Nread dav://host/path | :Nwrite dav://host/path | cadaver |
+---------------------------------+----------------------------+------------+
| DAV + SSL: | | |
| davs://host/path | | cadaver |
| :Nread davs://host/path | :Nwrite davs://host/path | cadaver |
+---------------------------------+----------------------------+------------+
| FETCH: | | |
| fetch://[user@]host/path | | |
| fetch://[user@]host:http/path | Not Available | fetch |
| :Nread fetch://[user@]host/path| | |
+---------------------------------+----------------------------+------------+
| FILE: | | |
| file:///* | file:///* | |
| file://localhost/* | file://localhost/* | |
+---------------------------------+----------------------------+------------+
| FTP: (*3) | (*3) | |
| ftp://[user@]host/path | ftp://[user@]host/path | ftp *2 |
| :Nread ftp://host/path | :Nwrite ftp://host/path | ftp+.netrc |
| :Nread host path | :Nwrite host path | ftp+.netrc |
| :Nread host uid pass path | :Nwrite host uid pass path | ftp |
+---------------------------------+----------------------------+------------+
| HTTP: wget is executable: (*4) | | |
| http://[user@]host/path | Not Available | wget |
+---------------------------------+----------------------------+------------+
| HTTP: fetch is executable (*4) | | |
| http://[user@]host/path | Not Available | fetch |
+---------------------------------+----------------------------+------------+
| RCP: | | |
| rcp://[user@]host/path | rcp://[user@]host/path | rcp |
+---------------------------------+----------------------------+------------+
| RSYNC: | | |
| rsync://[user@]host/path | rsync://[user@]host/path | rsync |
| :Nread rsync://host/path | :Nwrite rsync://host/path | rsync |
| :Nread rcp://host/path | :Nwrite rcp://host/path | rcp |
+---------------------------------+----------------------------+------------+
| SCP: | | |
| scp://[user@]host/path | scp://[user@]host/path | scp |
NETRC *netrw-netrc*
The <.netrc> file, typically located in your home directory, contains lines
therein which map a hostname (machine name) to the user id and password you
prefer to use with it.
The typical syntax for lines in a <.netrc> file is given as shown below.
Ftp under Unix usually supports <.netrc>; ftp under Windows usually doesn't.
machine {full machine name} login {user-id} password "{password}"
default login {user-id} password "{password}"
Your ftp client must handle the use of <.netrc> on its own, but if the
<.netrc> file exists, an ftp transfer will not ask for the user-id or
password.
Note:
Since this file contains passwords, make very sure nobody else can
read this file! Most programs will refuse to use a .netrc that is
readable for others. Don't forget that the system administrator can
still read the file! Ie. for Linux/Unix: chmod 600 .netrc
PASSWORD *netrw-passwd*
The script attempts to get passwords for ftp invisibly using |inputsecret()|,
a built-in Vim function. See |netrw-userpass| for how to change the password
after one has set it.
Unfortunately there doesn't appear to be a way for netrw to feed a password to
scp. Thus every transfer via scp will require re-entry of the password.
However, |netrw-ssh-hack| can help with this problem.
==============================================================================
5. Activation *netrw-activate* {{{1
Network-oriented file transfers are available by default whenever Vim's
|'nocompatible'| mode is enabled. Netrw's script files reside in your
system's plugin, autoload, and syntax directories; just the
plugin/netrwPlugin.vim script is sourced automatically whenever you bring up
vim. The main script in autoload/netrw.vim is only loaded when you actually
use netrw. I suggest that, at a minimum, you have at least the following in
your <.vimrc> customization file:
set nocp
if version >= 600
filetype plugin indent on
endif
==============================================================================
6. Transparent Remote File Editing *netrw-transparent* {{{1
==============================================================================
7. Ex Commands *netrw-ex* {{{1
The usual read/write commands are supported. There are also a few
additional commands available. Often you won't need to use Nwrite or
Nread as shown in |netrw-transparent| (ie. simply use
:e url
:r url
:w url
instead, as appropriate) -- see |netrw-urls|. In the explanations
below, a {netfile} is an url to a remote file.
*:Nwrite* *:Nw*
:[range]Nw[rite] Write the specified lines to the current
file as specified in b:netrw_lastfile.
(related: |netrw-nwrite|)
:[range]Nw[rite] {netfile} [{netfile}]...
Write the specified lines to the {netfile}.
*:Nread* *:Nr*
:Nr[ead] Read the lines from the file specified in b:netrw_lastfile
into the current buffer. (related: |netrw-nread|)
:Nr[ead] {netfile} {netfile}...
Read the {netfile} after the current line.
*:Nsource* *:Ns*
:Ns[ource] {netfile}
Source the {netfile}.
To start up vim using a remote .vimrc, one may use
the following (all on one line) (tnx to Antoine Mechelynck)
vim -u NORC -N
--cmd "runtime plugin/netrwPlugin.vim"
--cmd "source scp://HOSTNAME/.vimrc"
(related: |netrw-source|)
==============================================================================
8. Variables and Options *netrw-options* *netrw-var* {{{1
*netrw-protocol*
Netrw supports a number of protocols. These protocols are invoked using the
variables listed below, and may be modified by the user.
------------------------
Protocol Control Options
------------------------
Option Type Setting Meaning
--------- -------- -------------- ---------------------------
netrw_ftp variable =doesn't exist userid set by "user userid"
=0 userid set by "user userid"
=1 userid set by "userid"
NetReadFixup function =doesn't exist no change
=exists Allows user to have files
read via ftp automatically
transformed however they wish
by NetReadFixup()
g:netrw_dav_cmd variable ="cadaver" if cadaver is executable
g:netrw_dav_cmd variable ="curl -o" elseif curl is executable
g:netrw_fetch_cmd variable ="fetch -o" if fetch is available
g:netrw_ftp_cmd variable ="ftp"
g:netrw_http_cmd variable ="fetch -o" if fetch is available
g:netrw_http_cmd variable ="wget -O" else if wget is available
g:netrw_list_cmd variable ="ssh USEPORT HOSTNAME ls -Fa"
*netrw-ftp*
The g:netrw_..._cmd options (|g:netrw_ftp_cmd| and |g:netrw_sftp_cmd|)
specify the external program to use handle the ftp protocol. They may
include command line options (such as -p for passive mode). Example:
let g:netrw_ftp_cmd= "ftp -p"
Browsing is supported by using the |g:netrw_list_cmd|; the substring
"HOSTNAME" will be changed via substitution with whatever the current request
is for a hostname.
Two options (|g:netrw_ftp| and |netrw-fixup|) both help with certain ftp's
that give trouble . In order to best understand how to use these options if
ftp is giving you troubles, a bit of discussion is provided on how netrw does
ftp reads.
For ftp, netrw typically builds up lines of one of the following formats in a
temporary file:
IF g:netrw_ftp !exists or is not 1 IF g:netrw_ftp exists and is 1
---------------------------------- ------------------------------
open machine [port] open machine [port]
user userid password userid password
[g:netrw_ftpmode] password
[g:netrw_ftpextracmd] [g:netrw_ftpmode]
get filename tempfile [g:netrw_extracmd]
get filename tempfile
---------------------------------------------------------------------
The |g:netrw_ftpmode| and |g:netrw_ftpextracmd| are optional.
Netrw then executes the lines above by use of a filter:
:%! {g:netrw_ftp_cmd} -i [-n]
where
g:netrw_ftp_cmd is usually "ftp",
-i tells ftp not to be interactive
-n means don't use netrc and is used for Method #3 (ftp w/o <.netrc>)
If <.netrc> exists it will be used to avoid having to query the user for
userid and password. The transferred file is put into a temporary file.
The temporary file is then read into the main editing session window that
requested it and the temporary file deleted.
If your ftp doesn't accept the "user" command and immediately just demands a
userid, then try putting "let netrw_ftp=1" in your <.vimrc>.
*netrw-cadaver*
To handle the SSL certificate dialog for untrusted servers, one may pull
down the certificate and place it into /usr/ssl/cert.pem. This operation
renders the server treatment as "trusted".
*netrw-fixup* *netreadfixup*
If your ftp for whatever reason generates unwanted lines (such as AUTH
messages) you may write a NetReadFixup() function:
function! NetReadFixup(method,line1,line2)
" a:line1: first new line in current file
" a:line2: last new line in current file
if a:method == 1 "rcp
elseif a:method == 2 "ftp + <.netrc>
elseif a:method == 3 "ftp + machine,uid,password,filename
elseif a:method == 4 "scp
elseif a:method == 5 "http/wget
elseif a:method == 6 "dav/cadaver
elseif a:method == 7 "rsync
elseif a:method == 8 "fetch
==============================================================================
9. Browsing *netrw-browsing* *netrw-browse* *netrw-help* {{{1
*netrw-browser* *netrw-dir* *netrw-list*
*netrw-quickmap* *netrw-quickmaps*
QUICK REFERENCE: MAPS *netrw-browse-maps* {{{2
--- ----------------- ----
Map Quick Explanation Link
--- ----------------- ----
<F1> Causes Netrw to issue help
<cr> Netrw will enter the directory or read the file |netrw-cr|
<del> Netrw will attempt to remove the file/directory |netrw-del|
- Makes Netrw go up one directory |netrw--|
a Toggles between normal display, |netrw-a|
hiding (suppress display of files matching g:netrw_list_hide)
showing (display only files which match g:netrw_list_hide)
c Make browsing directory the current directory |netrw-c|
C Setting the editing window |netrw-C|
d Make a directory |netrw-d|
D Attempt to remove the file(s)/directory(ies) |netrw-D|
gb Go to previous bookmarked directory |netrw-gb|
gh Quick hide/unhide of dot-files |netrw-gh|
<c-h> Edit file hiding list |netrw-ctrl-h|
i Cycle between thin, long, wide, and tree listings |netrw-i|
<c-l> Causes Netrw to refresh the directory listing |netrw-ctrl-l|
mb Bookmark current directory |netrw-mb|
mc Copy marked files to marked-file target directory |netrw-mc|
md Apply diff to marked files (up to 3) |netrw-md|
me Place marked files on arg list and edit them |netrw-me|
mf Mark a file |netrw-mf|
mh Toggle marked file suffices' presence on hiding list |netrw-mh|
mm Move marked files to marked-file target directory |netrw-mm|
mp Print marked files |netrw-mp|
mr Mark files satisfying a shell-style |regexp| |netrw-mr|
mt Current browsing directory becomes markfile target |netrw-mt|
mT Apply ctags to marked files |netrw-mT|
mu Unmark all marked files |netrw-mu|
mx Apply arbitrary shell command to marked files |netrw-mx|
*netrw-quickcom* *netrw-quickcoms*
QUICK REFERENCE: COMMANDS *netrw-explore-cmds* *netrw-browse-cmds* {{{2
:NetrwClean[!] ...........................................|netrw-cleanYXXY
:NetrwSettings ...........................................|netrw-settingsYXXY
:Explore[!] [dir] Explore directory of current file......|netrw-exploreYXXY
:Hexplore[!] [dir] Horizontal Split & Explore.............|netrw-exploreYXXY
:Nexplore[!] [dir] Vertical Split & Explore...............|netrw-exploreYXXY
:Pexplore[!] [dir] Vertical Split & Explore...............|netrw-exploreYXXY
:Rexplore Return to Explorer.....................|netrw-exploreYXXY
:Sexplore[!] [dir] Split & Explore directory .............|netrw-exploreYXXY
:Texplore[!] [dir] Tab & Explore..........................|netrw-exploreYXXY
:Vexplore[!] [dir] Vertical Split & Explore...............|netrw-exploreYXXY
two or more spaces delimit filenames and directory names for the long and
wide listing formats. Thus, if your filename or directory name has two or
more sequential spaces embedded in it, or any trailing spaces, then you'll
need to use the "thin" format to select it.
The |g:netrw_browse_split| option, which is zero by default, may be used to
cause the opening of files to be done in a new window or tab instead of the
default. When the option is one or two, the splitting will be taken
horizontally or vertically, respectively. When the option is set to three, a
<cr> will cause the file to appear in a new tab.
When using the gui (gvim), one may select a file by pressing the <leftmouse>
button. In addition, if
*|g:netrw_retmap| == 1 AND (its default value is 0)
* in a netrw-selected file, AND
* the user doesn't already have a <2-leftmouse> mapping defined before
netrw is loaded
then a doubly-clicked leftmouse button will return to the netrw browser
window.
Netrw attempts to speed up browsing, especially for remote browsing where one
may have to enter passwords, by keeping and re-using previously obtained
directory listing buffers. The |g:netrw_fastbrowse| variable is used to
control this behavior; one may have slow browsing (no buffer re-use), medium
speed browsing (re-use directory buffer listings only for remote directories),
and fast browsing (re-use directory buffer listings as often as possible).
The price for such re-use is that when changes are made (such as new files
are introduced into a directory), the listing may become out-of-date. One may
always refresh directory listing buffers by pressing ctrl-L (see
|netrw-ctrl-l|).
With the "U" map, one can change to a later directory (successor).
This map is the opposite of the "u" map. (see |netrw-u|) Use the
q map to list both the bookmarks and history. (see |netrw-qb|)
*netrw-gx*
CUSTOMIZING BROWSING WITH A USER FUNCTION *netrw-x* *netrw-handler* {{{2
(also see |netrw_filehandler|)
Certain files, such as html, gif, jpeg, (word/office) doc, etc, files, are
best seen with a special handler (ie. a tool provided with your computer).
Netrw allows one to invoke such special handlers by:
* when Exploring, hit the "x" key
* when editing, hit gx with the cursor atop the special filename
(not available if the |g:netrw_nogx| variable exists)
Netrw determines which special handler by the following method:
* if |g:netrw_browsex_viewer| exists, then it will be used to attempt to
view files. Examples of useful settings (place into your <.vimrc>):
:let g:netrw_browsex_viewer= "kfmclient exec"
or
:let g:netrw_browsex_viewer= "gnome-open"
If g:netrw_browsex_viewer == '-', then netrwFileHandler() will be
invoked first (see |netrw_filehandler|).
* for Windows 32 or 64, the url and FileProtocolHandler dlls are used.
* for Gnome (with gnome-open): gnome-open is used.
* for KDE (with kfmclient) : kfmclient is used.
* for Mac OS X : open is used.
* otherwise the netrwFileHandler plugin is used.
The file's suffix is used by these various approaches to determine an
appropriate application to use to "handle" these files. Such things as
OpenOffice (*.sfx), visualization (*.jpg, *.gif, etc), and PostScript (*.ps,
*.eps) can be handled.
*netrw_filehandler*
The "x" map applies a function to a file, based on its extension. Of course,
the handler function must exist for it to be called!
Ex. mypgm.html x ->
NFH_html("scp://user@host/some/path/mypgm.html")
Users may write their own netrw File Handler functions to support more
suffixes with special handling. See <autoload/netrwFileHandlers.vim> for
examples on how to make file handler functions. As an example:
" NFH_suffix(filename)
fun! NFH_suffix(filename)
..do something special with filename..
endfun
These functions need to be defined in some file in your .vim/plugin
(vimfiles\plugin) directory. Vim's function names may not have punctuation
characters (except for the underscore) in them. To support suffices that
contain such characters, netrw will first convert the suffix using the
following table:
*netrw-curdir*
DELETING BOOKMARKS *netrw-mB* {{{2
To delete a bookmark, use
{cnt}mB
Related Topics:
|netrw-gb| how to return (go) to a bookmark
|netrw-mb| how to make a bookmark
|netrw-qb| how to list bookmarks
As an example, consider
:Explore */*.c
:Nexplore
:Nexplore
:Pexplore
The status line will show, on the right hand side of the status line, a
message like "Match 3 of 20".
Associated setting variables: |g:netrw_keepdir| |g:netrw_browse_split|
|g:netrw_fastbrowse| |g:netrw_ftp_browse_reject|
|g:netrw_ftp_list_cmd| |g:netrw_ftp_sizelist_cmd|
|g:netrw_ftp_timelist_cmd| |g:netrw_list_cmd|
|g:netrw_liststyle|
*netrw-gh* *netrw-hide*
As a quick shortcut, one may press
gh
to toggle between hiding files which begin with a period (dot) and not hiding
them.
Associated setting variable: |g:netrw_list_hide|
Associated topics: |netrw-a| |netrw-ctrl-h| |netrw-mh|
preceded by the netrw-compatible url used to obtain it. When one subsequently
uses one of the go to tag actions (|tags|), the url will be used by netrw to
edit the desired file and go to the tag.
Associated setting variables: |g:netrw_ctags| |g:netrw_ssh_cmd|
*g:netrw_compress* ="gzip"
Will compress marked files with this
command
*g:netrw_ctags* ="ctags"
The default external program used to create tags
*g:netrw_cursor* = 2 (default)
This option controls the use of the
|'cursorline'| (cul) and |'cursorcolumn'|
(cuc) settings by netrw:
Value Thin-Long-Tree Wide
=0 u-cul u-cuc u-cul u-cuc
=1 u-cul u-cuc cul u-cuc
=2 cul u-cuc cul u-cuc
=3 cul u-cuc cul cuc
=4 cul cuc cul cuc
Where
u-cul : user's |'cursorline'| setting used
u-cuc : user's |'cursorcolumn'| setting used
cul : |'cursorline'| locally set
cuc : |'cursorcolumn'| locally set
g:netrw_sort_options
variable's value is appended to the
sort command. Thus one may ignore case,
for example, with the following in your
.vimrc:
let g:netrw_sort_options="i"
default: ""
==============================================================================
OBTAINING A FILE *netrw-O* {{{2
If there are no marked files:
When browsing a remote directory, one may obtain a file under the cursor
(ie. get a copy on your local machine, but not edit it) by pressing the O
key.
If there are marked files:
The marked files will be obtained (ie. a copy will be transferred to your
local machine, but not set up for editing).
Only ftp and scp are supported for this operation (but since these two are
available for browsing, that shouldn't be a problem). The status bar will
then show, on its right hand side, a message like "Obtaining filename". The
statusline will be restored after the transfer is complete.
Netrw can also "obtain" a file using the local browser. Netrw's display
of a directory is not necessarily the same as Vim's "current directory",
unless |g:netrw_keepdir| is set to 0 in the user's <.vimrc>. One may select
a file using the local browser (by putting the cursor on it) and pressing
"O" will then "obtain" the file; ie. copy it to Vim's current directory.
Related topics:
*netrw-createfile*
OPEN A NEW FILE IN NETRW'S CURRENT DIRECTORY *netrw-%*
To open a file in netrw's current directory, press "%". This map will
query the user for a new filename; an empty file by that name will be
placed in the netrw's current directory (ie. b:netrw_curdir).
*netrw-p2*
P2. I use Windows, and my network browsing with ftp doesn't sort by
time or size! -or- The remote system is a Windows server; why
don't I get sorts by time or size?
Windows' ftp has a minimal support for ls (ie. it doesn't
accept sorting options). It doesn't support the -F which
gives an explanatory character (ABC/ for "ABC is a directory").
Netrw then uses "dir" to get both its thin and long listings.
If you think your ftp does support a full-up ls, put the
following into your <.vimrc>:
let g:netrw_ftp_list_cmd = "ls -lF"
let g:netrw_ftp_timelist_cmd= "ls -tlF"
let g:netrw_ftp_sizelist_cmd= "ls -slF"
Alternatively, if you have cygwin on your Windows box, put
into your <.vimrc>:
let g:netrw_cygwin= 1
*netrw-p3*
P3. I tried rcp://user@host/ (or protocol other than ftp) and netrw
used ssh! That wasn't what I asked for...
Netrw has two methods for browsing remote directories: ssh
and ftp. Unless you specify ftp specifically, ssh is used.
When it comes time to do download a file (not just a directory
listing), netrw will use the given protocol to do so.
*netrw-p4*
P4. I would like long listings to be the default.
Put the following statement into your YXXY.vimrc|:
let g:netrw_liststyle= 1
Check out |netrw-browser-var| for more customizations that
you can set.
*netrw-p5*
P5. My times come up oddly in local browsing
Does your system's strftime() accept the "%c" to yield dates
such as "Sun Apr 27 11:49:23 1997"? If not, do a "man strftime"
and find out what option should be used. Then put it into
your YXXY.vimrc|:
let g:netrw_timefmt= "%X" (where X is the option)
*netrw-p6*
P6. I want my current directory to track my browsing.
How do I do that?
Put the following line in your YXXY.vimrc|:
let g:netrw_keepdir= 0
*netrw-p7*
P7. I use Chinese (or other non-ascii) characters in my filenames, and
netrw (Explore, Sexplore, Hexplore, etc) doesn't display them!
(taken from an answer provided by Wu Yongwei on the vim
mailing list)
I now see the problem. You code page is not 936, right? Vim
seems only able to open files with names that are valid in the
current code page, as are many other applications that do not
use the Unicode version of Windows APIs. This is an OS-related
issue. You should not have such problems when the system
locale uses UTF-8, such as modern Linux distros.
(...it is one more reason to recommend that people use utf-8!)
*netrw-p8*
P8. I'm getting "ssh is not executable on your system" -- what do I
do?
(Dudley Fox) Most people I know use putty for windows ssh. It
is a free ssh/telnet application. You can read more about it
here:
http://www.chiark.greenend.org.uk/~sgtatham/putty/ Also:
(Marlin Unruh) This program also works for me. It's a single
executable, so he/she can copy it into the Windows\System32
folder and create a shortcut to it.
(Dudley Fox) You might also wish to consider plink, as it
*netrw-p10*
P10. I'm being pestered with "[something] is a directory" and
"Press ENTER or type command to continue" prompts...
The "[something] is a directory" prompt is issued by Vim,
not by netrw, and there appears to be no way to work around
it. Coupled with the default cmdheight of 1, this message
causes the "Press ENTER..." prompt. So: read |hit-enter|;
I also suggest that you set your |'cmdheight'| to 2 (or more) in
your <.vimrc> file.
*netrw-p11*
P11. I want to have two windows; a thin one on the left and my editing
window on the right. How can I do this?
* Put the following line in your <.vimrc>:
let g:netrw_altv = 1
* Edit the current directory: :e .
* Select some file, press v
* Resize the windows as you wish (see |CTRL-W_<| and
|CTRL-W_>|). If you're using gvim, you can drag
the separating bar with your mouse.
* When you want a new file, use ctrl-w h to go back to the
netrw browser, select a file, then press P (see |CTRL-W_h|
and |netrw-P|). If you're using gvim, you can press
<leftmouse> in the browser window and then press the
<middlemouse> to select the file.
*netrw-p12*
P12. My directory isn't sorting correctly, or unwanted letters are
appearing in the listed filenames, or things aren't lining
up properly in the wide listing, ...
This may be due to an encoding problem. I myself usually use
utf-8, but really only use ascii (ie. bytes from 32-126).
Multibyte encodings use two (or more) bytes per character.
You may need to change |g:netrw_sepchr| and/or |g:netrw_xstrlen|.
*netrw-p13*
P13. I'm a Windows + putty + ssh user, and when I attempt to browse,
the directories are missing trailing "/"s so netrw treats them
as file transfers instead of as attempts to browse
subdirectories. How may I fix this?
(mikeyao) If you want to use vim via ssh and putty under Windows,
try combining the use of pscp/psftp with plink. pscp/psftp will
be used to connect and plink will be used to execute commands on
the server, for example: list files and directory using 'ls'.
These are the settings I use to do this:
" list files, it's the key setting, if you haven't set,
" you will get a blank buffer
let g:netrw_list_cmd = "plink HOSTNAME ls -Fa"
" if you haven't add putty directory in system path, you should
" specify scp/sftp command. For examples:
"let g:netrw_sftp_cmd = "d:\\dev\\putty\\PSFTP.exe"
"let g:netrw_scp_cmd = "d:\\dev\\putty\\PSCP.exe"
==============================================================================
11. Debugging Netrw Itself *netrw-debug* {{{1
The <netrw.vim> script is typically available as something like:
/usr/local/share/vim/vim7x/plugin/netrwPlugin.vim
/usr/local/share/vim/vim7x/autoload/netrw.vim
-or-
/usr/local/share/vim/vim6x/plugin/netrwPlugin.vim
/usr/local/share/vim/vim6x/autoload/netrw.vim
which is loaded automatically at startup (assuming :set nocp).
1. Get the <Decho.vim> script, available as:
http://mysite.verizon.net/astronaut/vim/index.html#DECHO
or
http://vim.sourceforge.net/scripts/script.php?script_id=120
It now comes as a "vimball"; if you're using vim 7.0 or earlier,
you'll need to update vimball, too. See
http://mysite.verizon.net/astronaut/vim/index.html#VIMBALL
2. Edit the <netrw.vim> file by typing:
vim netrw.vim
:DechoOn
:wq
To restore to normal non-debugging behavior, re-edit <netrw.vim>
and type
vim netrw.vim
:DechoOff
:wq
This command, provided by <Decho.vim>, will comment out all
Decho-debugging statements (Dfunc(), Dret(), Decho(), Dredir()).
3. Then bring up vim and attempt to evoke the problem by doing a
transfer or doing some browsing. A set of messages should appear
concerning the steps that <netrw.vim> took in attempting to
read/write your file over the network in a separate tab.
To save the file, use
:tabnext
:set bt=
:w! DBG
Please send that information to <netrw.vim>'s maintainer,
NdrOchip at ScampbellPfamily.AbizM - NOSPAM
==============================================================================
12. History *netrw-history* {{{1
v141: Aug 28, 2010 * added -s:... support for Windows ftp
* restored 2-leftmouse for :Rex-like return
* added balloon help for banner
Oct 26, 2010 * :Texplore changed to start from netrw's idea
of the current directory, not pwd's
Feb 10, 2011 * netrwPlugin modified to use BufReadCmd
when the "filename" ends with a "/" or a "\"
Avoids "... is a directory" message, works
inside a try-catch-endtry clause.
Feb 22, 2011 * for menus, &go =~# used to insure correct case
v140: Jul 27, 2010 * (Lech Lorens) unexpected change of window
v139: May 14, 2010 * when viewing remote directory listings and
changing listing style, going to tree listing
mode was issuing two rather useless messages
about the buffer name. They have now been
silenced.
* (Jean Johner) with "behave mswin", clicking
on a filename in wide mode opened a new file
with a missing first letter
* (Britton Kerin) wanted netrw listings to be
buflisted; the |g:netrw_bufsettings| option
permits that.
Jun 18, 2010 * (Jan Steffens) added support for xz compression
Jun 23, 2010 * vimdiff dir1 dir2 now works
Jul 27, 2010 * (John Orr) pointed out that the intended maparg
test for gx was actually testing for g rather
than gx. Fixed.
v138: May 01, 2010 * added the bomb setting to the Save-Set-Restore
option handling (for Tony M)
May 14, 2010 * (Bram Moolenaar) netrw optionally sets cursorline
(and sometimes cursorcolumn) for its display.
This option setting was leaking through with
remote file handling.
v137: Dec 28, 2009 * modified the preview window handling for
vertically split windows. The preview
window will take up all but g:netrw_winsize
columns of the original window; those
g:netrw_winsize columns will be used for
the netrw listing.
preference.
v118: Jan 02, 2008 * Fixed a problem with Windows;
:Explore c:/path/ would not work,
but :Explore c:/path would.
* Fixed a bug in s:NetrwOptionRestore() - lcd's
argument wasn't being properly escaped so it
wouldn't handle spaces in directory names.
(Gary Johnson)
v117: Jan 02, 2008 * Fixed a problem with P; had to include
a b:netrw_curdir bypass (Bram Moolenaar)
v116: Nov 27, 2007 * netrw#LocalBrowseCheck() has &ft=="netrw"
check to prevent doing a directory listing
(was getting unexpected directory refreshes
in the middle of some function calls)
* NetrwOptionRestore moved after e! filename
in order to retain user options for editing
in s:NetrwBrowseChgDir()
Dec 12, 2007 * Bug fix -- netrw does a better job of retaining
user options when editing files under the aegis
of the browser
v115: Oct 04, 2007 * Erik Remmelzwaal pointed out that the use of
shellslash in s:GetTempfile() was incorrect
Oct 11, 2007 * Tracked down and eliminated a bug with editing
remote *.tar.gz and *.tar.bz2 files
Oct 11, 2007 * g:netrw_localmovecmd wasn't being initialized
properly, and g:netrw_localcopycmd was being
overwritten.
Oct 12, 2007 * Placed all :Rexplore and <2-leftmouse> setup
in a new support function (s:SetRexDir()).
Oct 15, 2007 * new: g:netrw_browse_split == 4; means <cr>
based selection will use previous window
Oct 20, 2007 * also checks on |'shellxquote'| to set g:netrw_shq
Oct 24, 2007 * Explore handles path/**/filename
Oct 27, 2007 * sourcing remote files often didn't work with ftp,
turns out that b:netrw_method was undefined, so
s:SaveBufVars and s:RestoreBufVars() fixed it.
v114: Sep 28, 2007 * mT, the map that invokes tags, has been improved
to support use of remote tags files.
Oct 02, 2007 * changed Netrw menu to use more submenus
v113: Sep 07, 2007 * worked out why the cursor position wasn't being
saved and restored as intended after doing such
things as deleting and renaming files.
Sep 11, 2007 * Fixed bug which effectively disabled <c-l> and
<c-h> maps
Sep 18, 2007 * there used to be one NetrwOptionRestore() call at
the end of the s:NetrwBrowseChgDir() function;
they're now at the end of every if..elseif..else
block. The edit-a-file one is not quite at the end
of its block; instead, it's just before the edit.
Restores user options, then this new placement
allows ftplugins, autocmds, etc to change settings
(ex. ftplugin/cpp.vim sets cindent).
Sep 19, 2007 * changed all strlen() calls to use s:Strlen(), a
function which handles utf-8 wide characters
correctly.
Sep 20, 2007 * (Nico Weber) the "x" command has been extended
to Mac's OS/X (macunix); it now uses open to
handle |netrw-x| browsing with special files.
Sep 22, 2007 * Added g:netrw_noretmap to netrw at Tony M's
request.
* Included path to NetrwRemoteRmFile()
v112: Aug 18, 2007 * added mx (|netrw-mx|) for executing arbitrary
commands on marked files
Aug 22, 2007 * more option save/restore work for
s:NetrwBrowseChgDir(); s:NetrwOptionSave()
and s:NetrwOptionRestore() now take a parameter
specifying the type of variables to be used for
saving and restoring (either "w:" or "s:")
Sep 04, 2007 * added the :NetrwClean[!] command
v111: Jul 25, 2007 * using Windows but not using Cygwin, netrw does a
"file bufname" where the bufname uses /s
instead of \s; Vim "fixes" it by changing the
bufname to use \s anyway. This meant that
NetrwGetBuffer() didn't find the appropriately
named buffer, and so would generate a new
buffer listing; hence the cursor would appear
to have been moved when doing a preview.
* added <2-leftmouse> map to return to netrw's
browser display
Aug 16, 2007 * added the mark-file system, including
maps for mf mp mt mz and mu. Modifications
==============================================================================
13. Todo *netrw-todo* {{{1
07/29/09 : banner :|g:netrw_banner| can be used to suppress the
suppression banner. This feature is new and experimental,
so its in the process of being debugged.
09/04/09 : "gp" : See if it can be made to work for remote systems.
: See if it can be made to work with marked files.
==============================================================================
14. Credits *netrw-credits* {{{1
Vim editor by Bram Moolenaar (Thanks, Bram!)
dav support by C Campbell
fetch support by Bram Moolenaar and C Campbell
ftp support by C Campbell <NdrOchip@ScampbellPfamily.AbizM>
http support by Bram Moolenaar <bram@moolenaar.net>
rcp
rsync support by C Campbell (suggested by Erik Warendorph)
scp support by raf <raf@comdyn.com.au>
sftp support by C Campbell
inputsecret(), BufReadCmd, BufWriteCmd contributed by C Campbell
Jérôme Augé -- also using new buffer method with ftp+.netrc
Bram Moolenaar -- obviously vim itself, :e and v:cmdarg use,
fetch,...
Yasuhiro Matsumoto -- pointing out undo+0r problem and a solution
Erik Warendorph -- for several suggestions (g:netrw_..._cmd
variables, rsync etc)
Doug Claar -- modifications to test for success with ftp
operation
==============================================================================
Modelines: {{{1
top - main help file
Vim can be tuned to work like you want it to. This chapter shows you how to
make Vim start with options set to different values. Add plugins to extend
Vim's capabilities. Or define your own macros.
|05.1| The vimrc file
|05.2| The example vimrc file explained
|05.3| Simple mappings
|05.4| Adding a plugin
|05.5| Adding a help file
|05.6| The option window
|05.7| Often used options
Next chapter: |usr_06.txt| Using syntax highlighting
Previous chapter: |usr_04.txt| Making small changes
Table of contents: |usr_toc.txt|
==============================================================================
*05.1* The vimrc file *vimrc-intro*
You probably got tired of typing commands that you use very often. To start
Vim with all your favorite option settings and mappings, you write them in
what is called the vimrc file. Vim executes the commands in this file when it
starts up.
If you already have a vimrc file (e.g., when your sysadmin has one setup for
you), you can edit it this way:
:edit $MYVIMRC
If you don't have a vimrc file yet, see |vimrc| to find out where you can
create a vimrc file. Also, the ":version" command mentions the name of the
"user vimrc file" Vim looks for.
For Unix and Macintosh this file is always used and is recommended:
~/.vimrc
For MS-DOS and MS-Windows you can use one of these:
$HOME/_vimrc
$VIM/_vimrc
The vimrc file can contain all the commands that you type after a colon. The
most simple ones are for setting options. For example, if you want Vim to
always start with the 'incsearch' option on, add this line you your vimrc
file:
set incsearch
For this new line to take effect you need to exit Vim and start it again.
Later you will learn how to do this without exiting Vim.
This chapter only explains the most basic items. For more information on how
to write a Vim script file: |usr_41.txt|.
==============================================================================
*05.2* The example vimrc file explained *vimrc_example.vim*
In the first chapter was explained how the example vimrc (included in the
Vim distribution) file can be used to make Vim startup in not-compatible mode
(see |not-compatible|). The file can be found here:
$VIMRUNTIME/vimrc_example.vim
In this section we will explain the various commands used in this file. This
will give you hints about how to set up your own preferences. Not everything
will be explained though. Use the ":help" command to find out more.
set nocompatible
As mentioned in the first chapter, these manuals explain Vim working in an
improved way, thus not completely Vi compatible. Setting the 'compatible'
option off, thus 'nocompatible' takes care of this.
set backspace=indent,eol,start
This specifies where in Insert mode the <BS> is allowed to delete the
character in front of the cursor. The three items, separated by commas, tell
Vim to delete the white space at the start of the line, a line break and the
character before where Insert mode started.
set autoindent
This makes Vim use the indent of the previous line for a newly created line.
Thus there is the same amount of white space before the new line. For example
when pressing <Enter> in Insert mode, and when using the "o" command to open a
new line.
if has("vms")
set nobackup
else
set backup
endif
This tells Vim to keep a backup copy of a file when overwriting it. But not
on the VMS system, since it keeps old versions of files already. The backup
file will have the same name as the original file with "~" added. See |07.4|
set history=50
Keep 50 commands and 50 search patterns in the history. Use another number if
you want to remember fewer or more lines.
set ruler
Always display the current cursor position in the lower right corner of the
Vim window.
set showcmd
Display an incomplete command in the lower right corner of the Vim window,
left of the ruler. For example, when you type "2f", Vim is waiting for you to
type the character to find and "2f" is displayed. When you press "w" next,
the "2fw" command is executed and the displayed "2f" is removed.
+-------------------------------------------------+
|text in the Vim window |
|~ |
|~ |
|-- VISUAL -- 2f 43,8 17% |
+-------------------------------------------------+
^^^^^^^^^^^ ^^^^^^^^ ^^^^^^^^^^
'showmode' 'showcmd' 'ruler'
set incsearch
Display the match for a search pattern when halfway typing it.
map Q gq
This defines a key mapping. More about that in the next section. This
defines the "Q" command to do formatting with the "gq" operator. This is how
it worked before Vim 5.0. Otherwise the "Q" command starts Ex mode, but you
will not need it.
*vimrc-filetype*
filetype plugin indent on
This switches on three very clever mechanisms:
1. Filetype detection.
Whenever you start editing a file, Vim will try to figure out what kind of
file this is. When you edit "main.c", Vim will see the ".c" extension and
recognize this as a "c" filetype. When you edit a file that starts with
"#!/bin/sh", Vim will recognize it as a "sh" filetype.
The filetype detection is used for syntax highlighting and the other two
items below.
See |filetypes|.
2. Using filetype plugin files
Many different filetypes are edited with different options. For example,
when you edit a "c" file, it's very useful to set the 'cindent' option to
automatically indent the lines. These commonly useful option settings are
included with Vim in filetype plugins. You can also add your own, see
|write-filetype-plugin|.
3. Using indent files
When editing programs, the indent of a line can often be computed
automatically. Vim comes with these indent rules for a number of
filetypes. See |:filetype-indent-on| and 'indentexpr'.
*restore-cursor*
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
Another autocommand. This time it is used after reading any file. The
complicated stuff after it checks if the '"' mark is defined, and jumps to it
if so. The backslash at the start of a line is used to continue the command
from the previous line. That avoids a line getting very long.
See |line-continuation|. This only works in a Vim script file, not when
typing commands at the command-line.
==============================================================================
*05.3* Simple mappings
A mapping enables you to bind a set of Vim commands to a single key. Suppose,
for example, that you need to surround certain words with curly braces. In
other words, you need to change a word such as "amount" into "{amount}". With
the :map command, you can tell Vim that the F5 key does this job. The command
is as follows:
:map <F5> i{<Esc>ea}<Esc>
Note:
When entering this command, you must enter <F5> by typing four
characters. Similarly, <Esc> is not entered by pressing the <Esc>
key, but by typing five characters. Watch out for this difference
when reading the manual!
Let's break this down:
<F5> The F5 function key. This is the trigger key that causes the
command to be executed as the key is pressed.
i{<Esc> Insert the { character. The <Esc> key ends Insert mode.
e Move to the end of the word.
a}<Esc> Append the } to the word.
After you execute the ":map" command, all you have to do to put {} around a
word is to put the cursor on the first character and press F5.
In this example, the trigger is a single key; it can be any string. But when
you use an existing Vim command, that command will no longer be available.
You better avoid that.
One key that can be used with mappings is the backslash. Since you
probably want to define more than one mapping, add another character. You
could map "\p" to add parentheses around a word, and "\c" to add curly braces,
for example:
:map \p i(<Esc>ea)<Esc>
:map \c i{<Esc>ea}<Esc>
You need to type the \ and the p quickly after another, so that Vim knows they
belong together.
The ":map" command (with no arguments) lists your current mappings. At
least the ones for Normal mode. More about mappings in section |40.1|.
==============================================================================
*05.4* Adding a plugin *add-plugin* *plugin*
Vim's functionality can be extended by adding plugins. A plugin is nothing
more than a Vim script file that is loaded automatically when Vim starts. You
can add a plugin very easily by dropping it in your plugin directory.
{not available when Vim was compiled without the |+eval| feature}
There are two types of plugins:
global plugin: Used for all kinds of files
filetype plugin: Only used for a specific type of file
The global plugins will be discussed first, then the filetype ones
|add-filetype-plugin|.
*add-global-plugin*
You can add a global plugin to add functionality that will always be present
when you use Vim. There are only two steps for adding a global plugin:
If that file already exists you already have a plugin for "stuff". You might
want to check if the existing plugin doesn't conflict with the one you are
adding. If it's OK, you can give the new one another name:
mv thefile ~/.vim/ftplugin/stuff_too.vim
The underscore is used to separate the name of the filetype from the rest,
which can be anything. If you use "otherstuff.vim" it wouldn't work, it would
be loaded for the "otherstuff" filetype.
On MS-DOS you cannot use long filenames. You would run into trouble if you
add a second plugin and the filetype has more than six characters. You can
use an extra directory to get around this:
mkdir $VIM/vimfiles/ftplugin/fortran
copy thefile $VIM/vimfiles/ftplugin/fortran/too.vim
The generic names for the filetype plugins are:
ftplugin/<filetype>.vim
ftplugin/<filetype>_<name>.vim
ftplugin/<filetype>/<name>.vim
Here "<name>" can be any name that you prefer.
Examples for the "stuff" filetype on Unix:
~/.vim/ftplugin/stuff.vim
~/.vim/ftplugin/stuff_def.vim
~/.vim/ftplugin/stuff/header.vim
The <filetype> part is the name of the filetype the plugin is to be used for.
Only files of this filetype will use the settings from the plugin. The <name>
part of the plugin file doesn't matter, you can use it to have several plugins
for the same filetype. Note that it must end in ".vim".
Further reading:
|filetype-plugins| Documentation for the filetype plugins and information
about how to avoid that mappings cause problems.
|load-plugins| When the global plugins are loaded during startup.
|ftplugin-overrule| Overruling the settings from a global plugin.
|write-plugin| How to write a plugin script.
|plugin-details| For more information about using plugins or when your
plugin doesn't work.
|new-filetype| How to detect a new file type.
==============================================================================
*05.5* Adding a help file *add-local-help* *matchit-install*
If you are lucky, the plugin you installed also comes with a help file. We
will explain how to install the help file, so that you can easily find help
for your new plugin.
Let us use the "matchit.vim" plugin as an example (it is included with
Vim). This plugin makes the "%" command jump to matching HTML tags,
if/else/endif in Vim scripts, etc. Very useful, although it's not backwards
compatible (that's why it is not enabled by default).
This plugin comes with documentation: "matchit.txt". Let's first copy the
plugin to the right directory. This time we will do it from inside Vim, so
that we can use $VIMRUNTIME. (You may skip some of the "mkdir" commands if
you already have the directory.)
:!mkdir ~/.vim
:!mkdir ~/.vim/plugin
:!cp $VIMRUNTIME/macros/matchit.vim ~/.vim/plugin
The "cp" command is for Unix, on MS-DOS you can use "copy".
Now create a "doc" directory in one of the directories in 'runtimepath'.
:!mkdir ~/.vim/doc
Copy the help file to the "doc" directory.
:!cp $VIMRUNTIME/macros/matchit.txt ~/.vim/doc
Now comes the trick, which allows you to jump to the subjects in the new help
file: Generate the local tags file with the |:helptags| command.
:helptags ~/.vim/doc
Now you can use the
:help g%
command to find help for "g%" in the help file you just added. You can see an
entry for the local help file when you do:
:help local-additions
The title lines from the local help files are automagically added to this
section. There you can see which local help files have been added and jump to
them through the tag.
For writing a local help file, see |write-local-help|.
==============================================================================
*05.6* The option window
If you are looking for an option that does what you want, you can search in
the help files here: |options|. Another way is by using this command:
:options
This opens a new window, with a list of options with a one-line explanation.
The options are grouped by subject. Move the cursor to a subject and press
<Enter> to jump there. Press <Enter> again to jump back. Or use CTRL-O.
You can change the value of an option. For example, move to the "displaying
text" subject. Then move the cursor down to this line:
set wrap nowrap
When you hit <Enter>, the line will change to:
set nowrap wrap
The option has now been switched off.
Just above this line is a short description of the 'wrap' option. Move the
cursor one line up to place it in this line. Now hit <Enter> and you jump to
the full help on the 'wrap' option.
For options that take a number or string argument you can edit the value.
Then press <Enter> to apply the new value. For example, move the cursor a few
lines up to this line:
set so=0
Position the cursor on the zero with "$". Change it into a five with "r5".
Then press <Enter> to apply the new value. When you now move the cursor
around you will notice that the text starts scrolling before you reach the
border. This is what the 'scrolloff' option does, it specifies an offset
from the window border where scrolling starts.
==============================================================================
*05.7* Often used options
There are an awful lot of options. Most of them you will hardly ever use.
Some of the more useful ones will be mentioned here. Don't forget you can
find more help on these options with the ":help" command, with single quotes
before and after the option name. For example:
:help 'wrap'
In case you have messed up an option value, you can set it back to the
default by putting an ampersand (&) after the option name. Example:
:set iskeyword&
:set nowrap
Vim will automatically scroll the text when you move to text that is not
displayed. To see a context of ten characters, do this:
:set sidescroll=10
This doesn't change the text in the file, only the way it is displayed.
VIEWING TABS
When there are tabs in a file, you cannot see where they are. To make them
visible:
:set list
Now every tab is displayed as ^I. And a $ is displayed at the end of each
line, so that you can spot trailing spaces that would otherwise go unnoticed.
A disadvantage is that this looks ugly when there are many Tabs in a file.
If you have a color terminal, or are using the GUI, Vim can show the spaces
and tabs as highlighted characters. Use the 'listchars' option:
:set listchars=tab:>-,trail:-
Now every tab will be displayed as ">---" (with more or less "-") and trailing
white space as "-". Looks a lot better, doesn't it?
KEYWORDS
The 'iskeyword' option specifies which characters can appear in a word:
:set iskeyword
iskeyword=@,48-57,_,192-255
The "@" stands for all alphabetic letters. "48-57" stands for ASCII
characters 48 to 57, which are the numbers 0 to 9. "192-255" are the
printable latin characters.
Sometimes you will want to include a dash in keywords, so that commands
like "w" consider "upper-case" to be one word. You can do it like this:
:set iskeyword+=-
:set iskeyword
iskeyword=@,48-57,_,192-255,-
If you look at the new value, you will see that Vim has added a comma for you.
To remove a character use "-=". For example, to remove the underscore:
:set iskeyword-=_
:set iskeyword
iskeyword=@,48-57,192-255,-
This time a comma is automatically deleted.
*athena-intellimouse*
If you have an Intellimouse and an X server that supports using the wheel,
then you can use the wheel to scroll the text up and down in gvim. This works
with XFree86 4.0 and later, and with some older versions when you add patches.
See |scroll-mouse-wheel|.
For older versions of XFree86 you must patch your X server. The following
page has a bit of information about using the Intellimouse on Linux as well as
links to the patches and X server binaries (may not have the one you need
though):
http://www.inria.fr/koala/colas/mouse-wheel-scroll/
==============================================================================
3. Mouse Control *gui-mouse*
The mouse only works if the appropriate flag in the 'mouse' option is set.
When the GUI is switched on, and 'mouse' wasn't set yet, the 'mouse' option is
automatically set to "a", enabling it for all modes except for the
|hit-enter| prompt. If you don't want this, a good place to change the
'mouse' option is the "gvimrc" file.
Other options that are relevant:
'mousefocus' window focus follows mouse pointer |gui-mouse-focus|
'mousemodel' what mouse button does which action
'mousehide' hide mouse pointer while typing text
'selectmode' whether to start Select mode or Visual mode
A quick way to set these is with the ":behave" command.
*:behave* *:be*
:be[have] {model} Set behavior for mouse and selection. Valid
arguments are:
mswin MS-Windows behavior
xterm Xterm behavior
Using ":behave" changes these options:
option mswin xterm
'selectmode' "mouse,key" ""
'mousemodel' "popup" "extend"
'keymodel' "startsel,stopsel" ""
'selection' "exclusive" "inclusive"
In the $VIMRUNTIME directory, there is a script called |mswin.vim|, which will
also map a few keys to the MS-Windows cut/copy/paste commands. This is NOT
compatible, since it uses the CTRL-V, CTRL-X and CTRL-C keys. If you don't
mind, use this command:
:so $VIMRUNTIME/mswin.vim
For scrolling with a wheel on a mouse, see |scroll-mouse-wheel|.
*gui-mouse-focus*
The 'mousefocus' option can be set to make the keyboard focus follow the
mouse pointer. This means that the window where the mouse pointer is, is the
active window. Warning: this doesn't work very well when using a menu,
because the menu command will always be applied to the top window.
If you are on the ':' line (or '/' or '?'), then clicking the left or right
mouse button will position the cursor on the ':' line (if 'mouse' contains
'c', 'a' or 'A').
In any situation the middle mouse button may be clicked to paste the current
selection.
<S-RightMouse> Search backward for the word under the mouse click.
<C-LeftMouse> Jump to the tag name under the mouse click.
<C-RightMouse> Jump back to position before the previous tag jump
(same as "CTRL-T")
*quotestar*
You may make selections with the mouse (see |gui-mouse-select|), or by using
Vim's Visual mode (see |v|). If 'a' is present in 'guioptions', then
whenever a selection is started (Visual or Select mode), or when the selection
is changed, Vim becomes the owner of the windowing system's primary selection
(on MS-Windows the |gui-clipboard| is used; under X11, the |x11-selection| is
used - you should read whichever of these is appropriate now).
*clipboard*
There is a special register for storing this selection, it is the "*
register. Nothing is put in here unless the information about what text is
selected is about to change (e.g. with a left mouse click somewhere), or when
another application wants to paste the selected text. Then the text is put
in the "* register. For example, to cut a line and make it the current
selection/put it on the clipboard:
"*dd
Similarly, when you want to paste a selection from another application, e.g.,
by clicking the middle mouse button, the selection is put in the "* register
first, and then 'put' like any other register. For example, to put the
selection (contents of the clipboard):
"*p
When using this register under X11, also see |x11-selection|. This also
explains the related "+ register.
Note that when pasting text from one Vim into another separate Vim, the type
of selection (character, line, or block) will also be copied. For other
applications the type is always character. However, if the text gets
transferred via the |x11-cut-buffer|, the selection type is ALWAYS lost.
When the "unnamed" string is included in the 'clipboard' option, the unnamed
register is the same as the "* register. Thus you can yank to and paste the
selection without prepending "* to commands.
==============================================================================
5. Menus *menus*
For an introduction see |usr_42.txt| in the user manual.
*menu.vim*
The default menus are read from the file "$VIMRUNTIME/menu.vim". See
|$VIMRUNTIME| for where the path comes from. You can set up your own menus.
Starting off with the default set is a good idea. You can add more items, or,
if you don't like the defaults at all, start with removing all menus
|:unmenu-all|. You can also avoid the default menus being loaded by adding
this line to your .vimrc file (NOT your .gvimrc file!):
:let did_install_default_menus = 1
If you also want to avoid the Syntax menu:
:let did_install_syntax_menu = 1
The first item in the Syntax menu can be used to show all available filetypes
in the menu (which can take a bit of time to load). If you want to have all
filetypes already present at startup, add:
:let do_syntax_sel_menu = 1
*console-menus*
Although this documentation is in the GUI section, you can actually use menus
in console mode too. You will have to load |menu.vim| explicitly then, it is
not done by default. You can use the |:emenu| command and command-line
completion with 'wildmenu' to access the menu entries almost like a real menu
system. To do this, put these commands in your .vimrc file:
:source $VIMRUNTIME/menu.vim
:set wildmenu
:set cpo-=<
:set wcm=<C-Z>
:map <F4> :emenu <C-Z>
Pressing <F4> will start the menu. You can now use the cursor keys to select
a menu entry. Hit <Enter> to execute it. Hit <Esc> if you want to cancel.
This does require the |+menu| feature enabled at compile time.
*tear-off-menus*
GTK+ and Motif support Tear-off menus. These are sort of sticky menus or
pop-up menus that are present all the time. If the resizing does not work
correctly, this may be caused by using something like "Vim*geometry" in the
defaults. Use "Vim.geometry" instead.
The Win32 GUI version emulates Motif's tear-off menus. Actually, a Motif user
will spot the differences easily, but hopefully they're just as useful. You
can also use the |:tearoff| command together with |hidden-menus| to create
floating menus that do not appear on the main menu bar.
because of the CTRL-O. If you have two or more commands, you will need to use
the ":imenu" command. For inserting text in any mode, you can use the
expression register:
:amenu Insert.foobar "='foobar'<CR>P
Note that the '<' and 'k' flags in 'cpoptions' also apply here (when
included they make the <> form and raw key codes not being recognized).
Note that <Esc> in Cmdline mode executes the command, like in a mapping. This
is Vi compatible. Use CTRL-C to quit Cmdline mode.
*:menu-<silent>* *:menu-silent*
To define a menu which will not be echoed on the command line, add
"<silent>" as the first argument. Example:
:menu <silent> Settings.Ignore\ case :set ic<CR>
The ":set ic" will not be echoed when using this menu. Messages from the
executed command are still given though. To shut them up too, add a ":silent"
in the executed command:
:menu <silent> Search.Header :exe ":silent normal /Header\r"<CR>
"<silent>" may also appear just after "<special>" or "<script>".
*:menu-<special>* *:menu-special*
Define a menu with <> notation for special keys, even though the "<" flag
may appear in 'cpoptions'. This is useful if the side effect of setting
'cpoptions' is not desired. Example:
:menu <special> Search.Header /Header<CR>
"<special>" must appear as the very first argument to the ":menu" command or
just after "<silent>" or "<script>".
*:menu-<script>* *:menu-script*
The "to" part of the menu will be inspected for mappings. If you don't want
this, use the ":noremenu" command (or the similar one for a specific mode).
If you do want to use script-local mappings, add "<script>" as the very first
argument to the ":menu" command or just after "<silent>" or "<special>".
*menu-priority*
You can give a priority to a menu. Menus with a higher priority go more to
the right. The priority is given as a number before the ":menu" command.
Example:
:80menu Buffer.next :bn<CR>
The default menus have these priorities:
File 10
Edit 20
Tools 40
Syntax 50
Buffers 60
Window 70
Help 9999
When no or zero priority is given, 500 is used.
The priority for the PopUp menu is not used.
The Help menu will be placed on the far right side of the menu bar on systems
which support this (Motif and GTK+). For GTK+ 2, this is not done anymore
because right-aligning the Help menu is now discouraged UI design.
You can use a priority higher than 9999, to make it go after the Help menu,
but that is non-standard and is discouraged. The highest possible priority is
about 32000. The lowest is 1.
*sub-menu-priority*
The same mechanism can be used to position a sub-menu. The priority is then
given as a dot-separated list of priorities, before the menu name:
:menu 80.500 Buffer.next :bn<CR>
Giving the sub-menu priority is only needed when the item is not to be put
in a normal position. For example, to put a sub-menu before the other items:
:menu 80.100 Buffer.first :brew<CR>
Or to put a sub-menu after the other items, and further items with default
priority will be put before it:
:menu 80.900 Buffer.last :blast<CR>
When a number is missing, the default value 500 will be used:
:menu .900 myMenu.test :echo "text"<CR>
The menu priority is only used when creating a new menu. When it already
existed, e.g., in another mode, the priority will not change. Thus, the
priority only needs to be given the first time a menu is used.
An exception is the PopUp menu. There is a separate menu for each mode
(Normal, Op-pending, Visual, Insert, Cmdline). The order in each of these
menus can be different. This is different from menu-bar menus, which have
the same order for all modes.
NOTE: sub-menu priorities currently don't work for all versions of the GUI.
*menu-separator* *E332*
Menu items can be separated by a special item that inserts some space between
items. Depending on the system this is displayed as a line or a dotted line.
These items must start with a '-' and end in a '-'. The part in between is
used to give it a unique name. Priorities can be used as with normal items.
Example:
:menu Example.item1 :do something
:menu Example.-Sep- :
:menu Example.item2 :do something different
Note that the separator also requires a rhs. It doesn't matter what it is,
because the item will never be selected. Use a single colon to keep it
simple.
*gui-toolbar*
The toolbar is currently available in the Win32, Athena, Motif, GTK+ (X11),
and Photon GUI. It should turn up in other GUIs in due course. The
default toolbar is setup in menu.vim.
The display of the toolbar is controlled by the 'guioptions' letter 'T'. You
can thus have menu & toolbar together, or either on its own, or neither.
The appearance is controlled by the 'toolbar' option. You can choose between
an image, text or both.
*toolbar-icon*
The toolbar is defined as a special menu called ToolBar, which only has one
level. Vim interprets the items in this menu as follows:
1) If an "icon=" argument was specified, the file with this name is used.
The file can either be specified with the full path or with the base name.
In the last case it is searched for in the "bitmaps" directory in
'runtimepath', like in point 3. Examples:
:amenu icon=/usr/local/pixmaps/foo_icon.xpm ToolBar.Foo :echo "Foo"<CR>
:amenu icon=FooIcon ToolBar.Foo :echo "Foo"<CR>
Note that in the first case the extension is included, while in the second
case it is omitted.
If the file cannot be opened the next points are tried.
A space in the file name must be escaped with a backslash.
A menu priority must come _after_ the icon argument:
:amenu icon=foo 1.42 ToolBar.Foo :echo "42!"<CR>
2) An item called 'BuiltIn##', where ## is a number, is taken as number ## of
the built-in bitmaps available in Vim. Currently there are 31 numbered
from 0 to 30 which cover most common editing operations |builtin-tools|.
:amenu ToolBar.BuiltIn22 :call SearchNext("back")<CR>
3) An item with another name is first searched for in the directory
"bitmaps" in 'runtimepath'. If found, the bitmap file is used as the
toolbar button image. Note that the exact filename is OS-specific: For
example, under Win32 the command
:amenu ToolBar.Hello :echo "hello"<CR>
would find the file 'hello.bmp'. Under GTK+/X11 it is 'Hello.xpm'. With
GTK+ 2 the files 'Hello.png', 'Hello.xpm' and 'Hello.bmp' are checked for
existence, and the first one found would be used.
For MS-Windows and GTK+ 2 the bitmap is scaled to fit the button. For
MS-Windows a size of 18 by 18 pixels works best.
For MS-Windows the bitmap should have 16 colors with the standard palette.
The light grey pixels will be changed to the Window frame color and the
dark grey pixels to the window shadow color. More colors might also work,
depending on your system.
4) If the bitmap is still not found, Vim checks for a match against its list
of built-in names. Each built-in button image has a name.
So the command
:amenu ToolBar.Open :e
will show the built-in "open a file" button image if no open.bmp exists.
All the built-in names can be seen used in menu.vim.
5) If all else fails, a blank, but functioning, button is displayed.
*builtin-tools*
nr Name Normal action
00 New open new window
*hidden-menus* *win32-hidden-menus*
In the Win32 and GTK+ GUI, starting a menu name with ']' excludes that menu
from the main menu bar. You must then use the |:popup| or |:tearoff| command
to display it.
*popup-menu*
In the Win32, GTK+, Motif, Athena and Photon GUI, you can define the
special menu "PopUp". This is the menu that is displayed when the right mouse
button is pressed, if 'mousemodel' is set to popup or popup_setpos.
When using a range, if the lines match with '<,'>, then the menu is executed
using the last visual selection.
*:unme* *:unmenu*
*:aun* *:aunmenu*
*:nunme* *:nunmenu*
*:ounme* *:ounmenu*
*:vunme* *:vunmenu*
*:xunme* *:xunmenu*
*:sunme* *:sunmenu*
*:iunme* *:iunmenu*
*:cunme* *:cunmenu*
To delete a menu item or a whole submenu, use the unmenu commands, which are
analogous to the unmap commands. Eg:
:unmenu! Edit.Paste
This will remove the Paste item from the Edit menu for Insert and
Command-line modes.
Note that hitting <Tab> while entering a menu name after an umenu command
may be used to complete the name of the menu item for the appropriate mode.
*:menu-disable* *:menu-enable*
If you do not want to remove a menu, but disable it for a moment, this can be
done by adding the "enable" or "disable" keyword to a ":menu" command.
Examples:
:menu disable &File.&Open\.\.\.
:amenu enable *
:amenu disable &Tools.*
The command applies to the modes as used with all menu commands. Note that
characters like "&" need to be included for translated names to be found.
When the argument is "*", all menus are affected. Otherwise the given menu
name and all existing submenus below it are affected.
*:tmenu* *:tm*
:tm[enu] {menupath} {rhs} Define a tip for a menu or tool. {only in
X11 and Win32 GUI}
:tm[enu] [menupath] List menu tips. {only in X11 and Win32 GUI}
*:tunmenu* *:tu*
:tu[nmenu] {menupath} Remove a tip for a menu or tool.
{only in X11 and Win32 GUI}
When a tip is defined for a menu item, it appears in the command-line area
when the mouse is over that item, much like a standard Windows menu hint in
the status bar. (Except when Vim is in Command-line mode, when of course
nothing is displayed.)
When a tip is defined for a ToolBar item, it appears as a tooltip when the
mouse pauses over that button, in the usual fashion. Use the |hl-Tooltip|
highlight group to change its colors.
A "tip" can be defined for each menu item. For example, when defining a menu
item like this:
:amenu MyMenu.Hello :echo "Hello"<CR>
The tip is defined like this:
:tmenu MyMenu.Hello Displays a greeting.
And delete it with:
:tunmenu MyMenu.Hello
Tooltips are currently only supported for the X11 and Win32 GUI. However, they
should appear for the other gui platforms in the not too distant future.
The ":tmenu" command works just like other menu commands, it uses the same
arguments. ":tunmenu" deletes an existing menu tip, in the same way as the
other unmenu commands.
If a menu item becomes invalid (i.e. its actions in all modes are deleted) Vim
deletes the menu tip (and the item) for you. This means that :aunmenu deletes
a menu item - you don't need to do a :tunmenu as well.
*:popup* *:popu*
:popu[p] {name} Popup the menu {name}. The menu named must
have at least one subentry, but need not
appear on the menu-bar (see |hidden-menus|).
{only available for Win32 and GTK GUI}
:popu[p]! {name} Like above, but use the position of the mouse
pointer instead of the cursor.
Example:
:popup File
will make the "File" menu (if there is one) appear at the text cursor (mouse
pointer if ! was used).
:amenu ]Toolbar.Make :make<CR>
:popup ]Toolbar
This creates a popup menu that doesn't exist on the main menu-bar.
Note that a menu that starts with ']' will not be displayed.
==============================================================================
6. Extras *gui-extras*
This section describes other features which are related to the GUI.
- With the GUI, there is no wait for one second after hitting escape, because
the key codes don't start with <Esc>.
- Typing ^V followed by a special key in the GUI will insert "<Key>", since
the internal string used is meaningless. Modifiers may also be held down to
get "<Modifiers-Key>".
- In the GUI, the modifiers SHIFT, CTRL, and ALT (or META) may be used within
mappings of special keys and mouse events. E.g.: :map <M-LeftDrag> <LeftDrag>
- In the GUI, several normal keys may have modifiers in mappings etc, these
are <Space>, <Tab>, <NL>, <CR>, <Esc>.
- To check in a Vim script if the GUI is being used, you can use something
like this:
if has("gui_running")
echo "yes, we have a GUI"
else
echo "Boring old console"
endif
*setting-guifont*
- When you use the same vimrc file on various systems, you can use something
like this to set options specifically for each type of GUI:
if has("gui_running")
if has("gui_gtk2")
:set guifont=Luxi\ Mono\ 12
elseif has("x11")
" Also for GTK 1
:set guifont=*-lucidatypewriter-medium-r-normal-*-*-180-*-*-m-*-*
elseif has("gui_win32")
:set guifont=Luxi_Mono:h12:cANSI
endif
endif
A recommended Japanese font is MS Mincho. You can find info here:
http://www.lexikan.com/mincho.htm
==============================================================================
7. Shell Commands *gui-shell*
For the X11 GUI the external commands are executed inside the gvim window.
See |gui-pty|.
WARNING: Executing an external command from the X11 GUI will not always
work. "normal" commands like "ls", "grep" and "make" mostly work fine.
Commands that require an intelligent terminal like "less" and "ispell" won't
work. Some may even hang and need to be killed from another terminal. So be
careful!
For the Win32 GUI the external commands are executed in a separate window.
See |gui-shell-win32|.
top - main help file
*:au* *:autocmd*
*:autocmd-verbose*
When 'verbose' is non-zero, listing an autocommand will also display where it
was last defined. Example:
:verbose autocmd BufEnter
FileExplorer BufEnter
* call s:LocalBrowse(expand("<amatch>"))
Last set from /usr/share/vim/vim-7.0/plugin/NetrwPlugin.vim
See |:verbose-cmd| for more information.
==============================================================================
5. Events *autocmd-events* *E215* *E216*
You can specify a comma-separated list of event names. No white space can be
used in this list. The command applies to all the events in the list.
For READING FILES there are four kinds of events possible:
BufNewFile starting to edit a non-existent file
BufReadPre BufReadPost starting to edit an existing file
FilterReadPre FilterReadPost read the temp file with filter output
FileReadPre FileReadPost any other file read
Vim uses only one of these four kinds when reading a file. The "Pre" and
"Post" events are both triggered, before and after reading the file.
Note that the autocommands for the *ReadPre events and all the Filter events
are not allowed to change the current buffer (you will get an error message if
this happens). This is to prevent the file to be read into the wrong buffer.
Note that the 'modified' flag is reset AFTER executing the BufReadPost
and BufNewFile autocommands. But when the 'modified' option was set by the
autocommands, this doesn't happen.
You can use the 'eventignore' option to ignore a number of events or all
events.
*autocommand-events* *{event}*
Vim recognizes the following events. Vim ignores the case of event names
(e.g., you can use "BUFread" or "bufread" instead of "BufRead").
First an overview by function with a short explanation. Then the list
alphabetically with full explanations |autocmd-events-abc|.
Name triggered by
Reading
|BufNewFile| starting to edit a file that doesn't exist
|BufReadPre| starting to edit a new buffer, before reading the file
|BufRead| starting to edit a new buffer, after reading the file
|BufReadPost| starting to edit a new buffer, after reading the file
|BufReadCmd| before starting to edit a new buffer |Cmd-event|
|FileReadPre| before reading a file with a ":read" command
|FileReadPost| after reading a file with a ":read" command
|FileReadCmd| before reading a file with a ":read" command |Cmd-event|
*BufCreate* *BufAdd*
BufAdd or BufCreate Just after creating a new buffer which is
added to the buffer list, or adding a buffer
to the buffer list.
Also used just after a buffer in the buffer
list has been renamed.
The BufCreate event is for historic reasons.
NOTE: When this autocommand is executed, the
current buffer "%" may be different from the
buffer being created "<afile>".
*BufDelete*
BufDelete Before deleting a buffer from the buffer list.
The BufUnload may be called first (if the
buffer was loaded).
Also used just before a buffer in the buffer
list is renamed.
NOTE: When this autocommand is executed, the
current buffer "%" may be different from the
buffer being deleted "<afile>" and "<abuf>".
Don't change to another buffer, it will cause
problems.
*BufEnter*
BufEnter After entering a buffer. Useful for setting
options for a file type. Also executed when
starting to edit a buffer, after the
BufReadPost autocommands.
*BufFilePost*
BufFilePost After changing the name of the current buffer
with the ":file" or ":saveas" command.
*BufFilePre*
BufFilePre Before changing the name of the current buffer
with the ":file" or ":saveas" command.
*BufHidden*
BufHidden Just after a buffer has become hidden. That
is, when there are no longer windows that show
the buffer, but the buffer is not unloaded or
deleted. Not used for ":qa" or ":q" when
exiting Vim.
NOTE: When this autocommand is executed, the
current buffer "%" may be different from the
buffer being unloaded "<afile>".
*BufLeave*
BufLeave Before leaving to another buffer. Also when
leaving or closing the current window and the
new current window is not for the same buffer.
Not used for ":qa" or ":q" when exiting Vim.
*BufNew*
*CursorHold*
CursorHold When the user doesn't press a key for the time
specified with 'updatetime'. Not re-triggered
until the user has pressed a key (i.e. doesn't
fire every 'updatetime' ms if you leave Vim to
make some coffee. :) See |CursorHold-example|
for previewing tags.
This event is only triggered in Normal mode.
It is not triggered when waiting for a command
argument to be typed, or a movement after an
operator.
While recording the CursorHold event is not
triggered. |q|
Note: Interactive commands cannot be used for
this event. There is no hit-enter prompt,
the screen is updated directly (when needed).
Note: In the future there will probably be
another option to set the time.
Hint: to force an update of the status lines
use:
:let &ro = &ro
{only on Amiga, Unix, Win32, MSDOS and all GUI
versions}
*CursorHoldI*
CursorHoldI Just like CursorHold, but in Insert mode.
*CursorMoved*
CursorMoved After the cursor was moved in Normal mode.
Also when the text of the cursor line has been
changed, e.g., with "x", "rx" or "p".
Not triggered when there is typeahead or when
an operator is pending.
For an example see |match-parens|.
Careful: Don't do anything that the user does
not expect or that is slow.
*CursorMovedI*
The file name that the pattern is matched against is after expanding
wildcards. Thus if you issue this command:
:e $ROOTDIR/main.$EXT
The argument is first expanded to:
/usr/root/main.py
Before it's matched with the pattern of the autocommand. Careful with this
when using events like FileReadCmd, the value of <amatch> may not be what you
expect.
*file-pattern*
The pattern is interpreted like mostly used in file names:
* matches any sequence of characters
? matches any single character
\? matches a '?'
. matches a '.'
~ matches a '~'
, separates patterns
\, matches a ','
{ } like \( \) in a |pattern|
, inside { }: like \| in a |pattern||||
\ special meaning like in a |pattern|
[ch] matches 'c' or 'h'
[^ch] match any character but 'c' and 'h'
Note that for all systems the '/' character is used for path separator (even
MS-DOS and OS/2). This was done because the backslash is difficult to use
in a pattern and to make the autocommands portable across different systems.
*autocmd-changes*
Matching with the pattern is done when an event is triggered. Changing the
buffer name in one of the autocommands, or even deleting the buffer, does not
change which autocommands will be executed. Example:
au BufEnter *.foo bdel
au BufEnter *.foo set modified
This will delete the current buffer and then set 'modified' in what has become
the current buffer instead. Vim doesn't take into account that "*.foo"
doesn't match with that buffer name. It matches "*.foo" with the name of the
buffer at the moment the event was triggered.
However, buffer-local autocommands will not be executed for a buffer that has
been wiped out with |:bwipe|. After deleting the buffer with |:bdel| the
buffer actually still exists (it becomes unlisted), thus the autocommands are
still executed.
==============================================================================
*:aug* *:augroup*
:aug[roup] {name} Define the autocmd group name for the
following ":autocmd" commands. The name "end"
or "END" selects the default group.
*:augroup-delete* *E367*
:aug[roup]! {name} Delete the autocmd group {name}. Don't use
this if there is still an autocommand using
this group! This is not checked.
To enter autocommands for a specific group, use this method:
1. Select the group with ":augroup {name}".
2. Delete any old autocommands with ":au!".
3. Define the autocommands.
4. Go back to the default group with "augroup END".
Example:
:augroup uncompress
: au!
: au BufEnter *.gz %!gunzip
:augroup END
This prevents having the autocommands defined twice (e.g., after sourcing the
.vimrc file again).
==============================================================================
9. Executing autocommands *autocmd-execute*
Vim can also execute Autocommands non-automatically. This is useful if you
have changed autocommands, or when Vim has executed the wrong autocommands
(e.g., the file pattern match was wrong).
Note that the 'eventignore' option applies here too. Events listed in this
option will not cause any commands to be executed.
*:doautoa* *:doautoall*
:doautoa[ll] [group] {event} [fname]
Like ":doautocmd", but apply the autocommands to each
loaded buffer. Note that [fname] is used to select
the autocommands, not the buffers to which they are
applied.
Careful: Don't use this for autocommands that delete a
buffer, change to another buffer or change the
contents of a buffer; the result is unpredictable.
This command is intended for autocommands that set
options, change highlighting, and things like that.
==============================================================================
10. Using autocommands *autocmd-use*
For WRITING FILES there are four possible sets of events. Vim uses only one
of these sets for a write command:
*gzip-example*
Examples for reading and writing compressed files:
:augroup gzip
: autocmd!
: autocmd BufReadPre,FileReadPre *.gz set bin
: autocmd BufReadPost,FileReadPost *.gz '[,']!gunzip
: autocmd BufReadPost,FileReadPost *.gz set nobin
: autocmd BufReadPost,FileReadPost *.gz execute ":doautocmd BufReadPost " . expand("%:r")
: autocmd BufWritePost,FileWritePost *.gz !mv <afile> <afile>:r
: autocmd BufWritePost,FileWritePost *.gz !gzip <afile>:r
: autocmd FileAppendPre *.gz !gunzip <afile>
: autocmd FileAppendPre *.gz !mv <afile>:r <afile>
: autocmd FileAppendPost *.gz !mv <afile> <afile>:r
: autocmd FileAppendPost *.gz !gzip <afile>:r
:augroup END
The "gzip" group is used to be able to delete any existing autocommands with
":autocmd!", for when the file is sourced twice.
("<afile>:r" is the file name without the extension, see |:_%:|)
The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost,
FileAppendPost and VimLeave events do not set or reset the changed flag of the
buffer. When you decompress the buffer with the BufReadPost autocommands, you
can still exit with ":q". When you use ":undo" in BufWritePost to undo the
changes made by BufWritePre commands, you can still do ":q" (this also makes
"ZZ" work). If you do want the buffer to be marked as modified, set the
'modified' option.
To execute Normal mode commands from an autocommand, use the ":normal"
command. Use with care! If the Normal mode command is not finished, the user
needs to type characters (e.g., after ":normal m" you need to type a mark
name).
If you want the buffer to be unmodified after changing it, reset the
'modified' option. This makes it possible to exit the buffer with ":q"
instead of ":q!".
*autocmd-nested* *E218*
*autocommand-pattern*
You can specify multiple patterns, separated by commas. Here are some
examples:
:autocmd BufRead * set tw=79 nocin ic infercase fo=2croq
:autocmd BufRead .letter set tw=72 fo=2tcrq
:autocmd BufEnter .letter set dict=/usr/lib/dict/words
:autocmd BufLeave .letter set dict=
:autocmd BufRead,BufNewFile *.c,*.h set tw=0 cin noic
:autocmd BufEnter *.c,*.h abbr FOR for (i = 0; i < 3; ++i)<CR>{<CR>}<Esc>O
:autocmd BufLeave *.c,*.h unabbr FOR
For makefiles (makefile, Makefile, imakefile, makefile.unix, etc.):
:autocmd BufEnter ?akefile* set include=^s\=include
:autocmd BufLeave ?akefile* set include&
To always start editing C files at the first function:
:autocmd BufRead *.c,*.h 1;/^{
Without the "1;" above, the search would start from wherever the file was
entered, rather than from the start of the file.
*skeleton* *template*
To read a skeleton (template) file when opening a new file:
:autocmd BufNewFile *.c 0r ~/vim/skeleton.c
:autocmd BufNewFile *.h 0r ~/vim/skeleton.h
:autocmd BufNewFile *.java 0r ~/vim/skeleton.java
To insert the current date and time in a *.html file when writing it:
:autocmd BufWritePre,FileWritePre *.html ks|call LastMod()|'s
:fun LastMod()
: if line("$") > 20
: let l = 20
: else
: let l = line("$")
: endif
: exe "1," . l . "g/Last modified: /s/Last modified: .*/Last modified: " .
: \ strftime("%Y %b %d")
:endfun
You need to have a line "Last modified: <date time>" in the first 20 lines
of the file for this to work. Vim replaces <date time> (and anything in the
same line after it) with the current date and time. Explanation:
ks mark current position with mark 's'
call LastMod() call the LastMod() function to do the work
's return the cursor to the old position
The LastMod() function checks if the file is shorter than 20 lines, and then
uses the ":g" command to find lines that contain "Last modified: ". For those
lines the ":s" command is executed to replace the existing date with the
current one. The ":execute" command is used to be able to use an expression
for the ":g" and ":s" commands. The date is obtained with the strftime()
function. You can change its argument to get another date string.
When entering :autocmd on the command-line, completion of events and command
names may be done (with <Tab>, CTRL-D, etc.) where appropriate.
Vim executes all matching autocommands in the order that you specify them.
It is recommended that your first autocommand be used for all files by using
"*" as the file pattern. This means that you can define defaults you like
here for any settings, and if there is another matching autocommand it will
override these. But if there is no other matching autocommand, then at least
your default settings are recovered (if entering this file from another for
which autocommands did match). Note that "*" will also match files starting
with ".", unlike Unix shells.
*autocmd-searchpat*
Autocommands do not change the current search patterns. Vim saves the current
search patterns before executing autocommands then restores them after the
autocommands finish. This means that autocommands do not affect the strings
highlighted with the 'hlsearch' option. Within autocommands, you can still
use search patterns normally, e.g., with the "n" command.
If you want an autocommand to set the search pattern, such that it is used
after the autocommand finishes, use the ":let @/ =" command.
The search-highlighting cannot be switched off with ":nohlsearch" in an
autocommand. Use the 'h' flag in the 'viminfo' option to disable search-
highlighting when starting Vim.
*Cmd-event*
When using one of the "*Cmd" events, the matching autocommands are expected to
do the file reading, writing or sourcing. This can be used when working with
a special kind of file, for example on a remote system.
CAREFUL: If you use these events in a wrong way, it may have the effect of
making it impossible to read or write the matching files! Make sure you test
your autocommands properly. Best is to use a pattern that will never match a
normal file name, for example "ftp://*".
When defining a BufReadCmd it will be difficult for Vim to recover a crashed
editing session. When recovering from the original file, Vim reads only those
parts of a file that are not found in the swap file. Since that is not
possible with a BufReadCmd, use the |:preserve| command to make sure the
original file isn't needed for recovery. You might want to do this only when
you expect the file to be modified.
For file read and write commands the |v:cmdarg| variable holds the "++enc="
and "++ff=" argument that are effective. These should be used for the command
that reads/writes the file. The |v:cmdbang| variable is one when "!" was
used, zero otherwise.
See the $VIMRUNTIME/plugin/netrwPlugin.vim for examples.
==============================================================================
11. Disabling autocommands *autocmd-disable*
To disable autocommands for some time use the 'eventignore' option. Note that
this may cause unexpected behavior, make sure you restore 'eventignore'
afterwards, using a |:try| block with |:finally|.
*:noautocmd* *:noa*
To disable autocommands for just one command use the ":noautocmd" command
modifier. This will set 'eventignore' to "all" for the duration of the
following command. Example:
:noautocmd w fname.gz
This will write the file without triggering the autocommands defined by the
gzip plugin.
*location-list* *E776*
A location list is similar to a quickfix list and contains a list of positions
in files. A location list is associated with a window and each window can
have a separate location list. A location list can be associated with only
one window. The location list is independent of the quickfix list.
When a window with a location list is split, the new window gets a copy of the
location list. When there are no references to a location list, the location
list is destroyed.
The following quickfix commands can be used. The location list commands are
similar to the quickfix commands, replacing the 'c' prefix in the quickfix
command with 'l'.
*:cc*
:cc[!] [nr] Display error [nr]. If [nr] is omitted, the same
*:ll*
:ll[!] [nr] Same as ":cc", except the location list for the
current window is used instead of the quickfix list.
*:lne* *:lnext*
:[count]lne[xt][!] Same as ":cnext", except the location list for the
current window is used instead of the quickfix list.
*:cnf* *:cnfile*
:[count]cnf[ile][!] Display the first error in the [count] next file in
the list that includes a file name. If there are no
file names at all or if there is no next file, go to
the [count] next error. See |:cc| for [!] and
'switchbuf'.
*:lnf* *:lnfile*
:[count]lnf[ile][!] Same as ":cnfile", except the location list for the
current window is used instead of the quickfix list.
*:crewind* *:cr*
:cr[ewind][!] [nr] Display error [nr]. If [nr] is omitted, the FIRST
error is displayed. See |:cc|.
*:lrewind* *:lr*
:lr[ewind][!] [nr] Same as ":crewind", except the location list for the
current window is used instead of the quickfix list.
*:cfirst* *:cfir*
:cfir[st][!] [nr] Same as ":crewind".
*:lfirst* *:lfir*
:lfir[st][!] [nr] Same as ":lrewind".
*:clast* *:cla*
:cla[st][!] [nr] Display error [nr]. If [nr] is omitted, the LAST
error is displayed. See |:cc|.
*:llast* *:lla*
:lla[st][!] [nr] Same as ":clast", except the location list for the
current window is used instead of the quickfix list.
*:cq* *:cquit*
:cq[uit][!] Quit Vim with an error code, so that the compiler
will not compile the same file again.
WARNING: All changes in files are lost! Also when the
[!] is not used. It works like ":qall!" |:qall|,
except that Vim returns a non-zero exit code.
*:cf* *:cfile*
:cf[ile][!] [errorfile] Read the error file and jump to the first error.
This is done automatically when Vim is started with
the -q option. You can use this command when you
keep Vim running while compiling. If you give the
name of the errorfile, the 'errorfile' option will
be set to [errorfile]. See |:cc| for [!].
*:lf* *:lfile*
:lf[ile][!] [errorfile] Same as ":cfile", except the location list for the
current window is used instead of the quickfix list.
You can not use the -q command-line option to set
the location list.
*:caddf* *:caddfile*
:caddf[ile] [errorfile] Read the error file and add the errors from the
errorfile to the current quickfix list. If a quickfix
list is not present, then a new list is created.
*:laddf* *:laddfile*
:laddf[ile] [errorfile] Same as ":caddfile", except the location list for the
current window is used instead of the quickfix list.
*:lb* *:lbuffer*
:lb[uffer][!] [bufnr] Same as ":cbuffer", except the location list for the
current window is used instead of the quickfix list.
*:cgetb* *:cgetbuffer*
:cgetb[uffer] [bufnr] Read the error list from the current buffer. Just
like ":cbuffer" but don't jump to the first error.
*:lgetb* *:lgetbuffer*
:lgetb[uffer] [bufnr] Same as ":cgetbuffer", except the location list for
the current window is used instead of the quickfix
list.
*:caddb* *:caddbuffer*
:caddb[uffer] [bufnr] Read the error list from the current buffer and add
the errors to the current quickfix list. If a
quickfix list is not present, then a new list is
created. Otherwise, same as ":cbuffer".
*:laddb* *:laddbuffer*
:laddb[uffer] [bufnr] Same as ":caddbuffer", except the location list for
the current window is used instead of the quickfix
list.
*:lex* *:lexpr*
:lex[pr][!] {expr} Same as ":cexpr", except the location list for the
current window is used instead of the quickfix list.
*:cgete* *:cgetexpr*
:cgete[xpr] {expr} Create a quickfix list using the result of {expr}.
Just like ":cexpr", but don't jump to the first error.
*:lgete* *:lgetexpr*
:lgete[xpr] {expr} Same as ":cgetexpr", except the location list for the
current window is used instead of the quickfix list.
*:cad* *:caddexpr*
:cad[dexpr] {expr} Evaluate {expr} and add the resulting lines to the
current quickfix list. If a quickfix list is not
present, then a new list is created. The current
cursor position will not be changed. See |:cexpr| for
more information.
Example:
:g/mypattern/caddexpr expand("%") . ":" . line(".") . ":" . getline(".")
*:lad* *:laddexpr*
:lad[dexpr] {expr} Same as ":caddexpr", except the location list for the
current window is used instead of the quickfix list.
*:cl* *:clist*
:cl[ist] [from] [, [to]]
List all errors that are valid |quickfix-valid|.
If numbers [from] and/or [to] are given, the respective
range of errors is listed. A negative number counts
from the last error backwards, -1 being the last error.
The 'switchbuf' settings are respected when jumping
to a buffer.
*:lli* *:llist*
:lli[st] [from] [, [to]]
Same as ":clist", except the location list for the
current window is used instead of the quickfix list.
:lli[st]! [from] [, [to]]
List all the entries in the location list for the
current window.
If you insert or delete lines, mostly the correct error location is still
found because hidden marks are used. Sometimes, when the mark has been
deleted for some reason, the message "line changed" is shown to warn you that
the error location may not be correct. If you quit Vim and start again the
marks are lost and the error locations may not be correct anymore.
If vim is built with |+autocmd| support, two autocommands are available for
running commands before and after a quickfix command (':make', ':grep' and so
on) is executed. See |QuickFixCmdPre| and |QuickFixCmdPost| for details.
*QuickFixCmdPost-example*
When 'encoding' differs from the locale, the error messages may have a
different encoding from what Vim is using. To convert the messages you can
use this code:
function QfMakeConv()
let qflist = getqflist()
for i in qflist
let i.text = iconv(i.text, "cp936", "utf-8")
endfor
call setqflist(qflist)
endfunction
au QuickfixCmdPost make call QfMakeConv()
=============================================================================
2. The error window *quickfix-window*
*:lop* *:lopen*
:lop[en] [height] Open a window to show the location list for the
current window. Works only when the location list for
the current window is present. You can have more than
one location window opened at a time. Otherwise, it
acts the same as ":copen".
*:ccl* *:cclose*
:ccl[ose] Close the quickfix window.
*:lcl* *:lclose*
:lcl[ose] Close the window showing the location list for the
current window.
*:cw* *:cwindow*
:cw[indow] [height] Open the quickfix window when there are recognized
*:lw* *:lwindow*
:lw[indow] [height] Same as ":cwindow", except use the window showing the
location list for the current window.
Normally the quickfix window is at the bottom of the screen. If there are
vertical splits, it's at the bottom of the rightmost column of windows. To
make it always occupy the full width:
:botright cwindow
You can move the window around with |window-moving| commands.
For example, to move it to the top: CTRL-W K
The 'winfixheight' option will be set, which means that the window will mostly
keep its height, ignoring 'winheight' and 'equalalways'. You can change the
height manually (e.g., by dragging the status line above it with the mouse).
In the quickfix window, each line is one error. The line number is equal to
the error number. You can use ":.cc" to jump to the error under the cursor.
Hitting the <Enter> key or double-clicking the mouse on a line has the same
effect. The file containing the error is opened in the window above the
quickfix window. If there already is a window for that file, it is used
instead. If the buffer in the used window has changed, and the error is in
another file, jumping to the error will fail. You will first have to make
sure the window contains a buffer which can be abandoned.
*CTRL-W_<Enter>* *CTRL-W_<CR>*
You can use CTRL-W <Enter> to open a new window and jump to the error there.
When the quickfix window has been filled, two autocommand events are
triggered. First the 'filetype' option is set to "qf", which triggers the
FileType event. Then the BufReadPost event is triggered, using "quickfix" for
the buffer name. This can be used to perform some action on the listed
errors. Example:
au BufReadPost quickfix setlocal modifiable
\ | silent exe 'g/^/s//\=line(".")." "/'
\ | setlocal nomodifiable
This prepends the line number to each line. Note the use of "\=" in the
substitute string of the ":s" command, which is used to evaluate an
expression.
The BufWinEnter event is also triggered, again using "quickfix" for the buffer
name.
Note: Making changes in the quickfix window has no effect on the list of
errors. 'modifiable' is off to avoid making changes. If you delete or insert
lines anyway, the relation between the text and the error number is messed up.
If you really want to do this, you could write the contents of the quickfix
window to a file and use ":cfile" to have it parsed and used as the new error
list.
*location-list-window*
The location list window displays the entries in a location list. When you
open a location list window, it is created below the current window and
displays the location list for the current window. The location list window
is similar to the quickfix window, except that you can have more than one
location list window open at a time. When you use a location list command in
this window, the displayed location list is used.
When you select a file from the location list window, the following steps are
used to find a window to edit the file:
1. If a window with the location list displayed in the location list window is
present, then the file is opened in that window.
2. If the above step fails and if the file is already opened in another
window, then that window is used.
3. If the above step fails then an existing window showing a buffer with
'buftype' not set is used.
4. If the above step fails, then the file is edited in a new window.
In all of the above cases, if the location list for the selected window is not
yet set, then it is set to the location list displayed in the location list
window.
=============================================================================
3. Using more than one list of errors *quickfix-error-lists*
So far has been assumed that there is only one list of errors. Actually the
ten last used lists are remembered. When starting a new list, the previous
ones are automatically kept. Two commands can be used to access older error
lists. They set one of the existing error lists as the current one.
*:lolder* *:lol*
:lol[der] [count] Same as ":colder", except use the location list for
the current window instead of the quickfix list.
*:lnewer* *:lnew*
:lnew[er] [count] Same as ":cnewer", except use the location list for
the current window instead of the quickfix list.
When adding a new error list, it becomes the current list.
When ":colder" has been used and ":make" or ":grep" is used to add a new error
list, one newer list is overwritten. This is especially useful if you are
browsing with ":grep" |grep|. If you want to keep the more recent error
lists, use ":cnewer 99" first.
=============================================================================
4. Using :make *:make_makeprg*
*:mak* *:make*
:mak[e][!] [arguments] 1. If vim was built with |+autocmd|, all relevant
|QuickFixCmdPre| autocommands are executed.
2. If the 'autowrite' option is on, write any changed
buffers
3. An errorfile name is made from 'makeef'. If
'makeef' doesn't contain "##", and a file with this
name already exists, it is deleted.
4. The program given with the 'makeprg' option is
started (default "make") with the optional
[arguments] and the output is saved in the
errorfile (for Unix it is also echoed on the
screen).
5. The errorfile is read using 'errorformat'.
6. If vim was built with |+autocmd|, all relevant
|QuickFixCmdPost| autocommands are executed.
See example below.
7. If [!] is not given the first error is jumped to.
8. The errorfile is deleted.
9. You can now move through the errors with commands
like |:cnext| and |:cprevious|, see above.
This command does not accept a comment, any "
characters are considered part of the arguments.
*:lmak* *:lmake*
:lmak[e][!] [arguments]
Same as ":make", except the location list for the
current window is used instead of the quickfix list.
The ":make" command executes the command given with the 'makeprg' option.
This is done by passing the command to the shell given with the 'shell'
option. This works almost like typing
":!{makeprg} [arguments] {shellpipe} {errorfile}".
{makeprg} is the string given with the 'makeprg' option. Any command can be
used, not just "make". Characters '%' and '#' are expanded as usual on a
command-line. You can use "%<" to insert the current file name without
extension, or "#<" to insert the alternate file name without extension, for
example:
:set makeprg=make\ #<.o
*:lv* *:lvimgrep*
:lv[imgrep][!] /{pattern}/[g][j] {file} ...
:lv[imgrep][!] {pattern} {file} ...
Same as ":vimgrep", except the location list for the
current window is used instead of the quickfix list.
*:vimgrepa* *:vimgrepadd*
:vimgrepa[dd][!] /{pattern}/[g][j] {file} ...
:vimgrepa[dd][!] {pattern} {file} ...
Just like ":vimgrep", but instead of making a new list
of errors the matches are appended to the current
list.
*:lvimgrepa* *:lvimgrepadd*
:lvimgrepa[dd][!] /{pattern}/[g][j] {file} ...
:lvimgrepa[dd][!] {pattern} {file} ...
Same as ":vimgrepadd", except the location list for
the current window is used instead of the quickfix
list.
5.2 External grep
Vim can interface with "grep" and grep-like programs (such as the GNU
id-utils) in a similar way to its compiler integration (see |:make| above).
[Unix trivia: The name for the Unix "grep" command comes from ":g/re/p", where
"re" stands for Regular Expression.]
*:gr* *:grep*
:gr[ep][!] [arguments] Just like ":make", but use 'grepprg' instead of
'makeprg' and 'grepformat' instead of 'errorformat'.
When 'grepprg' is "internal" this works like
|:vimgrep|. Note that the pattern needs to be
enclosed in separator characters then.
*:lgr* *:lgrep*
:lgr[ep][!] [arguments] Same as ":grep", except the location list for the
current window is used instead of the quickfix list.
*:grepa* *:grepadd*
:grepa[dd][!] [arguments]
Just like ":grep", but instead of making a new list of
errors the matches are appended to the current list.
Example:
:call setqflist([])
:bufdo grepadd! something %
The first command makes a new error list which is
empty. The second command executes "grepadd" for each
listed buffer. Note the use of ! to avoid that
":grepadd" jumps to the first error, which is not
allowed with |:bufdo|.
An example that uses the argument list and avoids
errors for files without matches:
:silent argdo try
\ | grepadd! something %
\ | catch /E480:/
\ | endtry"
*:lgrepa* *:lgrepadd*
:lgrepa[dd][!] [arguments]
Same as ":grepadd", except the location list for the
current window is used instead of the quickfix list.
5.3 Setting up external grep
If you have a standard "grep" program installed, the :grep command may work
well with the defaults. The syntax is very similar to the standard command:
:grep foo *.c
Will search all files with the .c extension for the substring "foo". The
arguments to :grep are passed straight to the "grep" program, so you can use
whatever options your "grep" supports.
By default, :grep invokes grep with the -n option (show file and line
numbers). You can change this with the 'grepprg' option. You will need to set
'grepprg' if:
a) You are using a program that isn't called "grep"
b) You have to call grep with a full path
c) You want to pass other options automatically (e.g. case insensitive
search.)
Once "grep" has executed, Vim parses the results using the 'grepformat'
option. This option works in the same way as the 'errorformat' option - see
that for details. You may need to change 'grepformat' from the default if
your grep outputs in a non-standard format, or you are using some other
program with a special format.
Once the results are parsed, Vim loads the first file containing a match and
jumps to the appropriate line, in the same way that it jumps to a compiler
error in |quickfix| mode. You can then use the |:cnext|, |:clist|, etc.
commands to see the other matches.
look for functions and the functions they call. For example, suppose that you
have to add an argument to the read_file() function. You enter this command:
:vimgrep /\<read_file\>/ *.c
You use ":cn" to go along the list of matches and add the argument. At one
place you have to get the new argument from a higher level function msg(), and
need to change that one too. Thus you use:
:vimgrep /\<msg\>/ *.c
While changing the msg() functions, you find another function that needs to
get the argument from a higher level. You can again use ":vimgrep" to find
these functions. Once you are finished with one function, you can use
:colder
to go back to the previous one.
This works like browsing a tree: ":vimgrep" goes one level deeper, creating a
list of branches. ":colder" goes back to the previous level. You can mix
this use of ":vimgrep" and "colder" to browse all the locations in a tree-like
way. If you do this consistently, you will find all locations without the
need to write down a "todo" list.
=============================================================================
6. Selecting a compiler *compiler-select*
The Vim plugins in the "compiler" directory will set options to use the
selected compiler. For ":compiler" local options are set, for ":compiler!"
global options.
*current_compiler*
To support older Vim versions, the plugins always use "current_compiler" and
not "b:current_compiler". What the command actually does is the following:
- Delete the "current_compiler" and "b:current_compiler" variables.
- Define the "CompilerSet" user command. With "!" it does ":set", without "!"
it does ":setlocal".
- Execute ":runtime! compiler/{name}.vim". The plugins are expected to set
options with "CompilerSet" and set the "current_compiler" variable to the
name of the compiler.
- Delete the "CompilerSet" user command.
- Set "b:current_compiler" to the value of "current_compiler".
- Without "!" the old value of "current_compiler" is restored.
following:
- Set the CCEDIT environment variable with the command:
mset "CCEDIT=vim -q"
- Compile with the -qf option. If the compiler finds any errors, Vim is
started and the cursor is positioned on the first error. The error message
will be displayed on the last line. You can go to other errors with the
commands mentioned above. You can fix the errors and write the file(s).
- If you exit Vim normally the compiler will re-compile the same file. If you
exit with the :cq command, the compiler will terminate. Do this if you
cannot fix the error, or if another file needs to be compiled first.
There are some restrictions to the Quickfix mode on the Amiga. The
compiler only writes the first 25 errors to the errorfile (Manx's
documentation does not say how to get more). If you want to find the others,
you will have to fix a few errors and exit the editor. After recompiling,
up to 25 remaining errors will be found.
If Vim was started from the compiler, the :sh and some :! commands will not
work, because Vim is then running in the same process as the compiler and
stdin (standard input) will not be interactive.
Note that you must specify a name of the file to process as an argument (to
process the right file when editing \input-ed or \include-ed file; portable
solution for substituting % for no arguments is welcome). This is not in the
semantics of make, where you specify a target, not source, but you may specify
filename without extension ".tex" and mean this as "make filename.dvi or
filename.pdf or filename.some_result_extension according to compiler".
Note: tex command line syntax is set to usable both for MikTeX (suggestion
by Srinath Avadhanula) and teTeX (checked by Artem Chuprina). Suggestion
from |errorformat-LaTeX| is too complex to keep it working for different
shells and OSes and also does not allow to use other available TeX options,
if any. If your TeX doesn't support "-interaction=nonstopmode", please
report it with different means to express \nonstopmode from the command line.
=============================================================================
7. The error format *error-file-format*
Basic items
%f file name (finds a string)
%l line number (finds a number)
%c column number (finds a number representing character
column of the error, (1 <tab> == 1 character column))
%v virtual column number (finds a number representing
screen column of the error (1 <tab> == 8 screen
columns))
%t error type (finds a single character)
%n error number (finds a number)
%m error message (finds a string)
%r matches the "rest" of a single-line file message %O/P/Q
%p pointer line (finds a sequence of '-', '.' or '' '' and
uses the length for the column number)
%*{conv} any scanf non-assignable conversion
%% the single '%' character
%s search text (finds a string)
The "%f" conversion may depend on the current 'isfname' setting. "~/" is
expanded to the home directory and environment variables are expanded.
The "%f" and "%m" conversions have to detect the end of the string. This
normally happens by matching following characters and items. When nothing is
following the rest of the line is matched. If "%f" is followed by a '%' or a
backslash, it will look for a sequence of 'isfname' characters.
On MS-DOS, MS-Windows and OS/2 a leading "C:" will be included in "%f", even
when using "%f:". This means that a file name which is a single alphabetical
letter will not be detected.
The "%p" conversion is normally followed by a "^". It's used for compilers
that output a line like:
^
or
---------^
to indicate the column of the error. This is to be used in a multi-line error
message. See |errorformat-javac| for a useful example.
The "%s" conversion specifies the text to search for to locate the error line.
The text is used as a literal string. The anchors "^" and "$" are added to
the text to locate the error line exactly matching the search text and the
text is prefixed with the "\V" atom to make it "very nomagic". The "%s"
conversion can be used to locate lines without a line number in the error
output. Like the output of the "grep" shell command.
When the pattern is present the line number will not be used.
Changing directory
The following uppercase conversion characters specify the type of special
format strings. At most one of them may be given as a prefix at the begin
of a single comma-separated format pattern.
Some compilers produce messages that consist of directory names that have to
be prepended to each file name read by %f (example: GNU make). The following
codes can be used to scan these directory names; they will be stored in an
internal directory stack. *E379*
%D "enter directory" format string; expects a following
%f that finds the directory name
%X "leave directory" format string; expects following %f
When defining an "enter directory" or "leave directory" format, the "%D" or
"%X" has to be given at the start of that substring. Vim tracks the directory
changes and prepends the current directory to each erroneous file found with a
relative path. See |quickfix-directory-stack| for details, tips and
limitations.
The codes '+' or '-' can be combined with the uppercase codes above; in that
case they have to precede the letter, e.g. '%+A' or '%-G':
%- do not include the matching multi-line in any output
%+ include the whole matching line in the %m error string
One prefix is only useful in combination with '+' or '-', namely %G. It parses
over lines containing general information like compiler version strings or
other headers that can be skipped.
%-G ignore this message
%+G general message
Pattern matching
The scanf()-like "%*[]" notation is supported for backward-compatibility
with previous versions of Vim. However, it is also possible to specify
(nearly) any Vim supported regular expression in format strings.
Since meta characters of the regular expression language can be part of
ordinary matching strings or file names (and therefore internally have to
be escaped), meta symbols have to be written with leading '%':
%\ The single '\' character. Note that this has to be
escaped ("%\\") in ":set errorformat=" definitions.
%. The single '.' character.
%# The single '*'(!) character.
%^ The single '^' character. Note that this is not
useful, the pattern already matches start of line.
%$ The single '$' character. Note that this is not
useful, the pattern already matches end of line.
%[ The single '[' character for a [] character range.
%~ The single '~' character.
When using character classes in expressions (see |/\i| for an overview),
terms containing the "\+" quantifier can be written in the scanf() "%*"
notation. Example: "%\\d%\\+" ("\d\+", "any number") is equivalent to "%*\\d".
Important note: The \(...\) grouping of sub-matches can not be used in format
specifications because it is reserved for internal conversions.
Examples
The format of the file from the Amiga Aztec compiler is:
filename>linenumber:columnnumber:errortype:errornumber:errormessage
filename name of the file in which the error was detected
linenumber line number where the error was detected
columnnumber column number where the error was detected
errortype type of the error, normally a single 'E' or 'W'
errornumber number of the error (for lookup in the manual)
errormessage description of the error
Filtering messages
If you have a compiler that produces error messages that do not fit in the
format string, you could write a program that translates the error messages
into this format. You can use this program with the ":make" command by
changing the 'makeprg' option. For example:
:set mp=make\ \\\|&\ error_filter
The backslashes before the pipe character are required to avoid it to be
recognized as a command separator. The backslash before each space is
required for the set command.
=============================================================================
8. The directory stack *quickfix-directory-stack*
Quickfix maintains a stack for saving all used directories parsed from the
make output. For GNU-make this is rather simple, as it always prints the
absolute path of all directories it enters and leaves. Regardless if this is
done via a 'cd' command in the makefile or with the parameter "-C dir" (change
to directory before reading the makefile). It may be useful to use the switch
"-w" to force GNU-make to print out the working directory before and after
processing.
Maintaining the correct directory is more complicated if you don't use
GNU-make. AIX-make for example doesn't print any information about its
working directory. Then you need to enhance the makefile. In the makefile of
LessTif there is a command which echoes "Making {target} in {dir}". The
special problem here is that it doesn't print information on leaving the
directory and that it doesn't print the absolute path.
To solve the problem with relative paths and missing "leave directory"
messages Vim uses following algorithm:
1) Check if the given directory is a subdirectory of the current directory.
If this is true, store it as the current directory.
2) If it is not a subdir of the current directory, try if this is a
subdirectory of one of the upper directories.
3) If the directory still isn't found, it is assumed to be a subdirectory
of Vim's current directory.
Additionally it is checked for every file, if it really exists in the
identified directory. If not, it is searched in all other directories of the
directory stack (NOT the directory subtree!). If it is still not found, it is
assumed that it is in Vim's current directory.
There are limitations in this algorithm. These examples assume that make just
prints information about entering a directory in the form "Making all in dir".
1) Assume you have following directories and files:
./dir1
./dir1/file1.c
./file1.c
If make processes the directory "./dir1" before the current directory and
there is an error in the file "./file1.c", you will end up with the file
"./dir1/file.c" loaded by Vim.
This can only be solved with a "leave directory" message.
2) Assume you have following directories and files:
./dir1
./dir1/dir2
./dir2
You get the following:
Make output Directory interpreted by Vim
------------------------ ----------------------------
Making all in dir1 ./dir1
Making all in dir2 ./dir1/dir2
Making all in dir2 ./dir1/dir2
This can be solved by printing absolute directories in the "enter directory"
message or by printing "leave directory" messages..
To avoid this problem, ensure to print absolute directory names and "leave
directory" messages.
Examples for Makefiles:
Unix:
libs:
for dn in $(LIBDIRS); do \
(cd $$dn; echo "Entering dir '$$(pwd)'"'; make); \
echo "Leaving dir"; \
done
Add
%DEntering\ dir\ '%f',%XLeaving\ dir
to your 'errorformat' to handle the above output.
Note that Vim doesn't check if the directory name in a "leave directory"
messages is the current directory. This is why you could just use the message
"Leaving dir".
=============================================================================
9. Specific error file formats *errorformats*
*errorformat-Jikes*
Jikes(TM), a source-to-bytecode Java compiler published by IBM Research,
produces simple multi-line error messages.
An 'errorformat' string matching the produced messages is shown below.
The following lines can be placed in the user's |vimrc| to overwrite Vim's
recognized default formats, or see |:set+=| how to install this format
additionally to the default.
:set efm=%A%f:%l:%c:%*\\d:%*\\d:,
\%C%*\\s%trror:%m,
\%+C%*[^:]%trror:%m,
\%C%*\\s%tarning:%m,
\%C%m
Jikes(TM) produces a single-line error message when invoked with the option
"+E", and can be matched with the following:
:setl efm=%f:%l:%v:%*\\d:%*\\d:%*\\s%m
*errorformat-javac*
This 'errorformat' has been reported to work well for javac, which outputs a
line with "^" to indicate the column of the error:
:setl efm=%A%f:%l:\ %m,%-Z%p^,%-C%.%#
or:
:setl efm=%A%f:%l:\ %m,%+Z%p^,%+C%.%#,%-G%.%#
Here is an alternative from Michael F. Lamb for Unix that filters the errors
first:
:setl errorformat=%Z%f:%l:\ %m,%A%p^,%-G%*[^sl]%.%#
:setl makeprg=javac\ %\ 2>&1\ \\\|\ vim-javac-filter
*errorformat-ant*
For ant http://jakarta.apache.org/ the above errorformat has to be modified
to honour the leading [javac] in front of each javac output line:
:set efm=%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%#
The 'errorformat' can also be configured to handle ant together with either
javac or jikes. If you're using jikes, you should tell ant to use jikes' +E
command line switch which forces jikes to generate one-line error messages.
This is what the second line (of a build.xml file) below does:
<property name = "build.compiler" value = "jikes"/>
<property name = "build.compiler.emacs" value = "true"/>
The 'errorformat' which handles ant with both javac and jikes is:
:set efm=\ %#[javac]\ %#%f:%l:%c:%*\\d:%*\\d:\ %t%[%^:]%#:%m,
\%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%#
*errorformat-jade*
parsing jade see http://www.jclark.com/ errors is simple:
:set efm=jade:%f:%l:%c:%t:%m
*errorformat-LaTeX*
The following is an example how an 'errorformat' string can be specified
for the (La)TeX typesetting system which displays error messages over
multiple lines. The output of ":clist" and ":cc" etc. commands displays
multi-lines in a single line, leading white space is removed.
It should be easy to adopt the above LaTeX errorformat to any compiler output
consisting of multi-line errors.
The commands can be placed in a |vimrc| file or some other Vim script file,
e.g. a script containing LaTeX related stuff which is loaded only when editing
LaTeX sources.
Make sure to copy all lines of the example (in the given order), afterwards
remove the comment lines. For the '\' notation at the start of some lines see
|line-continuation|.
First prepare 'makeprg' such that LaTeX will report multiple
errors; do not stop when the first error has occurred:
:set makeprg=latex\ \\\\nonstopmode\ \\\\input\\{$*}
Start of multi-line error messages:
:set efm=%E!\ LaTeX\ %trror:\ %m,
\%E!\ %m,
Start of multi-line warning messages; the first two also
include the line number. Meaning of some regular expressions:
- "%.%#" (".*") matches a (possibly empty) string
- "%*\\d" ("\d\+") matches a number
\%+WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%#,
\%+W%.%#\ at\ lines\ %l--%*\\d,
\%WLaTeX\ %.%#Warning:\ %m,
Possible continuations of error/warning messages; the first
one also includes the line number:
\%Cl.%l\ %m,
\%+C\ \ %m.,
\%+C%.%#-%.%#,
\%+C%.%#[]%.%#,
\%+C[]%.%#,
\%+C%.%#%[{}\\]%.%#,
\%+C<%.%#>%.%#,
\%C\ \ %m,
Lines that match the following patterns do not contain any
important information; do not include them in messages:
\%-GSee\ the\ LaTeX%m,
\%-GType\ \ H\ <return>%m,
\%-G\ ...%.%#,
\%-G%.%#\ (C)\ %.%#,
\%-G(see\ the\ transcript%.%#),
Generally exclude any empty or whitespace-only line from
being displayed:
\%-G\\s%#,
The LaTeX output log does not specify the names of erroneous
source files per line; rather they are given globally,
enclosed in parentheses.
The following patterns try to match these names and store
them in an internal stack. The patterns possibly scan over
the same input line (one after another), the trailing "%r"
conversion indicates the "rest" of the line that will be
parsed in the next go until the end of line is reached.
Overread a file name enclosed in '('...')'; do not push it
on a stack since the file apparently does not contain any
error:
\%+O(%f)%r,
Push a file name onto the stack. The name is given after '(':
\%+P(%f%r,
\%+P\ %\\=(%f%r,
\%+P%*[^()](%f%r,
\%+P[%\\d%[^()]%#(%f%r,
Pop the last stored file name when a ')' is scanned:
\%+Q)%r,
\%+Q%*[^()])%r,
\%+Q[%\\d%*[^()])%r
Note that in some cases file names in the LaTeX output log cannot be parsed
properly. The parser might have been messed up by unbalanced parentheses
then. The above example tries to catch the most relevant cases only.
You can customize the given setting to suit your own purposes, for example,
all the annoying "Overfull ..." warnings could be excluded from being
recognized as an error.
Alternatively to filtering the LaTeX compiler output, it is also possible
to directly read the *.log file that is produced by the [La]TeX compiler.
This contains even more useful information about possible error causes.
However, to properly parse such a complex file, an external filter should
be used. See the description further above how to make such a filter known
by Vim.
*errorformat-Perl*
In $VIMRUNTIME/tools you can find the efm_perl.pl script, which filters Perl
error messages into a format that quickfix mode will understand. See the
start of the file about how to use it. (This script is deprecated, see
|compiler-perl|.)
This file contains an alphabetical list of messages and error messages that
Vim produces. You can use this if you don't understand what the message
means. It is not complete though.
1. Old messages |:messages|
2. Error messages |error-messages|
3. Messages |messages|
==============================================================================
1. Old messages *:messages* *:mes* *message-history*
The ":messages" command can be used to view previously given messages. This
is especially useful when messages have been overwritten or truncated. This
depends on the 'shortmess' option.
The number of remembered messages is fixed at 20 for the tiny version and 200
for other versions.
*g<*
The "g<" command can be used to see the last page of previous command output.
This is especially useful if you accidentally typed <Space> at the hit-enter
prompt. You are then back at the hit-enter prompt and can then scroll further
back.
Note: when you stopped the output with "q" at the more prompt only up to that
point will be displayed.
The previous command output is cleared when another command produces output.
If you are using translated messages, the first printed line tells who
maintains the messages or the translations. You can use this to contact the
maintainer when you spot a mistake.
If you want to find help on a specific (error) message, use the ID at the
start of the message. For example, to get help on the message:
E72: Close error on swap file
or (translated):
E72: Errore durante chiusura swap file
Use:
:help E72
If you are lazy, it also works without the shift key:
:help e72
==============================================================================
2. Error messages *error-messages* *errors*
When an error message is displayed, but it is removed before you could read
it, you can see it again with:
:echo errmsg
LIST OF MESSAGES
*E222* *E228* *E232* *E256* *E293* *E298* *E304* *E317*
*E318* *E356* *E438* *E439* *E440* *E316* *E320* *E322*
*E323* *E341* *E473* *E570* *E685*
Add to read buffer
makemap: Illegal mode
Cannot create BalloonEval with both message and callback
Hangul automata ERROR
block was not locked
Didn't get block nr {N}?
ml_upd_block0(): Didn't get block 0??
pointer block id wrong {N}
Updated too many blocks?
get_varp ERROR
u_undo: line numbers wrong
undo list corrupt
undo line missing
ml_get: cannot find line {N}
cannot find line {N}
line number out of range: {N} past the end
line count wrong in block {N}
Internal error
Internal error: {function}
fatal error in cs_manage_matches
This is an internal error. If you can reproduce it, please send in a bug
report. |bugs|
ATTENTION
Found a swap file by the name ...
See |ATTENTION|.
*E92*
Buffer {N} not found
The buffer you requested does not exist. This can also happen when you have
wiped out a buffer which contains a mark or is referenced in another way.
|:bwipeout|
*E95*
Buffer with this name already exists
You cannot have two buffers with the same name.
*E72*
Close error on swap file
The |swap-file|, that is used to keep a copy of the edited text, could not be
closed properly. Mostly harmless.
*E169*
Command too recursive
This happens when an Ex command executes an Ex command that executes an Ex
command, etc. This is only allowed 200 times. When it's more there probably
is an endless loop. Probably a |:execute| or |:source| command is involved.
*E254*
Cannot allocate color {name}
The color name {name} is unknown. See |gui-colors| for a list of colors that
are available on most systems.
*E458*
Cannot allocate colormap entry, some colors may be incorrect
This means that there are not enough colors available for Vim. It will still
run, but some of the colors will not appear in the specified color. Try
stopping other applications that use many colors, or start them after starting
gvim.
Browsers are known to consume a lot of colors. You can avoid this with
netscape by telling it to use its own colormap:
netscape -install
Or tell it to limit to a certain number of colors (64 should work well):
netscape -ncols 64
This can also be done with a line in your Xdefaults file:
Netscape*installColormap: Yes
or
Netscape*maxImageColors: 64
*E79*
Cannot expand wildcards
A filename contains a strange combination of characters, which causes Vim to
attempt expanding wildcards but this fails. This does NOT mean that no
matching file names could be found, but that the pattern was illegal.
*E459*
Cannot go back to previous directory
While expanding a file name, Vim failed to go back to the previously used
directory. All file names being used may be invalid now! You need to have
execute permission on the current directory.
*E190* *E212*
Cannot open "{filename}" for writing
Can't open file for writing
For some reason the file you are writing to cannot be created or overwritten.
The reason could be that you do not have permission to write in the directory
or the file name is not valid.
*E166*
Can't open linked file for writing
You are trying to write to a file which can't be overwritten, and the file is
a link (either a hard link or a symbolic link). Writing might still be
possible if the directory that contains the link or the file is writable, but
Vim now doesn't know if you want to delete the link and write the file in its
place, or if you want to delete the file itself and write the new file in its
place. If you really want to write the file under this name, you have to
manually delete the link or the file, or change the permissions so that Vim
can overwrite.
*E46*
Cannot change read-only variable "{name}"
You are trying to assign a value to an argument of a function |a:var| or a Vim
internal variable |v:var| which is read-only.
*E90*
Cannot unload last buffer
Vim always requires one buffer to be loaded, otherwise there would be nothing
to display in the window.
*E40*
Can't open errorfile <filename>
When using the ":make" or ":grep" commands: The file used to save the error
messages or grep output cannot be opened. This can have several causes:
- 'shellredir' has a wrong value.
- The shell changes directory, causing the error file to be written in another
directory. This could be fixed by changing 'makeef', but then the make
command is still executed in the wrong directory.
*E12*
Command not allowed from exrc/vimrc in current dir or tag search
Some commands are not allowed for security reasons. These commands mostly
come from a .exrc or .vimrc file in the current directory, or from a tags
file. Also see 'secure'.
*E74*
Command too complex
A mapping resulted in a very long command string. Could be caused by a
mapping that indirectly calls itself.
CONVERSION ERROR
When writing a file and the text "CONVERSION ERROR" appears, this means that
some bits were lost when converting text from the internally used UTF-8 to the
format of the file. The file will not be marked unmodified. If you care
about the loss of information, set the 'fileencoding' option to another value
that can handle the characters in the buffer and write again. If you don't
care, you can abandon the buffer or reset the 'modified' option.
*E302*
Could not rename swap file
When the file name changes, Vim tries to rename the |swap-file| as well.
This failed and the old swap file is now still used. Mostly harmless.
*E43* *E44*
Damaged match string
Corrupted regexp program
Something inside Vim went wrong and resulted in a corrupted regexp. If you
know how to reproduce this problem, please report it. |bugs|
*E47*
Error while reading errorfile
Reading the error file was not possible. This is NOT caused by an error
message that was not recognized.
*E80*
Error while writing
Writing a file was not completed successfully. The file is probably
incomplete.
*E13* *E189*
File exists (add ! to override)
"{filename}" exists (add ! to override)
You are protected from accidentally overwriting a file. When you want to
write anyway, use the same command, but add a "!" just after the command.
Example:
:w /tmp/test
changes to:
:w! /tmp/test
*E768*
Swap file exists: {filename} (:silent! overrides)
You are protected from overwriting a file that is being edited by Vim. This
happens when you use ":w! filename" and a swapfile is found.
- If the swapfile was left over from an old crashed edit session you may want
to delete the swapfile. Edit {filename} to find out information about the
swapfile.
- If you want to write anyway prepend ":silent!" to the command. For example:
:silent! w! /tmp/test
The special command is needed, since you already added the ! for overwriting
an existing file.
*E139*
File is loaded in another buffer
You are trying to write a file under a name which is also used in another
buffer. This would result in two versions of the same file.
*E142*
File not written: Writing is disabled by 'write' option
The 'write' option is off. This makes all commands that try to write a file
generate this message. This could be caused by a |-m| commandline argument.
You can switch the 'write' option on with ":set write"
*E25*
GUI cannot be used: Not enabled at compile time
You are running a version of Vim that doesn't include the GUI code. Therefore
"gvim" and ":gui" don't work.
*E49*
Invalid scroll size
This is caused by setting an invalid value for the 'scroll', 'scrolljump' or
'scrolloff' options.
*E17*
"{filename}" is a directory
You tried to write a file with the name of a directory. This is not possible.
You probably need to append a file name.
*E19*
Mark has invalid line number
You are using a mark that has a line number that doesn't exist. This can
happen when you have a mark in another file, and some other program has
deleted lines from it.
*E219* *E220*
Missing {.
Missing }.
Using a {} construct in a file name, but there is a { without a matching } or
the other way around. It should be used like this: {foo,bar}. This matches
"foo" and "bar".
*E315*
ml_get: invalid lnum: {number}
This is an internal Vim error. Please try to find out how it can be
reproduced, and submit a bug report |bugreport.vim|.
*E173*
{number} more files to edit
You are trying to exit, while the last item in the argument list has not been
edited. This protects you from accidentally exiting when you still have more
files to work on. See |argument-list|. If you do want to exit, just do it
again and it will work.
*E23* *E194*
No alternate file
No alternate file name to substitute for '#'
The alternate file is not defined yet. See |alternate-file|.
*E32*
No file name
The current buffer has no name. To write it, use ":w fname". Or give the
buffer a name with ":file fname".
*E141*
No file name for buffer {number}
One of the buffers that was changed does not have a file name. Therefore it
cannot be written. You need to give the buffer a file name:
:buffer {number}
:file {filename}
*E33*
No previous substitute regular expression
When using the '~' character in a pattern, it is replaced with the previously
used pattern in a ":substitute" command. This fails when no such command has
been used yet. See |/~|. This also happens when using ":s/pat/%/", where the
"%" stands for the previous substitute string.
*E35*
No previous regular expression
When using an empty search pattern, the previous search pattern is used. But
that is not possible if there was no previous search.
*E24*
No such abbreviation
You have used an ":unabbreviate" command with an argument which is not an
existing abbreviation. All variations of this command give the same message:
":cunabbrev", ":iunabbrev", etc. Check for trailing white space.
*E31*
No such mapping
You have used an ":unmap" command with an argument which is not an existing
mapping. All variations of this command give the same message: ":cunmap",
":unmap!", etc. A few hints:
- Check for trailing white space.
- If the mapping is buffer-local you need to use ":unmap <buffer>".
|:map-<buffer>|
*E37* *E89*
No write since last change (add ! to override)
No write since last change for buffer {N} (add ! to override)
You are trying to |abandon| a file that has changes. Vim protects you from
losing your work. You can either write the changed file with ":w", or, if you
are sure, |abandon| it anyway, and lose all the changes. This can be done by
adding a '!' character just after the command you used. Example:
:e other_file
changes to:
:e! other_file
*E162*
No write since last change for buffer "{name}"
This appears when you try to exit Vim while some buffers are changed. You
will either have to write the changed buffer (with |:w|), or use a command to
abandon the buffer forcefully, e.g., with ":qa!". Careful, make sure you
don't throw away changes you really want to keep. You might have forgotten
about a buffer, especially when 'hidden' is set.
*E38*
Null argument
Something inside Vim went wrong and resulted in a NULL pointer. If you know
how to reproduce this problem, please report it. |bugs|
*E172*
Only one file name allowed
The ":edit" command only accepts one file name. When you want to specify
several files for editing use ":next" |:next|.
*E339*
Pattern too long
This happens on systems with 16 bit ints: The compiled regexp pattern is
longer than about 65000 characters. Try using a shorter pattern.
It also happens when the offset of a rule doesn't fit in the space available.
*E45*
'readonly' option is set (add ! to override)
You are trying to write a file that was marked as read-only. To write the
file anyway, either reset the 'readonly' option, or add a '!' character just
after the command you used. Example:
:w
changes to:
:w!
*E192*
Recursive use of :normal too deep
You are using a ":normal" command, whose argument again uses a ":normal"
command in a recursive way. This is restricted to 'maxmapdepth' levels. This
example illustrates how to get this message:
:map gq :normal gq<CR>
If you type "gq", it will execute this mapping, which will call "gq" again.
*E22*
Scripts nested too deep
Scripts can be read with the "-s" command-line argument and with the ":source"
command. The script can then again read another script. This can continue
for about 14 levels. When more nesting is done, Vim assumes that there is a
recursive loop somewhere and stops with this error message.
*E319*
Sorry, the command is not available in this version
You have used a command that is not present in the version of Vim you are
using. When compiling Vim, many different features can be enabled or
disabled. This depends on how big Vim has chosen to be and the operating
system. See |+feature-list| for when which feature is available. The
|:version| command shows which feature Vim was compiled with.
*E300*
Swap file already exists (symlink attack?)
This message appears when Vim is trying to open a swap file and finds it
already exists or finds a symbolic link in its place. This shouldn't happen,
because Vim already checked that the file doesn't exist. Either someone else
opened the same file at exactly the same moment (very unlikely) or someone is
attempting a symlink attack (could happen when editing a file in /tmp or when
'directory' starts with "/tmp", which is a bad choice).
*E432*
Tags file not sorted: {file name}
Vim (and Vi) expect tags files to be sorted in ASCII order. Binary searching
can then be used, which is a lot faster than a linear search. If your tags
files are not properly sorted, reset the |'tagbsearch'| option.
This message is only given when Vim detects a problem when searching for a
tag. Sometimes this message is not given, even though the tags file is not
properly sorted.
*E460*
The resource fork would be lost (add ! to override)
On the Macintosh (classic), when writing a file, Vim attempts to preserve all
info about a file, including its resource fork. If this is not possible you
get this error message. Append "!" to the command name to write anyway (and
lose the info).
*E424*
Too many different highlighting attributes in use
Vim can only handle about 223 different kinds of highlighting. If you run
into this limit, you have used too many |:highlight| commands with different
arguments. A ":highlight link" is not counted.
*E77*
Too many file names
When expanding file names, more than one match was found. Only one match is
allowed for the command that was used.
*E303*
Unable to open swap file for "{filename}", recovery impossible
Vim was not able to create a swap file. You can still edit the file, but if
Vim unexpectedly exits the changes will be lost. And Vim may consume a lot of
memory when editing a big file. You may want to change the 'directory' option
to avoid this error. See |swap-file|.
*E140*
Use ! to write partial buffer
When using a range to write part of a buffer, it is unusual to overwrite the
original file. It is probably a mistake (e.g., when Visual mode was active
when using ":w"), therefore Vim requires using a ! after the command, e.g.:
":3,10w!".
*W10*
Warning: Changing a readonly file
The file is read-only and you are making a change to it anyway. You can use
the |FileChangedRO| autocommand event to avoid this message (the autocommand
must reset the 'readonly' option). See 'modifiable' to completely disallow
making changes to a file.
This message is only given for the first change after 'readonly' has been set.
*W13*
Warning: File "{filename}" has been created after editing started
You are editing a file in Vim when it didn't exist, but it does exist now.
You will have to decide if you want to keep the version in Vim or the newly
created file. This message is not given when 'buftype' is not empty.
*W11*
Warning: File "{filename}" has changed since editing started
The file which you have started editing has got another timestamp and the
contents changed (more precisely: When reading the file again with the current
option settings and autocommands you would end up with different text). This
probably means that some other program changed the file. You will have to
find out what happened, and decide which version of the file you want to keep.
Set the 'autoread' option if you want to do this automatically.
This message is not given when 'buftype' is not empty.
There is one situation where you get this message even though there is nothing
wrong: If you save a file in Windows on the day the daylight saving time
*W12*
Warning: File "{filename}" has changed and the buffer was changed in Vim as well
Like the above, and the buffer for the file was changed in this Vim as well.
You will have to decide if you want to keep the version in this Vim or the one
on disk. This message is not given when 'buftype' is not empty.
*W16*
Warning: Mode of file "{filename}" has changed since editing started
When the timestamp for a buffer was changed and the contents are still the
same but the mode (permissions) have changed. This usually occurs when
checking out a file from a version control system, which causes the read-only
bit to be reset. It should be safe to reload the file. Set 'autoread' to
automatically reload the file.
*E211*
File "{filename}" no longer available
The file which you have started editing has disappeared, or is no longer
accessible. Make sure you write the buffer somewhere to avoid losing
changes. This message is not given when 'buftype' is not empty.
*W14*
Warning: List of file names overflow
You must be using an awful lot of buffers. It's now possible that two buffers
have the same number, which causes various problems. You might want to exit
Vim and restart it.
*E296* *E297*
Seek error in swap file write
Write error in swap file
This mostly happens when the disk is full. Vim could not write text into the
|swap-file|. It's not directly harmful, but when Vim unexpectedly exits some
text may be lost without recovery being possible. Vim might run out of memory
when this problem persists.
*connection-refused*
Xlib: connection to "<machine-name:0.0" refused by server
This happens when Vim tries to connect to the X server, but the X server does
not allow a connection. The connection to the X server is needed to be able
to restore the title and for the xterm clipboard support. Unfortunately this
error message cannot be avoided, except by disabling the |+xterm_clipboard|
and |+X11| features.
*E10*
\\ should be followed by /, ? or &
A command line started with a backslash or the range of a command contained a
backslash in a wrong place. This is often caused by command-line continuation
being disabled. Remove the 'C' flag from the 'cpoptions' option to enable it.
Or use ":set nocp"
*E471*
Argument required
This happens when an Ex command with mandatory argument(s) was executed, but
no argument has been specified.
*E474* *E475*
Invalid argument
Invalid argument: {arg}
An Ex command has been executed, but an invalid argument has been specified.
*E488*
Trailing characters
An argument has been added to an Ex command that does not permit one.
*E477* *E478*
No ! allowed
Don't panic!
You have added a "!" after an Ex command that doesn't permit one.
*E481*
No range allowed
A range was specified for an Ex command that doesn't permit one. See
|cmdline-ranges|.
*E482* *E483*
Can't create file {filename}
Can't get temp file name
Vim cannot create a temporary file.
*E484* *E485*
Can't open file {filename}
Can't read file {filename}
Vim cannot read a temporary file.
*E464*
Ambiguous use of user-defined command
There are two user-defined commands with a common name prefix, and you used
Command-line completion to execute one of them. |user-cmd-ambiguous|
Example:
:command MyCommand1 echo "one"
:command MyCommand2 echo "two"
:MyCommand
*E492*
Not an editor command
You tried to execute a command that is neither an Ex command nor
a user-defined command.
==============================================================================
3. Messages *messages*
This is an (incomplete) overview of various messages that Vim gives:
*more-prompt* *pager*
-- More --
-- More -- SPACE/d/j: screen/page/line down, b/u/k: up, q: quit
This message is given when the screen is filled with messages. It is only
given when the 'more' option is on. It is highlighted with the |hl-MoreMsg|
group.
Type effect
<CR> or <NL> or j or <Down> one more line
d down a page (half a screen)
<Space> or f or <PageDown> down a screen
G down all the way, until the hit-enter
prompt
<BS> or k or <Up> one line back (*)
u up a page (half a screen) (*)
b or <PageUp> back a screen (*)
g back to the start (*)
q, <Esc> or CTRL-C stop the listing
: stop the listing and enter a
command-line
<C-Y> yank (copy) a modeless selection to
the clipboard ("* and "+ registers)
{menu-entry} what the menu is defined to in
Cmdline-mode.
<LeftMouse> (**) next page
Any other key causes the meaning of the keys to be displayed.
(*) backwards scrolling is {not in Vi}. Only scrolls back to where messages
started to scroll.
(**) Clicking the left mouse button only works:
- For the GUI: in the last line of the screen.
- When 'r' is included in 'mouse' (but then selecting text won't work).
Note: The typed key is directly obtained from the terminal, it is not mapped
and typeahead is ignored.
The |g<| command can be used to see the last page of previous command output.
This is especially useful if you accidentally typed <Space> at the hit-enter
prompt.
top - main help file
*:syn-enable* *:syntax-enable*
This command switches on syntax highlighting:
:syntax enable
What this command actually does is to execute the command
:source $VIMRUNTIME/syntax/syntax.vim
If the VIM environment variable is not set, Vim will try to find
the path in another way (see |$VIMRUNTIME|). Usually this works just
fine. If it doesn't, try setting the VIM environment variable to the
directory where the Vim stuff is located. For example, if your syntax files
*:syn-on* *:syntax-on*
The ":syntax enable" command will keep your current color settings. This
allows using ":highlight" commands to set your preferred colors before or
after using this command. If you want Vim to overrule your settings with the
defaults, use:
:syntax on
*:hi-normal* *:highlight-normal*
If you are running in the GUI, you can get white text on a black background
with:
:highlight Normal guibg=Black guifg=White
For a color terminal see |:hi-normal-cterm|.
For setting up your own colors syntax highlighting see |syncolor|.
NOTE: The syntax files on MS-DOS and Windows have lines that end in <CR><NL>.
The files for Unix end in <NL>. This means you should use the right type of
file for your system. Although on MS-DOS and Windows the right format is
automatically selected if the 'fileformats' option is not empty.
NOTE: When using reverse video ("gvim -fg white -bg black"), the default value
of 'background' will not be set until the GUI window is opened, which is after
reading the |gvimrc|. This will cause the wrong default highlighting to be
used. To set the default value of 'background' before switching on
highlighting, include the ":gui" command in the YXXYgvimrc|:
:gui " open window and set default for 'background'
:syntax on " start highlighting, use 'background' to set colors
NOTE: Using ":gui" in the |gvimrc| means that "gvim -f" won't start in the
foreground! Use ":gui -f" then.
*g:syntax_on*
You can toggle the syntax on/off with this command:
:if exists("g:syntax_on") | syntax off | else | syntax enable | endif
To put this into a mapping, you can use:
:map <F7> :if exists("g:syntax_on") <Bar>
\ syntax off <Bar>
\ else <Bar>
\ syntax enable <Bar>
\ endif <CR>
[using the |<>| notation, type this literally]
Details:
The ":syntax" commands are implemented by sourcing a file. To see exactly how
this works, look in the file:
command file
:syntax enable $VIMRUNTIME/syntax/syntax.vim
:syntax on $VIMRUNTIME/syntax/syntax.vim
:syntax manual $VIMRUNTIME/syntax/manual.vim
:syntax off $VIMRUNTIME/syntax/nosyntax.vim
Also see |syntax-loading|.
NOTE: If displaying long lines is slow and switching off syntax highlighting
makes it fast, consider setting the 'synmaxcol' option to a lower value.
==============================================================================
2. Syntax files *:syn-files*
The syntax and highlighting commands for one language are normally stored in
a syntax file. The name convention is: "{name}.vim". Where {name} is the
name of the language, or an abbreviation (to fit the name in 8.3 characters,
a requirement in case the file is used on a DOS filesystem).
Examples:
c.vim perl.vim java.vim html.vim
cpp.vim sh.vim csh.vim
The syntax file can contain any Ex commands, just like a vimrc file. But
the idea is that only commands for a specific language are included. When a
language is a superset of another language, it may include the other one,
for example, the cpp.vim file could include the c.vim file:
:so $VIMRUNTIME/syntax/c.vim
The .vim files are normally loaded with an autocommand. For example:
:au Syntax c runtime! syntax/c.vim
:au Syntax cpp runtime! syntax/cpp.vim
These commands are normally in the file $VIMRUNTIME/syntax/synload.vim.
The name for a highlight or syntax group must consist of ASCII letters, digits
and the underscore. As a regexp: "[a-zA-Z0-9_]*"
To be able to allow each user to pick his favorite set of colors, there must
be preferred names for highlight groups that are common for many languages.
These are the suggested group names (if syntax highlighting works properly
you can see the actual color, except for "Ignore"):
*Comment any comment
*Constant any constant
String a string constant: "this is a string"
Character a character constant: 'c', '\n'
Number a number constant: 234, 0xff
Boolean a boolean constant: TRUE, false
Float a floating point constant: 2.3e10
*Identifier any variable name
Function function name (also: methods for classes)
*Statement any statement
Conditional if, then, else, endif, switch, etc.
Repeat for, do, while, etc.
Label case, default, etc.
Operator "sizeof", "+", "*", etc.
Keyword any other keyword
Exception try, catch, throw
*PreProc generic Preprocessor
Include preprocessor #include
Define preprocessor #define
Macro same as Define
PreCondit preprocessor #if, #else, #endif, etc.
*Type int, long, char, etc.
StorageClass static, register, volatile, etc.
Structure struct, union, enum, etc.
Typedef A typedef
*Special any special symbol
SpecialChar special character in a constant
Tag you can use CTRL-] on this
Delimiter character that needs attention
SpecialComment special things inside a comment
Debug debugging statements
*Underlined text that stands out, HTML links
*Ignore left blank, hidden |hl-Ignore|
*Error any erroneous construct
*Todo anything that needs extra attention; mostly the
keywords TODO FIXME and XXX
The names marked with * are the preferred groups; the others are minor groups.
For the preferred groups, the "syntax.vim" file contains default highlighting.
The minor groups are linked to the preferred groups, so they get the same
highlighting. You can override these defaults by using ":highlight" commands
after sourcing the "syntax.vim" file.
Note that highlight group names are not case sensitive. "String" and "string"
can be used for the same group.
The following names are reserved and cannot be used as a group name:
NONE ALL ALLBUT contains contained
*hl-Ignore*
When using the Ignore group, you may also consider using the conceal
mechanism. See |conceal|.
==============================================================================
3. Syntax loading procedure *syntax-loading*
This explains the details that happen when the command ":syntax enable" is
issued. When Vim initializes itself, it finds out where the runtime files are
located. This is used here as the variable |$VIMRUNTIME|.
Upon loading a file, Vim finds the relevant syntax file as follows:
Loading the file triggers the BufReadPost autocommands.
|
+- If there is a match with one of the autocommands from |synload-3|
| (known file types) or |synload-4| (user's file types), the 'filetype'
| option is set to the file type.
|
+- The autocommand at |synload-5| is triggered. If the file type was not
| found yet, then scripts.vim is searched for in 'runtimepath'. This
| should always load $VIMRUNTIME/scripts.vim, which does the following.
| |
| +- Source the user's optional file, from the *myscriptsfile*
| | variable. This is for backwards compatibility with Vim 5.x only.
| |
| +- If the file type is still unknown, check the contents of the file,
| again with checks like "getline(1) =~ pattern" as to whether the
| file type can be recognized, and set 'filetype'.
|
+- When the file type was determined and 'filetype' was set, this
| triggers the FileType autocommand |synload-6| above. It sets
| 'syntax' to the determined file type.
|
+- When the 'syntax' option was set above, this triggers an autocommand
| from |synload-1| (and |synload-2|). This find the main syntax file in
| 'runtimepath', with this command:
| runtime! syntax/<name>.vim
|
*b:current_syntax-variable*
Vim stores the name of the syntax that has been loaded in the
"b:current_syntax" variable. You can use this if you want to load other
settings, depending on which syntax is active. Example:
:au BufReadPost * if b:current_syntax == "csh"
:au BufReadPost * do-some-things
:au BufReadPost * endif
*:TOhtml*
Or use the ":TOhtml" user command. It is defined in a standard plugin.
":TOhtml" also works with a range and in a Visual area:
:10,40TOhtml
Warning: This can be slow! The script must process every character of every
line. Because it can take a long time, by default a progress bar is displayed
in the statusline for each major step in the conversion process. If you don't
like seeing this progress bar, you can disable it and get a very minor speed
improvement with:
let g:html_no_progress = 1
":TOhtml" has another special feature: if the window is in diff mode, it will
generate HTML that shows all the related windows. This can be disabled by
setting the g:html_diff_one_file variable:
let g:html_diff_one_file = 1
After you save the resulting file, you can view it with any browser. The
colors should be exactly the same as you see them in Vim.
To restrict the conversion to a range of lines, use a range with the |:TOhtml|
command, or set "g:html_start_line" and "g:html_end_line" to the first and
last line to be converted. Example, using the last set Visual area:
:let g:html_start_line = line("'<")
:let g:html_end_line = line("'>")
The lines are numbered according to 'number' option and the Number
highlighting. You can force lines to be numbered in the HTML output by
setting "html_number_lines" to non-zero value:
:let g:html_number_lines = 1
Force to omit the line numbers by using a zero value:
:let g:html_number_lines = 0
Go back to the default to use 'number' by deleting the variable:
:unlet g:html_number_lines
By default, valid HTML 4.01 using cascading style sheets (CSS1) is generated.
If you need to generate markup for really old browsers or some other user
agent that lacks basic CSS support, use:
:let g:html_use_css = 0
Concealed text is removed from the HTML and replaced with the appropriate
character from |:syn-cchar| or 'listchars' depending on the current value of
'conceallevel'. If you always want to display all text in your document,
either set 'conceallevel' to zero before invoking 2html, or use:
:let g:html_ignore_conceal = 1
Similarly, closed folds are put in the HTML as they are displayed. If you
don't want this, use the |zR| command before invoking 2html, or use:
:let g:html_ignore_folding = 1
You may want to generate HTML that includes all the data within the folds, and
allow the user to view the folded data similar to how they would in Vim. To
generate this dynamic fold information, use:
:let g:html_dynamic_folds = 1
Using html_dynamic_folds will imply html_use_css, because it would be far too
difficult to do it for old browsers. However, html_ignore_folding overrides
html_dynamic_folds.
Using html_dynamic_folds will default to generating a foldcolumn in the html
similar to Vim's foldcolumn, that will use javascript to open and close the
folds in the HTML document. The width of this foldcolumn starts at the current
setting of |'foldcolumn'| but grows to fit the greatest foldlevel in your
document. If you do not want to show a foldcolumn at all, use:
:let g:html_no_foldcolumn = 1
Using this option, there will be no foldcolumn available to open the folds in
the HTML. For this reason, another option is provided: html_hover_unfold.
Enabling this option will use CSS 2.0 to allow a user to open a fold by
hovering the mouse pointer over it. Note that old browsers (notably Internet
Explorer 6) will not support this feature. Browser-specific markup for IE6 is
included to fall back to the normal CSS1 code so that the folds show up
correctly for this browser, but they will not be openable without a
foldcolumn. Note that using html_hover_unfold will allow modern browsers with
disabled javascript to view closed folds. To use this option, use:
:let g:html_hover_unfold = 1
Setting html_no_foldcolumn with html_dynamic_folds will automatically set
html_hover_unfold, because otherwise the folds wouldn't be dynamic.
By default "<pre>" and "</pre>" is used around the text. This makes it show
up as you see it in Vim, but without wrapping. If you prefer wrapping, at the
risk of making some things look a bit different, use:
:let g:html_no_pre = 1
This will use <br> at the end of each line and use " " for repeated
spaces.
If you do use the "<pre>" tags, <Tab> characters in the text are included in
the generated output if they will have no effect on the appearance of the
text and it looks like they are in the document intentionally. This allows for
the HTML output to be copied and pasted from a browser without losing the
actual whitespace used in the document.
Specifically, <Tab> characters will be included if the 'tabstop' option is set
to the default of 8, 'expandtab' is not set, and if neither the foldcolumn nor
the line numbers are included in the HTML output (see options above). When any
of these conditions are not met, any <Tab> characters in the text are expanded
to the appropriate number of spaces in the HTML output.
When "<pre>" is included, you can force |:TOhtml| to keep the tabs even if the
other conditions are not met with:
:let g:html_expand_tabs = 0
Note that this can easily break text alignment and indentation in the HTML.
Force tabs to be expanded even when they would be kept using:
:let g:html_expand_tabs = 1
For diff mode on a single file (with g:html_diff_one_file) a sequence of more
than 3 filler lines is displayed as three lines with the middle line
mentioning the total number of inserted lines. If you prefer to see all the
inserted lines as with the side-by-side diff, use:
:let g:html_whole_filler = 1
And to go back to displaying up to three lines again:
:unlet g:html_whole_filler
TOhtml uses the current value of 'fileencoding' if set, or 'encoding' if not,
to determine the charset and 'fileencoding' of the HTML file. In general, this
works for the encodings mentioned specifically by name in |encoding-names|, but
TOhtml will only automatically use those encodings which are widely supported.
However, you can override this to support specific encodings that may not be
automatically detected by default.
To overrule all automatic charset detection, set g:html_use_encoding to the
name of the charset to be used. TOhtml will try to determine the appropriate
'fileencoding' setting from the charset, but you may need to set it manually
*convert-to-XML* *convert-to-XHTML*
If you do not like plain HTML, an alternative is to have the script generate
XHTML (XML compliant HTML). To do this set the "html_use_xhtml" variable:
:let g:html_use_xhtml = 1
Any of the on/off options listed above can be enabled or disabled by setting
them explicitly to the desired value, or restored to their default by removing
the variable using |:unlet|.
Remarks:
- Some truly ancient browsers may not show the background colors.
- From most browsers you can also print the file (in color)!
- This version of TOhtml may work with older versions of Vim, but some
features such as conceal support will not function, and the colors may be
incorrect for an old Vim without GUI support compiled in.
Here is an example how to run the script over all .c and .h files from a
Unix shell:
for f in *.[ch]; do gvim -f +"syn on" +"run! syntax/2html.vim" +"wq" +"q" $f; done
ADA
See |ft-ada-syntax|
*baan-folding*
Syntax folding can be enabled at various levels through the variables
mentioned below (Set those in your |.vimrc|). The more complex folding on
source blocks and SQL can be CPU intensive.
To allow any folding and enable folding at function level use:
let baan_fold=1
Folding can be enabled at source block level as if, while, for ,... The
indentation preceding the begin/end keywords has to match (spaces are not
considered equal to a tab).
let baan_fold_block=1
Folding can be enabled for embedded SQL blocks as SELECT, SELECTDO,
SELECTEMPTY, ... The indentation preceding the begin/end keywords has to
match (spaces are not considered equal to a tab).
let baan_fold_sql=1
Note: Block folding can result in many small folds. It is suggested to |:set|
the options 'foldminlines' and 'foldnestmax' in |.vimrc| or use |:setlocal| in
.../after/syntax/baan.vim (see |after-directory|). Eg:
set foldminlines=5
set foldnestmax=6
C *c.vim* *ft-c-syntax*
A few things in C highlighting are optional. To enable them assign any value
to the respective variable. Example:
:let c_comment_strings = 1
To disable them use ":unlet". Example:
:unlet c_comment_strings
Variable Highlight
c_gnu GNU gcc specific items
c_comment_strings strings and numbers inside a comment
c_space_errors trailing white space and spaces before a <Tab>
c_no_trail_space_error ... but no trailing spaces
c_no_tab_space_error ... but no spaces before a <Tab>
c_no_bracket_error don't highlight {}; inside [] as errors
c_no_curly_error don't highlight {}; inside [] and () as errors;
except { and } in first column
c_curly_error highlight a missing }; this forces syncing from the
CH *ch.vim* *ft-ch-syntax*
C/C++ interpreter. Ch has similar syntax highlighting to C and builds upon
the C syntax file. See |c.vim| for all the settings that are available for C.
By setting a variable you can tell Vim to use Ch syntax for *.h files, instead
of C or C++:
:let ch_syntax_for_h = 1
let g:changelog_spacing_errors = 0
This works the next time you edit a changelog file. You can also use
"b:changelog_spacing_errors" to set this per buffer (before loading the syntax
file).
You can change the highlighting used, e.g., to flag the spaces as an error:
:hi link ChangelogError Error
Or to avoid the highlighting:
:hi link ChangelogError NONE
This works immediately.
Case still matters for class names and TODO marks in comments.
Conversely, for even stricter checks, add one of the following lines:
:let eiffel_strict=1
:let eiffel_pedantic=1
Setting eiffel_strict will only catch improper capitalization for the
five predefined words "Current", "Void", "Result", "Precursor", and
"NONE", to warn against their accidental use as feature or class names.
Setting eiffel_pedantic will enforce adherence to the Eiffel style
guidelines fairly rigorously (like arbitrary mixes of upper- and
lowercase letters as well as outdated ways to capitalize keywords).
If you want to use the lower-case version of "Current", "Void",
"Result", and "Precursor", you can use
:let eiffel_lower_case_predef=1
instead of completely turning case-sensitive highlighting off.
Support for ISE's proposed new creation syntax that is already
experimentally handled by some compilers can be enabled by:
:let eiffel_ise=1
Finally, some vendors support hexadecimal constants. To handle them, add
:let eiffel_hex_constants=1
to your startup file.
- formConditional
- formNumber
- formStatement
- formHeaderStatement
- formComment
- formPreProc
- formDirective
- formType
- formString
Note that the form.vim syntax file implements FORM preprocessor commands and
directives per default in the same syntax group.
A predefined enhanced color mode for FORM is available to distinguish between
header statements and statements in the body of a FORM program. To activate
this mode define the following variable in your vimrc file
:let form_enhanced_color=1
The enhanced mode also takes advantage of additional color features for a dark
gvim display. Here, statements are colored LightYellow instead of Yellow, and
conditionals are LightBlue for better distinction.
using tabs. If your fortran files contain tabs, then you should set the
variable fortran_have_tabs in your .vimrc with a command such as
:let fortran_have_tabs=1
placed prior to the :syntax on command. Unfortunately, the use of tabs will
mean that the syntax file will not be able to detect incorrect margins.
Syntax folding of fortran files
If you wish to use foldmethod=syntax, then you must first set the variable
fortran_fold with a command such as
:let fortran_fold=1
to instruct the syntax script to define fold regions for program units, that
is main programs starting with a program statement, subroutines, function
subprograms, block data subprograms, interface blocks, and modules. If you
also set the variable fortran_fold_conditionals with a command such as
:let fortran_fold_conditionals=1
then fold regions will also be defined for do loops, if blocks, and select
case constructs. If you also set the variable
fortran_fold_multilinecomments with a command such as
:let fortran_fold_multilinecomments=1
then fold regions will also be defined for three or more consecutive comment
lines. Note that defining fold regions can be slow for large files.
If fortran_fold, and possibly fortran_fold_conditionals and/or
fortran_fold_multilinecomments, have been set, then vim will fold your file if
you set foldmethod=syntax. Comments or blank lines placed between two program
units are not folded because they are seen as not belonging to any program
unit.
More precise fortran syntax
If you set the variable fortran_more_precise with a command such as
:let fortran_more_precise=1
then the syntax coloring will be more precise but slower. In particular,
statement labels used in do, goto and arithmetic if statements will be
recognized, as will construct names at the end of a do, if, select or forall
construct.
Non-default fortran dialects
The syntax script supports five Fortran dialects: f95, f90, f77, the Lahey
subset elf90, and the Imagine1 subset F.
If you use f77 with extensions, even common ones like do/enddo loops, do/while
loops and free source form that are supported by most f77 compilers including
g77 (GNU Fortran), then you will probably find the default highlighting
satisfactory. However, if you use strict f77 with no extensions, not even free
source form or the MIL STD 1753 extensions, then the advantages of setting the
dialect to f77 are that names such as SUM are recognized as user variable
names and not highlighted as f9x intrinsic functions, that obsolete constructs
such as ASSIGN statements are not highlighted as todo items, and that fixed
source form will be assumed.
If you use elf90 or F, the advantage of setting the dialect appropriately is
that f90 features excluded from these dialects will be highlighted as todo
items and that free source form will be assumed as required for these
dialects.
The dialect can be selected by setting the variable fortran_dialect. The
permissible values of fortran_dialect are case-sensitive and must be "f95",
"f90", "f77", "elf" or "F". Invalid values of fortran_dialect are ignored.
If all your fortran files use the same dialect, set fortran_dialect in your
.vimrc prior to your syntax on statement. If the dialect depends upon the file
extension, then it is most convenient to set it in a ftplugin file. For more
information on ftplugin files, see |ftplugin|. For example, if all your
fortran files with an .f90 extension are written in the elf subset, your
ftplugin file should contain the code
let s:extfname = expand("%:e")
if s:extfname ==? "f90"
let fortran_dialect="elf"
else
unlet! fortran_dialect
endif
Note that this will work only if the "filetype plugin indent on" command
precedes the "syntax on" command in your .vimrc file.
Finer control is necessary if the file extension does not uniquely identify
the dialect. You can override the default dialect, on a file-by-file basis, by
including a comment with the directive "fortran_dialect=xx" (where xx=f77 or
elf or F or f90 or f95) in one of the first three lines in your file. For
example, your older .f files may be written in extended f77 but your newer
ones may be F codes, and you would identify the latter by including in the
first three lines of those files a Fortran comment of the form
! fortran_dialect=F
F overrides elf if both directives are present.
Limitations
Parenthesis checking does not catch too few closing parentheses. Hollerith
strings are not recognized. Some keywords may be highlighted incorrectly
because Fortran90 has no reserved words.
For further information related to fortran, see |ft-fortran-indent| and
|ft-fortran-plugin|.
:let java_highlight_debug=1
The result will be that those statements are highlighted as 'Special'
characters. If you prefer to have them highlighted differently you must define
new highlightings for the following groups.:
Debug, DebugSpecial, DebugString, DebugBoolean, DebugType
which are used for the statement itself, special characters used in debug
strings, strings, boolean constants and types (this, super) respectively. I
have opted to chose another background for those statements.
In order to help you write code that can be easily ported between Java and
C++, all C++ keywords can be marked as an error in a Java program. To
have this add this line in your .vimrc file:
:let java_allow_cpp_keywords = 0
Javadoc is a program that takes special comments out of Java program files and
creates HTML pages. The standard configuration will highlight this HTML code
similarly to HTML files (see |html.vim|). You can even add Javascript
and CSS inside this code (see below). There are four differences however:
1. The title (all characters up to the first '.' which is followed by
some white space or up to the first '@') is colored differently (to change
the color change the group CommentTitle).
2. The text is colored as 'Comment'.
3. HTML comments are colored as 'Special'
4. The special Javadoc tags (@see, @param, ...) are highlighted as specials
and the argument (for @see, @param, @exception) as Function.
To turn this feature off add the following line to your startup file:
:let java_ignore_javadoc=1
If you use the special Javadoc comment highlighting described above you
can also turn on special highlighting for Javascript, visual basic
scripts and embedded CSS (stylesheets). This makes only sense if you
actually have Javadoc comments that include either Javascript or embedded
CSS. The options to use are
:let java_javascript=1
:let java_css=1
:let java_vb=1
In order to highlight nested parens with different colors define colors
for javaParen, javaParen1 and javaParen2, for example with
:hi link javaParen Comment
or
:hi javaParen ctermfg=blue guifg=#0000ff
If you notice highlighting errors while scrolling backwards, which are fixed
when redrawing with CTRL-L, try setting the "java_minlines" internal variable
to a larger number:
:let java_minlines = 50
This will make the syntax synchronization start 50 lines before the first
displayed line. The default value is 10. The disadvantage of using a larger
number is that redrawing can become slow.
This syntax file may be used for Lua 4.0, Lua 5.0 or Lua 5.1 (the latter is
the default). You can select one of these versions using the global variables
lua_version and lua_subversion. For example, to activate Lua
4.0 syntax highlighting, use this command:
:let lua_version = 4
If you are using Lua 5.0, use these commands:
:let lua_version = 5
:let lua_subversion = 0
To restore highlighting for Lua 5.1:
:let lua_version = 5
:let lua_subversion = 1
:let b:nroff_is_groff = 1
Groff is different from the old AT&T n/troff that you may still find in
Solaris. Groff macro and request names can be longer than 2 characters and
there are extensions to the language primitives. For example, in AT&T troff
you access the year as a 2-digit number with the request \(yr. In groff you
can use the same request, recognized for compatibility, or you can use groff's
native syntax, \[yr]. Furthermore, you can use a 4-digit year directly:
\[year]. Macro requests can be longer than 2 characters, for example, GNU mm
accepts the requests ".VERBON" and ".VERBOFF" for creating verbatim
environments.
In order to obtain the best formatted output g/troff can give you, you should
follow a few simple rules about spacing and punctuation.
1. Do not leave empty spaces at the end of lines.
2. Leave one space and one space only after an end-of-sentence period,
exclamation mark, etc.
3. For reasons stated below, it is best to follow all period marks with a
carriage return.
The reason behind these unusual tips is that g/n/troff have a line breaking
algorithm that can be easily upset if you don't follow the rules given above.
Unlike TeX, troff fills text line-by-line, not paragraph-by-paragraph and,
furthermore, it does not have a concept of glue or stretch, all horizontal and
vertical space input will be output as is.
Therefore, you should be careful about not using more space between sentences
than you intend to have in your final document. For this reason, the common
practice is to insert a carriage return immediately after all punctuation
marks. If you want to have "even" text in your final processed output, you
need to maintaining regular spacing in the input text. To mark both trailing
spaces and two or more spaces after a punctuation as an error, use:
:let nroff_space_errors = 1
Another technique to detect extra spacing and other errors that will interfere
with the correct typesetting of your file, is to define an eye-catching
highlighting definition for the syntax groups "nroffDefinition" and
"nroffDefSpecial" in your configuration files. For example:
hi def nroffDefinition term=italic cterm=italic gui=reverse
hi def nroffDefSpecial term=italic,bold cterm=italic,bold
\ gui=reverse,bold
If you want to navigate preprocessor entries in your source file as easily as
with section markers, you can activate the following option in your .vimrc
file:
let b:preprocs_as_sections = 1
As well, the syntax file adds an extra paragraph marker for the extended
paragraph macro (.XP) in the ms package.
Finally, there is a |groff.vim| syntax file that can be used for enabling
groff syntax highlighting either on a file basis or globally by default.
:let perl_include_pod = 1
The reduce the complexity of parsing (and increase performance) you can switch
off two elements in the parsing of variable names and contents.
To handle package references in variable and function names not differently
from the rest of the name (like 'PkgName::' in '$PkgName::VarName'):
:let perl_no_scope_in_variables = 1
(In Vim 6.x it was the other way around: "perl_want_scope_in_variables"
enabled it.)
If you do not want complex things like '@{${"foo"}}' to be parsed:
:let perl_no_extended_vars = 1
(In Vim 6.x it was the other way around: "perl_extended_vars" enabled it.)
The coloring strings can be changed. By default strings and qq friends will be
highlighted like the first line. If you set the variable
perl_string_as_statement, it will be highlighted as in the second line.
"hello world!"; qq|hello world|;
^^^^^^^^^^^^^^NN^^^^^^^^^^^^^^^N (unlet perl_string_as_statement)
S^^^^^^^^^^^^SNNSSS^^^^^^^^^^^SN (let perl_string_as_statement)
(^ = perlString, S = perlStatement, N = None at all)
The syncing has 3 options. The first two switch off some triggering of
synchronization and should only be needed in case it fails to work properly.
If while scrolling all of a sudden the whole screen changes color completely
then you should try and switch off one of those. Let me know if you can figure
out the line that causes the mistake.
One triggers on "^\s*sub\s*" and the other on "^[$@%]" more or less.
:let perl_no_sync_on_sub
:let perl_no_sync_on_global_var
Below you can set the maximum distance VIM should look for starting points for
its attempts in syntax highlighting.
:let perl_sync_dist = 100
If you want to use folding with perl, set perl_fold:
:let perl_fold = 1
If you want to fold blocks in if statements, etc. as well set the following:
:let perl_fold_blocks = 1
To avoid folding packages or subs when perl_fold is let, let the appropriate
variable(s):
:unlet perl_nofold_packages
:unlet perl_nofold_subs
let php_htmlInStrings = 1
Using the old colorstyle:
let php_oldStyle = 1
Enable highlighting ASP-style short tags:
let php_asp_tags = 1
Disable short tags:
let php_noShortTags = 1
For highlighting parent error ] or ):
let php_parent_error_close = 1
For skipping an php end tag, if there exists an open ( or [ without a closing
one:
let php_parent_error_open = 1
Enable folding for classes and functions:
let php_folding = 1
Selecting syncing method:
let php_sync_method = x
x = -1 to sync by search (default),
x > 0 to sync at least x lines backwards,
x = 0 to sync from start.
:let phtml_sql_query = 1
For syncing, minlines defaults to 100. If you prefer another value, you can
set "phtml_minlines" to the value you desire. Example:
:let phtml_minlines = 200
*ptcap.vim* *ft-printcap-syntax*
PRINTCAP + TERMCAP *ft-ptcap-syntax* *ft-termcap-syntax*
This syntax file applies to the printcap and termcap databases.
In order for Vim to recognize printcap/termcap files that do not match
the patterns *printcap*, or *termcap*, you must put additional patterns
appropriate to your system in your |myfiletypefile| file. For these
patterns, you must set the variable "b:ptcap_type" to either "print" or
"term", and then the 'filetype' option to ptcap.
For example, to make Vim identify all files in /etc/termcaps/ as termcap
files, add the following:
This will add highlighting for the commands that BASH (version 2.05a and
later, and part earlier) adds.
:let ruby_no_comment_fold = 1
This will make the syntax synchronization start 1000 lines before the first
displayed line. If you set "tcsh_minlines" to "fromstart", then
synchronization is done from the start of the file. The default value for
tcsh_minlines is 100. The disadvantage of using a larger number is that
redrawing can become slow.
*tex-folding*
Tex: Want Syntax Folding?
As of version 28 of <syntax/tex.vim>, syntax-based folding of parts, chapters,
sections, subsections, etc are supported. Put
let g:tex_fold_enabled=1
in your <.vimrc>, and :set fdm=syntax. I suggest doing the latter via a
modeline at the end of your LaTeX file:
% vim: fdm=syntax
*tex-nospell*
Tex: Don't Want Spell Checking In Comments?
Some folks like to include things like source code in comments and so would
prefer that spell checking be disabled in comments in LaTeX files. To do
this, put the following in your <.vimrc>:
let g:tex_comment_nospell= 1
*tex-verb*
Tex: Want Spell Checking in Verbatim Zones?
Often verbatim regions are used for things like source code; seldom does
one want source code spell-checked. However, for those of you who do
want your verbatim zones spell-checked, put the following in your <.vimrc>:
let g:tex_verbspell= 1
*tex-runon*
Tex: Run-on Comments or MathZones
The <syntax/tex.vim> highlighting supports TeX, LaTeX, and some AmsTeX. The
highlighting supports three primary zones/regions: normal, texZone, and
texMathZone. Although considerable effort has been made to have these zones
terminate properly, zones delineated by $..$ and $$..$$ cannot be synchronized
as there's no difference between start and end patterns. Consequently, a
special "TeX comment" has been provided
%stopzone
which will forcibly terminate the highlighting of either a texZone or a
texMathZone.
*tex-slow*
Tex: Slow Syntax Highlighting?
If you have a slow computer, you may wish to reduce the values for
:syn sync maxlines=200
:syn sync minlines=50
(especially the latter). If your computer is fast, you may wish to
increase them. This primarily affects synchronizing (i.e. just what group,
if any, is the text at the top of the screen supposed to be in?).
*tex-morecommands* *tex-package*
Tex: Want To Highlight More Commands?
LaTeX is a programmable language, and so there are thousands of packages full
of specialized LaTeX commands, syntax, and fonts. If you're using such a
package you'll often wish that the distributed syntax/tex.vim would support
it. However, clearly this is impractical. So please consider using the
techniques in |mysyntaxfile-add| to extend or modify the highlighting provided
by syntax/tex.vim.
*tex-error*
Tex: Excessive Error Highlighting?
*tex-math*
Tex: Need a new Math Group?
If you want to include a new math group in your LaTeX, the following
code shows you an example as to how you might do so:
call TexNewMathZone(sfx,mathzone,starform)
You'll want to provide the new math group with a unique suffix
(currently, A-L and V-Z are taken by <syntax/tex.vim> itself).
As an example, consider how eqnarray is set up by <syntax/tex.vim>:
call TexNewMathZone("D","eqnarray",1)
You'll need to change "mathzone" to the name of your new math group,
and then to the call to it in .vim/after/syntax/tex.vim.
The "starform" variable, if true, implies that your new math group
has a starred form (ie. eqnarray*).
*tex-style*
Tex: Starting a New Style?
One may use "\makeatletter" in *.tex files, thereby making the use of "@" in
commands available. However, since the *.tex file doesn't have one of the
following suffices: sty cls clo dtx ltx, the syntax highlighting will flag
such use of @ as an error. To solve this:
:let b:tex_stylish = 1
:set ft=tex
Putting "let g:tex_stylish=1" into your <.vimrc> will make <syntax/tex.vim>
always accept such use of @.
*g:tex_conceal*
Tex: Selective Conceal Mode
You may selectively use conceal mode by setting g:tex_conceal in your
<.vimrc>. By default it is set to "admgs" to enable conceal for the
following sets of characters:
a = accents/ligatures
d = delimiters
m = math symbols
g = Greek
s = superscripts/subscripts
By leaving one or more of these out, the associated conceal-character
substitution will not be made.
TF *tf.vim* *ft-tf-syntax*
There is one option for the tf syntax highlighting.
For syncing, minlines defaults to 100. If you prefer another value, you can
set "tf_minlines" to the value you desire. Example:
*g:vimsyn_embed*
The g:vimsyn_embed option allows users to select what, if any, types of
embedded script highlighting they wish to have.
g:vimsyn_embed == 0 : don't embed any scripts
g:vimsyn_embed =~ 'm' : embed mzscheme (but only if vim supports it)
g:vimsyn_embed =~ 'p' : embed perl (but only if vim supports it)
g:vimsyn_embed =~ 'P' : embed python (but only if vim supports it)
g:vimsyn_embed =~ 'r' : embed ruby (but only if vim supports it)
g:vimsyn_embed =~ 't' : embed tcl (but only if vim supports it)
By default, g:vimsyn_embed is "mpPr"; ie. syntax/vim.vim will support
highlighting mzscheme, perl, python, and ruby by default. Vim's has("tcl")
test appears to hang vim when tcl is not truly available. Thus, by default,
tcl is not supported for embedding (but those of you who like tcl embedded in
their vim syntax highlighting can simply include it in the g:vimembedscript
option).
*g:vimsyn_folding*
Some folding is now supported with syntax/vim.vim:
g:vimsyn_folding == 0 or doesn't exist: no syntax-based folding
g:vimsyn_folding =~ 'a' : augroups
g:vimsyn_folding =~ 'f' : fold functions
g:vimsyn_folding =~ 'm' : fold mzscheme script
g:vimsyn_folding =~ 'p' : fold perl script
g:vimsyn_folding =~ 'P' : fold python script
g:vimsyn_folding =~ 'r' : fold ruby script
g:vimsyn_folding =~ 't' : fold tcl script
*g:vimsyn_noerror*
Not all error highlighting that syntax/vim.vim does may be correct; VimL is a
difficult language to highlight correctly. A way to suppress error
highlighting is to put the following line in your YXXYvimrc|:
let g:vimsyn_noerror = 1
*xml-folding*
The xml syntax file provides syntax |folding| (see |:syn-fold|) between
start and end tags. This can be turned on by
:let g:xml_syntax_folding = 1
:set foldmethod=syntax
Note: syntax folding might slow down syntax highlighting significantly,
especially for large files.
defined LAST wins. Thus you can override previously defined syntax items by
using an item that matches the same text. But a keyword always goes before a
match or region. And a keyword with matching case always goes before a
keyword with ignoring case.
PRIORITY *:syn-priority*
When several syntax items may match, these rules are used:
1. When multiple Match or Region items start in the same position, the item
defined last has priority.
2. A Keyword has priority over Match and Region items.
3. An item that starts in an earlier position has priority over items that
start in later positions.
keyword is used if more than one item matches. Keywords do not nest
and a keyword can't contain anything else.
Note that when you have a keyword that is the same as an option (even
one that isn't allowed here), you can not use it. Use a match
instead.
The maximum length of a keyword is 80 characters.
The same keyword can be defined multiple times, when its containment
differs. For example, you can define the keyword once not contained
and use one highlight group, and once contained, and use a different
highlight group. Example:
:syn keyword vimCommand tag
:syn keyword vimSetting contained tag
When finding "tag" outside of any syntax item, the "vimCommand"
highlight group is used. When finding "tag" in a syntax item that
contains "vimSetting", the "vimSetting" group is used.
*:syn-keepend*
By default, a contained match can obscure a match for the end pattern.
This is useful for nesting. For example, a region that starts with
"{" and ends with "}", can contain another region. An encountered "}"
will then end the contained region, but not the outer region:
{ starts outer "{}" region
{ starts contained "{}" region
} ends contained "{}" region
} ends outer "{} region
If you don't want this, the "keepend" argument will make the matching
of an end pattern of the outer region also end any contained item.
This makes it impossible to nest the same region, but allows for
contained items to highlight parts of the end pattern, without causing
that to skip the match with the end pattern. Example:
:syn match vimComment +"[^"]\+$+
:syn region vimCommand start="set" end="$" contains=vimComment keepend
The "keepend" makes the vimCommand always end at the end of the line,
even though the contained vimComment includes a match with the <EOL>.
When "keepend" is not used, a match with an end pattern is retried
after each contained match. When "keepend" is included, the first
encountered match with an end pattern is used, truncating any
contained matches.
*:syn-extend*
The "keepend" behavior can be changed by using the "extend" argument.
When an item with "extend" is contained in an item that uses
"keepend", the "keepend" is ignored and the containing region will be
extended.
This can be used to have some contained items extend a region while
others don't. Example:
:syn region htmlRef start=+<a>+ end=+</a>+ keepend contains=htmlItem,htmlScript
:syn match htmlItem +<[^>]*>+ contained
:syn region htmlScript start=+<script+ end=+</script[^>]*>+ contained extend
Here the htmlItem item does not make the htmlRef item continue
further, it is only used to highlight the <> items. The htmlScript
*:syn-excludenl*
When a pattern for a match or end pattern of a region includes a '$'
to match the end-of-line, it will make a region item that it is
contained in continue on the next line. For example, a match with
"\\$" (backslash at the end of the line) can make a region continue
that would normally stop at the end of the line. This is the default
behavior. If this is not wanted, there are two ways to avoid it:
1. Use "keepend" for the containing item. This will keep all
contained matches from extending the match or region. It can be
used when all contained items must not extend the containing item.
2. Use "excludenl" in the contained item. This will keep that match
from extending the containing match or region. It can be used if
only some contained items must not extend the containing item.
"excludenl" must be given before the pattern it applies to.
*:syn-matchgroup*
"matchgroup" can be used to highlight the start and/or end pattern
differently than the body of the region. Example:
:syntax region String matchgroup=Quote start=+"+ skip=+\\"+ end=+"+
This will highlight the quotes with the "Quote" group, and the text in
between with the "String" group.
The "matchgroup" is used for all start and end patterns that follow,
until the next "matchgroup". Use "matchgroup=NONE" to go back to not
using a matchgroup.
In a start or end pattern that is highlighted with "matchgroup" the
contained items of the region are not used. This can be used to avoid
that a contained item matches in the start or end pattern match. When
using "transparent", this does not apply to a start or end pattern
match that is highlighted with "matchgroup".
Here is an example, which highlights three levels of parentheses in
different colors:
:sy region par1 matchgroup=par1 start=/(/ end=/)/ contains=par2
:sy region par2 matchgroup=par2 start=/(/ end=/)/ contains=par3 contained
:sy region par3 matchgroup=par3 start=/(/ end=/)/ contains=par1 contained
:hi par1 ctermfg=red guifg=red
:hi par2 ctermfg=blue guifg=blue
:hi par3 ctermfg=darkgreen guifg=darkgreen
*E849*
The maximum number of syntax groups is 19999.
==============================================================================
6. :syntax arguments *:syn-arguments*
The :syntax commands that define syntax items take a number of arguments.
The common ones are explained here. The arguments may be given in any order
and may be mixed with patterns.
Not all commands accept all arguments. This table shows which arguments
can not be used for all commands:
*E395*
contains oneline fold display extend concealends
:syntax keyword - - - - - -
:syntax match yes - yes yes yes -
:syntax region yes yes yes yes yes yes
These arguments can be used for all three commands:
conceal
cchar
contained
containedin
nextgroup
transparent
skipwhite
skipnl
skipempty
concealends *:syn-concealends*
When the "concealends" argument is given, the start and end matches of
the region, but not the contents of the region, are marked as concealable.
Whether or not they are actually concealed depends on the setting on the
'conceallevel' option. The ends of a region can only be concealed separately
in this way when they have their own highlighting via "matchgroup"
cchar *:syn-cchar*
*E844*
The "cchar" argument defines the character shown in place of the item
when it is concealed (setting "cchar" only makes sense when the conceal
argument is given.) If "cchar" is not set then the default conceal
character defined in the 'listchars' option is used. The character cannot be
a control character such as Tab. Example:
:syntax match Entity "&" conceal cchar=&
See |hl-Conceal| for highlighting.
contained *:syn-contained*
When the "contained" argument is given, this item will not be recognized at
the top level, but only when it is mentioned in the "contains" field of
another match. Example:
:syntax keyword Todo TODO contained
:syntax match Comment "//.*" contains=Todo
display *:syn-display*
If the "display" argument is given, this item will be skipped when the
detected highlighting will not be displayed. This will speed up highlighting,
by skipping this item when only finding the syntax state for the text that is
to be displayed.
Generally, you can use "display" for match and region items that meet these
conditions:
- The item does not continue past the end of a line. Example for C: A region
for a "/*" comment can't contain "display", because it continues on the next
line.
- The item does not contain items that continue past the end of the line or
make it continue on the next line.
- The item does not change the size of any item it is contained in. Example
for C: A match with "\\$" in a preprocessor match can't have "display",
because it may make that preprocessor match shorter.
- The item does not allow other items to match that didn't match otherwise,
and that item may extend the match too far. Example for C: A match for a
"//" comment can't use "display", because a "/*" inside that comment would
match then and start a comment which extends past the end of the line.
Examples, for the C language, where "display" can be used:
- match with a number
- match with a label
transparent *:syn-transparent*
If the "transparent" argument is given, this item will not be highlighted
itself, but will take the highlighting of the item it is contained in. This
is useful for syntax items that don't need any highlighting but are used
only to skip over a part of the text.
The "contains=" argument is also inherited from the item it is contained in,
unless a "contains" argument is given for the transparent item itself. To
avoid that unwanted items are contained, use "contains=NONE". Example, which
highlights words in strings, but makes an exception for "vim":
:syn match myString /'[^']*'/ contains=myWord,myVim
:syn match myWord /\<[a-z]*\>/ contained
:syn match myVim /\<vim\>/ transparent contained contains=NONE
:hi link myString String
:hi link myWord Comment
Since the "myVim" match comes after "myWord" it is the preferred match (last
match in the same position overrules an earlier one). The "transparent"
argument makes the "myVim" match use the same highlighting as "myString". But
it does not contain anything. If the "contains=NONE" argument would be left
out, then "myVim" would use the contains argument from myString and allow
"myWord" to be contained, which will be highlighted as a Constant. This
happens because a contained match doesn't match inside itself in the same
position, thus the "myVim" match doesn't overrule the "myWord" match here.
When you look at the colored text, it is like looking at layers of contained
items. The contained item is on top of the item it is contained in, thus you
see the contained item. When a contained item is transparent, you can look
through, thus you see the item it is contained in. In a picture:
look from here
| | | | | |
V V V V V V
xxxx yyy more contained items
.................... contained item (transparent)
============================= first item
The 'x', 'y' and '=' represent a highlighted syntax item. The '.' represent a
transparent group.
What you see is:
=======xxxx=======yyy========
Thus you look through the transparent "....".
oneline *:syn-oneline*
The "oneline" argument indicates that the region does not cross a line
boundary. It must match completely in the current line. However, when the
region has a contained item that does cross a line boundary, it continues on
the next line anyway. A contained item can be used to recognize a line
continuation pattern. But the "end" pattern must still match in the first
line, otherwise the region doesn't even start.
When the start pattern includes a "\n" to match an end-of-line, the end
pattern must be found in the same line as where the start pattern ends. The
end pattern may also include an end-of-line. Thus the "oneline" argument
means that the end of the start pattern and the start of the end pattern must
be within one line. This can't be changed by a skip pattern that matches a
line break.
fold *:syn-fold*
The "fold" argument makes the fold level increase by one for this item.
Example:
:syn region myFold start="{" end="}" transparent fold
:syn sync fromstart
:set foldmethod=syntax
This will make each {} block form one fold.
The fold will start on the line where the item starts, and end where the item
ends. If the start and end are within the same line, there is no fold.
The 'foldnestmax' option limits the nesting of syntax folds.
{not available when Vim was compiled without |+folding| feature}
The {group-name} in the "contains" list can be a pattern. All group names
that match the pattern will be included (or excluded, if "ALLBUT" is used).
The pattern cannot contain white space or a ','. Example:
... contains=Comment.*,Keyw[0-3]
The matching will be done at moment the syntax command is executed. Groups
that are defined later will not be matched. Also, if the current syntax
command defines a new group, it is not matched. Be careful: When putting
syntax commands in a file you can't rely on groups NOT being defined, because
the file may have been sourced before, and ":syn clear" doesn't remove the
group names.
The contained groups will also match in the start and end patterns of a
region. If this is not wanted, the "matchgroup" argument can be used
|:syn-matchgroup|. The "ms=" and "me=" offsets can be used to change the
region where contained items do match. Note that this may also limit the
area that is highlighted
containedin={groupname}... *:syn-containedin*
The "containedin" argument is followed by a list of syntax group names. The
item will be allowed to begin inside these groups. This works as if the
containing item has a "contains=" argument that includes this item.
The {groupname}... can be used just like for "contains", as explained above.
This is useful when adding a syntax item afterwards. An item can be told to
be included inside an already existing item, without changing the definition
of that item. For example, to highlight a word in a C comment after loading
the C syntax:
:syn keyword myword HELP containedin=cComment contained
Note that "contained" is also used, to avoid that the item matches at the top
level.
Matches for "containedin" are added to the other places where the item can
appear. A "contains" argument may also be added as usual. Don't forget that
keywords never contain another item, thus adding them to "containedin" won't
work.
nextgroup={groupname},.. *:syn-nextgroup*
The "nextgroup" argument is followed by a list of syntax group names,
separated by commas (just like with "contains", so you can also use patterns).
skipwhite *:syn-skipwhite*
skipnl *:syn-skipnl*
skipempty *:syn-skipempty*
These arguments are only used in combination with "nextgroup". They can be
used to allow the next group to match after skipping some text:
skipwhite skip over space and tab characters
skipnl skip over the end of a line
skipempty skip over empty lines (implies a "skipnl")
When "skipwhite" is present, the white space is only skipped if there is no
next group that matches the white space.
When "skipnl" is present, the match with nextgroup may be found in the next
line. This only happens when the current item ends at the end of the current
line! When "skipnl" is not present, the nextgroup will only be found after
the current item in the same line.
When skipping text while looking for a next group, the matches for other
groups are ignored. Only when no next group matches, other items are tried
for a match again. This means that matching a next group and skipping white
space and <EOL>s has a higher priority than other items.
Example:
:syn match ifstart "\<if.*" nextgroup=ifline skipwhite skipempty
:syn match ifline "[^ \t].*" nextgroup=ifline skipwhite skipempty contained
:syn match ifline "endif" contained
Note that the "[^ \t].*" match matches all non-white text. Thus it would also
match "endif". Therefore the "endif" match is put last, so that it takes
precedence.
Note that this example doesn't work for nested "if"s. You need to add
"contains" arguments to make that work (omitted for simplicity of the
example).
*:syn-pattern-offset*
The pattern can be followed by a character offset. This can be used to
change the highlighted part, and to change the text area included in the
match or region (which only matters when trying to match other items). Both
are relative to the matched pattern. The character offset for a skip
pattern can be used to tell where to continue looking for an end pattern.
The offset takes the form of "{what}={offset}"
The {what} can be one of seven strings:
ms Match Start offset for the start of the matched text
me Match End offset for the end of the matched text
hs Highlight Start offset for where the highlighting starts
he Highlight End offset for where the highlighting ends
rs Region Start offset for where the body of a region starts
re Region End offset for where the body of a region ends
lc Leading Context offset past "leading context" of pattern
The {offset} can be:
s start of the matched pattern
s+{nr} start of the matched pattern plus {nr} chars to the right
s-{nr} start of the matched pattern plus {nr} chars to the left
e end of the matched pattern
e+{nr} end of the matched pattern plus {nr} chars to the right
e-{nr} end of the matched pattern plus {nr} chars to the left
{nr} (for "lc" only): start matching {nr} chars to the left
Examples: "ms=s+1", "hs=e-2", "lc=3".
Although all offsets are accepted after any pattern, they are not always
meaningful. This table shows which offsets are actually used:
ms me hs he rs re lc
match item yes yes yes yes - - yes
region item start yes - yes - yes - yes
region item skip - yes - - - - yes
region item end - yes - yes - yes yes
Offsets can be concatenated, with a ',' in between. Example:
:syn match String /"[^"]*"/hs=s+1,he=e-1
some "string" text
^^^^^^ highlighted
Notes:
- There must be no white space between the pattern and the character
offset(s).
- The highlighted area will never be outside of the matched text.
- A negative offset for an end pattern may not always work, because the end
pattern may be detected when the highlighting should already have stopped.
- Before Vim 7.2 the offsets were counted in bytes instead of characters.
This didn't work well for multi-byte characters, so it was changed with the
Vim 7.2 release.
- The start of a match cannot be in a line other than where the pattern
matched. This doesn't work: "a\nb"ms=e. You can make the highlighting
start in another line, this does work: "a\nb"hs=e.
Example (match a comment but don't highlight the /* and */):
:syntax region Comment start="/\*"hs=e+1 end="\*/"he=s-1
/* this is a comment */
^^^^^^^^^^^^^^^^^^^ highlighted
A more complicated Example:
:syn region Exa matchgroup=Foo start="foo"hs=s+2,rs=e+2 matchgroup=Bar end="bar"me=e-1,he=e-
1,re=s-1
abcfoostringbarabc
mmmmmmmmmmm match
sssrrreee highlight start/region/end ("Foo", "Exa" and "Bar")
*E848*
The maximum number of clusters is 9767.
==============================================================================
9. Including syntax files *:syn-include* *E397*
It is often useful for one language's syntax file to include a syntax file for
a related language. Depending on the exact relationship, this can be done in
two different ways:
- If top-level syntax items in the included syntax file are to be
allowed at the top level in the including syntax, you can simply use
the |:runtime| command:
" In cpp.vim:
:runtime! syntax/c.vim
:unlet b:current_syntax
- If top-level syntax items in the included syntax file are to be
contained within a region in the including syntax, you can use the
":syntax include" command:
:sy[ntax] include [@{grouplist-name}] {file-name}
All syntax items declared in the included file will have the
"contained" flag added. In addition, if a group list is specified,
all top-level syntax items in the included file will be added to
that list.
" In perl.vim:
:syntax include @Pod <sfile>:p:h/pod.vim
:syntax region perlPOD start="^=head" end="^=cut" contains=@Pod
When {file-name} is an absolute path (starts with "/", "c:", "$VAR"
or "<sfile>") that file is sourced. When it is a relative path
(e.g., "syntax/pod.vim") the file is searched for in 'runtimepath'.
All matching files are loaded. Using a relative path is
recommended, because it allows a user to replace the included file
with his own version, without replacing the file that does the ":syn
include".
*E847*
The maximum number of includes is 999.
==============================================================================
10. Synchronizing *:syn-sync* *E403* *E404*
Vim wants to be able to start redrawing in any position in the document. To
make this possible it needs to know the syntax state at the position where
redrawing starts.
:sy[ntax] sync [ccomment [group-name] | minlines={N} | ...]
There are four ways to synchronize:
1. Always parse from the start of the file.
|:syn-sync-first|
2. Based on C-style comments. Vim understands how C-comments work and can
figure out if the current line starts inside or outside a comment.
|:syn-sync-second|
3. Jumping back a certain number of lines and start parsing there.
|:syn-sync-third|
4. Searching backwards in the text for a pattern to sync on.
|:syn-sync-fourth|
*:syn-sync-maxlines* *:syn-sync-minlines*
For the last three methods, the line range where the parsing can start is
limited by "minlines" and "maxlines".
If the "minlines={N}" argument is given, the parsing always starts at least
that many lines backwards. This can be used if the parsing may take a few
lines before it's correct, or when it's not possible to use syncing.
If the "maxlines={N}" argument is given, the number of lines that are searched
for a comment or syncing pattern is restricted to N lines backwards (after
adding "minlines"). This is useful if you have few things to sync on and a
slow machine. Example:
:syntax sync ccomment maxlines=500
*:syn-sync-linebreaks*
When using a pattern that matches multiple lines, a change in one line may
cause a pattern to no longer match in a previous line. This means has to
start above where the change was made. How many lines can be specified with
the "linebreaks" argument. For example, when a pattern may include one line
break use this:
:syntax sync linebreaks=1
The result is that redrawing always starts at least one line before where a
change was made. The default value for "linebreaks" is zero. Usually the
value for "minlines" is bigger than "linebreaks".
- When a match with a sync pattern is found, the rest of the line (or group of
continued lines) is searched for another match. The last match is used.
This is used when a line can contain both the start end the end of a region
(e.g., in a C-comment like /* this */, the last "*/" is used).
There are two ways how a match with a sync pattern can be used:
1. Parsing for highlighting starts where redrawing starts (and where the
search for the sync pattern started). The syntax group that is expected
to be valid there must be specified. This works well when the regions
that cross lines cannot contain other regions.
2. Parsing for highlighting continues just after the match. The syntax group
that is expected to be present just after the match must be specified.
This can be used when the previous method doesn't work well. It's much
slower, because more text needs to be parsed.
Both types of sync patterns can be used at the same time.
Besides the sync patterns, other matches and regions can be specified, to
avoid finding unwanted matches.
[The reason that the sync patterns are given separately, is that mostly the
search for the sync point can be much simpler than figuring out the
highlighting. The reduced number of patterns means it will go (much)
faster.]
*syn-sync-groupthere*
:syntax sync match {sync-group-name} groupthere {group-name} "pattern" ..
Like "grouphere", but {group-name} is the name of a syntax group that
is to be used at the start of the line where searching for the sync
point started. The text between the match and the start of the sync
pattern searching is assumed not to change the syntax highlighting.
For example, in C you could search backwards for "/*" and "*/". If
"/*" is found first, you know that you are inside a comment, so the
"groupthere" is "cComment". If "*/" is found first, you know that you
are not in a comment, so the "groupthere" is "NONE". (in practice
it's a bit more complicated, because the "/*" and "*/" could appear
inside a string. That's left as an exercise to the reader...).
:syntax sync match ..
:syntax sync region ..
Without a "groupthere" argument. Define a region or match that is
skipped while searching for a sync point.
*syn-sync-linecont*
:syntax sync linecont {pattern}
When {pattern} matches in a line, it is considered to continue in
the next line. This means that the search for a sync point will
consider the lines to be concatenated.
If the "maxlines={N}" argument is given too, the number of lines that are
searched for a match is restricted to N. This is useful if you have very
few things to sync on and a slow machine. Example:
:syntax sync maxlines=100
You can clear all sync settings with:
:syntax sync clear
You can clear specific sync patterns with:
:syntax sync clear {sync-group-name} ..
==============================================================================
11. Listing syntax items *:syntax* *:sy* *:syn* *:syn-list*
This command lists all the syntax items:
:sy[ntax] [list]
To show the syntax items for one syntax group:
:sy[ntax] list {group-name}
highlight commands to change the arguments that you want to set to non-default
values. The value "NONE" can be used to switch the value off or go back to
the default value.
A simple way to change colors is with the |:colorscheme| command. This loads
a file with ":highlight" commands such as this:
:hi Comment gui=bold
Note that all settings that are not included remain the same, only the
specified field is used, and settings are merged with previous ones. So, the
result is like this single command has been used:
:hi Comment term=bold ctermfg=Cyan guifg=#80a0ff gui=bold
*:highlight-verbose*
When listing a highlight group and 'verbose' is non-zero, the listing will
also tell where it was last set. Example:
:verbose hi Comment
Comment xxx term=bold ctermfg=4 guifg=Blue
Last set from /home/mool/vim/vim7/runtime/syntax/syncolor.vim
When ":hi clear" is used then the script where this command is used will be
mentioned for the default values. See |:verbose-cmd| for more information.
"t_" and blanks are not allowed. The <> notation is recognized
here, so you can use things like "<Esc>" and "<Space>". Example:
start=<Esc>[27h;<Esc>[<Space>r;
2. A list of terminal codes.
Each terminal code has the form "t_xx", where "xx" is the name of
the termcap entry. The codes have to be separated with commas.
White space is not allowed. Example:
start=t_C1,t_BL
The terminal codes must exist for this to work.
cterm={attr-list} *highlight-cterm*
See above for the description of {attr-list} |attr-list|.
The "cterm" argument is likely to be different from "term", when
colors are used. For example, in a normal terminal comments could
be underlined, in a color terminal they can be made Blue.
Note: Many terminals (e.g., DOS console) can't mix these attributes
with coloring. Use only one of "cterm=" OR "ctermfg=" OR "ctermbg=".
*cterm-colors*
NR-16 NR-8 COLOR NAME
0 0 Black
1 4 DarkBlue
2 2 DarkGreen
3 6 DarkCyan
4 1 DarkRed
5 5 DarkMagenta
6 3 Brown, DarkYellow
7 7 LightGray, LightGrey, Gray, Grey
8 0* DarkGray, DarkGrey
9 4* Blue, LightBlue
10 2* Green, LightGreen
11 6* Cyan, LightCyan
12 1* Red, LightRed
13 5* Magenta, LightMagenta
14 3* Yellow, LightYellow
15 7* White
The number under "NR-16" is used for 16-color terminals ('t_Co'
greater than or equal to 16). The number under "NR-8" is used for
8-color terminals ('t_Co' less than 16). The '*' indicates that the
bold attribute is set for ctermfg. In many 8-color terminals (e.g.,
"linux"), this causes the bright colors to appear. This doesn't work
for background colors! Without the '*' the bold attribute is removed.
If you want to set the bold attribute in a different way, put a
"cterm=" argument AFTER the "ctermfg=" or "ctermbg=" argument. Or use
a number instead of a color name.
The case of the color names is ignored.
Note that for 16 color ansi style terminals (including xterms), the
numbers in the NR-8 column is used. Here '*' means 'add 8' so that Blue
is 12, DarkGray is 8 etc.
Note that for some color terminals these names may result in the wrong
colors!
*:hi-normal-cterm*
When setting the "ctermfg" or "ctermbg" colors for the Normal group,
these will become the colors used for the non-highlighted text.
Example:
:highlight Normal ctermfg=grey ctermbg=darkblue
When setting the "ctermbg" color for the Normal group, the
'background' option will be adjusted automatically. This causes the
highlight groups that depend on 'background' to change! This means
you should set the colors for Normal first, before setting other
colors.
When a colorscheme is being used, changing 'background' causes it to
be reloaded, which may reset all colors (including Normal). First
delete the "g:colors_name" variable when you don't want this.
When you have set "ctermfg" or "ctermbg" for the Normal group, Vim
needs to reset the color when exiting. This is done with the "op"
termcap entry |t_op|. If this doesn't work correctly, try setting the
't_op' option in your .vimrc.
*E419* *E420*
When Vim knows the normal foreground and background colors, "fg" and
"bg" can be used as color names. This only works after setting the
colors for the Normal group and for the MS-DOS console. Example, for
reverse video:
:highlight Visual ctermfg=bg ctermbg=fg
Note that the colors are used that are valid at the moment this
command are given. If the Normal group colors are changed later, the
"fg" and "bg" colors will not be adjusted.
gui={attr-list} *highlight-gui*
These give the attributes to use in the GUI mode.
See |attr-list| for a description.
Note that "bold" can be used here and by using a bold font. They
have the same effect.
Note that the attributes are ignored for the "Normal" group.
font={font-name} *highlight-font*
font-name is the name of a font, as it is used on the system Vim
runs on. For X11 this is a complicated name, for example:
font=-misc-fixed-bold-r-normal--14-130-75-75-c-70-iso8859-1
The font-name "NONE" can be used to revert to the default font.
When setting the font for the "Normal" group, this becomes the default
font (until the 'guifont' option is changed; the last one set is
used).
The following only works with Motif and Athena, not with other GUIs:
When setting the font for the "Menu" group, the menus will be changed.
When setting the font for the "Tooltip" group, the tooltips will be
changed.
All fonts used, except for Menu and Tooltip, should be of the same
character size as the default font! Otherwise redrawing problems will
occur.
guifg={color-name} *highlight-guifg*
guibg={color-name} *highlight-guibg*
guisp={color-name} *highlight-guisp*
These give the foreground (guifg), background (guibg) and special
(guisp) color to use in the GUI. "guisp" is used for undercurl.
There are a few special names:
NONE no color (transparent)
bg use normal background color
background use normal background color
fg use normal foreground color
foreground use normal foreground color
To use a color name with an embedded space or other special character,
put it in single quotes. The single quote cannot be used then.
Example:
*gui-colors*
Suggested color names (these are available on most systems):
Red LightRed DarkRed
Green LightGreen DarkGreen SeaGreen
Blue LightBlue DarkBlue SlateBlue
Cyan LightCyan DarkCyan
Magenta LightMagenta DarkMagenta
Yellow LightYellow Brown DarkYellow
Gray LightGray DarkGray
Black White
Orange Purple Violet
In the Win32 GUI version, additional system colors are available. See
|win32-colors|.
You can also specify a color by its Red, Green and Blue values.
The format is "#rrggbb", where
"rr" is the Red value
"gg" is the Green value
"bb" is the Blue value
All values are hexadecimal, range from "00" to "ff". Examples:
:highlight Comment guifg=#11f0c3 guibg=#ff00ff
*highlight-groups* *highlight-default*
These are the default highlighting groups. These groups are used by the
'highlight' option default. Note that the highlighting depends on the value
of 'background'. You can see the current settings with the ":highlight"
command.
*hl-ColorColumn*
ColorColumn used for the columns set with 'colorcolumn'
*hl-Conceal*
Conceal placeholder characters substituted for concealed
text (see 'conceallevel')
*hl-Cursor*
Cursor the character under the cursor
*hl-CursorIM*
CursorIM like Cursor, but used when in IME mode |CursorIM|
*hl-CursorColumn*
CursorColumn the screen column that the cursor is in when 'cursorcolumn' is
set
*hl-CursorLine*
CursorLine the screen line that the cursor is in when 'cursorline' is
set
*hl-Directory*
Directory directory names (and other special names in listings)
*hl-DiffAdd*
DiffAdd diff mode: Added line |diff.txt|
*hl-DiffChange*
DiffChange diff mode: Changed line |diff.txt|
*hl-DiffDelete*
DiffDelete diff mode: Deleted line |diff.txt|
*hl-DiffText*
DiffText diff mode: Changed text within a changed line |diff.txt|
*hl-ErrorMsg*
ErrorMsg error messages on the command line
*hl-VertSplit*
VertSplit the column separating vertically split windows
*hl-Folded*
Folded line used for closed folds
*hl-FoldColumn*
FoldColumn 'foldcolumn'
*hl-SignColumn*
SignColumn column where |signs| are displayed
*hl-IncSearch*
IncSearch 'incsearch' highlighting; also used for the text replaced with
":s///c"
*hl-LineNr*
LineNr Line number for ":number" and ":#" commands, and when 'number'
or 'relativenumber' option is set.
*hl-MatchParen*
MatchParen The character under the cursor or just before it, if it
is a paired bracket, and its match. |pi_paren.txt|
*hl-ModeMsg*
ModeMsg 'showmode' message (e.g., "-- INSERT --")
*hl-MoreMsg*
MoreMsg |more-prompt|
*hl-NonText*
NonText '~' and '@' at the end of the window, characters from
'showbreak' and other characters that do not really exist in
the text (e.g., ">" displayed when a double-wide character
doesn't fit at the end of the line).
*hl-Normal*
Normal normal text
*hl-Pmenu*
Pmenu Popup menu: normal item.
*hl-PmenuSel*
PmenuSel Popup menu: selected item.
*hl-PmenuSbar*
PmenuSbar Popup menu: scrollbar.
*hl-PmenuThumb*
PmenuThumb Popup menu: Thumb of the scrollbar.
*hl-Question*
Question |hit-enter| prompt and yes/no questions
*hl-Search*
Search Last search pattern highlighting (see 'hlsearch').
Also used for highlighting the current line in the quickfix
window and similar items that need to stand out.
*hl-SpecialKey*
SpecialKey Meta and special keys listed with ":map", also for text used
to show unprintable characters in the text, 'listchars'.
Generally: text that is displayed differently from what it
really is.
*hl-SpellBad*
SpellBad Word that is not recognized by the spellchecker. |spell|
This will be combined with the highlighting used otherwise.
*hl-SpellCap*
SpellCap Word that should start with a capital. |spell|
This will be combined with the highlighting used otherwise.
*hl-SpellLocal*
SpellLocal Word that is recognized by the spellchecker as one that is
used in another region. |spell|
This will be combined with the highlighting used otherwise.
*hl-SpellRare*
SpellRare Word that is recognized by the spellchecker as one that is
hardly ever used. |spell|
This will be combined with the highlighting used otherwise.
*hl-StatusLine*
StatusLine status line of current window
*hl-StatusLineNC*
StatusLineNC status lines of not-current windows
Note: if this is equal to "StatusLine" Vim will use "^^^" in
the status line of the current window.
*hl-TabLine*
TabLine tab pages line, not active tab page label
*hl-TabLineFill*
TabLineFill tab pages line, where there are no labels
*hl-TabLineSel*
TabLineSel tab pages line, active tab page label
*hl-Title*
Title titles for output from ":set all", ":autocmd" etc.
*hl-Visual*
Visual Visual mode selection
*hl-VisualNOS*
VisualNOS Visual mode selection when vim is "Not Owning the Selection".
Only X11 Gui's |gui-x11| and |xterm-clipboard| supports this.
*hl-WarningMsg*
WarningMsg warning messages
*hl-WildMenu*
WildMenu current match in 'wildmenu' completion
*hl-Menu*
Menu Current font, background and foreground colors of the menus.
Also used for the toolbar.
Applicable highlight arguments: font, guibg, guifg.
NOTE: For Motif and Athena the font argument actually
specifies a fontset at all times, no matter if 'guifontset' is
empty, and as such it is tied to the current |:language| when
set.
*hl-Scrollbar*
Scrollbar Current background and foreground of the main window's
scrollbars.
Applicable highlight arguments: guibg, guifg.
*hl-Tooltip*
Tooltip Current font, background and foreground of the tooltips.
Applicable highlight arguments: font, guibg, guifg.
NOTE: For Motif and Athena the font argument actually
specifies a fontset at all times, no matter if 'guifontset' is
empty, and as such it is tied to the current |:language| when
set.
==============================================================================
13. Linking groups *:hi-link* *:highlight-link* *E412* *E413*
When you want to use the same highlighting for several syntax groups, you
can do this more easily by linking the groups into one common highlight
group, and give the color attributes only for that group.
To set a link:
:hi[ghlight][!] [default] link {from-group} {to-group}
To remove a link:
:hi[ghlight][!] [default] link {from-group} NONE
Notes: *E414*
- If the {from-group} and/or {to-group} doesn't exist, it is created. You
don't get an error message for a non-existing group.
- As soon as you use a ":highlight" command for a linked group, the link is
removed.
- If there are already highlight settings for the {from-group}, the link is
not made, unless the '!' is given. For a ":highlight link" command in a
sourced file, you don't get an error message. This can be used to skip
links for groups that already have settings.
*:hi-default* *:highlight-default*
The [default] argument is used for setting the default highlighting for a
group. If highlighting has already been specified for the group the command
will be ignored. Also when there is an existing link.
Using [default] is especially useful to overrule the highlighting of a
specific syntax file. For example, the C syntax file contains:
:highlight default link cComment Comment
If you like Question highlighting for C comments, put this in your vimrc file:
:highlight link cComment Question
Without the "default" in the C syntax file, the highlighting would be
overruled when the syntax file is loaded.
==============================================================================
14. Cleaning up *:syn-clear* *E391*
If you want to clear the syntax stuff for the current buffer, you can use this
command:
:syntax clear
This command should be used when you want to switch off syntax highlighting,
or when you want to switch to using another syntax. It's normally not needed
in a syntax file itself, because syntax is cleared by the autocommands that
load the syntax file.
The command also deletes the "b:current_syntax" variable, since no syntax is
loaded after this command.
If you want to disable syntax highlighting for all buffers, you need to remove
the autocommands that load the syntax files:
:syntax off
What this command actually does, is executing the command
:source $VIMRUNTIME/syntax/nosyntax.vim
See the "nosyntax.vim" file for details. Note that for this to work
$VIMRUNTIME must be valid. See |$VIMRUNTIME|.
To clean up specific syntax groups for the current buffer:
:syntax clear {group-name} ..
This removes all patterns and keywords for {group-name}.
To clean up specific syntax group lists for the current buffer:
:syntax clear @{grouplist-name} ..
This sets {grouplist-name}'s contents to an empty list.
*:syntax-reset* *:syn-reset*
If you have changed the colors and messed them up, use this command to get the
defaults back:
:syntax reset
This doesn't change the colors for the 'highlight' option.
Note that the syntax colors that you set in your vimrc file will also be reset
back to their Vim default.
Note that if you are using a color scheme, the colors defined by the color
scheme for syntax highlighting will be lost.
What this actually does is:
let g:syntax_cmd = "reset"
runtime! syntax/syncolor.vim
Note that this uses the 'runtimepath' option.
*syncolor*
If you want to use different colors for syntax highlighting, you can add a Vim
script file to set these colors. Put this file in a directory in
'runtimepath' which comes after $VIMRUNTIME, so that your settings overrule
the default colors. This way these colors will be used after the ":syntax
reset" command.
For Unix you can use the file ~/.vim/after/syntax/syncolor.vim. Example:
if &background == "light"
highlight comment ctermfg=darkgreen guifg=darkgreen
else
highlight comment ctermfg=green guifg=green
endif
*E679*
Do make sure this syncolor.vim script does not use a "syntax on", set the
'background' option or uses a "colorscheme" command, because it results in an
endless loop.
Note that when a color scheme is used, there might be some confusion whether
your defined colors are to be used or the colors from the scheme. This
depends on the color scheme file. See |:colorscheme|.
*syntax_cmd*
The "syntax_cmd" variable is set to one of these values when the
syntax/syncolor.vim files are loaded:
"on" ":syntax on" command. Highlight colors are overruled but
links are kept
"enable" ":syntax enable" command. Only define colors for groups that
don't have highlighting yet. Use ":syntax default".
"reset" ":syntax reset" command or loading a color scheme. Define all
the colors.
"skip" Don't define colors. Used to skip the default settings when a
syncolor.vim file earlier in 'runtimepath' has already set
them.
==============================================================================
15. Highlighting tags *tag-highlight*
If you want to highlight all the tags in your file, you can use the following
mappings.
<F11> -- Generate tags.vim file, and highlight tags.
<F12> -- Just highlight tags based on existing tags.vim file.
:map <F11> :sp tags<CR>:%s/^\([^ :]*:\)\=\([^ ]*\).*/syntax keyword Tag \2/<CR>:wq!
tags.vim<CR>/^<CR><F12>
:map <F12> :so tags.vim<CR>
WARNING: The longer the tags file, the slower this will be, and the more
memory Vim will consume.
Only highlighting typedefs, unions and structs can be done too. For this you
must use Exuberant ctags found at http://ctags.sf.net.
Put these lines in your Makefile:
# Make a highlight file for types. Requires Exuberant ctags and awk
types: types.vim
types.vim: *.[ch]
ctags --c-kinds=gstu -o- *.[ch] YXXY\
awk 'BEGIN{printf("syntax keyword Type\t")}\
{printf("%s ", $$1)}END{print ""}' > $@
And put these lines in your .vimrc:
" load the types.vim highlighting file, if it exists
autocmd BufRead,BufNewFile *.[ch] let fname = expand('<afile>:p:h') . '/types.vim'
autocmd BufRead,BufNewFile *.[ch] if filereadable(fname)
autocmd BufRead,BufNewFile *.[ch] exe 'so ' . fname
autocmd BufRead,BufNewFile *.[ch] endif
==============================================================================
16. Window-local syntax *:ownsyntax*
Normally all windows on a buffer share the same syntax settings. It is
possible, however, to set a particular window on a file to have its own
private syntax setting. A possible example would be to edit LaTeX source
with conventional highlighting in one window, while seeing the same source
highlighted differently (so as to hide control sequences and indicate bold,
italic etc regions) in another. The 'scrollbind' option is useful here.
To set the current window to have the syntax "foo", separately from all other
windows on the buffer:
:ownsyntax foo
*w:current_syntax*
This will set the "w:current_syntax" variable to "foo". The value of
"b:current_syntax" does not change. This is implemented by saving and
restoring "b:current_syntax", since the syntax files do set
"b:current_syntax". The value set by the syntax file is assigned to
"w:current_syntax".
Once a window has its own syntax, syntax commands executed from other windows
on the same buffer (including :syntax clear) have no effect. Conversely,
syntax commands executed from that window do not effect other windows on the
same buffer.
A window with its own syntax reverts to normal behavior when another buffer
is loaded into that window or the file is reloaded.
When splitting the window, the new window will use the original syntax.
==============================================================================
17. Color xterms *xterm-color* *color-xterm*
Most color xterms have only eight colors. If you don't get colors with the
default setup, it should work with these lines in your .vimrc:
:if &term =~ "xterm"
: if has("terminfo")
: set t_Co=8
: set t_Sf=<Esc>[3%p1%dm
: set t_Sb=<Esc>[4%p1%dm
: else
: set t_Co=8
: set t_Sf=<Esc>[3%dm
: set t_Sb=<Esc>[4%dm
: endif
:endif
[<Esc> is a real escape, type CTRL-V <Esc>]
You might want to change the first "if" to match the name of your terminal,
e.g. "dtterm" instead of "xterm".
Note: Do these settings BEFORE doing ":syntax on". Otherwise the colors may
be wrong.
*xiterm* *rxvt*
The above settings have been mentioned to work for xiterm and rxvt too.
But for using 16 colors in an rxvt these should work with terminfo:
:set t_AB=<Esc>[%?%p1%{8}%<%t25;%p1%{40}%+%e5;%p1%{32}%+%;%dm
:set t_AF=<Esc>[%?%p1%{8}%<%t22;%p1%{30}%+%e1;%p1%{22}%+%;%dm
*colortest.vim*
To test your color setup, a file has been included in the Vim distribution.
To use it, execute this command:
:runtime syntax/colortest.vim
Some versions of xterm (and other terminals, like the Linux console) can
output lighter foreground colors, even though the number of colors is defined
at 8. Therefore Vim sets the "cterm=bold" attribute for light foreground
colors, when 't_Co' is 8.
*xfree-xterm*
To get 16 colors or more, get the newest xterm version (which should be
included with XFree86 3.3 and later). You can also find the latest version
at:
http://invisible-island.net/xterm/xterm.html
Here is a good way to configure it. This uses 88 colors and enables the
termcap-query feature, which allows Vim to ask the xterm how many colors it
supports.
./configure --disable-bold-color --enable-88-color --enable-tcap-query
If you only get 8 colors, check the xterm compilation settings.
(Also see |UTF8-xterm| for using this xterm with UTF-8 character encoding).
This xterm should work with these lines in your .vimrc (for 16 colors):
:if has("terminfo")
: set t_Co=16
: set t_AB=<Esc>[%?%p1%{8}%<%t%p1%{40}%+%e%p1%{92}%+%;%dm
: set t_AF=<Esc>[%?%p1%{8}%<%t%p1%{30}%+%e%p1%{82}%+%;%dm
:else
: set t_Co=16
: set t_Sf=<Esc>[3%dm
: set t_Sb=<Esc>[4%dm
:endif
[<Esc> is a real escape, type CTRL-V <Esc>]
Without |+terminfo|, Vim will recognize these settings, and automatically
translate cterm colors of 8 and above to "<Esc>[9%dm" and "<Esc>[10%dm".
Colors above 16 are also translated automatically.
For 256 colors this has been reported to work:
:set t_AB=<Esc>[48;5;%dm
:set t_AF=<Esc>[38;5;%dm
Or just set the TERM environment variable to "xterm-color" or "xterm-16color"
and try if that works.
You probably want to use these X resources (in your ~/.Xdefaults file):
XTerm*color0: #000000
XTerm*color1: #c00000
XTerm*color2: #008000
XTerm*color3: #808000
XTerm*color4: #0000c0
XTerm*color5: #c000c0
XTerm*color6: #008080
XTerm*color7: #c0c0c0
XTerm*color8: #808080
XTerm*color9: #ff6060
XTerm*color10: #00ff00
XTerm*color11: #ffff00
XTerm*color12: #8080ff
XTerm*color13: #ff40ff
XTerm*color14: #00ffff
XTerm*color15: #ffffff
Xterm*cursorColor: Black
[Note: The cursorColor is required to work around a bug, which changes the
cursor color to the color of the last drawn text. This has been fixed by a
newer version of xterm, but not everybody is using it yet.]
To get these right away, reload the .Xdefaults file to the X Option database
Manager (you only need to do this when you just changed the .Xdefaults file):
xrdb -merge ~/.Xdefaults
*xterm-blink* *xterm-blinking-cursor*
To make the cursor blink in an xterm, see tools/blink.c. Or use Thomas
Dickey's xterm above patchlevel 107 (see above for where to get it), with
these resources:
XTerm*cursorBlink: on
XTerm*cursorOnTime: 400
XTerm*cursorOffTime: 250
XTerm*cursorColor: White
*hpterm-color*
These settings work (more or less) for an hpterm, which only supports 8
foreground colors:
:if has("terminfo")
: set t_Co=8
: set t_Sf=<Esc>[&v%p1%dS
: set t_Sb=<Esc>[&v7S
:else
: set t_Co=8
: set t_Sf=<Esc>[&v%dS
: set t_Sb=<Esc>[&v7S
:endif
[<Esc> is a real escape, type CTRL-V <Esc>]
*Eterm* *enlightened-terminal*
These settings have been reported to work for the Enlightened terminal
emulator, or Eterm. They might work for all xterm-like terminals that use the
bold attribute to get bright colors. Add an ":if" like above when needed.
:set t_Co=16
:set t_AF=^[[%?%p1%{8}%<%t3%p1%d%e%p1%{22}%+%d;1%;m
:set t_AB=^[[%?%p1%{8}%<%t4%p1%d%e%p1%{32}%+%d;1%;m
*TTpro-telnet*
These settings should work for TTpro telnet. Tera Term Pro is a freeware /
open-source program for MS-Windows.
set t_Co=16
set t_AB=^[[%?%p1%{8}%<%t%p1%{40}%+%e%p1%{32}%+5;%;%dm
set t_AF=^[[%?%p1%{8}%<%t%p1%{30}%+%e%p1%{22}%+1;%;%dm
Also make sure TTpro's Setup / Window / Full Color is enabled, and make sure
that Setup / Font / Enable Bold is NOT enabled.
(info provided by John Love-Jensen <eljay@Adobe.COM>)
top - main help file
*cscope* *Cscope*
This document explains how to use Vim's cscope interface.
Cscope is a tool like ctags, but think of it as ctags on steroids since it
does a lot more than what ctags provides. In Vim, jumping to a result from
a cscope query is just like jumping to any tag; it is saved on the tag stack
so that with the right keyboard mappings, you can jump back and forth between
functions as you normally would with |tags|.
1. Cscope introduction |cscope-intro|
2. Cscope related commands |cscope-commands|
3. Cscope options |cscope-options|
4. How to use cscope in Vim |cscope-howtouse|
5. Limitations |cscope-limitations|
6. Suggested usage |cscope-suggestions|
7. Availability & Information |cscope-info|
This is currently for Unix and Win32 only.
{Vi does not have any of these commands}
==============================================================================
1. Cscope introduction *cscope-intro*
The following text is taken from a version of the cscope man page:
-----
Cscope is an interactive screen-oriented tool that helps you:
Learn how a C program works without endless flipping through a thick
listing.
Locate the section of code to change to fix a bug without having to
learn the entire program.
Examine the effect of a proposed change such as adding a value to an
enum variable.
Verify that a change has been made in all source files such as adding
an argument to an existing function.
Rename a global variable in all source files.
Change a constant to a preprocessor symbol in selected lines of files.
It is designed to answer questions like:
Where is this symbol used?
Where is it defined?
Where did this variable get its value?
What is this global symbol's definition?
Where is this function in the source files?
What functions call this function?
What functions are called by this function?
Where does the message "out of space" come from?
Where is this source file in the directory structure?
What files include this header file?
Cscope answers these questions from a symbol database that it builds the
first time it is used on the source files. On a subsequent call, cscope
rebuilds the database only if a source file has changed or the list of
source files is different. When the database is rebuilt the data for the
unchanged files is copied from the old database, which makes rebuilding
much faster than the initial build.
-----
When cscope is normally invoked, you will get a full-screen selection
screen allowing you to make a query for one of the above questions.
However, once a match is found to your query and you have entered your
text editor to edit the source file containing match, you cannot simply
jump from tag to tag as you normally would with vi's Ctrl-] or :tag
command.
Vim's cscope interface is done by invoking cscope with its line-oriented
interface, and then parsing the output returned from a query. The end
result is that cscope query results become just like regular tags, so
you can jump to them just like you do with normal tags (Ctrl-] or :tag)
and then go back by popping off the tagstack with Ctrl-T. (Please note
however, that you don't actually jump to a cscope tag simply by doing
Ctrl-] or :tag without remapping these commands or setting an option.
See the remaining sections on how the cscope interface works and for
suggested use.)
==============================================================================
2. Cscope related commands *cscope-commands*
EXAMPLES
:cscope find c vim_free
:cscope find 3 vim_free
These two examples perform the same query: functions calling
"vim_free".
:cscope find t initOnce
:cscope find t initOnce
The first one searches for the text "initOnce", the second one for
" initOnce".
:cscope find 0 DEFAULT_TERM
Executing this example on the source code for Vim 5.1 produces the
following output:
Cscope tag: DEFAULT_TERM
# line filename / context / line
1 1009 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"amiga"
2 1013 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"win32"
3 1017 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"pcterm"
4 1021 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"ansi"
5 1025 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"vt52"
6 1029 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"os2ansi"
7 1033 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"ansi"
8 1037 vim-5.1-gtk/src/term.c <<GLOBAL>>
# undef DEFAULT_TERM
9 1038 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"beos-ansi"
10 1042 vim-5.1-gtk/src/term.c <<GLOBAL>>
#define DEFAULT_TERM (char_u *)"mac-ansi"
11 1335 vim-5.1-gtk/src/term.c <<set_termname>>
term = DEFAULT_TERM;
12 1459 vim-5.1-gtk/src/term.c <<set_termname>>
if (STRCMP(term, DEFAULT_TERM))
13 1826 vim-5.1-gtk/src/term.c <<termcapinit>>
term = DEFAULT_TERM;
14 1833 vim-5.1-gtk/src/term.c <<termcapinit>>
term = DEFAULT_TERM;
15 3635 vim-5.1-gtk/src/term.c <<update_tcap>>
p = find_builtin_term(DEFAULT_TERM);
Enter nr of choice (<CR> to abort):
The output shows several pieces of information:
1. The tag number (there are 15 in this example).
2. The line number where the tag occurs.
3. The filename where the tag occurs.
4. The context of the tag (e.g., global, or the function name).
5. The line from the file itself.
help : Show a brief synopsis.
USAGE :cs help
*E261*
kill : Kill a cscope connection (or kill all cscope connections).
USAGE :cs kill {num|partial_name}
To kill a cscope connection, the connection number or a partial
name must be specified. The partial name is simply any part of
the pathname of the cscope database. Kill a cscope connection
using the partial name with caution!
If the specified connection number is -1, then _ALL_ cscope
connections will be killed.
reset : Reinit all cscope connections.
USAGE :cs reset
*:lcscope* *:lcs*
This command is same as the ":cscope" command, except when the
'cscopequickfix' option is set, the location list for the current window is
used instead of the quickfix list to show the cscope results.
==============================================================================
3. Cscope options *cscope-options*
Use the |:set| command to set all cscope options. Ideally, you would do
this in one of your startup files (e.g., .vimrc). Some cscope related
variables are only valid within |.vimrc|. Setting them after vim has
started will have no effect!
*cscopeprg* *csprg*
'cscopeprg' specifies the command to execute cscope. The default is
"cscope". For example:
:set csprg=/usr/local/bin/cscope
*cscopetag* *cst*
If 'cscopetag' set, the commands ":tag" and CTRL-] as well as "vim -t" will
always use |:cstag| instead of the default :tag behavior. Effectively, by
setting 'cst', you will always search your cscope databases as well as your
tag files. The default is off. Examples:
:set cst
:set nocst
*cscopetagorder* *csto*
The value of 'csto' determines the order in which |:cstag| performs a search.
If 'csto' is set to zero, cscope database(s) are searched first, followed
by tag file(s) if cscope did not return any matches. If 'csto' is set to
one, tag file(s) are searched before cscope database(s). The default is zero.
Examples:
:set csto=0
:set csto=1
*cscopeverbose* *csverb*
If 'cscopeverbose' is not set (the default), messages will not be printed
indicating success or failure when adding a cscope database. Ideally, you
should reset this option in your |.vimrc| before adding any cscope databases,
and after adding them, set it. From then on, when you add more databases
within Vim, you will get a (hopefully) useful message should the database fail
to be added. Examples:
:set csverb
:set nocsverb
*cscopepathcomp* *cspc*
The value of 'cspc' determines how many components of a file's path to
display. With the default value of zero the entire path will be displayed.
The value one will display only the filename with no path. Other values
display that many components. For example:
:set cspc=3
will display the last 3 components of the file's path, including the file
name itself.
==============================================================================
4. How to use cscope in Vim *cscope-howtouse*
The first thing you need to do is to build a cscope database for your
source files. For the most basic case, simply do "cscope -b". Please
refer to the cscope man page for more details.
Assuming you have a cscope database, you need to "add" the database to Vim.
This establishes a cscope "connection" and makes it available for Vim to use.
You can do this in your .vimrc file, or you can do it manually after starting
vim. For example, to add the cscope database "cscope.out", you would do:
:cs add cscope.out
You can double-check the result of this by executing ":cs show". This will
produce output which looks like this:
# pid database name prepend path
0 28806 cscope.out <none>
Note:
Because of the Microsoft RTL limitations, Win32 version shows 0 instead
of the real pid.
Once a cscope connection is established, you can make queries to cscope and
the results will be printed to you. Queries are made using the command
":cs find". For example:
:cs find g ALIGN_SIZE
This can get a little cumbersome since one ends up doing a significant
amount of typing. Fortunately, there are ways around this by mapping
shortcut keys. See |cscope-suggestions| for suggested usage.
If the results return only one match, you will automatically be taken to it.
If there is more than one match, you will be given a selection screen to pick
the match you want to go to. After you have jumped to the new location,
simply hit Ctrl-T to get back to the previous one.
==============================================================================
5. Limitations *cscope-limitations*
Cscope support for Vim is only available on systems that support these four
system calls: fork(), pipe(), execl(), waitpid(). This means it is mostly
limited to Unix systems.
Additionally Cscope support works for Win32. For more information and a
cscope version for Win32 see:
http://iamphet.nm.ru/cscope/index.html
The DJGPP-built version from http://cscope.sourceforge.net is known to not
work with Vim.
Hard-coded limitation: doing a |:tjump| when |:cstag| searches the tag files
is not configurable (e.g., you can't do a tselect instead).
==============================================================================
6. Suggested usage *cscope-suggestions*
Put these entries in your .vimrc (adjust the pathname accordingly to your
setup):
if has("cscope")
set csprg=/usr/local/bin/cscope
set csto=0
set cst
set nocsverb
" add any database in current directory
if filereadable("cscope.out")
cs add cscope.out
" else add database pointed to by environment
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
set csverb
endif
By setting 'cscopetag', we have effectively replaced all instances of the :tag
command with :cstag. This includes :tag, Ctrl-], and "vim -t". In doing
this, the regular tag command not only searches your ctags generated tag
files, but your cscope databases as well.
Some users may want to keep the regular tag behavior and have a different
shortcut to access :cstag. For example, one could map Ctrl-_ (underscore)
to :cstag with the following command:
map <C-_> :cstag <C-R>=expand("<cword>")<CR><CR>
A couple of very commonly used cscope queries (using ":cs find") is to
find all functions calling a certain function and to find all occurrences
of a particular C symbol. To do this, you can use these mappings as an
example:
map g<C-]> :cs find 3 <C-R>=expand("<cword>")<CR><CR>
map g<C-\> :cs find 0 <C-R>=expand("<cword>")<CR><CR>
These mappings for Ctrl-] (right bracket) and Ctrl-\ (backslash) allow you to
place your cursor over the function name or C symbol and quickly query cscope
for any matches.
Or you may use the following scheme, inspired by Vim/Cscope tutorial from
Cscope Home Page http://cscope.sourceforge.net/:
nmap <C-_>s :cs find s <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>g :cs find g <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>c :cs find c <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>t :cs find t <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>e :cs find e <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>f :cs find f <C-R>=expand("<cfile>")<CR><CR>
nmap <C-_>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
nmap <C-_>d :cs find d <C-R>=expand("<cword>")<CR><CR>
" Using 'CTRL-spacebar' then a search type makes the vim window
" split horizontally, with search result displayed in
" the new window.
nmap <C-Space>s :scs find s <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space>g :scs find g <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space>c :scs find c <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space>t :scs find t <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space>e :scs find e <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space>f :scs find f <C-R>=expand("<cfile>")<CR><CR>
nmap <C-Space>i :scs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
nmap <C-Space>d :scs find d <C-R>=expand("<cword>")<CR><CR>
" Hitting CTRL-space *twice* before the search type does a vertical
" split instead of a horizontal one
nmap <C-Space><C-Space>s
\:vert scs find s <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space><C-Space>g
\:vert scs find g <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space><C-Space>c
\:vert scs find c <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space><C-Space>t
\:vert scs find t <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space><C-Space>e
\:vert scs find e <C-R>=expand("<cword>")<CR><CR>
nmap <C-Space><C-Space>i
\:vert scs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
nmap <C-Space><C-Space>d
\:vert scs find d <C-R>=expand("<cword>")<CR><CR>
==============================================================================
7. Cscope availability and information *cscope-info*
If you do not already have cscope (it did not come with your compiler
license or OS distribution), then you can download it for free from:
http://cscope.sourceforge.net/
This is released by SCO under the BSD license.
If you want a newer version of cscope, you will probably have to buy it.
According to the (old) nvi documentation:
You can buy version 13.3 source with an unrestricted license
for $400 from AT&T Software Solutions by calling +1-800-462-8146.
Also you can download cscope 13.x and mlcscope 14.x (multi-lingual cscope
which supports C, C++, Java, lex, yacc, breakpoint listing, Ingres, and SDL)
from World-Wide Exptools Open Source packages page:
http://www.bell-labs.com/project/wwexptools/packages.html
In Solaris 2.x, if you have the C compiler license, you will also have
cscope. Both are usually located under /opt/SUNWspro/bin
SGI developers can also get it. Search for Cscope on this page:
http://freeware.sgi.com/index-by-alpha.html
https://toolbox.sgi.com/toolbox/utilities/cscope/
The second one is for those who have a password for the SGI toolbox.
There is source to an older version of a cscope clone (called "cs") available
on the net. Due to various reasons, this is not supported with Vim.
The cscope interface/support for Vim was originally written by
Andy Kahn <ackahn@netapp.com>. The original structure (as well as a tiny
bit of code) was adapted from the cscope interface in nvi. Please report
any problems, suggestions, patches, et al., you have for the usage of
cscope within Vim to him.
*cscope-win32*
For a cscope version for Win32 see:
http://code.google.com/p/cscope-win32/
Win32 support was added by Sergey Khorev <sergey.khorev@gmail.com>. Contact
him if you have Win32-specific issues.
top - main help file
*:helpg* *:helpgrep*
:helpg[rep] {pattern}[@xx]
Search all help text files and make a list of lines
in which {pattern} matches. Jumps to the first match.
The optional [@xx] specifies that only matches in the
"xx" language are to be found.
You can navigate through the matches with the
|quickfix| commands, e.g., |:cnext| to jump to the
next one. Or use |:cwindow| to get the list of
matches in the quickfix window.
{pattern} is used as a Vim regexp |pattern|.
'ignorecase' is not used, add "\c" to ignore case.
Example for case sensitive search:
:helpgrep Uganda
Example for case ignoring search:
:helpgrep uganda\c
Example for searching in French help:
:helpgrep backspace@fr
The pattern does not support line breaks, it must
match within one line. You can use |:grep| instead,
but then you need to get the list of help files in a
complicated way.
Cannot be followed by another command, everything is
used as part of the pattern. But you can use
|:execute| when needed.
Compressed help files will not be searched (Fedora
compresses the help files).
{not in Vi}
*:lh* *:lhelpgrep*
:lh[elpgrep] {pattern}[@xx]
Same as ":helpgrep", except the location list is used
instead of the quickfix list. If the help window is
already opened, then the location list for that window
is used. Otherwise, a new help window is opened and
the location list for that window is set. The
location list for the current window is not changed.
*:exu* *:exusage*
:exu[sage] Show help on Ex commands. Added to simulate the Nvi
command. {not in Vi}
*:viu* *:viusage*
:viu[sage] Show help on Normal mode commands. Added to simulate
the Nvi command. {not in Vi}
When no argument is given to |:help| the file given with the 'helpfile' option
will be opened. Otherwise the specified tag is searched for in all "doc/tags"
files in the directories specified in the 'runtimepath' option.
The initial height of the help window can be set with the 'helpheight' option
(default 20).
Jump to specific subjects by using tags. This can be done in two ways:
- Use the "CTRL-]" command while standing on the name of a command or option.
This only works when the tag is a keyword. "<C-Leftmouse>" and
"g<LeftMouse>" work just like "CTRL-]".
- use the ":ta {subject}" command. This also works with non-keyword
characters.
Use CTRL-T or CTRL-O to jump back.
Use ":q" to close the help window.
If there are several matches for an item you are looking for, this is how you
can jump to each one of them:
1. Open a help window
2. Use the ":tag" command with a slash prepended to the tag. E.g.:
:tag /min
3. Use ":tnext" to jump to the next matching tag.
It is possible to add help files for plugins and other items. You don't need
to change the distributed help files for that. See |add-local-help|.
To write a local help file, see |write-local-help|.
Note that the title lines from the local help files are automagically added to
the "LOCAL ADDITIONS" section in the "help.txt" help file |local-additions|.
This is done when viewing the file in Vim, the file itself is not changed. It
is done by going through all help files and obtaining the first line of each
file. The files in $VIMRUNTIME/doc are skipped.
*help-xterm-window*
If you want to have the help in another xterm window, you could use this
command:
:!xterm -e vim +help &
*:helpfind* *:helpf*
:helpf[ind] Like |:help|, but use a dialog to enter the argument.
Only for backwards compatibility. It now executes the
ToolBar.FindHelp menu entry instead of using a builtin
dialog. {only when compiled with YXXY+GUI_GTK|}
{not in Vi}
*:helpt* *:helptags*
*E154* *E150* *E151* *E152* *E153* *E670*
:helpt[ags] [++t] {dir}
Generate the help tags file(s) for directory {dir}.
All "*.txt" and "*.??x" files in the directory are
scanned for a help tag definition in between stars.
The "*.??x" files are for translated docs, they
generate the "tags-??" file, see |help-translated|.
The generated tags files are sorted.
When there are duplicates an error message is given.
An existing tags file is silently overwritten.
The optional "++t" argument forces adding the
"help-tags" tag. This is also done when the {dir} is
equal to $VIMRUNTIME/doc.
To rebuild the help tags in the runtime directory
(requires write permission there):
:helptags $VIMRUNTIME/doc
{not in Vi}
==============================================================================
2. Translated help files *help-translated*
It is possible to add translated help files, next to the original English help
files. Vim will search for all help in "doc" directories in 'runtimepath'.
This is only available when compiled with the |+multi_lang| feature.
At this moment translations are available for:
Chinese - multiple authors
French - translated by David Blanchet
Italian - translated by Antonio Colombo
Polish - translated by Mikolaj Machowski
Russian - translated by Vassily Ragosin
See the Vim website to find them: http://www.vim.org/translations.php
A set of translated help files consists of these files:
help.abx
howto.abx
...
tags-ab
"ab" is the two-letter language code. Thus for Italian the names are:
help.itx
howto.itx
...
tags-it
The 'helplang' option can be set to the preferred language(s). The default is
set according to the environment. Vim will first try to find a matching tag
in the preferred language(s). English is used when it cannot be found.
To find a tag in a specific language, append "@ab" to a tag, where "ab" is the
two-letter language code. Example:
:he user-manual@it
:he user-manual@en
The first one finds the Italian user manual, even when 'helplang' is empty.
The second one finds the English user manual, even when 'helplang' is set to
"it".
When using command-line completion for the ":help" command, the "@en"
extension is only shown when a tag exists for multiple languages. When the
tag only exists for English "@en" is omitted.
When using |CTRL-]| or ":help!" in a non-English help file Vim will try to
find the tag in the same language. If not found then 'helplang' will be used
to select a language.
Help files must use latin1 or utf-8 encoding. Vim assumes the encoding is
utf-8 when finding non-ASCII characters in the first line. Thus you must
translate the header with "For Vim version".
The same encoding must be used for the help files of one language in one
directory. You can use a different encoding for different languages and use
a different encoding for help files of the same language but in a different
directory.
Hints for translators:
- Do not translate the tags. This makes it possible to use 'helplang' to
specify the preferred language. You may add new tags in your language.
- When you do not translate a part of a file, add tags to the English version,
using the "tag@en" notation.
- Make a package with all the files and the tags file available for download.
Users can drop it in one of the "doc" directories and start use it.
Report this to Bram, so that he can add a link on www.vim.org.
- Use the |:helptags| command to generate the tags files. It will find all
languages in the specified directory.
==============================================================================
3. Writing help files *help-writing*
For ease of use, a Vim help file for a plugin should follow the format of the
standard Vim help files. If you are writing a new help file it's best to copy
one of the existing files and use it as a template.
The first line in a help file should have the following format:
TAGS
To define a help tag, place the name between asterisks (*tag-name*). The
tag-name should be different from all the Vim help tag names and ideally
should begin with the name of the Vim plugin. The tag name is usually right
aligned on a line.
When referring to an existing help tag and to create a hot-link, place the
name between two bars (|) eg. |help-writing|.|||
When referring to a Vim option in the help file, place the option name between
two single quotes, eg. 'statusline'
HIGHLIGHTING
To define a column heading, use a tilde character at the end of the line.
This will highlight the column heading in a different color. E.g.
Column heading
To separate sections in a help file, place a series of '=' characters in a
line starting from the first column. The section separator line is highlighted
differently.
To quote a block of ex-commands verbatim, place a greater than (>) character
at the end of the line before the block and a less than (<) character as the
first non-blank on a line following the block. Any line starting in column 1
also implicitly stops the block of ex-commands before it. E.g.
function Example_Func()
echo "Example"
endfunction
*:filetype* *:filet*
To enable file type detection, use this command in your vimrc:
:filetype on
Each time a new or existing file is edited, Vim will try to recognize the type
of the file and set the 'filetype' option. This will trigger the FileType
event, which can be used to set the syntax highlighting, set options, etc.
NOTE: Filetypes and 'compatible' don't work together well, since being Vi
compatible means options are global. Resetting 'compatible' is recommended,
if you didn't do that already.
Detail: The ":filetype on" command will load one of these files:
Amiga $VIMRUNTIME/filetype.vim
Mac $VIMRUNTIME:filetype.vim
MS-DOS $VIMRUNTIME\filetype.vim
RiscOS Vim:Filetype
Unix $VIMRUNTIME/filetype.vim
VMS $VIMRUNTIME/filetype.vim
This file is a Vim script that defines autocommands for the
BufNewFile and BufRead events. If the file type is not found by the
name, the file $VIMRUNTIME/scripts.vim is used to detect it from the
contents of the file.
When the GUI is running or will start soon, the menu.vim script is
also sourced. See |'go-M'| about avoiding that.
To add your own file types, see |new-filetype| below. To search for help on a
filetype prepend "ft-" and optionally append "-syntax", "-indent" or
"-plugin". For example:
:help ft-vim-indent
:help ft-vim-syntax
:help ft-man-plugin
If the file type is not detected automatically, or it finds the wrong type,
you can either set the 'filetype' option manually, or add a modeline to your
file. Example, for an IDL file use the command:
:set filetype=idl
*:filetype-plugin-on*
You can enable loading the plugin files for specific file types with:
:filetype plugin on
If filetype detection was not switched on yet, it will be as well.
This actually loads the file "ftplugin.vim" in 'runtimepath'.
The result is that when a file is edited its plugin file is loaded (if there
is one for the detected filetypefiletype). |filetype-plugin|
*:filetype-plugin-off*
You can disable it again with:
:filetype plugin off
The filetype detection is not switched off then. But if you do switch off
filetype detection, the plugins will not be loaded either.
This actually loads the file "ftplugof.vim" in 'runtimepath'.
*:filetype-indent-on*
You can enable loading the indent file for specific file types with:
:filetype indent on
If filetype detection was not switched on yet, it will be as well.
This actually loads the file "indent.vim" in 'runtimepath'.
The result is that when a file is edited its indent file is loaded (if there
is one for the detected filetype). |indent-expression|
*:filetype-indent-off*
You can disable it again with:
:filetype indent off
The filetype detection is not switched off then. But if you do switch off
filetype detection, the indent files will not be loaded either.
This actually loads the file "indoff.vim" in 'runtimepath'.
This disables auto-indenting for files you will open. It will keep working in
already opened files. Reset 'autoindent', 'cindent', 'smartindent' and/or
'indentexpr' to disable indenting in an opened file.
*:filetype-off*
To disable file type detection, use this command:
:filetype off
This will keep the flags for "plugin" and "indent", but since no file types
are being detected, they won't work until the next ":filetype on".
Overview: *:filetype-overview*
command detection plugin indent
:filetype on on unchanged unchanged
:filetype off off unchanged unchanged
:filetype plugin on on on unchanged
:filetype plugin off unchanged off unchanged
:filetype indent on on unchanged on
:filetype indent off unchanged unchanged off
:filetype plugin indent on on on on
:filetype plugin indent off unchanged off off
To see the current status, type:
:filetype
The output looks something like this:
filetype detection:ON plugin:ON indent:OFF
The file types are also used for syntax highlighting. If the ":syntax on"
command is used, the file type detection is installed too. There is no need
to do ":filetype on" after ":syntax on".
To disable one of the file types, add a line in your filetype file, see
|remove-filetype|.
*filetype-detect*
To detect the file type again:
:filetype detect
Use this if you started with an empty file and typed text that makes it
possible to detect the file type. For example, when you entered this in a
*filetype-overrule*
When the same extension is used for two filetypes, Vim tries to guess what
kind of file it is. This doesn't always work. A number of global variables
can be used to overrule the filetype used for certain extensions:
file name variable
*.asa g:filetype_asa |ft-aspvbs-syntax| |ft-aspperl-syntax|
*.asp g:filetype_asp |ft-aspvbs-syntax| |ft-aspperl-syntax|
*.asm g:asmsyntax |ft-asm-syntax|
*.prg g:filetype_prg
*.pl g:filetype_pl
*.inc g:filetype_inc
*.w g:filetype_w |ft-cweb-syntax|
*.i g:filetype_i |ft-progress-syntax|
*.p g:filetype_p |ft-pascal-syntax|
*.sh g:bash_is_sh |ft-sh-syntax|
*.tex g:tex_flavor |ft-tex-plugin|
*filetype-ignore*
To avoid that certain files are being inspected, the g:ft_ignore_pat variable
is used. The default value is set like this:
:let g:ft_ignore_pat = '\.\(Z\|gz\|bz2\|zip\|tgz\)$'
This means that the contents of compressed files are not inspected.
*new-filetype*
If a file type that you want to use is not detected yet, there are four ways
to add it. In any way, it's better not to modify the $VIMRUNTIME/filetype.vim
file. It will be overwritten when installing a new version of Vim.
A. If you want to overrule all default file type checks.
This works by writing one file for each filetype. The disadvantage is that
means there can be many files. The advantage is that you can simply drop
this file in the right directory to make it work.
*ftdetect*
1. Create your user runtime directory. You would normally use the first
item of the 'runtimepath' option. Then create the directory "ftdetect"
inside it. Example for Unix:
:!mkdir ~/.vim
:!mkdir ~/.vim/ftdetect
2. Create a file that contains an autocommand to detect the file type.
Example:
au BufRead,BufNewFile *.mine set filetype=mine
Note that there is no "augroup" command, this has already been done
when sourcing your file. You could also use the pattern "*" and then
check the contents of the file to recognize it.
Write this file as "mine.vim" in the "ftdetect" directory in your user
runtime directory. For example, for Unix:
:w ~/.vim/ftdetect/mine.vim
3. To use the new filetype detection you must restart Vim.
The files in the "ftdetect" directory are used after all the default
checks, thus they can overrule a previously detected file type. But you
can also use |:setfiletype| to keep a previously detected filetype.
B. If you want to detect your file after the default file type checks.
This works like A above, but instead of setting 'filetype' unconditionally
use ":setfiletype". This will only set 'filetype' if no file type was
detected yet. Example:
au BufRead,BufNewFile *.txt setfiletype text
You can also use the already detected file type in your command. For
example, to use the file type "mypascal" when "pascal" has been detected:
au BufRead,BufNewFile * if &ft == 'pascal' | set ft=mypascal
| endif
C. If your file type can be detected by the file name.
1. Create your user runtime directory. You would normally use the first
item of the 'runtimepath' option. Example for Unix:
:!mkdir ~/.vim
2. Create a file that contains autocommands to detect the file type.
Example:
" my filetype file
if exists("did_load_filetypes")
finish
endif
augroup filetypedetect
au! BufRead,BufNewFile *.mine setfiletype mine
au! BufRead,BufNewFile *.xyz setfiletype drawing
augroup END
Write this file as "filetype.vim" in your user runtime directory. For
example, for Unix:
:w ~/.vim/filetype.vim
3. To use the new filetype detection you must restart Vim.
Your filetype.vim will be sourced before the default FileType autocommands
have been installed. Your autocommands will match first, and the
":setfiletype" command will make sure that no other autocommands will set
'filetype' after this.
*new-filetype-scripts*
D. If your filetype can only be detected by inspecting the contents of the
file.
1. Create your user runtime directory. You would normally use the first
item of the 'runtimepath' option. Example for Unix:
:!mkdir ~/.vim
2. Create a vim script file for doing this. Example:
if did_filetype() " filetype already set..
finish " ..don't do these checks
endif
if getline(1) =~ '^#!.*\<mine\>'
setfiletype mine
elseif getline(1) =~? '\<drawing\>'
setfiletype drawing
endif
See $VIMRUNTIME/scripts.vim for more examples.
Write this file as "scripts.vim" in your user runtime directory. For
example, for Unix:
:w ~/.vim/scripts.vim
3. The detection will work right away, no need to restart Vim.
Your scripts.vim is loaded before the default checks for file types, which
means that your rules override the default rules in
$VIMRUNTIME/scripts.vim.
*remove-filetype*
If a file type is detected that is wrong for you, install a filetype.vim or
scripts.vim to catch it (see above). You can set 'filetype' to a non-existing
name to avoid that it will be set later anyway:
:set filetype=ignored
If you are setting up a system with many users, and you don't want each user
to add/remove the same filetypes, consider writing the filetype.vim and
scripts.vim files in a runtime directory that is used for everybody. Check
the 'runtimepath' for a directory to use. If there isn't one, set
'runtimepath' in the |system-vimrc|. Be careful to keep the default
directories!
*autocmd-osfiletypes*
On operating systems which support storing a file type with the file, you can
specify that an autocommand should only be executed if the file is of a
certain type.
The actual type checking depends on which platform you are running Vim
on; see your system's documentation for details.
To use osfiletype checking in an autocommand you should put a list of types to
match in angle brackets in place of a pattern, like this:
*plugin-details*
The "plugin" directory can be in any of the directories in the 'runtimepath'
option. All of these directories will be searched for plugins and they are
all loaded. For example, if this command:
set runtimepath
produces this output:
runtimepath=/etc/vim,~/.vim,/usr/local/share/vim/vim60
then Vim will load all plugins in these directories and below:
/etc/vim/plugin/
~/.vim/plugin/
/usr/local/share/vim/vim60/plugin/
Note that the last one is the value of $VIMRUNTIME which has been expanded.
What if it looks like your plugin is not being loaded? You can find out what
happens when Vim starts up by using the |-V| argument:
vim -V2
You will see a lot of messages, in between them is a remark about loading the
plugins. It starts with:
Searching for "plugin/**/*.vim" in
There you can see where Vim looks for your plugin scripts.
==============================================================================
2. Filetype plugin *filetype-plugins*
When loading filetype plugins has been enabled |:filetype-plugin-on|, options
will be set and mappings defined. These are all local to the buffer, they
will not be used for other files.
Defining mappings for a filetype may get in the way of the mappings you
define yourself. There are a few ways to avoid this:
1. Set the "maplocalleader" variable to the key sequence you want the mappings
to start with. Example:
:let maplocalleader = ","
All mappings will then start with a comma instead of the default, which
is a backslash. Also see |<LocalLeader>|.
2. Define your own mapping. Example:
:map ,p <Plug>MailQuote
You need to check the description of the plugin file below for the
functionality it offers and the string to map to.
You need to define your own mapping before the plugin is loaded (before
editing a file of that type). The plugin will then skip installing the
default mapping.
3. Disable defining mappings for a specific filetype by setting a variable,
which contains the name of the filetype. For the "mail" filetype this
would be:
:let no_mail_maps = 1
*ftplugin-overrule*
If a global filetype plugin does not do exactly what you want, there are three
ways to change this:
1. Add a few settings.
You must create a new filetype plugin in a directory early in
'runtimepath'. For Unix, for example you could use this file:
vim ~/.vim/ftplugin/fortran.vim
You can set those settings and mappings that you would like to add. Note
that the global plugin will be loaded after this, it may overrule the
settings that you do here. If this is the case, you need to use one of the
following two methods.
2. Make a copy of the plugin and change it.
You must put the copy in a directory early in 'runtimepath'. For Unix, for
example, you could do this:
cp $VIMRUNTIME/ftplugin/fortran.vim ~/.vim/ftplugin/fortran.vim
Then you can edit the copied file to your liking. Since the b:did_ftplugin
variable will be set, the global plugin will not be loaded.
A disadvantage of this method is that when the distributed plugin gets
improved, you will have to copy and modify it again.
3. Overrule the settings after loading the global plugin.
You must create a new filetype plugin in a directory from the end of
'runtimepath'. For Unix, for example, you could use this file:
vim ~/.vim/after/ftplugin/fortran.vim
In this file you can change just those settings that you want to change.
==============================================================================
3. Docs for the default filetype plugins. *ftplugin-docs*
CHANGELOG *ft-changelog-plugin*
Allows for easy entrance of Changelog entries in Changelog files. There are
some commands, mappings, and variables worth exploring:
Options:
'comments' is made empty to not mess up formatting.
'textwidth' is set to 78, which is standard.
'formatoptions' the 't' flag is added to wrap when inserting text.
Commands:
NewChangelogEntry Adds a new Changelog entry in an intelligent fashion
(see below).
Local mappings:
<Leader>o Starts a new Changelog entry in an equally intelligent
fashion (see below).
Global mappings:
NOTE: The global mappings are accessed by sourcing the
ftplugin/changelog.vim file first, e.g. with
runtime ftplugin/changelog.vim
in your |.vimrc|.
<Leader>o Switches to the ChangeLog buffer opened for the
current directory, or opens it in a new buffer if it
exists in the current directory. Then it does the
same as the local <Leader>o described above.
Variables:
g:changelog_timeformat Deprecated; use g:changelog_dateformat instead.
g:changelog_dateformat The date (and time) format used in ChangeLog entries.
The format accepted is the same as for the
|strftime()| function.
The default is "%Y-%m-%d" which is the standard format
for many ChangeLog layouts.
g:changelog_username The name and email address of the user.
The default is deduced from environment variables and
system files. It searches /etc/passwd for the comment
part of the current user, which informally contains
the real name of the user up to the first separating
b:changelog_name *b:changelog_name*
Name of the ChangeLog file to look for.
The default is 'ChangeLog'.
b:changelog_path
Path of the ChangeLog to use for the current buffer.
The default is empty, thus looking for a file named
|b:changelog_name| in the same directory as the
current buffer. If not found, the parent directory of
the current buffer is searched. This continues
recursively until a file is found or there are no more
parent directories to search.
b:changelog_entry_prefix
Name of a function to call to generate a prefix to a
new entry. This function takes no arguments and
should return a string containing the prefix.
Returning an empty prefix is fine.
The default generates the shortest path between the
ChangeLog's pathname and the current buffers pathname.
In the future, it will also be possible to use other
variable contexts for this variable, for example, g:.
The Changelog entries are inserted where they add the least amount of text.
After figuring out the current date and user, the file is searched for an
entry beginning with the current date and user and if found adds another item
under it. If not found, a new entry and item is prepended to the beginning of
the Changelog.
FORTRAN *ft-fortran-plugin*
Options:
'expandtab' is switched on to avoid tabs as required by the Fortran
standards unless the user has set fortran_have_tabs in .vimrc.
'textwidth' is set to 72 for fixed source format as required by the
Fortran standards and to 80 for free source format.
'formatoptions' is set to break code and comment lines and to preserve long
lines. You can format comments with |gq|.
For further discussion of fortran_have_tabs and the method used for the
detection of source format see |ft-fortran-syntax|.
MAIL *ft-mail-plugin*
Options:
'modeline' is switched off to avoid the danger of trojan horses, and to
avoid that a Subject line with "Vim:" in it will cause an
error message.
'textwidth' is set to 72. This is often recommended for e-mail.
'formatoptions' is set to break text lines and to repeat the comment leader
in new lines, so that a leading ">" for quotes is repeated.
You can also format quoted text with |gq|.
Local mappings:
<LocalLeader>q or \\MailQuote
Quotes the text selected in Visual mode, or from the cursor position
to the end of the file in Normal mode. This means "> " is inserted in
each line.
PDF *ft-pdf-plugin*
Two maps, <C-]> and <C-T>, are provided to simulate a tag stack for navigating
the PDF. The following are treated as tags:
- The byte offset after "startxref" to the xref table
- The byte offset after the /Prev key in the trailer to an earlier xref table
- A line of the form "0123456789 00000 n" in the xref table
- An object reference like "1 0 R" anywhere in the PDF
These maps can be disabled with
:let g:no_pdf_maps = 1
SQL *ft-sql*
Since the text for this plugin is rather long it has been put in a separate
file: |ft_sql.txt|.
TEX *ft-tex-plugin*
If the first line of a *.tex file has the form
%&<format>
then this determined the file type: plaintex (for plain TeX), context (for
ConTeXt), or tex (for LaTeX). Otherwise, the file is searched for keywords to
choose context or tex. If no keywords are found, it defaults to plaintex.
You can change the default by defining the variable g:tex_flavor to the format
(not the file type) you use most. Use one of these:
let g:tex_flavor = "plain"
let g:tex_flavor = "context"
let g:tex_flavor = "latex"
Currently no other formats are recognized.
The Vim script language is used for the startup vimrc file, syntax files, and
many other things. This chapter explains the items that can be used in a Vim
script. There are a lot of them, thus this is a long chapter.
|41.1| Introduction
|41.2| Variables
|41.3| Expressions
|41.4| Conditionals
|41.5| Executing an expression
|41.6| Using functions
|41.7| Defining a function
|41.8| Lists and Dictionaries
|41.9| Exceptions
|41.10| Various remarks
|41.11| Writing a plugin
|41.12| Writing a filetype plugin
|41.13| Writing a compiler plugin
|41.14| Writing a plugin that loads quickly
|41.15| Writing library scripts
|41.16| Distributing Vim scripts
Next chapter: |usr_42.txt| Add new menus
Previous chapter: |usr_40.txt| Make new commands
Table of contents: |usr_toc.txt|
==============================================================================
*41.1* Introduction *vim-script-intro* *script*
Your first experience with Vim scripts is the vimrc file. Vim reads it when
it starts up and executes the commands. You can set options to values you
prefer. And you can use any colon command in it (commands that start with a
":"; these are sometimes referred to as Ex commands or command-line commands).
Syntax files are also Vim scripts. As are files that set options for a
specific file type. A complicated macro can be defined by a separate Vim
script file. You can think of other uses yourself.
Let's start with a simple example:
:let i = 1
:while i < 5
: echo "count is" i
: let i += 1
:endwhile
Note:
The ":" characters are not really needed here. You only need to use
them when you type a command. In a Vim script file they can be left
out. We will use them here anyway to make clear these are colon
commands and make them stand out from Normal mode commands.
Note:
You can try out the examples by yanking the lines from the text here
and executing them with :@"
The output of the example code is:
count is 1
count is 2
count is 3
count is 4
In the first line the ":let" command assigns a value to a variable. The
generic form is:
:let {variable} = {expression}
In this case the variable name is "i" and the expression is a simple value,
the number one.
The ":while" command starts a loop. The generic form is:
:while {condition}
: {statements}
:endwhile
The statements until the matching ":endwhile" are executed for as long as the
condition is true. The condition used here is the expression "i < 5". This
is true when the variable i is smaller than five.
Note:
If you happen to write a while loop that keeps on running, you can
interrupt it by pressing CTRL-C (CTRL-Break on MS-Windows).
The ":echo" command prints its arguments. In this case the string "count is"
and the value of the variable i. Since i is one, this will print:
count is 1
Then there is the ":let i += 1" command. This does the same thing as
":let i = i + 1". This adds one to the variable i and assigns the new value
to the same variable.
The example was given to explain the commands, but would you really want to
make such a loop it can be written much more compact:
:for i in range(1, 4)
: echo "count is" i
:endfor
We won't explain how |:for| and |range()| work until later. Follow the links
if you are impatient.
very_long_variable_name_with_underscores
FuncLength
LENGTH
Invalid names are "foo+bar" and "6var".
These variables are global. To see a list of currently defined variables
use this command:
:let
You can use global variables everywhere. This also means that when the
variable "count" is used in one script file, it might also be used in another
file. This leads to confusion at least, and real problems at worst. To avoid
this, you can use a variable local to a script file by prepending "s:". For
example, one script contains this code:
:let s:count = 1
:while s:count < 5
: source other.vim
: let s:count += 1
:endwhile
Since "s:count" is local to this script, you can be sure that sourcing the
"other.vim" script will not change this variable. If "other.vim" also uses an
"s:count" variable, it will be a different copy, local to that script. More
about script-local variables here: |script-variable|.
There are more kinds of variables, see |internal-variables|. The most often
used ones are:
b:name variable local to a buffer
w:name variable local to a window
g:name global variable (also in a function)
v:name variable predefined by Vim
DELETING VARIABLES
Variables take up memory and show up in the output of the ":let" command. To
delete a variable use the ":unlet" command. Example:
:unlet s:count
This deletes the script-local variable "s:count" to free up the memory it
uses. If you are not sure if the variable exists, and don't want an error
message when it doesn't, append !:
:unlet! s:count
When a script finishes, the local variables used there will not be
automatically freed. The next time the script executes, it can still use the
old value. Example:
:if !exists("s:call_count")
: let s:call_count = 0
:endif
:let s:call_count = s:call_count + 1
:echo "called" s:call_count "times"
The "exists()" function checks if a variable has already been defined. Its
argument is the name of the variable you want to check. Not the variable
itself! If you would do this:
:if !exists(s:call_count)
Then the value of s:call_count will be used as the name of the variable that
exists() checks. That's not what you want.
The exclamation mark ! negates a value. When the value was true, it
becomes false. When it was false, it becomes true. You can read it as "not".
Thus "if !exists()" can be read as "if not exists()".
What Vim calls true is anything that is not zero. Zero is false.
Note:
Vim automatically converts a string to a number when it is looking for
a number. When using a string that doesn't start with a digit the
resulting number is zero. Thus look out for this:
:if "true"
The "true" will be interpreted as a zero, thus as false!
MATHEMATICS
It becomes more interesting if we combine these basic items. Let's start with
mathematics on numbers:
a + b add
a - b subtract
a * b multiply
a / b divide
a % b modulo
The usual precedence is used. Example:
:echo 10 + 5 * 2
20
Grouping is done with parentheses. No surprises here. Example:
:echo (10 + 5) * 2
30
Strings can be concatenated with ".". Example:
:echo "foo" . "bar"
foobar
When the ":echo" command gets multiple arguments, it separates them with a
space. In the example the argument is a single expression, thus no space is
inserted.
Borrowed from the C language is the conditional expression:
a ? b : c
If "a" evaluates to true "b" is used, otherwise "c" is used. Example:
:let i = 4
:echo i > 5 ? "i is big" : "i is small"
i is small
The three parts of the constructs are always evaluated first, thus you could
see it work as:
(a) ? (b) : (c)
==============================================================================
*41.4* Conditionals
The ":if" commands executes the following statements, until the matching
":endif", only when a condition is met. The generic form is:
:if {condition}
{statements}
:endif
Only when the expression {condition} evaluates to true (non-zero) will the
{statements} be executed. These must still be valid commands. If they
contain garbage, Vim won't be able to find the ":endif".
You can also use ":else". The generic form for this is:
:if {condition}
{statements}
:else
{statements}
:endif
The second {statements} is only executed if the first one isn't.
Finally, there is ":elseif":
:if {condition}
{statements}
:elseif {condition}
{statements}
:endif
This works just like using ":else" and then "if", but without the need for an
extra ":endif".
A useful example for your vimrc file is checking the 'term' option and
doing something depending upon its value:
:if &term == "xterm"
: " Do stuff for xterm
:elseif &term == "vt100"
: " Do stuff for a vt100 terminal
:else
: " Do something for other terminals
:endif
LOGIC OPERATIONS
We already used some of them in the examples. These are the most often used
ones:
a == b equal to
a != b not equal to
a > b greater than
a >= b greater than or equal to
a < b less than
a <= b less than or equal to
The result is one if the condition is met and zero otherwise. An example:
:if v:version >= 700
: echo "congratulations"
:else
: echo "you are using an old version, upgrade!"
:endif
Here "v:version" is a variable defined by Vim, which has the value of the Vim
version. 600 is for version 6.0. Version 6.1 has the value 601. This is
very useful to write a script that works with multiple versions of Vim.
|v:version|
The logic operators work both for numbers and strings. When comparing two
strings, the mathematical difference is used. This compares byte values,
which may not be right for some languages.
When comparing a string with a number, the string is first converted to a
number. This is a bit tricky, because when a string doesn't look like a
number, the number zero is used. Example:
:if 0 == "one"
: echo "yes"
:endif
This will echo "yes", because "one" doesn't look like a number, thus it is
converted to the number zero.
For strings there are two more items:
a =~ b matches with
a !~ b does not match with
The left item "a" is used as a string. The right item "b" is used as a
pattern, like what's used for searching. Example:
:if str =~ " "
: echo "str contains a space"
:endif
:if str !~ '\.$'
: echo "str does not end in a full stop"
:endif
Notice the use of a single-quote string for the pattern. This is useful,
because backslashes would need to be doubled in a double-quote string and
patterns tend to contain many backslashes.
The 'ignorecase' option is used when comparing strings. When you don't want
that, append "#" to match case and "?" to ignore case. Thus "==?" compares
two strings to be equal while ignoring case. And "!~#" checks if a pattern
doesn't match, also checking the case of letters. For the full table see
|expr-==|.
MORE LOOPING
The ":while" command was already mentioned. Two more statements can be used
in between the ":while" and the ":endwhile":
:continue Jump back to the start of the while loop; the
loop continues.
:break Jump forward to the ":endwhile"; the loop is
discontinued.
Example:
:while counter < 40
: call do_something()
: if skip_flag
: continue
: endif
: if finished_flag
: break
: endif
: sleep 50m
:endwhile
The ":sleep" command makes Vim take a nap. The "50m" specifies fifty
milliseconds. Another example is ":sleep 4", which sleeps for four seconds.
Even more looping can be done with the ":for" command, see below in |41.8|.
==============================================================================
*41.5* Executing an expression
So far the commands in the script were executed by Vim directly. The
":execute" command allows executing the result of an expression. This is a
very powerful way to build commands and execute them.
An example is to jump to a tag, which is contained in a variable:
:execute "tag " . tag_name
The "." is used to concatenate the string "tag " with the value of variable
"tag_name". Suppose "tag_name" has the value "get_cmd", then the command that
will be executed is:
:tag get_cmd
The ":execute" command can only execute colon commands. The ":normal" command
executes Normal mode commands. However, its argument is not an expression but
the literal command characters. Example:
:normal gg=G
This jumps to the first line and formats all lines with the "=" operator.
To make ":normal" work with an expression, combine ":execute" with it.
Example:
:execute "normal " . normal_commands
The variable "normal_commands" must contain the Normal mode commands.
Make sure that the argument for ":normal" is a complete command. Otherwise
Vim will run into the end of the argument and abort the command. For example,
if you start Insert mode, you must leave Insert mode as well. This works:
:execute "normal Inew text \<Esc>"
This inserts "new text " in the current line. Notice the use of the special
key "\<Esc>". This avoids having to enter a real <Esc> character in your
script.
If you don't want to execute a string but evaluate it to get its expression
value, you can use the eval() function:
:let optname = "path"
:let optval = eval('&' . optname)
A "&" character is prepended to "path", thus the argument to eval() is
"&path". The result will then be the value of the 'path' option.
The same thing can be done with:
:exe 'let optval = &' . optname
==============================================================================
FUNCTIONS *function-list*
There are many functions. We will mention them here, grouped by what they are
used for. You can find an alphabetical list here: |functions|. Use CTRL-] on
the function name to jump to detailed help on it.
Variables: *var-functions*
type() type of a variable
islocked() check if a variable is locked
function() get a Funcref for a function name
getbufvar() get a variable value from a specific buffer
setbufvar() set a variable in a specific buffer
getwinvar() get a variable from specific window
gettabvar() get a variable from specific tab page
gettabwinvar() get a variable from specific window & tab page
setwinvar() set a variable in a specific window
settabvar() set a variable in a specific tab page
settabwinvar() set a variable in a specific window & tab page
garbagecollect() possibly free memory
*system-functions* *file-functions*
System functions and manipulation of files:
glob() expand wildcards
globpath() expand wildcards in a number of directories
findfile() find a file in a list of directories
finddir() find a directory in a list of directories
resolve() find out where a shortcut points to
fnamemodify() modify a file name
pathshorten() shorten directory names in a path
simplify() simplify a path without changing its meaning
executable() check if an executable program exists
filereadable() check if a file can be read
filewritable() check if a file can be written to
getfperm() get the permissions of a file
getftype() get the kind of a file
isdirectory() check if a directory exists
getfsize() get the size of a file
getcwd() get the current working directory
haslocaldir() check if current window used |:lcd|
tempname() get the name of a temporary file
mkdir() create a new directory
delete() delete a file
rename() rename a file
system() get the result of a shell command
hostname() name of the system
readfile() read a file into a List of lines
writefile() write a List of lines into a file
Folding: *folding-functions*
foldclosed() check for a closed fold at a specific line
foldclosedend() like foldclosed() but return the last line
foldlevel() check for the fold level at a specific line
foldtext() generate the line displayed for a closed fold
foldtextresult() get the text displayed for a closed fold
Spelling: *spell-functions*
spellbadword() locate badly spelled word at or after cursor
spellsuggest() return suggested spelling corrections
soundfold() return the sound-a-like equivalent of a word
History: *history-functions*
histadd() add an item to a history
histdel() delete an item from a history
histget() get an item from a history
histnr() get highest index of a history list
Interactive: *interactive-functions*
browse() put up a file requester
browsedir() put up a directory requester
confirm() let the user make a choice
getchar() get a character from the user
getcharmod() get modifiers for the last typed character
feedkeys() put characters in the typeahead queue
input() get a line from the user
inputlist() let the user pick an entry from a list
inputsecret() get a line from the user without showing it
GUI: *gui-functions*
getfontname() get name of current font being used
getwinposx() X position of the GUI Vim window
getwinposy() Y position of the GUI Vim window
Various: *various-functions*
mode() get current editing mode
visualmode() last visual mode used
hasmapto() check if a mapping exists
mapcheck() check if a matching mapping exists
maparg() get rhs of a mapping
exists() check if a variable, function, etc. exists
has() check if a feature is supported in Vim
changenr() return number of most recent change
cscope_connection() check if a cscope connection exists
did_filetype() check if a FileType autocommand was used
eventhandler() check if invoked by an event handler
getpid() get process ID of Vim
libcall() call a function in an external library
libcallnr() idem, returning a number
getreg() get contents of a register
getregtype() get type of a register
setreg() set contents and type of a register
taglist() get list of matching tags
tagfiles() get a list of tags files
mzeval() evaluate |MzScheme| expression
==============================================================================
*41.7* Defining a function
Vim enables you to define your own functions. The basic function declaration
begins as follows:
:function {name}({var1}, {var2}, ...)
: {body}
:endfunction
Note:
Function names must begin with a capital letter.
Let's define a short function to return the smaller of two numbers. It starts
with this line:
:function Min(num1, num2)
This tells Vim that the function is named "Min" and it takes two arguments:
"num1" and "num2".
The first thing you need to do is to check to see which number is smaller:
: if a:num1 < a:num2
The special prefix "a:" tells Vim that the variable is a function argument.
Let's assign the variable "smaller" the value of the smallest number:
: if a:num1 < a:num2
: let smaller = a:num1
: else
: let smaller = a:num2
: endif
The variable "smaller" is a local variable. Variables used inside a function
are local unless prefixed by something like "g:", "a:", or "s:".
Note:
To access a global variable from inside a function you must prepend
"g:" to it. Thus "g:today" inside a function is used for the global
variable "today", and "today" is another variable, local to the
function.
You now use the ":return" statement to return the smallest number to the user.
Finally, you end the function:
: return smaller
:endfunction
The complete function definition is as follows:
:function Min(num1, num2)
: if a:num1 < a:num2
: let smaller = a:num1
: else
: let smaller = a:num2
: endif
: return smaller
:endfunction
For people who like short functions, this does the same thing:
:function Min(num1, num2)
: if a:num1 < a:num2
: return a:num1
: endif
: return a:num2
:endfunction
A user defined function is called in exactly the same way as a built-in
function. Only the name is different. The Min function can be used like
this:
:echo Min(5, 8)
Only now will the function be executed and the lines be interpreted by Vim.
If there are mistakes, like using an undefined variable or function, you will
now get an error message. When defining the function these errors are not
detected.
When a function reaches ":endfunction" or ":return" is used without an
argument, the function returns zero.
To redefine a function that already exists, use the ! for the ":function"
command:
:function! Min(num1, num2, num3)
USING A RANGE
The ":call" command can be given a line range. This can have one of two
meanings. When a function has been defined with the "range" keyword, it will
take care of the line range itself.
The function will be passed the variables "a:firstline" and "a:lastline".
These will have the line numbers from the range the function was called with.
Example:
:function Count_words() range
: let lnum = a:firstline
: let n = 0
: while lnum <= a:lastline
: let n = n + len(split(getline(lnum)))
: let lnum = lnum + 1
: endwhile
: echo "found " . n . " words"
:endfunction
You can call this function with:
:10,30call Count_words()
It will be executed once and echo the number of words.
The other way to use a line range is by defining a function without the
"range" keyword. The function will be called once for every line in the
range, with the cursor in that line. Example:
:function Number()
: echo "line " . line(".") . " contains: " . getline(".")
:endfunction
If you call this function with:
:10,15call Number()
The function will be called six times.
LISTING FUNCTIONS
The ":function" command lists the names and arguments of all user-defined
functions:
:function
function Show(start, ...)
function GetVimIndent()
function SetSyn(name)
To see what a function does, use its name as an argument for ":function":
:function SetSyn
1 if &syntax == ''
2 let &syntax = a:name
3 endif
endfunction
DEBUGGING
The line number is useful for when you get an error message or when debugging.
See |debug-scripts| about debugging mode.
You can also set the 'verbose' option to 12 or higher to see all function
calls. Set it to 15 or higher to see every executed line.
DELETING A FUNCTION
To delete the Show() function:
:delfunction Show
You get an error when the function doesn't exist.
FUNCTION REFERENCES
Sometimes it can be useful to have a variable point to one function or
another. You can do it with the function() function. It turns the name of a
function into a reference:
:let result = 0 " or 1
:function! Right()
: return 'Right!'
:endfunc
:function! Wrong()
: return 'Wrong!'
:endfunc
:
:if result == 1
: let Afunc = function('Right')
:else
: let Afunc = function('Wrong')
:endif
:echo call(Afunc, [])
Wrong!
Note that the name of a variable that holds a function reference must start
with a capital. Otherwise it could be confused with the name of a builtin
function.
The way to invoke a function that a variable refers to is with the call()
function. Its first argument is the function reference, the second argument
is a List with arguments.
Function references are most useful in combination with a Dictionary, as is
explained in the next section.
==============================================================================
*41.8* Lists and Dictionaries
So far we have used the basic types String and Number. Vim also supports two
composite types: List and Dictionary.
A List is an ordered sequence of things. The things can be any kind of value,
thus you can make a List of numbers, a List of Lists and even a List of mixed
items. To create a List with three strings:
:let alist = ['aap', 'mies', 'noot']
The List items are enclosed in square brackets and separated by commas. To
create an empty List:
:let alist = []
You can add items to a List with the add() function:
:let alist = []
:call add(alist, 'foo')
:call add(alist, 'bar')
:echo alist
['foo', 'bar']
List concatenation is done with +:
:echo alist + ['foo', 'bar']
['foo', 'bar', 'foo', 'bar']
FOR LOOP
One of the nice things you can do with a List is iterate over it:
:let alist = ['one', 'two', 'three']
:for n in alist
: echo n
:endfor
one
two
three
This will loop over each element in List "alist", assigning the value to
variable "n". The generic form of a for loop is:
:for {varname} in {listexpression}
: {commands}
:endfor
To loop a certain number of times you need a List of a specific length. The
range() function creates one for you:
:for a in range(3)
: echo a
:endfor
0
1
2
Notice that the first item of the List that range() produces is zero, thus the
last item is one less than the length of the list.
You can also specify the maximum value, the stride and even go backwards:
:for a in range(8, 4, -2)
: echo a
:endfor
8
6
4
A more useful example, looping over lines in the buffer:
:for line in getline(1, 20)
: if line =~ "Date: "
: echo matchstr(line, 'Date: \zs.*')
: endif
:endfor
This looks into lines 1 to 20 (inclusive) and echoes any date found in there.
DICTIONARIES
A Dictionary stores key-value pairs. You can quickly lookup a value if you
know the key. A Dictionary is created with curly braces:
:let uk2nl = {'one': 'een', 'two': 'twee', 'three': 'drie'}
Now you can lookup words by putting the key in square brackets:
:echo uk2nl['two']
twee
The generic form for defining a Dictionary is:
{<key> : <value>, ...}
An empty Dictionary is one without any keys:
{}
The possibilities with Dictionaries are numerous. There are various functions
for them as well. For example, you can obtain a list of the keys and loop
over them:
:for key in keys(uk2nl)
: echo key
:endfor
three
one
two
You will notice the keys are not ordered. You can sort the list to get a
specific order:
:for key in sort(keys(uk2nl))
: echo key
:endfor
one
three
two
But you can never get back the order in which items are defined. For that you
need to use a List, it stores items in an ordered sequence.
DICTIONARY FUNCTIONS
The items in a Dictionary can normally be obtained with an index in square
brackets:
:echo uk2nl['one']
een
A method that does the same, but without so many punctuation characters:
:echo uk2nl.one
een
This only works for a key that is made of ASCII letters, digits and the
underscore. You can also assign a new value this way:
:let uk2nl.four = 'vier'
:echo uk2nl
{'three': 'drie', 'four': 'vier', 'one': 'een', 'two': 'twee'}
And now for something special: you can directly define a function and store a
reference to it in the dictionary:
:function uk2nl.translate(line) dict
: return join(map(split(a:line), 'get(self, v:val, "???")'))
:endfunction
Let's first try it out:
:echo uk2nl.translate('three two five one')
drie twee ??? een
The first special thing you notice is the "dict" at the end of the ":function"
line. This marks the function as being used from a Dictionary. The "self"
local variable will then refer to that Dictionary.
Now let's break up the complicated return command:
split(a:line)
The split() function takes a string, chops it into whitespace separated words
and returns a list with these words. Thus in the example it returns:
WHITE SPACE
Blank lines are allowed and ignored.
Leading whitespace characters (blanks and TABs) are always ignored. The
whitespaces between parameters (e.g. between the 'set' and the 'cpoptions' in
the example below) are reduced to one blank character and plays the role of a
separator, the whitespaces after the last (visible) character may or may not
be ignored depending on the situation, see below.
For a ":set" command involving the "=" (equal) sign, such as in:
:set cpoptions =aABceFst
the whitespace immediately before the "=" sign is ignored. But there can be
no whitespace after the "=" sign!
To include a whitespace character in the value of an option, it must be
escaped by a "\" (backslash) as in the following example:
:set tags=my\ nice\ file
The same example written as:
:set tags=my nice file
will issue an error, because it is interpreted as:
:set tags=my
:set nice
:set file
COMMENTS
The character " (the double quote mark) starts a comment. Everything after
and including this character until the end-of-line is considered a comment and
is ignored, except for commands that don't consider comments, as shown in
examples below. A comment can start on any character position on the line.
There is a little "catch" with comments for some commands. Examples:
:abbrev dev development " shorthand
:map <F3> o#include " insert include
:execute cmd " do it
:!ls *.c " list C files
The abbreviation 'dev' will be expanded to 'development " shorthand'. The
mapping of <F3> will actually be the whole line after the 'o# ....' including
the '"' insert include'. The "execute" command will give an error. The "!"
command will send everything after it to the shell, causing an error for an
unmatched '"'' character.
There can be no comment after ":map", ":abbreviate", ":execute" and "!"
commands (there are a few more commands with this restriction). For the
":map", ":abbreviate" and ":execute" commands there is a trick:
:abbrev dev development|" shorthand
:map <F3> o#include|" insert include
:execute cmd |" do it
With the '|' character the command is separated from the next one. And that
next command is only a comment. For the last command you need to do two
things: |:execute| and use '|':
:exe '!ls *.c' |" list C files
Notice that there is no white space before the '|' in the abbreviation and
mapping. For these commands, any character until the end-of-line or '|' is
included. As a consequence of this behavior, you don't always see that
trailing whitespace is included:
:map <F4> o#include
To spot these problems, you can set the 'list' option when editing vimrc
files.
For Unix there is one special way to comment a line, that allows making a Vim
script executable:
#!/usr/bin/env vim -S
echo "this is a Vim script"
quit
The "#" command by itself lists a line with the line number. Adding an
exclamation mark changes it into doing nothing, so that you can add the shell
command to execute the rest of the file. |:#!| |-S|
PITFALLS
Even bigger problem arises in the following example:
:map ,ab o#include
:unmap ,ab
Here the unmap command will not work, because it tries to unmap ",ab ". This
does not exist as a mapped sequence. An error will be issued, which is very
hard to identify, because the ending whitespace character in ":unmap ,ab " is
not visible.
And this is the same as what happens when one uses a comment after an 'unmap'
command:
:unmap ,ab " comment
Here the comment part will be ignored. However, Vim will try to unmap
',ab '', which does not exist. Rewrite it as:
:unmap ,ab| " comment
PACKAGING
To avoid your function names to interfere with functions that you get from
others, use this scheme:
- Prepend a unique string before each function name. I often use an
abbreviation. For example, "OW_" is used for the option window functions.
- Put the definition of your functions together in a file. Set a global
variable to indicate that the functions have been loaded. When sourcing the
file again, first unload the functions.
Example:
" This is the XXX package
if exists("XXX_loaded")
delfun XXX_one
delfun XXX_two
endif
function XXX_one(a)
... body of function ...
endfun
function XXX_two(b)
... body of function ...
endfun
let XXX_loaded = 1
==============================================================================
*41.11* Writing a plugin *write-plugin*
You can write a Vim script in such a way that many people can use it. This is
called a plugin. Vim users can drop your script in their plugin directory and
use its features right away |add-plugin|.
There are actually two types of plugins:
global plugins: For all types of files.
filetype plugins: Only for files of a specific type.
In this section the first type is explained. Most items are also relevant for
writing filetype plugins. The specifics for filetype plugins are in the next
section |write-filetype-plugin|.
NAME
First of all you must choose a name for your plugin. The features provided
by the plugin should be clear from its name. And it should be unlikely that
someone else writes a plugin with the same name but which does something
different. And please limit the name to 8 characters, to avoid problems on
old Windows systems.
A script that corrects typing mistakes could be called "typecorr.vim". We
will use it here as an example.
For the plugin to work for everybody, it should follow a few guidelines. This
will be explained step-by-step. The complete example plugin is at the end.
BODY
Let's start with the body of the plugin, the lines that do the actual work:
14 iabbrev teh the
15 iabbrev otehr other
16 iabbrev wnat want
17 iabbrev synchronisation
18 \ synchronization
19 let s:count = 4
The actual list should be much longer, of course.
The line numbers have only been added to explain a few things, don't put them
in your plugin file!
HEADER
You will probably add new corrections to the plugin and soon have several
versions laying around. And when distributing this file, people will want to
know who wrote this wonderful plugin and where they can send remarks.
Therefore, put a header at the top of your plugin:
1 " Vim global plugin for correcting typing mistakes
2 " Last Change: 2000 Oct 15
3 " Maintainer: Bram Moolenaar <Bram@vim.org>
About copyright and licensing: Since plugins are very useful and it's hardly
worth restricting their distribution, please consider making your plugin
either public domain or use the Vim |license|. A short note about this near
NOT LOADING
It's possible that a user doesn't always want to load this plugin. Or the
system administrator has dropped it in the system-wide plugin directory, but a
user has his own plugin he wants to use. Then the user must have a chance to
disable loading this specific plugin. This will make it possible:
6 if exists("g:loaded_typecorr")
7 finish
8 endif
9 let g:loaded_typecorr = 1
This also avoids that when the script is loaded twice it would cause error
messages for redefining functions and cause trouble for autocommands that are
added twice.
The name is recommended to start with "loaded_" and then the file name of the
plugin, literally. The "g:" is prepended just to avoid mistakes when using
the variable in a function (without "g:" it would be a variable local to the
function).
Using "finish" stops Vim from reading the rest of the file, it's much quicker
than using if-endif around the whole file.
MAPPING
Now let's make the plugin more interesting: We will add a mapping that adds a
correction for the word under the cursor. We could just pick a key sequence
for this mapping, but the user might already use it for something else. To
allow the user to define which keys a mapping in a plugin uses, the <Leader>
item can be used:
22 map <unique> <Leader>a <Plug>TypecorrAdd
The "<Plug>TypecorrAdd" thing will do the work, more about that further on.
The user can set the "mapleader" variable to the key sequence that he wants
this mapping to start with. Thus if the user has done:
let mapleader = "_"
the mapping will define "_a". If the user didn't do this, the default value
will be used, which is a backslash. Then a map for "\a" will be defined.
Note that <unique> is used, this will cause an error message if the mapping
already happened to exist. |:map-<unique>|
But what if the user wants to define his own key sequence? We can allow that
with this mechanism:
21 if !hasmapto('<Plug>TypecorrAdd')
22 map <unique> <Leader>a <Plug>TypecorrAdd
23 endif
This checks if a mapping to "<Plug>TypecorrAdd" already exists, and only
defines the mapping from "<Leader>a" if it doesn't. The user then has a
chance of putting this in his vimrc file:
map ,c <Plug>TypecorrAdd
Then the mapped key sequence will be ",c" instead of "_a" or "\a".
PIECES
If a script gets longer, you often want to break up the work in pieces. You
can use functions or mappings for this. But you don't want these functions
and mappings to interfere with the ones from other scripts. For example, you
could define a function Add(), but another script could try to define the same
function. To avoid this, we define the function local to the script by
prepending it with "s:".
We will define a function that adds a new typing correction:
30 function s:Add(from, correct)
31 let to = input("type the correction for " . a:from . ": ")
32 exe ":iabbrev " . a:from . " " . to
..
36 endfunction
Now we can call the function s:Add() from within this script. If another
script also defines s:Add(), it will be local to that script and can only
be called from the script it was defined in. There can also be a global Add()
function (without the "s:"), which is again another function.
<SID> can be used with mappings. It generates a script ID, which identifies
the current script. In our typing correction plugin we use it like this:
24 noremap <unique> <script> <Plug>TypecorrAdd <SID>Add
..
28 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR>
Thus when a user types "\a", this sequence is invoked:
\a -> <Plug>TypecorrAdd -> <SID>Add -> :call <SID>Add()
If another script would also map <SID>Add, it would get another script ID and
thus define another mapping.
Note that instead of s:Add() we use <SID>Add() here. That is because the
mapping is typed by the user, thus outside of the script. The <SID> is
translated to the script ID, so that Vim knows in which script to look for
the Add() function.
This is a bit complicated, but it's required for the plugin to work together
with other plugins. The basic rule is that you use <SID>Add() in mappings and
s:Add() in other places (the script itself, autocommands, user commands).
We can also add a menu entry to do the same as the mapping:
26 noremenu <script> Plugin.Add\ Correction <SID>Add
The "Plugin" menu is recommended for adding menu items for plugins. In this
case only one item is used. When adding more items, creating a submenu is
recommended. For example, "Plugin.CVS" could be used for a plugin that offers
CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
Note that in line 28 ":noremap" is used to avoid that any other mappings cause
trouble. Someone may have remapped ":call", for example. In line 24 we also
use ":noremap", but we do want "<SID>Add" to be remapped. This is why
"<script>" is used here. This only allows mappings which are local to the
script. |:map-<script>| The same is done in line 26 for ":noremenu".
|:menu-<script>|
with mappings that are only to be used from other mappings. Note the
difference between using <SID> and <Plug>:
<Plug> is visible outside of the script. It is used for mappings which the
user might want to map a key sequence to. <Plug> is a special code
that a typed key will never produce.
To make it very unlikely that other plugins use the same sequence of
characters, use this structure: <Plug> scriptname mapname
In our example the scriptname is "Typecorr" and the mapname is "Add".
This results in "<Plug>TypecorrAdd". Only the first character of
scriptname and mapname is uppercase, so that we can see where mapname
starts.
<SID> is the script ID, a unique identifier for a script.
Internally Vim translates <SID> to "<SNR>123_", where "123" can be any
number. Thus a function "<SID>Add()" will have a name "<SNR>11_Add()"
in one script, and "<SNR>22_Add()" in another. You can see this if
you use the ":function" command to get a list of functions. The
translation of <SID> in mappings is exactly the same, that's how you
can call a script-local function from a mapping.
USER COMMAND
Now let's add a user command to add a correction:
38 if !exists(":Correct")
39 command -nargs=1 Correct :call s:Add(<q-args>, 0)
40 endif
The user command is defined only if no command with the same name already
exists. Otherwise we would get an error here. Overriding the existing user
command with ":command!" is not a good idea, this would probably make the user
wonder why the command he defined himself doesn't work. |:command|
SCRIPT VARIABLES
When a variable starts with "s:" it is a script variable. It can only be used
inside a script. Outside the script it's not visible. This avoids trouble
with using the same variable name in different scripts. The variables will be
kept as long as Vim is running. And the same variables are used when sourcing
the same script again. |s:var|
The fun is that these variables can also be used in functions, autocommands
and user commands that are defined in the script. In our example we can add
a few lines to count the number of corrections:
19 let s:count = 4
..
30 function s:Add(from, correct)
..
34 let s:count = s:count + 1
35 echo s:count . " corrections now"
36 endfunction
First s:count is initialized to 4 in the script itself. When later the
s:Add() function is called, it increments s:count. It doesn't matter from
where the function was called, since it has been defined in the script, it
will use the local variables from this script.
THE RESULT
Here is the resulting complete example:
1 " Vim global plugin for correcting typing mistakes
2 " Last Change: 2000 Oct 15
3 " Maintainer: Bram Moolenaar <Bram@vim.org>
4 " License: This file is placed in the public domain.
5
6 if exists("g:loaded_typecorr")
7 finish
8 endif
9 let g:loaded_typecorr = 1
10
11 let s:save_cpo = &cpo
12 set cpo&vim
13
DOCUMENTATION *write-local-help*
It's a good idea to also write some documentation for your plugin. Especially
when its behavior can be changed by the user. See |add-local-help| for how
they are installed.
Here is a simple example for a plugin help file, called "typecorr.txt":
1 *typecorr.txt* Plugin for correcting typing mistakes
2
3 If you make typing mistakes, this plugin will have them corrected
4 automatically.
5
6 There are currently only a few corrections. Add your own if you like.
7
8 Mappings:
9 <Leader>a or <Plug>TypecorrAdd
10 Add a correction for the word under the cursor.
11
12 Commands:
13 :Correct {word}
14 Add a correction for {word}.
15
16 *typecorr-settings*
17 This plugin doesn't have any settings.
The first line is actually the only one for which the format matters. It will
be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of
help.txt |local-additions|. The first "*" must be in the first column of the
first line. After adding your help file do ":help" and check that the entries
line up nicely.
You can add more tags inside ** in your help file. But be careful not to use
existing help tags. You would probably use the name of your plugin in most of
them, like "typecorr-settings" in the example.
Using references to other parts of the help in || is recommended. This makes
it easy for the user to find associated help.
SUMMARY *plugin-special*
Summary of special things to use in a plugin:
s:name Variables local to the script.
<SID> Script-ID, used for mappings and functions local to
the script.
hasmapto() Function to test if the user already defined a mapping
for functionality the script offers.
<Leader> Value of "mapleader", which the user defines as the
keys that plugin mappings start with.
:map <unique> Give a warning if a mapping already exists.
:noremap <script> Use only mappings local to the script, not global
mappings.
exists(":Cmd") Check if a user command already exists.
==============================================================================
*41.12* Writing a filetype plugin *write-filetype-plugin* *ftplugin*
A filetype plugin is like a global plugin, except that it sets options and
defines mappings for the current buffer only. See |add-filetype-plugin| for
how this type of plugin is used.
First read the section on global plugins above |41.11|. All that is said there
also applies to filetype plugins. There are a few extras, which are explained
here. The essential thing is that a filetype plugin should only have an
effect on the current buffer.
DISABLING
If you are writing a filetype plugin to be used by many people, they need a
chance to disable loading it. Put this at the top of the plugin:
" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
finish
endif
let b:did_ftplugin = 1
This also needs to be used to avoid that the same plugin is executed twice for
the same buffer (happens when using an ":edit" command without arguments).
Now users can disable loading the default plugin completely by making a
filetype plugin with only this line:
let b:did_ftplugin = 1
This does require that the filetype plugin directory comes before $VIMRUNTIME
in 'runtimepath'!
If you do want to use the default plugin, but overrule one of the settings,
you can write the different setting in a script:
setlocal textwidth=70
Now write this in the "after" directory, so that it gets sourced after the
distributed "vim.vim" ftplugin |after-directory|. For Unix this would be
"~/.vim/after/ftplugin/vim.vim". Note that the default plugin will have set
"b:did_ftplugin", but it is ignored here.
OPTIONS
To make sure the filetype plugin only affects the current buffer use the
:setlocal
command to set options. And only set options which are local to a buffer (see
the help for the option to check that). When using |:setlocal| for global
options or options local to a window, the value will change for many buffers,
and that is not what a filetype plugin should do.
When an option has a value that is a list of flags or items, consider using
"+=" and "-=" to keep the existing value. Be aware that the user may have
changed an option value already. First resetting to the default value and
then changing it is often a good idea. Example:
:setlocal formatoptions& formatoptions+=ro
MAPPINGS
To make sure mappings will only work in the current buffer use the
:map <buffer>
command. This needs to be combined with the two-step mapping explained above.
An example of how to define functionality in a filetype plugin:
if !hasmapto('<Plug>JavaImport')
map <buffer> <unique> <LocalLeader>i <Plug>JavaImport
endif
noremap <buffer> <unique> <Plug>JavaImport oimport ""<Left><Esc>
|hasmapto()| is used to check if the user has already defined a map to
<Plug>JavaImport. If not, then the filetype plugin defines the default
mapping. This starts with |<LocalLeader>|, which allows the user to select
the key(s) he wants filetype plugin mappings to start with. The default is a
backslash.
"<unique>" is used to give an error message if the mapping already exists or
overlaps with an existing mapping.
|:noremap| is used to avoid that any other mappings that the user has defined
interferes. You might want to use ":noremap <script>" to allow remapping
mappings defined in this script that start with <SID>.
The user must have a chance to disable the mappings in a filetype plugin,
without disabling everything. Here is an example of how this is done for a
plugin for the mail filetype:
" Add mappings, unless the user didn't want this.
if !exists("no_plugin_maps") && !exists("no_mail_maps")
" Quote text by inserting "> "
if !hasmapto('<Plug>MailQuote')
vmap <buffer> <LocalLeader>q <Plug>MailQuote
nmap <buffer> <LocalLeader>q <Plug>MailQuote
endif
vnoremap <buffer> <Plug>MailQuote :s/^/> /<CR>
nnoremap <buffer> <Plug>MailQuote :.,$s/^/> /<CR>
endif
Two global variables are used:
no_plugin_maps disables mappings for all filetype plugins
no_mail_maps disables mappings for a specific filetype
USER COMMANDS
To add a user command for a specific file type, so that it can only be used in
one buffer, use the "-buffer" argument to |:command|. Example:
:command -buffer Make make %:r.s
VARIABLES
A filetype plugin will be sourced for each buffer of the type it's for. Local
script variables |s:var| will be shared between all invocations. Use local
buffer variables |b:var| if you want a variable specifically for one buffer.
FUNCTIONS
When defining a function, this only needs to be done once. But the filetype
plugin will be sourced every time a file with this filetype will be opened.
This construct makes sure the function is only defined once:
:if !exists("*s:Func")
: function s:Func(arg)
: ...
: endfunction
:endif
UNDO *undo_ftplugin*
When the user does ":setfiletype xyz" the effect of the previous filetype
should be undone. Set the b:undo_ftplugin variable to the commands that will
undo the settings in your filetype plugin. Example:
let b:undo_ftplugin = "setlocal fo< com< tw< commentstring<"
\ . "| unlet b:match_ignorecase b:match_words b:match_skip"
Using ":setlocal" with "<" after the option name resets the option to its
global value. That is mostly the best way to reset the option value.
This does require removing the "C" flag from 'cpoptions' to allow line
continuation, as mentioned above |use-cpo-save|.
FILE NAME
The filetype must be included in the file name |ftplugin-name|. Use one of
these three forms:
.../ftplugin/stuff.vim
.../ftplugin/stuff_foo.vim
.../ftplugin/stuff/bar.vim
"stuff" is the filetype, "foo" and "bar" are arbitrary names.
SUMMARY *ftplugin-special*
Summary of special things to use in a filetype plugin:
<LocalLeader> Value of "maplocalleader", which the user defines as
the keys that filetype plugin mappings start with.
:map <buffer> Define a mapping local to the buffer.
:noremap <script> Only remap mappings defined in this script that start
with <SID>.
:setlocal Set an option for the current buffer only.
:command -buffer Define a user command local to the buffer.
exists("*s:Func") Check if a function was already defined.
Also see |plugin-special|, the special things used for all plugins.
==============================================================================
*41.13* Writing a compiler plugin *write-compiler-plugin*
A compiler plugin sets options for use with a specific compiler. The user can
load it with the |:compiler| command. The main use is to set the
'errorformat' and 'makeprg' options.
Easiest is to have a look at examples. This command will edit all the default
compiler plugins:
:next $VIMRUNTIME/compiler/*.vim
Use |:next| to go to the next plugin file.
There are two special items about these files. First is a mechanism to allow
a user to overrule or add to the default file. The default files start with:
:if exists("current_compiler")
: finish
:endif
:let current_compiler = "mine"
When you write a compiler file and put it in your personal runtime directory
(e.g., ~/.vim/compiler for Unix), you set the "current_compiler" variable to
make the default file skip the settings.
*:CompilerSet*
The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for
":compiler". Vim defines the ":CompilerSet" user command for this. However,
older Vim versions don't, thus your plugin should define it then. This is an
example:
if exists(":CompilerSet") != 2
command -nargs=* CompilerSet setlocal <args>
endif
CompilerSet errorformat& " use the default 'errorformat'
CompilerSet makeprg=nmake
When you write a compiler plugin for the Vim distribution or for a system-wide
runtime directory, use the mechanism mentioned above. When
"current_compiler" was already set by a user plugin nothing will be done.
When you write a compiler plugin to overrule settings from a default plugin,
don't check "current_compiler". This plugin is supposed to be loaded
last, thus it should be in a directory at the end of 'runtimepath'. For Unix
that could be ~/.vim/after/compiler.
==============================================================================
*41.14* Writing a plugin that loads quickly *write-plugin-quickload*
A plugin may grow and become quite long. The startup delay may become
noticeable, while you hardly ever use the plugin. Then it's time for a
quickload plugin.
The basic idea is that the plugin is loaded twice. The first time user
commands and mappings are defined that offer the functionality. The second
time the functions that implement the functionality are defined.
It may sound surprising that quickload means loading a script twice. What we
mean is that it loads quickly the first time, postponing the bulk of the
script to the second time, which only happens when you actually use it. When
you always use the functionality it actually gets slower!
Note that since Vim 7 there is an alternative: use the |autoload|
functionality |41.15|.
The following example shows how it's done:
" Vim global plugin for demonstrating quick loading
" Last Change: 2005 Feb 25
" Maintainer: Bram Moolenaar <Bram@vim.org>
" License: This file is placed in the public domain.
if !exists("s:did_load")
command -nargs=* BNRead call BufNetRead(<f-args>)
map <F19> :call BufNetWrite('something')<CR>
let s:did_load = 1
exe 'au FuncUndefined BufNet* source ' . expand('<sfile>')
finish
endif
function BufNetRead(...)
echo 'BufNetRead(' . string(a:000) . ')'
" read functionality here
endfunction
function BufNetWrite(...)
echo 'BufNetWrite(' . string(a:000) . ')'
" write functionality here
endfunction
When the script is first loaded "s:did_load" is not set. The commands between
the "if" and "endif" will be executed. This ends in a |:finish| command, thus
the rest of the script is not executed.
The second time the script is loaded "s:did_load" exists and the commands
after the "endif" are executed. This defines the (possible long)
BufNetRead() and BufNetWrite() functions.
If you drop this script in your plugin directory Vim will execute it on
startup. This is the sequence of events that happens:
1. The "BNRead" command is defined and the <F19> key is mapped when the script
is sourced at startup. A |FuncUndefined| autocommand is defined. The
":finish" command causes the script to terminate early.
2. The user types the BNRead command or presses the <F19> key. The
BufNetRead() or BufNetWrite() function will be called.
3. Vim can't find the function and triggers the |FuncUndefined| autocommand
event. Since the pattern "BufNet*" matches the invoked function, the
command "source fname" will be executed. "fname" will be equal to the name
of the script, no matter where it is located, because it comes from
expanding "<sfile>" (see |expand()|).
4. The script is sourced again, the "s:did_load" variable exists and the
functions are defined.
Notice that the functions that are loaded afterwards match the pattern in the
|FuncUndefined| autocommand. You must make sure that no other plugin defines
functions that match this pattern.
==============================================================================
*41.15* Writing library scripts *write-library-script*
Some functionality will be required in several places. When this becomes more
than a few lines you will want to put it in one script and use it from many
scripts. We will call that one script a library script.
Manually loading a library script is possible, so long as you avoid loading it
when it's already done. You can do this with the |exists()| function.
Example:
if !exists('*MyLibFunction')
runtime library/mylibscript.vim
endif
call MyLibFunction(arg)
Here you need to know that MyLibFunction() is defined in a script
"library/mylibscript.vim" in one of the directories in 'runtimepath'.
To make this a bit simpler Vim offers the autoload mechanism. Then the
example looks like this:
call mylib#myfunction(arg)
That's a lot simpler, isn't it? Vim will recognize the function name and when
it's not defined search for the script "autoload/mylib.vim" in 'runtimepath'.
That script must define the "mylib#myfunction()" function.
You can put many other functions in the mylib.vim script, you are free to
organize your functions in library scripts. But you must use function names
where the part before the '#' matches the script name. Otherwise Vim would
not know what script to load.
If you get really enthusiastic and write lots of library scripts, you may
want to use subdirectories. Example:
call netlib#ftp#read('somefile')
For Unix the library script used for this could be:
~/.vim/autoload/netlib/ftp.vim
Where the function is defined like this:
function netlib#ftp#read(fname)
" Read the file fname through ftp
endfunction
Notice that the name the function is defined with is exactly the same as the
name used for calling the function. And the part before the last '#'
exactly matches the subdirectory and script name.
You can use the same mechanism for variables:
let weekdays = dutch#weekdays
This will load the script "autoload/dutch.vim", which should contain something
like:
let dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag',
\ 'donderdag', 'vrijdag', 'zaterdag']
Further reading: |autoload|.
==============================================================================
*41.16* Distributing Vim scripts *distribute-script*
Vim users will look for scripts on the Vim website: http://www.vim.org.
If you made something that is useful for others, share it!
Vim scripts can be used on any system. There might not be a tar or gzip
command. If you want to pack files together and/or compress them the "zip"
utility is recommended.
For utmost portability use Vim itself to pack scripts together. This can be
done with the Vimball utility. See |vimball|.
It's good if you add a line to allow automatic updating. See |glvs-plugins|.
==============================================================================
Next chapter: |usr_42.txt| Add new menus
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
*gui-fork*
When the GUI is started, it does a fork() and exits the current process.
When gvim was started from a shell this makes the shell accept further
commands. If you don't want this (e.g. when using gvim for a mail program
that waits for gvim to exit), start gvim with "gvim -f", "vim -gf" or use
":gui -f". Don't use "vim -fg", because "-fg" specifies the foreground
color.
When using "gvim -f" and then ":gui", Vim will run in the foreground. The
"-f" argument will be remembered. To force running Vim in the background use
":gui -b".
"gvim --nofork" does the same as "gvim -f".
If you want the GUI to run in the foreground always, include the 'f'
*font-sizes*
Note: All fonts (except for the menu and tooltip) must be of the same size!!!
If you don't do this, text will disappear or mess up the display. Vim does
not check the font sizes. It's the size in screen pixels that must be the
same. Note that some fonts that have the same point size don't have the same
pixel size! Additionally, the positioning of the fonts must be the same
(ascent and descent). You can check this with "xlsfonts -l {fontname}".
If any of these things are also set with Vim commands, e.g. with
":set guifont=Screen15", then this will override the X resources (currently
'guifont' is the only option that is supported).
Here is an example of what you might put in your ~/.Xdefaults file:
Vim*useSchemes: all
Vim*sgiMode: true
Vim*useEnhancedFSB: true
Vim.foreground: Black
Vim.background: Wheat
Vim*fontList: 7x13
The first three of these are standard resources on Silicon Graphics machines
which make Motif applications look even better, highly recommended!
The "Vim*fontList" is to set the menu font for Motif. Example:
Vim*menuBar*fontList: -*-courier-medium-r-*-*-10-*-*-*-*-*-*-*
With Athena:
Vim*menuBar*SmeBSB*font: -*-courier-medium-r-*-*-10-*-*-*-*-*-*-*
Vim*menuBar*MenuButton*font: -*-courier-medium-r-*-*-10-*-*-*-*-*-*-*
NOTE: A more portable, and indeed more correct, way to specify the menu font
in either Motif or Athena is through the resource:
Vim.menuFont: -*-courier-medium-r-*-*-10-*-*-*-*-*-*-*
Or, when compiled with the |+xfontset| feature:
Vim.menuFontSet: -*-courier-medium-r-*-*-10-*-*-*-*-*-*-*
Don't use "Vim*geometry" in the defaults. This will break the menus. Use
"Vim.geometry" instead.
If you get an error message "Cannot allocate colormap entry for "gray60",
try adding this to your Vim resources (change the colors to your liking):
Vim*scrollBackground: Black
Vim*scrollForeground: Blue
The resources can also be set with arguments to Vim:
argument meaning
*-gui*
-display {display} Run vim on {display} *-display*
-iconic Start vim iconified *-iconic*
-background {color} Use {color} for the background *-background*
-bg {color} idem *-bg*
-foreground {color} Use {color} for normal text *-foreground*
-fg {color} idem *-fg*
-ul {color} idem *-ul*
-font {font} Use {font} for normal text *-font*
-fn {font} idem *-fn*
-boldfont {font} Use {font} for bold text *-boldfont*
-italicfont {font} Use {font} for italic text *-italicfont*
-menufont {font} Use {font} for menu items *-menufont*
-menufontset {fontset} Use {fontset} for menu items *-menufontset*
-mf {font} idem *-mf*
-geometry {geom} Use {geom} for initial geometry *-geometry*
-geom {geom} idem, see |-geometry-example| *-geom*
-borderwidth {width} Use a border width of {width} *-borderwidth*
-bw {width} idem *-bw*
*-scrollbarwidth*
-scrollbarwidth {width} Use a scrollbar width of {width}
-sw {width} idem *-sw*
-menuheight {height} Use a menu bar height of {height} *-menuheight*
-mh {height} idem *-mh*
NOTE: On Motif the value is ignored, the menu height
is computed to fit the menus.
-reverse Use reverse video *-reverse*
-rv idem *-rv*
+reverse Don't use reverse video *-+reverse*
+rv idem *-+rv*
*-geometry-example*
An example for the geometry argument:
gvim -geometry 80x63+8+100
This creates a window with 80 columns and 63 lines at position 8 pixels from
the left and 100 pixels from the top of the screen.
==============================================================================
3. Shell Commands *gui-pty*
WARNING: Executing an external command from the GUI will not always work.
"normal" commands like "ls", "grep" and "make" mostly work fine. Commands
that require an intelligent terminal like "less" and "ispell" won't work.
Some may even hang and need to be killed from another terminal. So be
careful!
There are two ways to do the I/O with a shell command: Pipes and a pseudo-tty.
The default is to use a pseudo-tty. This should work best on most systems.
Unfortunately, the implementation of the pseudo-tty is different on every Unix
system. And some systems require root permission. To avoid running into
problems with a pseudo-tty when you least expect it, test it when not editing
a file. Be prepared to "kill" the started command or Vim. Commands like
":r !cat" may hang!
If using a pseudo-tty does not work for you, reset the 'guipty' option:
:set noguipty
Using a pipe should work on any Unix system, but there are disadvantages:
- Some shell commands will notice that a pipe is being used and behave
differently. E.g., ":!ls" will list the files in one column.
- The ":sh" command won't show a prompt, although it will sort of work.
- When using ":make" it's not possible to interrupt with a CTRL-C.
Typeahead while the external command is running is often lost. This happens
both with a pipe and a pseudo-tty. This is a known problem, but it seems it
can't be fixed (or at least, it's very difficult).
*gui-pty-erase*
When your erase character is wrong for an external command, you should fix
this in your "~/.cshrc" file, or whatever file your shell uses for
initializations. For example, when you want to use backspace to delete
characters, but hitting backspaces produces "^H" instead, try adding this to
your "~/.cshrc":
stty erase ^H
The ^H is a real CTRL-H, type it as CTRL-V CTRL-H.
==============================================================================
4. Various *gui-x11-various*
*gui-x11-printing*
The "File/Print" menu simply sends the current buffer to "lpr". No options or
whatever. If you want something else, you can define your own print command.
For example:
:10amenu File.Print :w !lpr -Php3
:10vmenu File.Print :w !lpr -Php3
*X11-icon*
Vim uses a black&white icon by default when compiled with Motif or Athena. A
colored Vim icon is included as $VIMRUNTIME/vim32x32.xpm. For GTK+, this is
the builtin icon used. Unfortunately, how you should install it depends on
your window manager. When you use this, remove the 'i' flag from
'guioptions', to remove the black&white icon:
:set guioptions-=i
If you use one of the fvwm* family of window managers simply add this line to
your .fvwm2rc configuration file:
Style "vim" Icon vim32x32.xpm
Make sure the icon file's location is consistent with the window manager's
ImagePath statement. Either modify the ImagePath from within your .fvwm2rc or
drop the icon into one the pre-defined directories:
ImagePath /usr/X11R6/include/X11/pixmaps:/usr/X11R6/include/X11/bitmaps
Note: older versions of fvwm use "IconPath" instead of "ImagePath".
For CDE "dtwm" (a derivative of Motif) add this line in the .Xdefaults:
Dtwm*Vim*iconImage: /usr/local/share/vim/vim32x32.xpm
For "mwm" (Motif window manager) the line would be:
Mwm*Vim*iconImage: /usr/local/share/vim/vim32x32.xpm
--gtk-module
--display (GTK+ counterpart of -display; works the same way.)
--screen (The screen number; for GTK+ 2.2 multihead support.)
These arguments are ignored when the |+netbeans_intg| feature is used:
-xrm
-mf
As for colors, Vim's color settings (for syntax highlighting) is still
done the traditional Vim way. See |:highlight| for more help.
If you want to set the colors of remaining gui components (e.g., the
menubar, scrollbar, whatever), those are GTK specific settings and you
need to set those up in some sort of gtkrc file. You'll have to refer
to the GTK documentation, however little there is, on how to do this.
See http://developer.gnome.org/doc/API/2.0/gtk/gtk-Resource-Files.html
for more information.
*gtk-tooltip-colors*
Example, which sets the tooltip colors to black on light-yellow:
style "tooltips"
{
bg[NORMAL] = "#ffffcc"
fg[NORMAL] = "#000000"
}
widget "gtk-tooltips*" style "tooltips"
Write this in the file ~/.gtkrc and it will be used by GTK+. For GTK+ 2
you might have to use the file ~/.gtkrc-2.0 instead, depending on your
distribution.
*gui-x11-gtk*
At the time of this writing, GTK+ version 1.0.6 and 1.2 are outdated. It
is suggested that you use GTK 2. The GTK 1 support will most likely be
dropped soon.
For the GTK+ 2 GUI, using the latest release of the GTK+ 2.0 or GTK+ 2.2
series is recommended.
Lastly, although GTK+ has supposedly been ported to the Win32 platform, this
has not been tested with Vim and is also unsupported. Also, it's unlikely to
even compile since GTK+ GUI uses parts of the generic X11 code. This might
change in distant future; particularly because getting rid of the X11 centric
code parts is also required for GTK+ framebuffer support.
*gui-x11-motif*
For Motif, you need at least Motif version 1.2 and/or X11R5. Motif 2.0 and
X11R6 are OK. Motif 1.1 and X11R4 might work, no guarantee (there may be a
few problems, but you might make it compile and run with a bit of work, please
send me the patches if you do). The newest releases of LessTif have been
reported to work fine too.
*gui-x11-athena*
The Athena version uses the Xaw widget set by default. If you have the 3D
version, you might want to link with Xaw3d instead. This will make the
menus look a bit better. Edit the Makefile and look for "XAW_LIB". The
scrollbars will remain the same, because Vim has its own, which are already
3D (in fact, they look more like Motif).
*gui-x11-neXtaw*
The neXtaw version is mostly like Athena, but uses different widgets.
*gui-x11-misc*
In general, do not try to mix files from different GTK+, Motif, Athena and X11
versions. This will cause problems. For example, using header files for
X11R5 with a library for X11R6 probably doesn't work (although the linking
won't give an error message, Vim will crash later).
==============================================================================
9. X11 selection mechanism *x11-selection*
If using X11, in either the GUI or an xterm with an X11-aware Vim, then Vim
provides varied access to the X11 selection and clipboard. These are accessed
by using the two selection registers "* and "+.
X11 provides two basic types of global store, selections and cut-buffers,
which differ in one important aspect: selections are "owned" by an
application, and disappear when that application (e.g., Vim) exits, thus
losing the data, whereas cut-buffers, are stored within the X-server itself
and remain until written over or the X-server exits (e.g., upon logging out).
The contents of selections are held by the originating application (e.g., upon
a copy), and only passed on to another application when that other application
asks for them (e.g., upon a paste).
The contents of cut-buffers are immediately written to, and are then
accessible directly from the X-server, without contacting the originating
application.
*quoteplus* *quote+*
There are three documented X selections: PRIMARY (which is expected to
represent the current visual selection - as in Vim's Visual mode), SECONDARY
(which is ill-defined) and CLIPBOARD (which is expected to be used for
cut, copy and paste operations).
Of these three, Vim uses PRIMARY when reading and writing the "* register
(hence when the X11 selections are available, Vim sets a default value for
|'clipboard'| of "autoselect"), and CLIPBOARD when reading and writing the "+
register. Vim does not access the SECONDARY selection.
Examples: (assuming the default option values)
- Select an URL in Visual mode in Vim. Go to your browser and click the
middle mouse button in the URL text field. The selected text will be
inserted (hopefully!). Note: in Firefox you can set the
middlemouse.contentLoadURL preference to true in about:config, then the
selected URL will be used when pressing middle mouse button in most places
in the window.
- Select some text in your browser by dragging with the mouse. Go to Vim and
press the middle mouse button: The selected text is inserted.
- Select some text in Vim and do "+y. Go to your browser, select some text in
a textfield by dragging with the mouse. Now use the right mouse button and
select "Paste" from the popup menu. The selected text is overwritten by the
text from Vim.
Note that the text in the "+ register remains available when making a Visual
selection, which makes other text available in the "* register. That allows
overwriting selected text.
*x11-cut-buffer*
There are, by default, 8 cut-buffers: CUT_BUFFER0 to CUT_BUFFER7. Vim only
uses CUT_BUFFER0, which is the one that xterm uses by default.
Whenever Vim is about to become unavailable (either via exiting or becoming
suspended), and thus unable to respond to another application's selection
request, it writes the contents of any owned selection to CUT_BUFFER0. If the
"+ CLIPBOARD selection is owned by Vim, then this is written in preference,
otherwise if the "* PRIMARY selection is owned by Vim, then that is written.
Similarly, when Vim tries to paste from "* or "+ (either explicitly, or, in
the case of the "* register, when the middle mouse button is clicked), if the
requested X selection is empty or unavailable, Vim reverts to reading the
current value of the CUT_BUFFER0.
Note that when text is copied to CUT_BUFFER0 in this way, the type of
selection (character, line or block) is always lost, even if it is a Vim which
later pastes it.
Xterm, by default, always writes visible selections to both PRIMARY and
CUT_BUFFER0. When it pastes, it uses PRIMARY if this is available, or else
falls back upon CUT_BUFFER0. For this reason, when cutting and pasting
between Vim and an xterm, you should use the "* register. Xterm doesn't use
CLIPBOARD, thus the "+ doesn't work with xterm.
Most newer applications will provide their current selection via PRIMARY ("*)
and use CLIPBOARD ("+) for cut/copy/paste operations. You thus have access to
both by choosing to use either of the "* or "+ registers.
Printing *printing*
1. Introduction |print-intro|
2. Print options |print-options|
3. PostScript Printing |postscript-printing|
4. PostScript Printing Encoding |postscript-print-encoding|
5. PostScript CJK Printing |postscript-cjk-printing|
6. PostScript Printing Troubleshooting |postscript-print-trouble|
7. PostScript Utilities |postscript-print-util|
8. Formfeed Characters |printing-formfeed|
{Vi has None of this}
{only available when compiled with the |+printer| feature}
==============================================================================
1. Introduction *print-intro*
On MS-Windows Vim can print your text on any installed printer. On other
systems a PostScript file is produced. This can be directly sent to a
PostScript printer. For other printers a program like ghostscript needs to be
used.
Note: If you have problems printing with |:hardcopy|, an alternative is to use
|:TOhtml| and print the resulting html file from a browser.
abort printing use the interrupt key (CTRL-C or, on MS-systems, CTRL-Break).
Printer output is controlled by the 'printfont' and 'printoptions' options.
'printheader' specifies the format of a page header.
The printed file is always limited to the selected margins, irrespective of
the current window's 'wrap' or 'linebreak' settings. The "wrap" item in
'printoptions' can be used to switch wrapping off.
The current highlighting colors are used in the printout, with the following
considerations:
1) The normal background is always rendered as white (i.e. blank paper).
2) White text or the default foreground is rendered as black, so that it shows
up!
3) If 'background' is "dark", then the colours are darkened to compensate for
the fact that otherwise they would be too bright to show up clearly on
white paper.
==============================================================================
2. Print options *print-options*
Here are the details for the options that change the way printing is done.
For generic info about setting options see |options.txt|.
*pdev-option*
'printdevice' 'pdev' string (default empty)
global
This defines the name of the printer to be used when the |:hardcopy| command
is issued with a bang (!) to skip the printer selection dialog. On Win32, it
should be the printer name exactly as it appears in the standard printer
dialog.
If the option is empty, then vim will use the system default printer for
":hardcopy!"
*penc-option* *E620*
'printencoding' 'penc' String (default empty, except for:
Windows, OS/2: cp1252,
Macintosh: mac-roman,
VMS: dec-mcs,
HPUX: hp-roman8,
EBCDIC: ebcdic-uk)
global
Sets the character encoding used when printing. This option tells VIM which
print character encoding file from the "print" directory in 'runtimepath' to
use.
This option will accept any value from |encoding-names|. Any recognized names
are converted to VIM standard names - see 'encoding' for more details. Names
not recognized by VIM will just be converted to lower case and underscores
replaced with '-' signs.
If 'printencoding' is empty or VIM cannot find the file then it will use
'encoding' (if VIM is compiled with |+multi_byte| and it is set an 8-bit
encoding) to find the print character encoding file. If VIM is unable to find
a character encoding file then it will use the "latin1" print character
encoding file.
When 'encoding' is set to a multi-byte encoding, VIM will try to convert
characters to the printing encoding for printing (if 'printencoding' is empty
then the conversion will be to latin1). Conversion to a printing encoding
other than latin1 will require VIM to be compiled with the |+iconv| feature.
If no conversion is possible then printing will fail. Any characters that
cannot be converted will be replaced with upside down question marks.
Four print character encoding files are provided to support default Mac, VMS,
HPUX, and EBCDIC character encodings and are used by default on these
platforms. Code page 1252 print character encoding is used by default on
Windows and OS/2 platforms.
*pexpr-option*
'printexpr' 'pexpr' String (default: see below)
global
Expression that is evaluated to print the PostScript produced with
|:hardcopy|.
The file name to be printed is in |v:fname_in|.
The arguments to the ":hardcopy" command are in |v:cmdarg|.
The expression must take care of deleting the file after printing it.
*pfn-option* *E613*
'printfont' 'pfn' string (default "courier")
global
This is the name of the font that will be used for the |:hardcopy| command's
output. It has the same format as the 'guifont' option, except that only one
font may be named, and the special "guifont=*" syntax is not available.
In the Win32 GUI version this specifies a font name with its extra attributes,
as with the 'guifont' option.
For other systems, only ":h11" is recognized, where "11" is the point size of
the font. When omitted, the point size is 10.
*pheader-option*
'printheader' 'pheader' string (default "%<%f%h%m%=Page %N")
global
This defines the format of the header produced in |:hardcopy| output. The
option is defined in the same way as the 'statusline' option. If Vim has not
been compiled with the |+statusline| feature, this option has no effect and a
simple default header is used, which shows the page number. The same simple
header is used when this option is empty.
*pmbcs-option*
'printmbcharset' 'pmbcs' string (default "")
global
Sets the CJK character set to be used when generating CJK output from
|:hardcopy|. The following predefined values are currently recognised by VIM:
Value Description
Chinese GB_2312-80
(Simplified) GBT_12345-90
MAC Apple Mac Simplified Chinese
*pmbfn-option*
'printmbfont' 'pmbfn' string (default "")
global
This is a comma-separated list of fields for font names to be used when
generating CJK output from |:hardcopy|. Each font name has to be preceded
with a letter indicating the style the font is to be used for as follows:
r:{font-name} font to use for normal characters
b:{font-name} font to use for bold characters
i:{font-name} font to use for italic characters
o:{font-name} font to use for bold-italic characters
A field with the r: prefix must be specified when doing CJK printing. The
other fontname specifiers are optional. If a specifier is missing then
another font will be used as follows:
*popt-option*
'printoptions' 'popt' string (default "")
global
This is a comma-separated list of items that control the format of the output
of YXXY:hardcopy|:
left:{spec} left margin (default: 10pc)
right:{spec} right margin (default: 5pc)
top:{spec} top margin (default: 5pc)
bottom:{spec} bottom margin (default: 5pc)
{spec} is a number followed by "in" for inches, "pt"
for points (1 point is 1/72 of an inch), "mm" for
millimeters or "pc" for a percentage of the media
size.
Weird example:
left:2in,top:30pt,right:16mm,bottom:3pc
If the unit is not recognized there is no error and
the default value is used.
header:{nr} Number of lines to reserve for the header.
Only the first line is actually filled, thus when {nr}
is 2 there is one empty line. The header is formatted
according to 'printheader'.
header:0 Do not print a header.
header:2 (default) Use two lines for the header
syntax:n Do not use syntax highlighting. This is faster and
thus useful when printing large files.
syntax:y Do syntax highlighting.
syntax:a (default) Use syntax highlighting if the printer appears to be
able to print color or grey.
number:y Include line numbers in the printed output.
number:n (default) No line numbers.
wrap:y (default) Wrap long lines.
wrap:n Truncate long lines.
duplex:off Print on one side.
duplex:long (default) Print on both sides (when possible), bind on long
side.
duplex:short Print on both sides (when possible), bind on short
side.
collate:y (default) Collating: 1 2 3, 1 2 3, 1 2 3
collate:n No collating: 1 1 1, 2 2 2, 3 3 3
jobsplit:n (default) Do all copies in one print job
jobsplit:y Do each copy as a separate print job. Useful when
doing N-up postprocessing.
portrait:y (default) Orientation is portrait.
portrait:n Orientation is landscape.
*a4* *letter*
paper:A4 (default) Paper size: A4
paper:{name} Paper size from this table:
iii. Edit your renamed copy of latin1.ps, replacing all occurrences of latin1
with your unique name (don't forget the line starting %%Title:), and
modify the array of glyph names to define your new encoding vector. The
array must have exactly 256 entries or you will not be able to print!
iv. Within VIM, set 'printencoding' to your unique encoding name and then
print your file. VIM will now use your custom print character encoding.
VIM will report an error with the resource file if you change the order or
content of the first 3 lines, other than the name of the encoding on the line
starting %%Title: or the version number on the line starting %%Version:.
[Technical explanation for those that know PostScript - VIM looks for a file
with the same name as the encoding it will use when printing. The file
defines a new PostScript Encoding resource called /VIM-name, where name is the
print character encoding VIM will use.]
==============================================================================
5. PostScript CJK Printing *postscript-cjk-printing*
*E673* *E674* *E675*
VIM supports printing of Chinese, Japanese, and Korean files. Setting up VIM
to correctly print CJK files requires setting up a few more options.
Each of these countries has many standard character sets and encodings which
require that both be specified when printing. In addition, CJK fonts normally
do not have the concept of italic glyphs and use different weight or stroke
style to achieve emphasis when printing. This in turn requires a different
approach to specifying fonts to use when printing.
The encoding and character set are specified with the 'printencoding' and
'printmbcharset' options. If 'printencoding' is not specified then 'encoding'
is used as normal. If 'printencoding' is specified then characters will be
translated to this encoding for printing. You should ensure that the encoding
is compatible with the character set needed for the file contents or some
characters may not appear when printed.
The fonts to use for CJK printing are specified with 'printmbfont'. This
option allows you to specify different fonts to use when printing characters
which are syntax highlighted with the font styles normal, italic, bold and
bold-italic.
No CJK fonts are supplied with VIM. There are some free Korean, Japanese, and
Traditional Chinese fonts available at:
http://examples.oreilly.com/cjkvinfo/adobe/samples/
You can find descriptions of the various fonts in the read me file at
http://examples.oreilly.de/english_examples/cjkvinfo/adobe/00README
Please read your printer documentation on how to install new fonts.
CJK fonts can be large containing several thousand glyphs, and it is not
uncommon to find that they only contain a subset of a national standard. It
is not unusual to find the fonts to not include characters for codes in the
ASCII code range. If you find half-width Roman characters are not appearing
in your printout then you should configure VIM to use the Courier font the
half-width ASCII characters with 'printmbfont'. If your font does not include
other characters then you will need to find another font that does.
Another issue with ASCII characters, is that the various national character
sets specify a couple of different glyphs in the ASCII code range. If you
print ASCII text using the national character set you may see some unexpected
characters. If you want true ASCII code printing then you need to configure
VIM to output ASCII characters for the ASCII code range with 'printmbfont'.
It is possible to define your own multi-byte character set although this
should not be attempted lightly. A discussion on the process if beyond the
scope of these help files. You can find details on CMap (character map) files
in the document 'Adobe CMap and CIDFont Files Specification, Version 1.0',
available from http://www.adobe.com as a PDF file.
==============================================================================
6. PostScript Printing Troubleshooting *postscript-print-trouble*
*E621*
Usually the only sign of a problem when printing with PostScript is that your
printout does not appear. If you are lucky you may get a printed page that
tells you the PostScript operator that generated the error that prevented the
print job completing.
There are a number of possible causes as to why the printing may have failed:
- Wrong version of the prolog resource file. The prolog resource file
contains some PostScript that VIM needs to be able to print. Each version
of VIM needs one particular version. Make sure you have correctly installed
the runtime files, and don't have any old versions of a file called prolog
in the print directory in your 'runtimepath' directory.
- Paper size. Some PostScript printers will abort printing a file if they do
not support the requested paper size. By default VIM uses A4 paper. Find
out what size paper your printer normally uses and set the appropriate paper
size with 'printoptions'. If you cannot find the name of the paper used,
measure a sheet and compare it with the table of supported paper sizes listed
for 'printoptions', using the paper that is closest in both width AND height.
Note: The dimensions of actual paper may vary slightly from the ones listed.
If there is no paper listed close enough, then you may want to try psresize
from PSUtils, discussed below.
- Two-sided printing (duplex). Normally a PostScript printer that does not
support two-sided printing will ignore any request to do it. However, some
printers may abort the job altogether. Try printing with duplex turned off.
Note: Duplex prints can be achieved manually using PS utils - see below.
- Collated printing. As with Duplex printing, most PostScript printers that
do not support collating printouts will ignore a request to do so. Some may
not. Try printing with collation turned off.
- Syntax highlighting. Some print management code may prevent the generated
PostScript file from being printed on a black and white printer when syntax
highlighting is turned on, even if solid black is the only color used. Try
printing with syntax highlighting turned off.
A safe printoptions setting to try is:
:set printoptions=paper:A4,duplex:off,collate:n,syntax:n
Replace "A4" with the paper size that best matches your printer paper.
==============================================================================
7. PostScript Utilities *postscript-print-util*
7.1 Ghostscript
Ghostscript is a PostScript and PDF interpreter that can be used to display
and print on non-PostScript printers PostScript and PDF files. It can also
generate PDF files from PostScript.
Ghostscript will run on a wide variety of platforms.
There are three available versions:
- AFPL Ghostscript (formerly Aladdin Ghostscript) which is free for
non-commercial use. It can be obtained from:
http://www.cs.wisc.edu/~ghost/
- GNU Ghostscript which is available under the GNU General Public License. It
can be obtained from:
ftp://mirror.cs.wisc.edu/pub/mirrors/ghost/gnu/
- A commercial version for inclusion in commercial products.
Additional information on Ghostscript can also be found at:
http://www.ghostscript.com/
Support for a number of non PostScript printers is provided in the
distribution as standard, but if you cannot find support for your printer
check the Ghostscript site for other printers not included by default.
ends have been created. These allow easier PostScript file selection,
previewing at different zoom levels, and printing. Check supplied
documentation for full details.
X11
- Ghostview. Obtainable from:
http://www.cs.wisc.edu/~ghost/gv/
- gv. Derived from Ghostview. Obtainable from:
http://wwwthep.physik.uni-mainz.de/~plass/gv/
Copies (possibly not the most recent) can be found at:
http://www.cs.wisc.edu/~ghost/gv/
OpenVMS
- Is apparently supported in the main code now (untested). See:
http://wwwthep.physik.uni-mainz.de/~plass/gv/
Windows and OS/2
- GSview. Obtainable from:
http://www.cs.wisc.edu/~ghost/gsview/
DOS
- ps_view. Obtainable from:
ftp://ftp.pg.gda.pl/pub/TeX/support/ps_view/
ftp://ftp.dante.de/tex-archive/support/ps_view/
Linux
- GSview. Linux version of the popular Windows and OS/2 previewer.
Obtainable from:
http://www.cs.wisc.edu/~ghost/gsview/
- BMV. Different from Ghostview and gv in that it doesn't use X but svgalib.
Obtainable from:
ftp://sunsite.unc.edu/pub/Linux/apps/graphics/viewers/svga/bmv-1.2.tgz
7.3 PSUtils
PSUtils is a collection of utility programs for manipulating PostScript
documents. Binary distributions are available for many platforms, as well as
the full source. PSUtils can be found at:
http://knackered.org/angus/psutils
The utilities of interest include:
- psnup. Convert PS files for N-up printing.
- psselect. Select page range and order of printing.
- psresize. Change the page size.
- psbook. Reorder and lay out pages ready for making a book.
The output of one program can be used as the input to the next, allowing for
complex print document creation.
N-UP PRINTING
The psnup utility takes an existing PostScript file generated from VIM and
convert it to an n-up version. The simplest way to create a 2-up printout is
to first create a PostScript file with:
:hardcopy > test.ps
Then on your command line execute:
psnup -n 2 test.ps final.ps
Note: You may get warnings from some Ghostscript previewers for files produced
by psnup - these may safely be ignored.
Finally print the file final.ps to your PostScript printer with your
platform's print command. (You will need to delete the two PostScript files
afterwards yourself.) 'printexpr' could be modified to perform this extra
step before printing.
==============================================================================
8. Formfeed Characters *printing-formfeed*
By default VIM does not do any special processing of |formfeed| control
characters. Setting the 'printoptions' formfeed item will make VIM recognize
formfeed characters and continue printing the current line at the beginning
of the first line on a new page. The use of formfeed characters provides
rudimentary print control but there are certain things to be aware of.
VIM will always start printing a line (including a line number if enabled)
containing a formfeed character, even if it is the first character on the
line. This means if a line starting with a formfeed character is the first
line of a page then VIM will print a blank page.
Since the line number is printed at the start of printing the line containing
the formfeed character, the remainder of the line printed on the new page
will not have a line number printed for it (in the same way as the wrapped
lines of a long line when wrap in 'printoptions' is enabled).
If the formfeed character is the last character on a line, then printing will
continue on the second line of the new page, not the first. This is due to
VIM processing the end of the line after the formfeed character and moving
down a line to continue printing.
Due to the points made above it is recommended that when formfeed character
processing is enabled, printing of line numbers is disabled, and that form
feed characters are not the last character on a line. Even then you may need
to adjust the number of lines before a formfeed character to prevent
accidental blank pages.
==============================================================================
top - main help file
they are for the same language and encoding. If you do not get the menu
translations you expected, check the output of this command:
echo v:lang
Now check the "$VIMRUNTIME/lang" directory for menu translation files that use
a similar language. A difference in a "-" being a "_" already causes a file
not to be found! Another common difference to watch out for is "iso8859-1"
versus "iso_8859-1". Fortunately Vim makes all names lowercase, thus you
don't have to worry about case differences. Spaces are changed to
underscores, to avoid having to escape them.
If you find a menu translation file for your language with a different name,
create a file in your own runtime directory to load that one. The name of
that file could be:
~/.vim/lang/menu_<v:lang>.vim
Check the 'runtimepath' option for directories which are searched. In that
file put a command to load the menu file with the other name:
runtime lang/menu_<other_lang>.vim
TRANSLATING MENUS
If you want to do your own translations, you can use the |:menutrans| command,
explained below. It is recommended to put the translations for one language
in a Vim script. For a language that has no translation yet, please consider
becoming the maintainer and make your translations available to all Vim users.
Send an e-mail to the Vim maintainer <maintainer@vim.org>.
*:lua*
:[range]lua {chunk}
Execute Lua chunk {chunk}. {not in Vi}
Examples:
:lua print("Hello, Vim!")
:lua local curbuf = vim.buffer() curbuf[7] = "line #7"
*:luado*
:[range]luado {body} Execute Lua function "function (line) {body} end" for
each line in the [range], with the function argument
being set to the text of each line in turn, without a
trailing <EOL>. If the value returned by the function
is a string it becomes the text of the line in the
current turn. The default for [range] is the whole
file: "1,$". {not in Vi}
Examples:
:luado return string.format("%s\t%d", line:reverse(), #line)
:lua require"lpeg"
:lua -- balanced parenthesis grammar:
:lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
:luado if bp:match(line) then return "-->\t" .. line end
*:luafile*
:[range]luafile {file}
Execute Lua script in {file}. {not in Vi}
The whole argument is used as a single file name.
Examples:
:luafile script.lua
:luafile %
All these commands execute a Lua chunk from either the command line (:lua and
:luado) or a file (:luafile) with the given line [range]. Similarly to the Lua
interpreter, each chunk has its own scope and so only global variables are
shared between command calls. Lua default libraries "table", "string", "math",
and "package" are available, "io" and "debug" are not, and "os" is restricted
to functions "date", "clock", "time", "difftime", and "getenv". In addition,
Lua "print" function has its output redirected to the Vim message area, with
arguments separated by a white space instead of a tab.
Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim
and manage buffers (|lua-buffer|) and windows (|lua-window|). However,
procedures that alter buffer content, open new buffers, and change cursor
position are restricted when the command is executed in the |sandbox|.
==============================================================================
2. The vim module *lua-vim*
Lua interfaces Vim through the "vim" module. The first and last line of the
input range are stored in "vim.firstline" and "vim.lastline" respectively. The
module also includes routines for buffer, window, and current line queries,
Vim evaluation and command execution, and others.
vim.isbuffer(value) Returns 'true' (boolean, not string) if
"value" is a buffer userdata and 'false'
otherwise (see |lua-buffer|).
vim.buffer([arg]) If "arg" is a number, returns buffer with
number "arg" in the buffer list or, if "arg"
is a string, returns buffer whose full or short
name is "arg". In both cases, returns 'nil'
(nil value, not string) if the buffer is not
found. Otherwise, if "toboolean(arg)" is
'true' returns the first buffer in the buffer
list or else the current buffer.
vim.iswindow(value) Returns 'true' (boolean, not string) if
"value" is a window userdata and
'false' otherwise (see |lua-window|).
vim.window([arg]) If "arg" is a number, returns window with
number "arg" or 'nil' (nil value, not string)
if not found. Otherwise, if "toboolean(arg)"
is 'true' returns the first window or else the
current window.
vim.command({cmd}) Executes the vim (ex-mode) command {cmd}.
Examples:
:lua vim.command"set tw=60"
==============================================================================
3. Buffer userdata *lua-buffer*
Buffer userdata represent vim buffers. A buffer userdata "b" has the following
properties and methods:
Properties
o "b()" sets "b" as the current buffer.
o "#b" is the number of lines in buffer "b".
o "b[k]" represents line number k: "b[k] = newline" replaces line k
with string "newline" and "b[k] = nil" deletes line k.
o "b.name" contains the short name of buffer "b" (read-only).
o "b.fname" contains the full name of buffer "b" (read-only).
o "b.number" contains the position of buffer "b" in the buffer list
(read-only).
Methods
o "b:insert(newline[, pos])" inserts string "newline" at (optional)
position "pos" in the buffer. The default value for "pos" is
"#b + 1". If "pos == 0" then "newline" becomes the first line in
the buffer.
o "b:next()" returns the buffer next to "b" in the buffer list.
o "b:previous()" returns the buffer previous to "b" in the buffer
list.
o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to
a "real" (not freed from memory) Vim buffer.
Examples:
:lua b = vim.buffer() -- current buffer
:lua print(b.name, b.number)
:lua b[1] = "first line"
:lua b:insert("FIRST!", 0)
:lua b[1] = nil -- delete top line
:lua for i=1,3 do b:insert(math.random()) end
:3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end
:lua vim.open"myfile"() -- open buffer and set it as current
function! ListBuffers()
lua << EOF
local b = vim.buffer(true) -- first buffer in list
while b ~= nil do
print(b.number, b.name, #b)
b = b:next()
end
vim.beep()
EOF
endfunction
==============================================================================
4. Window userdata *lua-window*
Window objects represent vim windows. A window userdata "w" has the following
properties and methods:
Properties
o "w()" sets "w" as the current window.
o "w.buffer" contains the buffer of window "w" (read-only).
o "w.line" represents the cursor line position in window "w".
o "w.col" represents the cursor column position in window "w".
o "w.width" represents the width of window "w".
o "w.height" represents the height of window "w".
Methods
o "w:next()" returns the window next to "w".
o "w:previous()" returns the window previous to "w".
o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to
a "real" (not freed from memory) Vim window.
Examples:
:lua w = vim.window() -- current window
:lua print(w.buffer.name, w.line, w.col)
:lua w.width = w.width + math.random(10)
:lua w.height = 2 * math.random() * w.height
:lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end
:lua print("There are " .. n .. " windows")
==============================================================================
top - main help file
*builtin-terms* *builtin_terms*
Which builtin terminals are available depends on a few defines in feature.h,
which need to be set at compile time:
define output of ":version" terminals builtin
NO_BUILTIN_TCAPS -builtin_terms none
SOME_BUILTIN_TCAPS +builtin_terms most common ones (default)
ALL_BUILTIN_TCAPS ++builtin_terms all available
You can see a list of available builtin terminals with ":set term=xxx" (when
not running the GUI). Also see |+builtin_terms|.
If the termcap code is included Vim will try to get the strings for the
terminal you are using from the termcap file and the builtin termcaps. Both
are always used, if an entry for the terminal you are using is present. Which
one is used first depends on the 'ttybuiltin' option:
*raw-terminal-mode*
For normal editing the terminal will be put into "raw" mode. The strings
defined with 't_ti' and 't_ks' will be sent to the terminal. Normally this
puts the terminal in a state where the termcap codes are valid and activates
the cursor and function keys. When Vim exits the terminal will be put back
into the mode it was before Vim started. The strings defined with 't_te' and
't_ke' will be sent to the terminal. On the Amiga, with commands that execute
an external command (e.g., "!!"), the terminal will be put into Normal mode
for a moment. This means that you can stop the output to the screen by
hitting a printing key. Output resumes when you hit <BS>.
*cs7-problem*
Note: If the terminal settings are changed after running Vim, you might have
an illegal combination of settings. This has been reported on Solaris 2.5
with "stty cs8 parenb", which is restored as "stty cs7 parenb". Use
"stty cs8 -parenb -istrip" instead, this is restored correctly.
Some termcap entries are wrong in the sense that after sending 't_ks' the
cursor keys send codes different from the codes defined in the termcap. To
avoid this you can set 't_ks' (and 't_ke') to empty strings. This must be
done during initialization (see |initialization|), otherwise it's too late.
Some termcap entries assume that the highest bit is always reset. For
example: The cursor-up entry for the Amiga could be ":ku=\E[A:". But the
Amiga really sends "\233A". This works fine if the highest bit is reset,
e.g., when using an Amiga over a serial line. If the cursor keys don't work,
try the entry ":ku=\233A:".
Some termcap entries have the entry ":ku=\E[A:". But the Amiga really sends
"\233A". On output "\E[" and "\233" are often equivalent, on input they
aren't. You will have to change the termcap entry, or change the key code with
the :set command to fix this.
Many cursor key codes start with an <Esc>. Vim must find out if this is a
single hit of the <Esc> key or the start of a cursor key sequence. It waits
for a next character to arrive. If it does not arrive within one second a
single <Esc> is assumed. On very slow systems this may fail, causing cursor
keys not to work sometimes. If you discover this problem reset the 'timeout'
option. Vim will wait for the next character to arrive after an <Esc>. If
you want to enter a single <Esc> you must type it twice. Resetting the
'esckeys' option avoids this problem in Insert mode, but you lose the
possibility to use cursor and function keys in Insert mode.
On the Amiga the recognition of window resizing is activated only when the
terminal name is "amiga" or "builtin_amiga".
Some terminals have confusing codes for the cursor keys. The televideo 925 is
such a terminal. It sends a CTRL-H for cursor-left. This would make it
impossible to distinguish a backspace and cursor-left. To avoid this problem
CTRL-H is never recognized as cursor-left.
*vt100-cursor-keys* *xterm-cursor-keys*
Other terminals (e.g., vt100 and xterm) have cursor keys that send <Esc>OA,
<Esc>OB, etc. Unfortunately these are valid commands in insert mode: Stop
insert, Open a new line above the new one, start inserting 'A', 'B', etc.
Instead of performing these commands Vim will erroneously recognize this typed
key sequence as a cursor key movement. To avoid this and make Vim do what you
want in either case you could use these settings:
:set notimeout " don't timeout on mappings
:set ttimeout " do timeout on terminal key codes
:set timeoutlen=100 " timeout after 100 msec
This requires the key-codes to be sent within 100 msec in order to recognize
them as a cursor key. When you type you normally are not that fast, so they
are recognized as individual typed commands, even though Vim receives the same
sequence of bytes.
*vt100-function-keys* *xterm-function-keys*
An xterm can send function keys F1 to F4 in two modes: vt100 compatible or
not. Because Vim may not know what the xterm is sending, both types of keys
are recognized. The same happens for the <Home> and <End> keys.
normal vt100
<F1> t_k1 <Esc>[11~ <xF1> <Esc>OP *<xF1>-xterm*
<F2> t_k2 <Esc>[12~ <xF2> <Esc>OQ *<xF2>-xterm*
<F3> t_k3 <Esc>[13~ <xF3> <Esc>OR *<xF3>-xterm*
<F4> t_k4 <Esc>[14~ <xF4> <Esc>OS *<xF4>-xterm*
<Home> t_kh <Esc>[7~ <xHome> <Esc>OH *<xHome>-xterm*
<End> t_@7 <Esc>[4~ <xEnd> <Esc>OF *<xEnd>-xterm*
When Vim starts, <xF1> is mapped to <F1>, <xF2> to <F2> etc. This means that
by default both codes do the same thing. If you make a mapping for <xF2>,
because your terminal does have two keys, the default mapping is overwritten,
thus you can use the <F2> and <xF2> keys for something different.
*xterm-shifted-keys*
Newer versions of xterm support shifted function keys and special keys. Vim
recognizes most of them. Use ":set termcap" to check which are supported and
what the codes are. Mostly these are not in a termcap, they are only
supported by the builtin_xterm termcap.
*xterm-modifier-keys*
Newer versions of xterm support Alt and Ctrl for most function keys. To avoid
having to add all combinations of Alt, Ctrl and Shift for every key a special
sequence is recognized at the end of a termcap entry: ";*X". The "X" can be
any character, often '~' is used. The ";*" stands for an optional modifier
argument. ";2" is Shift, ";3" is Alt, ";5" is Ctrl and ";9" is Meta (when
it's different from Alt). They can be combined. Examples:
:set <F8>=^[[19;*~
:set <Home>=^[[1;*H
Another speciality about these codes is that they are not overwritten by
another code. That is to avoid that the codes obtained from xterm directly
|t_RV| overwrite them.
*xterm-scroll-region*
The default termcap entry for xterm on Sun and other platforms does not
contain the entry for scroll regions. Add ":cs=\E[%i%d;%dr:" to the xterm
entry in /etc/termcap and everything should work.
*xterm-end-home-keys*
On some systems (at least on FreeBSD with XFree86 3.1.2) the codes that the
<End> and <Home> keys send contain a <Nul> character. To make these keys send
the proper key code, add these lines to your ~/.Xdefaults file:
*VT100.Translations: #override \n\
<Key>Home: string("0x1b") string("[7~") \n\
<Key>End: string("0x1b") string("[8~")
*xterm-8bit* *xterm-8-bit*
Xterm can be run in a mode where it uses 8-bit escape sequences. The CSI code
is used instead of <Esc>[. The advantage is that an <Esc> can quickly be
recognized in Insert mode, because it can't be confused with the start of a
special key.
For the builtin termcap entries, Vim checks if the 'term' option contains
"8bit" anywhere. It then uses 8-bit characters for the termcap entries, the
mouse and a few other things. You would normally set $TERM in your shell to
"xterm-8bit" and Vim picks this up and adjusts to the 8-bit setting
automatically.
When Vim receives a response to the |t_RV| (request version) sequence and it
starts with CSI, it assumes that the terminal is in 8-bit mode and will
convert all key sequences to their 8-bit variants.
==============================================================================
2. Terminal options *terminal-options* *termcap-options* *E436*
The terminal options can be set just like normal options. But they are not
shown with the ":set all" command. Instead use ":set termcap"
It is always possible to change individual strings by setting the
appropriate option. For example:
:set t_ce=^V^[[K (CTRL-V, <Esc>, [, K)
{Vi: no terminal options. You have to exit Vi, edit the termcap entry and
try again}
The options are listed below. The associated termcap code is always equal to
the last two characters of the option name. Only one termcap code is
required: Cursor motion, 't_cm'.
The options 't_da', 't_db', 't_ms', 't_xs' represent flags in the termcap.
When the termcap flag is present, the option will be set to "y". But any
non-empty string means that the flag is set. An empty string means that the
flag is not set. 't_CS' works like this too, but it isn't a termcap flag.
OUTPUT CODES
option meaning
<S-F3>
<S-xF3> alternate <S-F3> *<S-xF3>*
<S-F4> shifted function key 4 *<S-F4>*
<S-xF4> alternate <S-F4> *<S-xF4>*
<S-F5> shifted function key 5 *<S-F5>*
<S-F6> shifted function key 6 *<S-F6>*
<S-F7> shifted function key 7 *<S-F7>*
<S-F8> shifted function key 8 *<S-F8>*
<S-F9> shifted function key 9 *<S-F9>*
<S-F10> shifted function key 10 *<S-F10>*
<S-F11> shifted function key 11 *<S-F11>*
<S-F12> shifted function key 12 *<S-F12>*
t_%1 <Help> help key *t_%1* *'t_%1'*
t_&8 <Undo> undo key *t_&8* *'t_&8'*
t_kI <Insert> insert key *t_kI* *'t_kI'*
t_kD <Del> delete key *t_kD* *'t_kD'*
t_kb <BS> backspace key *t_kb* *'t_kb'*
t_kB <S-Tab> back-tab (shift-tab) *<S-Tab>* *t_kB* *'t_kB'*
t_kh <Home> home key *t_kh* *'t_kh'*
t_#2 <S-Home> shifted home key *<S-Home>* *t_#2* *'t_#2'*
<xHome> alternate home key *<xHome>*
t_@7 <End> end key *t_@7* *'t_@7'*
t_*7 <S-End> shifted end key *<S-End>* *t_star7* *'t_star7'*
<xEnd> alternate end key *<xEnd>*
t_kP <PageUp> page-up key *t_kP* *'t_kP'*
t_kN <PageDown> page-down key *t_kN* *'t_kN'*
t_K1 <kHome> keypad home key *t_K1* *'t_K1'*
t_K4 <kEnd> keypad end key *t_K4* *'t_K4'*
t_K3 <kPageUp> keypad page-up key *t_K3* *'t_K3'*
t_K5 <kPageDown> keypad page-down key *t_K5* *'t_K5'*
t_K6 <kPlus> keypad plus key *<kPlus>* *t_K6* *'t_K6'*
t_K7 <kMinus> keypad minus key *<kMinus>* *t_K7* *'t_K7'*
t_K8 <kDivide> keypad divide *<kDivide>* *t_K8* *'t_K8'*
t_K9 <kMultiply> keypad multiply *<kMultiply>* *t_K9* *'t_K9'*
t_KA <kEnter> keypad enter key *<kEnter>* *t_KA* *'t_KA'*
t_KB <kPoint> keypad decimal point *<kPoint>* *t_KB* *'t_KB'*
t_KC <k0> keypad 0 *<k0>* *t_KC* *'t_KC'*
t_KD <k1> keypad 1 *<k1>* *t_KD* *'t_KD'*
t_KE <k2> keypad 2 *<k2>* *t_KE* *'t_KE'*
*keypad-comma*
The keypad keys, when they are not mapped, behave like the equivalent normal
key. There is one exception: if you have a comma on the keypad instead of a
decimal point, Vim will use a dot anyway. Use these mappings to fix that:
:noremap <kPoint> ,
:noremap! <kPoint> ,
*xterm-codes*
There is a special trick to obtain the key codes which currently only works
for xterm. When |t_RV| is defined and a response is received which indicates
an xterm with patchlevel 141 or higher, Vim uses special escape sequences to
request the key codes directly from the xterm. The responses are used to
adjust the various t_ codes. This avoids the problem that the xterm can
produce different codes, depending on the mode it is in (8-bit, VT102,
VT220, etc.). The result is that codes like <xF1> are no longer needed.
Note: This is only done on startup. If the xterm options are changed after
Vim has started, the escape sequences may not be recognized any more.
*xterm-resize*
Window resizing with xterm only works if the allowWindowOps resource is
enabled. On some systems and versions of xterm it's disabled by default
because someone thought it would be a security issue. It's not clear if this
is actually the case.
To overrule the default, put this line in your ~/.Xdefaults or
~/.Xresources:
XTerm*allowWindowOps: true
And run "xrdb -merge .Xresources" to make it effective. You can check the
value with the context menu (right mouse button while CTRL key is pressed),
there should be a tick at allow-window-ops.
*termcap-colors*
Note about colors: The 't_Co' option tells Vim the number of colors available.
When it is non-zero, the 't_AB' and 't_AF' options are used to set the color.
If one of these is not available, 't_Sb' and 't_Sf' are used. 't_me' is used
to reset to the default colors.
*termcap-cursor-shape* *termcap-cursor-color*
When Vim enters Insert mode the 't_SI' escape sequence is sent. When leaving
Insert mode 't_EI' is used. But only if both are defined. This can be used
to change the shape or color of the cursor in Insert mode. These are not
standard termcap/terminfo entries, you need to set them yourself.
Example for an xterm, this changes the color of the cursor:
if &term =~ "xterm"
let &t_SI = "\<Esc>]12;purple\x7"
let &t_EI = "\<Esc>]12;blue\x7"
endif
NOTE: When Vim exits the shape for Normal mode will remain. The shape from
before Vim started will not be restored.
{not available when compiled without the |+cursorshape| feature}
*termcap-title*
The 't_ts' and 't_fs' options are used to set the window title if the terminal
allows title setting via sending strings. They are sent before and after the
title string, respectively. Similar 't_IS' and 't_IE' are used to set the
icon text. These are Vim-internal extensions of the Unix termcap, so they
cannot be obtained from an external termcap. However, the builtin termcap
contains suitable entries for xterm and iris-ansi, so you don't need to set
them here.
*hpterm*
If inversion or other highlighting does not work correctly, try setting the
't_xs' option to a non-empty string. This makes the 't_ce' code be used to
remove highlighting from a line. This is required for "hpterm". Setting the
'weirdinvert' option has the same effect as making 't_xs' non-empty, and vice
versa.
*scroll-region*
Some termcaps do not include an entry for 'cs' (scroll region), although the
terminal does support it. For example: xterm on a Sun. You can use the
builtin_xterm or define t_cs yourself. For example:
:set t_cs=^V^[[%i%d;%dr
Where ^V is CTRL-V and ^[ is <Esc>.
The vertical scroll region t_CV is not a standard termcap code. Vim uses it
internally in the GUI. But it can also be defined for a terminal, if you can
find one that supports it. The two arguments are the left and right column of
the region which to restrict the scrolling to. Just like t_cs defines the top
and bottom lines. Defining t_CV will make scrolling in vertically split
windows a lot faster. Don't set t_CV when t_da or t_db is set (text isn't
cleared when scrolling).
Unfortunately it is not possible to deduce from the termcap how cursor
positioning should be done when using a scrolling region: Relative to the
beginning of the screen or relative to the beginning of the scrolling region.
Most terminals use the first method. A known exception is the MS-DOS console
(pcterm). The 't_CS' option should be set to any string when cursor
positioning is relative to the start of the scrolling region. It should be
set to an empty string otherwise. It defaults to "yes" when 'term' is
"pcterm".
Note for xterm users: The shifted cursor keys normally don't work. You can
make them work with the xmodmap command and some mappings in Vim.
Give these commands in the xterm:
xmodmap -e "keysym Up = Up F13"
xmodmap -e "keysym Down = Down F16"
xmodmap -e "keysym Left = Left F18"
xmodmap -e "keysym Right = Right F19"
And use these mappings in Vim:
:map <t_F3> <S-Up>
:map! <t_F3> <S-Up>
:map <t_F6> <S-Down>
:map! <t_F6> <S-Down>
:map <t_F8> <S-Left>
:map! <t_F8> <S-Left>
:map <t_F9> <S-Right>
:map! <t_F9> <S-Right>
Instead of, say, <S-Up> you can use any other command that you want to use the
shift-cursor-up key for. (Note: To help people that have a Sun keyboard with
left side keys F14 is not used because it is confused with the undo key; F15
is not used, because it does a window-to-front; F17 is not used, because it
closes the window. On other systems you can probably use them.)
==============================================================================
3. Window size *window-size*
[This is about the size of the whole window Vim is using, not a window that is
created with the ":split" command.]
If you are running Vim on an Amiga and the terminal name is "amiga" or
"builtin_amiga", the amiga-specific window resizing will be enabled. On Unix
systems three methods are tried to get the window size:
- an ioctl call (TIOCGSIZE or TIOCGWINSZ, depends on your system)
- the environment variables "LINES" and "COLUMNS"
*xterm-clipboard*
In the Athena and Motif GUI versions, when running in a terminal and there is
access to the X-server (DISPLAY is set), the copy and paste will behave like
in the GUI. If not, the middle mouse button will insert the unnamed register.
In that case, here is how you copy and paste a piece of text:
Copy/paste with the mouse and Visual mode ('mouse' option must be set, see
above):
1. Press left mouse button on first letter of text, move mouse pointer to last
letter of the text and release the button. This will start Visual mode and
highlight the selected area.
2. Press "y" to yank the Visual text in the unnamed register.
3. Click the left mouse button at the insert position.
4. Click the middle mouse button.
Shortcut: If the insert position is on the screen at the same time as the
Visual text, you can do 2, 3 and 4 all in one: Click the middle mouse button
at the insert position.
Note: When the |-X| command line argument is used, Vim will not connect to the
X server and copy/paste to the X clipboard (selection) will not work. Use the
shift key with the mouse buttons to let the xterm do the selection.
*xterm-command-server*
When the X-server clipboard is available, the command server described in
|x11-clientserver| can be enabled with the --servername command line argument.
*xterm-copy-paste*
NOTE: In some (older) xterms, it's not possible to move the cursor past column
95. This is an xterm problem, not Vim's. Get a newer xterm |color-xterm|.
Now the limit is 223 columns.
Copy/paste in xterm with (current mode NOT included in 'mouse'):
1. Press left mouse button on first letter of text, move mouse pointer to last
letter of the text and release the button.
2. Use normal Vim commands to put the cursor at the insert position.
3. Press "a" to start Insert mode.
4. Click the middle mouse button.
5. Press ESC to end Insert mode.
(The same can be done with anything in 'mouse' if you keep the shift key
pressed while using the mouse.)
Note: if you lose the 8th bit when pasting (special characters are translated
into other characters), you may have to do "stty cs8 -istrip -parenb" in your
shell before starting Vim.
Thus in an xterm the shift and ctrl keys cannot be used with the mouse. Mouse
commands requiring the CTRL modifier can be simulated by typing the "g" key
before using the mouse:
"g<LeftMouse>" is "<C-LeftMouse> (jump to tag under mouse click)
"g<RightMouse>" is "<C-RightMouse> ("CTRL-T")
*mouse-mode-table* *mouse-overview*
A short overview of what the mouse buttons do, when 'mousemodel' is "extend":
Normal Mode:
event position selection change action
cursor window
<LeftMouse> yes end yes
<C-LeftMouse> yes end yes "CTRL-]" (2)
<S-LeftMouse> yes no change yes "*" (2) *<S-LeftMouse>*
<LeftDrag> yes start or extend (1) no *<LeftDrag>*
<LeftRelease> yes start or extend (1) no
<MiddleMouse> yes if not active no put
<MiddleMouse> yes if active no yank and put
<RightMouse> yes start or extend yes
<A-RightMouse> yes start or extend blockw. yes *<A-RightMouse>*
<S-RightMouse> yes no change yes "#" (2) *<S-RightMouse>*
<C-RightMouse> no no change no "CTRL-T"
<RightDrag> yes extend no *<RightDrag>*
<RightRelease> yes extend no *<RightRelease>*
Insert or Replace Mode:
event position selection change action
cursor window
<LeftMouse> yes (cannot be active) yes
<C-LeftMouse> yes (cannot be active) yes "CTRL-O^]" (2)
<S-LeftMouse> yes (cannot be active) yes "CTRL-O*" (2)
<LeftDrag> yes start or extend (1) no like CTRL-O (1)
<LeftRelease> yes start or extend (1) no like CTRL-O (1)
<MiddleMouse> no (cannot be active) no put register
<RightMouse> yes start or extend yes like CTRL-O
<A-RightMouse> yes start or extend blockw. yes
<S-RightMouse> yes (cannot be active) yes "CTRL-O#" (2)
<C-RightMouse> no (cannot be active) no "CTRL-O CTRL-T"
In a help window:
event position selection change action
cursor window
<2-LeftMouse> yes (cannot be active) no "^]" (jump to help tag)
When 'mousemodel' is "popup", these are different:
Normal Mode:
event position selection change action
cursor window
<S-LeftMouse> yes start or extend (1) no
<A-LeftMouse> yes start or extend blockw. no *<A-LeftMouse>*
<RightMouse> no popup menu no
Insert or Replace Mode:
event position selection change action
cursor window
<S-LeftMouse> yes start or extend (1) no like CTRL-O (1)
<A-LeftMouse> yes start or extend blockw. no
<RightMouse> no popup menu no
(1) only if mouse pointer moved since press
(2) only if click is in same buffer
Clicking the left mouse button causes the cursor to be positioned. If the
click is in another window that window is made the active window. When
editing the command-line the cursor can only be positioned on the
command-line. When in Insert mode Vim remains in Insert mode. If 'scrolloff'
is set, and the cursor is positioned within 'scrolloff' lines from the window
border, the text is scrolled.
A selection can be started by pressing the left mouse button on the first
character, moving the mouse to the last character, then releasing the mouse
button. You will not always see the selection until you release the button,
only in some versions (GUI, MS-DOS, WIN32) will the dragging be shown
immediately. Note that you can make the text scroll by moving the mouse at
least one character in the first/last line in the window when 'scrolloff' is
non-zero.
In Normal, Visual and Select mode clicking the right mouse button causes the
Visual area to be extended. When 'mousemodel' is "popup", the left button has
to be used while keeping the shift key pressed. When clicking in a window
which is editing another buffer, the Visual or Select mode is stopped.
In Normal, Visual and Select mode clicking the right mouse button with the alt
key pressed causes the Visual area to become blockwise. When 'mousemodel' is
"popup" the left button has to be used with the alt key. Note that this won't
work on systems where the window manager consumes the mouse events when the
alt key is pressed (it may move the window).
*double-click*
Double, triple and quadruple clicks are supported when the GUI is active,
for MS-DOS and Win32, and for an xterm (if the gettimeofday() function is
available). For selecting text, extra clicks extend the selection:
click select
double word or % match *<2-LeftMouse>*
triple line *<3-LeftMouse>*
quadruple rectangular block *<4-LeftMouse>*
Exception: In a Help window a double click jumps to help for the word that is
clicked on.
A double click on a word selects that word. 'iskeyword' is used to specify
which characters are included in a word. A double click on a character
that has a match selects until that match (like using "v%"). If the match is
an #if/#else/#endif block, the selection becomes linewise.
For MS-DOS and xterm the time for double clicking can be set with the
'mousetime' option. For the other systems this time is defined outside of
Vim.
An example, for using a double click to jump to the tag under the cursor:
:map <2-LeftMouse> :exe "tag ". expand("<cword>")<CR>
Dragging the mouse with a double click (button-down, button-up, button-down
and then drag) will result in whole words to be selected. This continues
until the button is released, at which point the selection is per character
again.
*gpm-mouse*
The GPM mouse is only supported when the |+mouse_gpm| feature was enabled at
compile time. The GPM mouse driver (Linux console) does not support quadruple
clicks.
In Insert mode, when a selection is started, Vim goes into Normal mode
temporarily. When Visual or Select mode ends, it returns to Insert mode.
This is like using CTRL-O in Insert mode. Select mode is used when the
'selectmode' option contains "mouse".
*sysmouse*
The sysmouse is only supported when the |+mouse_sysmouse| feature was enabled
at compile time. The sysmouse driver (*BSD console) does not support keyboard
modifiers.
*drag-status-line*
When working with several windows, the size of the windows can be changed by
dragging the status line with the mouse. Point the mouse at a status line,
press the left button, move the mouse to the new position of the status line,
release the button. Just clicking the mouse in a status line makes that window
the current window, without moving the cursor. If by selecting a window it
will change position or size, the dragging of the status line will look
confusing, but it will work (just try it).
*<MiddleRelease>* *<MiddleDrag>*
Mouse clicks can be mapped. The codes for mouse clicks are:
code mouse button normal action
<LeftMouse> left pressed set cursor position
<LeftDrag> left moved while pressed extend selection
<LeftRelease> left released set selection end
<MiddleMouse> middle pressed paste text at cursor position
<MiddleDrag> middle moved while pressed -
<MiddleRelease> middle released -
<RightMouse> right pressed extend selection
<RightDrag> right moved while pressed extend selection
<RightRelease> right released set selection end
<X1Mouse> X1 button pressed - *X1Mouse*
<X1Drag> X1 moved while pressed - *X1Drag*
<X1Release> X1 button release - *X1Release*
<X2Mouse> X2 button pressed - *X2Mouse*
<X2Drag> X2 moved while pressed - *X2Drag*
<X2Release> X2 button release - *X2Release*
The X1 and X2 buttons refer to the extra buttons found on some mice. The
'Microsoft Explorer' mouse has these buttons available to the right thumb.
Currently X1 and X2 only work on Win32 environments.
Examples:
:noremap <MiddleMouse> <LeftMouse><MiddleMouse>
Paste at the position of the middle mouse button click (otherwise the paste
would be done at the cursor position).
:noremap <LeftRelease> <LeftRelease>y
Immediately yank the selection, when using Visual mode.
Note the use of ":noremap" instead of "map" to avoid a recursive mapping.
:map <X1Mouse> <C-O>
:map <X2Mouse> <C-I>
Map the X1 and X2 buttons to go forwards and backwards in the jump list, see
|CTRL-O| and |CTRL-I|.
*mouse-swap-buttons*
To swap the meaning of the left and right mouse buttons:
:noremap <LeftMouse> <RightMouse>
:noremap <LeftDrag> <RightDrag>
:noremap <LeftRelease> <RightRelease>
:noremap <RightMouse> <LeftMouse>
:noremap <RightDrag> <LeftDrag>
:noremap <RightRelease> <LeftRelease>
:noremap g<LeftMouse> <C-RightMouse>
:noremap g<RightMouse> <C-LeftMouse>
:noremap! <LeftMouse> <RightMouse>
:noremap! <LeftDrag> <RightDrag>
:noremap! <LeftRelease> <RightRelease>
:noremap! <RightMouse> <LeftMouse>
:noremap! <RightDrag> <LeftDrag>
:noremap! <RightRelease> <LeftRelease>
top - main help file
*:mzscheme* *:mz*
:[range]mz[scheme] {stmt}
Execute MzScheme statement {stmt}. {not in Vi}
:[range]mz[scheme] << {endmarker}
{script}
{endmarker}
Execute inlined MzScheme script {script}.
Note: This command doesn't work if the MzScheme
feature wasn't compiled in. To avoid errors, see
|script-here|.
*:mzfile* *:mzf*
:[range]mzf[ile] {file} Execute the MzScheme script in {file}. {not in Vi}
All of these commands do essentially the same thing - they execute a piece of
MzScheme code, with the "current range" set to the given line
range.
In the case of :mzscheme, the code to execute is in the command-line.
In the case of :mzfile, the code to execute is the contents of the given file.
MzScheme interface defines exception exn:vim, derived from exn.
It is raised for various Vim errors.
During compilation, the MzScheme interface will remember the current MzScheme
collection path. If you want to specify additional paths use the
'current-library-collection-paths' parameter. E.g., to cons the user-local
*mzscheme-sandbox*
When executed in the |sandbox|, access to some filesystem and Vim interface
procedures is restricted.
==============================================================================
2. Examples *mzscheme-examples*
:mzscheme (display "Hello")
:mz (display (string-append "Using MzScheme version " (version)))
:mzscheme (require (prefix vim- vimext)) ; for MzScheme < 4.x
:mzscheme (require (prefix-in vim- 'vimext)) ; MzScheme 4.x
:mzscheme (vim-set-buff-line 10 "This is line #10")
Inline script usage:
function! <SID>SetFirstLine()
:mz << EOF
(display "!!!")
(require (prefix vim- vimext))
; for newer versions (require (prefix-in vim- 'vimext))
(vim-set-buff-line 1 "This is line #1")
(vim-beep)
EOF
endfunction
nmap <F9> :call <SID>SetFirstLine() <CR>
File execution:
:mzfile supascript.scm
Vim exception handling:
:mz << EOF
(require (prefix vim- vimext))
; for newer versions (require (prefix-in vim- 'vimext))
(with-handlers
([exn:vim? (lambda (e) (display (exn-message e)))])
(vim-eval "nonsense-string"))
EOF
Auto-instantiation of vimext module (can be placed in your |vimrc|):
function! MzRequire()
:redir => l:mzversion
:mz (version)
:redir END
if strpart(l:mzversion, 1, 1) < "4"
" MzScheme versions < 4.x:
:mz (require (prefix vim- vimext))
else
" newer versions:
:mz (require (prefix-in vim- 'vimext))
endif
endfunction
if has("mzscheme")
silent call MzRequire()
endif
==============================================================================
3. Threads *mzscheme-threads*
The MzScheme interface supports threads. They are independent from OS threads,
thus scheduling is required. The option 'mzquantum' determines how often
Vim should poll for available MzScheme threads.
NOTE
Thread scheduling in the console version of Vim is less reliable than in the
GUI version.
==============================================================================
4. Vim access from MzScheme *mzscheme-vim*
*mzscheme-vimext*
The 'vimext' module provides access to procedures defined in the MzScheme
interface.
Common
(command {command-string}) Perform the vim ":Ex" style command.
(eval {expr-string}) Evaluate the vim expression into
respective MzScheme object: |Lists| are
represented as Scheme lists,
|Dictionaries| as hash tables.
NOTE the name clashes with MzScheme eval
(range-start) Start/End of the range passed with
(range-end) the Scheme command.
(beep) beep
(get-option {option-name} [buffer-or-window]) Get Vim option value (either
local or global, see set-option).
(set-option {string} [buffer-or-window])
Set a Vim option. String must have option
setting form (like optname=optval, or
optname+=optval, etc.) When called with
{buffer} or {window} the local option will
be set. The symbol 'global can be passed
as {buffer-or-window}. Then |:setglobal|
will be used.
Buffers *mzscheme-buffer*
(buff? {object}) Is object a buffer?
(buff-valid? {object}) Is object a valid buffer? (i.e.
corresponds to the real Vim buffer)
(get-buff-line {linenr} [buffer])
Get line from a buffer.
(set-buff-line {linenr} {string} [buffer])
Set a line in a buffer. If {string} is #f,
the line gets deleted. The [buffer]
argument is optional. If omitted, the
current buffer will be used.
(get-buff-line-list {start} {end} [buffer])
Get a list of lines in a buffer. {Start}
and {end} are 1-based and inclusive.
(set-buff-line-list {start} {end} {string-list} [buffer])
Set a list of lines in a buffer. If
string-list is #f or null, the lines get
deleted. If a list is shorter than
{end}-{start} the remaining lines will
be deleted.
(get-buff-name [buffer]) Get a buffer's text name.
(get-buff-num [buffer]) Get a buffer's number.
(get-buff-size [buffer]) Get buffer line count.
(insert-buff-line-list {linenr} {string/string-list} [buffer])
Insert a list of lines into a buffer after
{linenr}. If {linenr} is 0, lines will be
inserted at start.
(curr-buff) Get the current buffer. Use other MzScheme
interface procedures to change it.
(buff-count) Get count of total buffers in the editor.
(get-next-buff [buffer]) Get next buffer.
(get-prev-buff [buffer]) Get previous buffer. Return #f when there
are no more buffers.
(open-buff {filename}) Open a new buffer (for file "name")
(get-buff-by-name {buffername}) Get a buffer by its filename or #f
if there is no such buffer.
(get-buff-by-num {buffernum}) Get a buffer by its number (return #f if
there is no buffer with this number).
Windows *mzscheme-window*
(win? {object}) Is object a window?
(win-valid? {object}) Is object a valid window (i.e. corresponds
to the real Vim window)?
(curr-win) Get the current window.
(win-count) Get count of windows.
(get-win-num [window]) Get window number.
(get-win-by-num {windownum}) Get window by its number.
(get-win-buffer [window]) Get the buffer for a given window.
(get-win-height [window])
(set-win-height {height} [window]) Get/Set height of window.
(get-win-width [window])
(set-win-width {width} [window])Get/Set width of window.
(get-win-list [buffer]) Get list of windows for a buffer.
(get-cursor [window]) Get cursor position in a window as
a pair (linenr . column).
(set-cursor (line . col) [window]) Set cursor position.
==============================================================================
5. mzeval() Vim function *mzscheme-mzeval*
To facilitate bi-directional interface, you can use |mzeval()| function to
evaluate MzScheme expressions and pass their values to VimL.
==============================================================================
6. Dynamic loading *mzscheme-dynamic* *E815*
On MS-Windows the MzScheme libraries can be loaded dynamically. The |:version|
output then includes |+mzscheme/dyn|.
This means that Vim will search for the MzScheme DLL files only when needed.
When you don't use the MzScheme interface you don't need them, thus you can
use Vim without these DLL files.
To use the MzScheme interface the MzScheme DLLs must be in your search path.
In a console window type "path" to see what directories are used.
The names of the DLLs must match the MzScheme version Vim was compiled with.
For MzScheme version 209 they will be "libmzsch209_000.dll" and
"libmzgc209_000.dll". To know for sure look at the output of the ":version"
command, look for -DDYNAMIC_MZSCH_DLL="something" and
-DDYNAMIC_MZGC_DLL="something" in the "Compilation" info.
vim:tw=78:ts=8:sts=4:ft=help:norl:
top - main help file
In the rest of this help page, we will use the term "Vim Controller" to
describe the program controlling Vim through the NetBeans socket interface.
==============================================================================
3. Configuring Vim for NetBeans *netbeans-configure*
For more help about installing Vim, please read |usr_90.txt| in the Vim User
Manual.
On Unix:
When running configure without arguments the NetBeans interface should be
included. That is, if the configure check to find out if your system supports
the required features succeeds.
In case you do not want the NetBeans interface you can disable it by
uncommenting a line with "--disable-netbeans" in the Makefile.
Currently the NetBeans interface is supported by Vim running in a terminal and
by GVim when it is run with one of the following GUIs: GTK, GNOME, Windows,
Athena and Motif.
If Motif support is required the user must supply XPM libraries. See
|workshop-xpm| for details on obtaining the latest version of XPM.
On MS-Windows:
The Win32 support is now in beta stage.
To use XPM signs on Win32 (e.g. when using with NetBeans) you can compile
XPM by yourself or use precompiled libraries from http://iamphet.nm.ru/misc/
for MS Visual C++ or http://gnuwin32.sourceforge.net for MinGW.
Enable debugging:
To enable debugging of Vim and of the NetBeans protocol, the "NBDEBUG" macro
needs to be defined. Search in the Makefile of the platform you are using for
"NBDEBUG" to see what line needs to be uncommented. This effectively adds
*E463*
Region is guarded, cannot modify
The Vim Controller has defined guarded areas in the text,
which you cannot change. Also sets the current buffer, if
necessary.
*E532*
The defineAnnoType highlighting color name is too long
The maximum length of the "fg" or "bg" color argument in the
defineAnnoType command is 32 characters.
New in version 2.5.
*E656*
Writes of unmodified buffers forbidden
Writes of unmodified buffers that were opened from the
Vim Controller are not possible.
*E657*
Partial writes disallowed
Partial writes for buffers that were opened from the
Vim Controller are not allowed.
*E658*
Connection lost for this buffer
The Vim Controller has become confused about the state of
this file. Rather than risk data corruption, it has severed
the connection for this file. Vim will take over
responsibility for saving changes to this file and the
Vim Controller will no longer know of these changes.
*E744*
Read-only file
Vim normally allows changes to a read-only file and only
enforces the read-only rule if you try to write the file.
However, NetBeans does not let you make changes to a file
which is read-only and becomes confused if Vim does this.
So Vim does not allow modifications to files when run
in NetBeans mode.
==============================================================================
5. Running Vim in NetBeans mode *netbeans-run*
There are two different ways to run Vim in NetBeans mode:
+ an IDE may start Vim with the |-nb| command line argument
+ NetBeans can be started from within Vim with the |:nbstart| command
*netbeans-parameters*
Three forms can be used to setup the NetBeans connection parameters.
When started from the command line, the |-nb| command line argument may be:
-nb={fname} from a file
-nb:{hostname}:{addr}:{password} directly
-nb from a file or environment
When started from within Vim, the |:nbstart| optional argument may be:
={fname} from a file
:{hostname}:{addr}:{password} directly
<MISSING ARGUMENT> from a file or environment
*E660* *E668*
When NetBeans is started from the command line, for security reasons, the best
method is to write the information in a file readable only by the user. The
name of the file can be passed with the "-nb={fname}" argument or, when "-nb"
is used without a parameter, the environment variable "__NETBEANS_CONINFO".
The file must contain these three lines, in any order:
host={hostname}
port={addr}
auth={password}
Other lines are ignored. The Vim Controller is responsible for deleting the
file afterwards.
{hostname} is the name of the machine where Vim Controller is running. When
omitted the environment variable "__NETBEANS_HOST" is used or the default
"localhost".
{addr} is the port number for the NetBeans interface. When omitted the
environment variable "__NETBEANS_SOCKET" is used or the default 3219.
{password} is the password for connecting to NetBeans. When omitted the
environment variable "__NETBEANS_VIM_PASSWORD" is used or "changeme".
Vim will initiate a socket connection (client side) to the specified host and
port upon startup. The password will be sent with the AUTH event when the
connection has been established.
==============================================================================
6. NetBeans protocol *netbeans-protocol*
The communication between the Vim Controller and Vim uses plain text
messages. This protocol was first designed to work with the external editor
module of NetBeans. Later it was extended to work with Agide (A-A-P GUI IDE,
see http://www.a-a-p.org and then with other IDE. The extensions are marked
with "version 2.1".
Version 2.2 of the protocol has several minor changes which should only affect
NetBeans users (ie, not Agide users). However, a bug was fixed which could
cause confusion. The netbeans_saved() function sent a "save" protocol
command. In protocol version 2.1 and earlier this was incorrectly interpreted
as a notification that a write had taken place. In reality, it told NetBeans
to save the file so multiple writes were being done. This caused various
problems and has been fixed in 2.2. To decrease the likelihood of this
confusion happening again, netbeans_saved() has been renamed to
netbeans_save_buffer().
We are now at version 2.5. For the differences between 2.4 and 2.5 search for
"2.5" below.
The messages are currently sent over a socket. Since the messages are in
plain UTF-8 text this protocol could also be used with any other communication
mechanism.
6.1 Kinds of messages |nb-messages|
6.2 Terms |nb-terms|
6.3 Commands |nb-commands|
6.4 Functions and Replies |nb-functions|
6.5 Events |nb-events|
6.6 Special messages |nb-special|
6.7 Protocol errors |nb-protocol_errors|
close Close the buffer. This leaves us without current buffer, very
dangerous to use!
create Creates a buffer without a name. Replaces the current buffer
(it's hidden when it was changed).
The Vim Controller should use this as the first command for a
file that is being opened. The sequence of commands could be:
create
setCaretListener (ignored)
setModified (no effect)
setContentType (ignored)
startDocumentListen
setTitle
setFullName
defineAnnoType typeNum typeName tooltip glyphFile fg bg
Define a type of annotation for this buffer.
Arguments:
typeNum number sequence number (not really used)
typeName string name that identifies this annotation
tooltip string not used
glyphFile string name of icon file
fg color foreground color for line highlighting
bg color background color for line highlighting
Vim will define a sign for the annotation.
When color is a number, this is the "#rrggbb" Red, Green and
Blue values of the color (see |gui-colors|) and the
highlighting is only defined for GVim.
When color is a name, this color is defined both for Vim
running in a color terminal and for GVim.
When both "fg" and "bg" are "none" no line highlighting is
used (new in version 2.1).
When "glyphFile" is empty, no text sign is used (new in
version 2.1).
When "glyphFile" is one or two characters long, a text sign is
defined (new in version 2.1).
Note: the annotations will be defined in sequence, and the
sequence number is later used with addAnno.
editFile pathname
Set the name for the buffer and edit the file "pathname", a
string argument.
Normal way for the IDE to tell the editor to edit a file.
You must set a bufId different of 0 with this command to
assign a bufId to the buffer. It will trigger an event
fileOpened with a bufId of 0 but the buffer has been assigned.
If the IDE is going to pass the file text to the editor use
these commands instead:
setFullName
insert
initDone
New in version 2.1.
enableBalloonEval
Not implemented.
endAtomic End an atomic operation. The changes between "startAtomic"
and "endAtomic" can be undone as one operation. But it's not
implemented yet. Redraw when necessary.
guard off len
Mark an area in the buffer as guarded. This means it cannot
be edited. "off" and "len" are numbers and specify the text
to be guarded.
initDone Mark the buffer as ready for use. Implicitly makes the buffer
the current buffer. Fires the BufReadPost autocommand event.
insertDone
Sent by Vim Controller to tell Vim an initial file insert is
done. This triggers a read message being printed. Prior to
version 2.3, no read messages were displayed after opening a
file. New in version 2.3.
moveAnnoToFront serNum
Not implemented.
netbeansBuffer isNetbeansBuffer
"len".
Only fired when enabled, see "startDocumentListen".
revert Not implemented.
save The buffer has been saved and is now unmodified.
Only fired when enabled, see "startDocumentListen".
startupDone The editor has finished its startup work and is ready for
editing files.
New in version 2.1.
unmodified The buffer is now unmodified.
Only fired when enabled, see "startDocumentListen".
version vers Report the version of the interface implementation. Vim
reports "2.4" (including the quotes).
==============================================================================
7. NetBeans commands *netbeans-commands*
*:nbclose*
:nbc[lose] Close the current NetBeans session. Remove all placed
signs.
*:nbkey*
:nb[key] {key} Pass the {key} to the Vim Controller for processing
When a hot-key has been installed with the specialKeys command, this command
can be used to generate a hotkey messages to the Vim Controller. The events
newDotAndMark, keyCommand and keyAtPos are generated (in this order).
==============================================================================
8. Known problems *netbeans-problems*
NUL bytes are not possible. For editor -> IDE they will appear as NL
characters. For IDE -> editor they cannot be inserted.
A NetBeans session may be initiated with Vim running in a terminal, and
continued later in a GUI environment after running the |:gui| command. In this
case, the highlighting defined for the NetBeans annotations may be cleared
when the ":gui" command sources .gvimrc and this file loads a colorscheme
that runs the command ":highlight clear".
New in version 2.5.
==============================================================================
9. Debugging NetBeans protocol *netbeans-debugging*
To debug the Vim protocol, you must first compile Vim with debugging support
and NetBeans debugging support. See |netbeans-configure| for instructions
about Vim compiling and how to enable debug support.
When running Vim, set the following environment variables:
export SPRO_GVIM_DEBUG=netbeans.log
export SPRO_GVIM_DLEVEL=0xffffffff
Vim will then log all the incoming and outgoing messages of the NetBeans
protocol to the file netbeans.log .
The content of netbeans.log after a session looks like this:
Tue May 20 17:19:27 2008
EVT: 0:startupDone=0
CMD 1: (1) create
CMD 2: (1) setTitle "testfile1.txt"
CMD 3: (1) setFullName "testfile1.txt"
EVT(suppressed): 1:remove=3 0 -1
EVT: 1:fileOpened=0 "d:\\work\\vimWrapper\\vimWrapper2\\pyvimwrapper\\tests\\testfile1.txt" T F
CMD 4: (1) initDone
FUN 5: (0) getCursor
REP 5: 1 1 0 0
CMD 6: (2) create
CMD 7: (2) setTitle "testfile2.txt"
CMD 8: (2) setFullName "testfile2.txt"
EVT(suppressed): 2:remove=8 0 -1
EVT: 2:fileOpened=0 "d:\\work\\vimWrapper\\vimWrapper2\\pyvimwrapper\\tests\\testfile2.txt" T F
CMD 9: (2) initDone
==============================================================================
10. NetBeans External Editor
NOTE: This information is obsolete! Only relevant if you are using an old
version of NetBeans.
'hardtabs' 'ht'
number of spaces that a <Tab> moves on the display
mesg boolean (default on) *'mesg'*
novice boolean (default off) *'novice'*
open boolean (default on) *'open'*
optimize (op) boolean (default off) *'optimize'* *'op'*
redraw boolean (default off) *'redraw'*
slowopen (slow) boolean (default off) *'slowopen'* *'slow'*
sourceany boolean (default off) *'sourceany'*
w300 number (default 23) *'w300'*
w1200 number (default 23) *'w1200'*
w9600 number (default 23) *'w9600'*
==============================================================================
3. Limits *limits*
Vim has only a few limits for the files that can be edited {Vi: can not handle
<Nul> characters and characters above 128, has limited line length, many other
limits}.
*E340*
Maximum line length On machines with 16-bit ints (Amiga and MS-DOS real
mode): 32767, otherwise 2147483647 characters.
Longer lines are split.
Maximum number of lines 2147483647 lines.
Maximum file size 2147483647 bytes (2 Gbyte) when a long integer is
32 bits. Much more for 64 bit longs. Also limited
by available disk space for the |swap-file|.
*E75*
Length of a file path Unix and Win32: 1024 characters, otherwise 256
characters (or as much as the system supports).
Length of an expanded string option
Unix and Win32: 1024 characters, otherwise 256
characters
Maximum display width Unix and Win32: 1024 characters, otherwise 255
characters
Maximum lhs of a mapping 50 characters.
Number of different highlighting types: over 30000
Range of a Number variable: -2147483648 to 2147483647 (more on 64 bit
systems)
Maximum length of a line in a tags file: 512 bytes.
Information for undo and text in registers is kept in memory, thus when making
(big) changes the amount of (virtual) memory available limits the number of
undo levels and the text that can be kept in registers. Other things are also
kept in memory: Command-line history, error messages for Quickfix mode, etc.
Memory usage limits
The option 'maxmem' ('mm') is used to set the maximum memory used for one
buffer (in kilobytes). 'maxmemtot' is used to set the maximum memory used for
all buffers (in kilobytes). The defaults depend on the system used. For the
Amiga and MS-DOS, 'maxmemtot' is set depending on the amount of memory
available.
These are not hard limits, but tell Vim when to move text into a swap file.
If you don't like Vim to swap to a file, set 'maxmem' and 'maxmemtot' to a
very large value. The swap file will then only be used for recovery. If you
don't want a swap file at all, set 'updatecount' to 0, or use the "-n"
argument when starting Vim.
==============================================================================
4. The most interesting additions *vim-additions*
Vi compatibility. |'compatible'|
Although Vim is 99% Vi compatible, some things in Vi can be
considered to be a bug, or at least need improvement. But still, Vim
what example
- command :e<Tab>
- tag :ta scr<Tab>
- option :set sc<Tab>
- option value :set hf=<Tab>
- file name :e ve<Tab>
- etc.
If there are multiple matches, CTRL-N (next) and CTRL-P (previous)
will walk through the matches. <Tab> works like CTRL-N, but wraps
around to the first match.
The 'wildchar' option can be set to the character for command-line
completion, <Tab> is the default. CTRL-D can be typed after an
(incomplete) wildcard; all matches will be listed. CTRL-A will insert
all matches. CTRL-L will insert the longest common part of the
matches.
Insert-mode completion. |ins-completion|
In Insert mode the CTRL-N and CTRL-P keys can be used to complete a
word that appears elsewhere. |i_CTRL-N|
With CTRL-X another mode is entered, through which completion can be
done for:
|i_CTRL-X_CTRL-F| file names
|i_CTRL-X_CTRL-K| words from 'dictionary' files
|i_CTRL-X_CTRL-T| words from 'thesaurus' files
|i_CTRL-X_CTRL-I| words from included files
|i_CTRL-X_CTRL-L| whole lines
|i_CTRL-X_CTRL-]| words from the tags file
|i_CTRL-X_CTRL-D| definitions or macros
|i_CTRL-X_CTRL-O| Omni completion: clever completion
specifically for a file type
etc.
Long line support. |'wrap'| |'linebreak'|
If the 'wrap' option is off, long lines will not wrap and only part
of them will be shown. When the cursor is moved to a part that is not
shown, the screen will scroll horizontally. The minimum number of
columns to scroll can be set with the 'sidescroll' option. The |zh|
and |zl| commands can be used to scroll sideways.
Alternatively, long lines are broken in between words when the
'linebreak' option is set. This allows editing a single-line
paragraph conveniently (e.g. when the text is later read into a DTP
program). Move the cursor up/down with the |gk| and |gj| commands.
Text formatting. |formatting|
The 'textwidth' option can be used to automatically limit the line
length. This supplements the 'wrapmargin' option of Vi, which was not
very useful. The |gq| operator can be used to format a piece of text
(for example, |gqap| formats the current paragraph). Commands for
text alignment: |:center|, |:left| and |:right|.
Extended search patterns. |pattern|
There are many extra items to match various text items. Examples:
A "\n" can be used in a search pattern to match a line break.
"x\{2,4}" matches "x" 2 to 4 times.
"\s" matches a white space character.
Directory, remote and archive browsing. |netrw|
Vim can browse the file system. Simply edit a directory. Move around
in the list with the usual commands and press <Enter> to go to the
directory or file under the cursor.
This also works for remote files over ftp, http, ssh, etc.
Zip and tar archives can also be browsed. |tar| |zip|
Edit-compile-edit speedup. |quickfix|
The |:make| command can be used to run the compilation and jump to the
first error. A file with compiler error messages is interpreted. Vim
jumps to the first error.
Each line in the error file is scanned for the name of a file, line
number and error message. The 'errorformat' option can be set to a
list of scanf-like strings to handle output from many compilers.
The |:cn| command can be used to jump to the next error.
|:cl| lists all the error messages. Other commands are available.
The 'makeef' option has the name of the file with error messages.
The 'makeprg' option contains the name of the program to be executed
with the |:make| command.
The 'shellpipe' option contains the string to be used to put the
When Vim is started with "-s scriptfile", the characters read from
"scriptfile" are treated as if you typed them. If end of file is reached
before the editor exits, further characters are read from the console.
The "-w" option can be used to record all typed characters in a script file.
This file can then be used to redo the editing, possibly on another file or
after changing some commands in the script file.
The "-o" option opens a window for each argument. "-o4" opens four windows.
Vi requires several termcap entries to be able to work full-screen. Vim only
requires the "cm" entry (cursor motion).
In command mode:
When the 'showcmd' option is set, the command characters are shown in the last
line of the screen. They are removed when the command is finished.
If the 'ruler' option is set, the current cursor position is shown in the
last line of the screen.
"U" still works after having moved off the last changed line and after "u".
Characters with the 8th bit set are displayed. The characters between '~' and
0xa0 are displayed as "~?", "~@", "~A", etc., unless they are included in the
'isprint' option.
"][" goes to the next ending of a C function ('}' in column 1).
"[]" goes to the previous ending of a C function ('}' in column 1).
"]f", "[f" and "gf" start editing the file whose name is under the cursor.
CTRL-W f splits the window and starts editing the file whose name is under
the cursor.
"*" searches forward for the identifier under the cursor, "#" backward.
"K" runs the program defined by the 'keywordprg' option, with the identifier
under the cursor as argument.
"%" can be preceded with a count. The cursor jumps to the line that
percentage down in the file. The normal "%" function to jump to the matching
brace skips braces inside quotes.
With the CTRL-] command, the cursor may be in the middle of the identifier.
The used tags are remembered. Commands that can be used with the tag stack
are CTRL-T, ":pop" and ":tag". ":tags" lists the tag stack.
The 'tags' option can be set to a list of tag file names. Thus multiple
tag files can be used. For file names that start with "./", the "./" is
replaced with the path of the current file. This makes it possible to use a
tags file in the same directory as the file being edited.
Previously used file names are remembered in the alternate file name list.
CTRL-^ accepts a count, which is an index in this list.
":files" command shows the list of alternate file names.
"#<N>" is replaced with the <N>th alternate file name in the list.
"#<" is replaced with the current file name without extension.
Search patterns have more features. The <NL> character is seen as part of the
search pattern and the substitute string of ":s". Vi sees it as the end of
the command.
Searches can put the cursor on the end of a match and may include a character
offset.
Count added to "~", ":next", ":Next", "n" and "N".
The command ":next!" with 'autowrite' set does not write the file. In vi the
file was written, but this is considered to be a bug, because one does not
expect it and the file is not written with ":rewind!".
In Vi when entering a <CR> in replace mode deletes a character only when 'ai'
is set (but does not show it until you hit <Esc>). Vim always deletes a
character (and shows it immediately).
Added :wnext command. Same as ":write" followed by ":next".
The ":w!" command always writes, also when the file is write protected. In Vi
you would have to do ":!chmod +w %" and ":set noro"
When 'tildeop' has been set, "~" is an operator (must be followed by a
movement command).
With the "J" (join) command you can reset the 'joinspaces' option to have only
one space after a period (Vi inserts two spaces).
"cw" can be used to change white space formed by several characters (Vi is
confusing: "cw" only changes one space, while "dw" deletes all white space).
"o" and "O" accept a count for repeating the insert (Vi clears a part of
display).
Flags after Ex commands not supported (no plans to include it).
On non-UNIX systems ":cd" command shows current directory instead of going to
the home directory (there isn't one). ":pwd" prints the current directory on
all systems.
After a ":cd" command the file names (in the argument list, opened files)
still point to the same files. In Vi ":cd" is not allowed in a changed file;
otherwise the meaning of file names change.
":source!" command reads Vi commands from a file.
":mkexrc" command writes current modified options and mappings to a ".exrc"
file. ":mkvimrc" writes to a ".vimrc" file.
No check for "tail recursion" with mappings. This allows things like
":map! foo ^]foo".
When a mapping starts with number, vi loses the count typed before it (e.g.
when using the mapping ":map g 4G" the command "7g" goes to line 4). This is
considered a vi bug. Vim concatenates the counts (in the example it becomes
"74G"), as most people would expect.
The :put! command inserts the contents of a register above the current line.
The "p" and "P" commands of vi cannot be repeated with "." when the putted
text is less than a line. In Vim they can always be repeated.
":noremap" command can be used to enter a mapping that will not be remapped.
This is useful to exchange the meaning of two keys. ":cmap", ":cunmap" and
":cnoremap" can be used for mapping in command-line editing only. ":imap",
":iunmap" and ":inoremap" can be used for mapping in insert mode only.
Similar commands exist for abbreviations: ":noreabbrev", ":iabbrev"
":cabbrev", ":iunabbrev", ":cunabbrev", ":inoreabbrev", ":cnoreabbrev".
In Vi the command ":map foo bar" would remove a previous mapping
":map bug foo". This is considered a bug, so it is not included in Vim.
":unmap! foo" does remove ":map! bug foo", because unmapping would be very
difficult otherwise (this is vi compatible).
The ':' register contains the last command-line.
The '%' register contains the current file name.
The '.' register contains the last inserted text.
":dis" command shows the contents of the yank registers.
CTRL-O/CTRL-I can be used to jump to older/newer positions. These are the
same positions as used with the '' command, but may be in another file. The
":jumps" command lists the older positions.
If the 'shiftround' option is set, an indent is rounded to a multiple of
'shiftwidth' with ">" and "<" commands.
The 'scrolljump' option can be set to the minimum number of lines to scroll
when the cursor gets off the screen. Use this when scrolling is slow.
The 'scrolloff' option can be set to the minimum number of lines to keep
above and below the cursor. This gives some context to where you are
editing. When set to a large number the cursor line is always in the middle
of the window.
Uppercase marks can be used to jump between files. The ":marks" command lists
all currently set marks. The commands "']" and "`]" jump to the end of the
previous operator or end of the text inserted with the put command. "'[" and
"`[" do jump to the start.
The 'shelltype' option can be set to reflect the type of shell used on the
Amiga.
The 'highlight' option can be set for the highlight mode to be used for
several commands.
The CTRL-A (add) and CTRL-X (subtract) commands are new. The count to the
command (default 1) is added to/subtracted from the number at or after the
cursor. That number may be decimal, octal (starts with a '0') or hexadecimal
(starts with '0x'). Very useful in macros.
With the :set command the prefix "inv" can be used to invert boolean options.
In both Vi and Vim you can create a line break with the ":substitute" command
by using a CTRL-M. For Vi this means you cannot insert a real CTRL-M in the
text. With Vim you can put a real CTRL-M in the text by preceding it with a
CTRL-V.
In Insert mode:
If the 'revins' option is set, insert happens backwards. This is for typing
Hebrew. When inserting normal characters the cursor will not be shifted and
the text moves rightwards. Backspace, CTRL-W and CTRL-U will also work in
the opposite direction. CTRL-B toggles the 'revins' option. In replace mode
'revins' has no effect. Only when enabled at compile time.
The backspace key can be used just like CTRL-D to remove auto-indents.
You can backspace, CTRL-U and CTRL-W over line breaks if the 'backspace' (bs)
option includes "eol". You can backspace over the start of insert if the
'backspace' option includes "start".
When the 'paste' option is set, a few option are reset and mapping in insert
mode and abbreviation are disabled. This allows for pasting text in windowing
systems without unexpected results. When the 'paste' option is reset, the old
option values are restored.
CTRL-T/CTRL-D always insert/delete an indent in the current line, no matter
what column the cursor is in.
CTRL-@ (insert previously inserted text) works always (Vi: only when typed as
first character).
CTRL-A works like CTRL-@ but does not leave insert mode.
CTRL-R {0-9a-z..} can be used to insert the contents of a register.
When the 'smartindent' option is set, C programs will be better auto-indented.
With 'cindent' even more.
CTRL-Y and CTRL-E can be used to copy a character from above/below the
current cursor position.
After CTRL-V you can enter a three digit decimal number. This byte value is
inserted in the text as a single character. Useful for international
characters that are not on your keyboard.
When the 'expandtab' (et) option is set, a <Tab> is expanded to the
appropriate number of spaces.
The window always reflects the contents of the buffer (Vi does not do this
In Command-line mode:
<Esc> terminates the command-line without executing it. In vi the command
line would be executed, which is not what most people expect (hitting <Esc>
should always get you back to command mode). To avoid problems with some
obscure macros, an <Esc> in a macro will execute the command. If you want a
typed <Esc> to execute the command like vi does you can fix this with
":cmap ^V<Esc> ^V<CR>"
General:
The 'ttimeout' option is like 'timeout', but only works for cursor and
function keys, not for ordinary mapped characters. The 'timeoutlen' option
gives the number of milliseconds that is waited for. If the 'esckeys' option
is not set, cursor and function keys that start with <Esc> are not recognized
in insert mode.
There is an option for each terminal string. Can be used when termcap is not
supported or to change individual strings.
The 'fileformat' option can be set to select the <EOL>: "dos" <CR><NL>, "unix"
<NL> or "mac" <CR>.
When the 'fileformats' option is not empty, Vim tries to detect the type of
<EOL> automatically. The 'fileformat' option is set accordingly.
On systems that have no job control (older Unix systems and non-Unix systems)
the CTRL-Z, ":stop" or ":suspend" command starts a new shell.
If Vim is started on the Amiga without an interactive window for output, a
window is opened (and :sh still works). You can give a device to use for
editing with the |-d| argument, e.g. "-d con:20/20/600/150".
The 'columns' and 'lines' options are used to set or get the width and height
of the display.
Option settings are read from the first and last few lines of the file.
Option 'modelines' determines how many lines are tried (default is 5). Note
that this is different from the Vi versions that can execute any Ex command
in a modeline (a major security problem). |trojan-horse|
If the 'insertmode' option is set (e.g. in .exrc), Vim starts in insert mode.
And it comes back there, when pressing <Esc>.
Undo information is kept in memory. Available memory limits the number and
size of change that can be undone. This may be a problem with MS-DOS, is
hardly a problem on the Amiga and almost never with Unix and Win32.
If the 'backup' or 'writebackup' option is set: Before a file is overwritten,
a backup file (.bak) is made. If the "backup" option is set it is left
behind.
Vim creates a file ending in ".swp" to store parts of the file that have been
changed or that do not fit in memory. This file can be used to recover from
an aborted editing session with "vim -r file". Using the swap file can be
switched off by setting the 'updatecount' option to 0 or starting Vim with
the "-n" option. Use the 'directory' option for placing the .swp file
somewhere else.
Vim is able to work correctly on filesystems with 8.3 file names, also when
using messydos or crossdos filesystems on the Amiga, or any 8.3 mounted
filesystem under Unix. See |'shortname'|.
Error messages are shown at least one second (Vi overwrites error messages).
If Vim gives the |hit-enter| prompt, you can hit any key. Characters other
than <CR>, <NL> and <Space> are interpreted as the (start of) a command. (Vi
only accepts a command starting with ':').
The contents of the numbered and unnamed registers is remembered when
changing files.
The "No lines in buffer" message is a normal message instead of an error
message, since that may cause a mapping to be aborted.
The AUX: device of the Amiga is supported.
==============================================================================
6. Command-line arguments *cmdline-arguments*
Different versions of Vi have different command-line arguments. This can be
confusing. To help you, this section gives an overview of the differences.
Five variants of Vi will be considered here:
Elvis Elvis version 2.1b
Nvi Nvi version 1.79
Posix Posix 1003.2
Vi Vi version 3.7 (for Sun 4.1.x)
Vile Vile version 7.4 (incomplete)
Vim Vim version 5.2
Only Vim is able to accept options in between and after the file names.
+{command} Elvis, Nvi, Posix, Vi, Vim: Same as "-c {command}".
- Nvi, Posix, Vi: Run Ex in batch mode.
Vim: Read file from stdin (use -s for batch mode).
-- Vim: End of options, only file names are following.
--cmd {command} Vim: execute {command} before sourcing vimrc files.
--echo-wid Vim: GTK+ echoes the Window ID on stdout
--help Vim: show help message and exit.
--literal Vim: take file names literally, don't expand wildcards.
--nofork Vim: same as |-f|
--noplugin[s] Vim: Skip loading plugins.
--remote Vim: edit the files in another Vim server
--remote-expr {expr} Vim: evaluate {expr} in another Vim server
--remote-send {keys} Vim: send {keys} to a Vim server and exit
--remote-silent {file} Vim: edit the files in another Vim server if possible
--remote-wait Vim: edit the files in another Vim server and wait for it
--remote-wait-silent Vim: like --remote-wait, no complaints if not possible
--role {role} Vim: GTK+ 2: set role of main window
--serverlist Vim: Output a list of Vim servers and exit
--servername {name} Vim: Specify Vim server name
--socketid {id} Vim: GTK window socket to run Vim in
--windowid {id} Vim: Win32 window ID to run Vim in
--version Vim: show version message and exit.
-? Vile: print usage summary and exit.
-a Elvis: Load all specified file names into a window (use -o for
Vim).
-A Vim: Start in Arabic mode (when compiled with Arabic).
-b {blksize} Elvis: Use {blksize} blocksize for the session file.
-b Vim: set 'binary' mode.
*posix-screen-size*
The $COLUMNS and $LINES environment variables are ignored by Vim if
the size can be obtained from the terminal in a more reliable way.
Add the '|' flag to 'cpoptions' to have $COLUMNS and $LINES overrule
sizes obtained in another way.
The "{" and "}" commands don't stop at a "{" in the original Vi, but
POSIX specifies it does. Add the '{' flag to 'cpoptions' if you want
it the POSIX way.
The "D", "o" and "O" commands accept a count. Also when repeated.
Add the '#' flag to 'cpoptions' if you want to ignore the count.
The ":cd" command fails if the current buffer is modified when the '.'
flag is present in 'cpoptions'.
There is no ATTENTION message, the "A" flag is added to 'shortmess'.
These are remarks about running the POSIX test suite:
- vi test 33 sometimes fails for unknown reasons
- vi test 250 fails; behavior will be changed in a new revision
http://www.opengroup.org/austin/mailarchives/ag-review/msg01710.html
(link no longer works, perhaps it's now:
https://www.opengroup.org/sophocles/show_mail.tpl?
CALLER=show_archive.tpl&source=L&listname=austin-review-l&id=1711)
- vi test 310 fails; exit code non-zero when any error occurred?
- ex test 24 fails because test is wrong. Changed between SUSv2 and SUSv3.
- ex tests 47, 48, 49, 72, 73 fail because .exrc file isn't read in silent
mode and $EXINIT isn't used.
- ex tests 76, 78 fail because echo is used instead of printf. (fixed)
Also: problem with \s not changed to space.
- ex test 355 fails because 'window' isn't used for "30z".
- ex test 368 fails because shell command isn't echoed in silent mode.
- ex test 394 fails because "=" command output isn't visible in silent mode.
- ex test 411 fails because test file is wrong, contains stray ':'.
- ex test 475 and 476 fail because reprint output isn't visible in silent mode.
- ex test 480 and 481 fail because the tags file has spaces instead of a tab.
- ex test 502 fails because .exrc isn't read in silent mode.
- ex test 509 fails because .exrc isn't read in silent mode. and exit code is
1 instead of 2.
- ex test 534 fails because .exrc isn't read in silent mode.
*:perl* *:pe*
:pe[rl] {cmd} Execute Perl command {cmd}. The current package
is "main".
:pe[rl] << {endpattern}
{script}
{endpattern}
Execute Perl script {script}.
{endpattern} must NOT be preceded by any white space.
If {endpattern} is omitted, it defaults to a dot '.'
like for the |:append| and |:insert| commands. Using
'.' helps when inside a function, because "$i;" looks
like the start of an |:insert| command to Vim.
This form of the |:perl| command is mainly useful for
including perl code in vim scripts.
Note: This command doesn't work when the Perl feature
wasn't compiled in. To avoid errors, see
|script-here|.
*:perldo* *:perld*
:[range]perld[o] {cmd} Execute Perl command {cmd} for each line in the
[range], with $_ being set to the text of each line in
turn, without a trailing <EOL>. Setting $_ will change
the text, but note that it is not possible to add or
delete lines using this command.
The default for [range] is the whole file: "1,$".
Here are some things you can try:
:perl $a=1
:perldo $_ = reverse($_);1
:perl VIM::Msg("hello")
:perl $line = $curbuf->Get(42)
*E299*
Executing Perl commands in the |sandbox| is limited. ":perldo" will not be
possible at all. ":perl" will be evaluated in the Safe environment, if
possible.
*perl-overview*
Here is an overview of the functions that are available to Perl:
:perl VIM::Msg("Text") # displays a message
:perl VIM::Msg("Error", "ErrorMsg") # displays an error message
:perl VIM::Msg("remark", "Comment") # displays a highlighted message
:perl VIM::SetOption("ai") # sets a vim option
:perl $nbuf = VIM::Buffers() # returns the number of buffers
:perl @buflist = VIM::Buffers() # returns array of all buffers
:perl $mybuf = (VIM::Buffers('qq.c'))[0] # returns buffer object for 'qq.c'
:perl @winlist = VIM::Windows() # returns array of all windows
:perl $nwin = VIM::Windows() # returns the number of windows
:perl ($success, $v) = VIM::Eval('&path') # $v: option 'path', $success: 1
:perl ($success, $v) = VIM::Eval('&xyz') # $v: '' and $success: 0
:perl $v = VIM::Eval('expand("<cfile>")') # expands <cfile>
:perl $curwin->SetHeight(10) # sets the window height
:perl @pos = $curwin->Cursor() # returns (row, col) array
:perl @pos = (10, 10)
:perl $curwin->Cursor(@pos) # sets cursor to @pos
:perl $curwin->Cursor(10,10) # sets cursor to row 10 col 10
:perl $mybuf = $curwin->Buffer() # returns the buffer object for window
:perl $curbuf->Name() # returns buffer name
:perl $curbuf->Number() # returns buffer number
:perl $curbuf->Count() # returns the number of lines
:perl $l = $curbuf->Get(10) # returns line 10
:perl @l = $curbuf->Get(1 .. 5) # returns lines 1 through 5
:perl $curbuf->Delete(10) # deletes line 10
*perl-Msg*
VIM::Msg({msg}, {group}?)
Displays the message {msg}. The optional {group}
argument specifies a highlight group for Vim to use
for the message.
*perl-SetOption*
VIM::SetOption({arg}) Sets a vim option. {arg} can be any argument that the
":set" command accepts. Note that this means that no
spaces are allowed in the argument! See |:set|.
*perl-Buffers*
VIM::Buffers([{bn}...]) With no arguments, returns a list of all the buffers
in an array context or returns the number of buffers
in a scalar context. For a list of buffer names or
numbers {bn}, returns a list of the buffers matching
{bn}, using the same rules as Vim's internal
|bufname()| function.
WARNING: the list becomes invalid when |:bwipe| is
used. Using it anyway may crash Vim.
*perl-Windows*
VIM::Windows([{wn}...]) With no arguments, returns a list of all the windows
in an array context or returns the number of windows
in a scalar context. For a list of window numbers
{wn}, returns a list of the windows with those
numbers.
WARNING: the list becomes invalid when a window is
closed. Using it anyway may crash Vim.
*perl-DoCommand*
VIM::DoCommand({cmd}) Executes Ex command {cmd}.
*perl-Eval*
VIM::Eval({expr}) Evaluates {expr} and returns (success, val).
success=1 indicates that val contains the value of
{expr}; success=0 indicates a failure to evaluate
the expression. '@x' returns the contents of register
x, '&x' returns the value of option x, 'x' returns the
value of internal |variables| x, and '$x' is equivalent
to perl's $ENV{x}. All |functions| accessible from
the command-line are valid for {expr}.
A |List| is turned into a string by joining the items
and inserting line breaks.
*perl-SetHeight*
Window->SetHeight({height})
Sets the Window height to {height}, within screen
limits.
*perl-GetCursor*
Window->Cursor({row}?, {col}?)
With no arguments, returns a (row, col) array for the
current cursor position in the Window. With {row} and
{col} arguments, sets the Window's cursor position to
{row} and {col}. Note that {col} is numbered from 0,
Perl-fashion, and thus is one less than the value in
Vim's ruler.
Window->Buffer() *perl-Buffer*
Returns the Buffer object corresponding to the given
Window.
*perl-Name*
Buffer->Name() Returns the filename for the Buffer.
*perl-Number*
Buffer->Number() Returns the number of the Buffer.
*perl-Count*
Buffer->Count() Returns the number of lines in the Buffer.
*perl-Get*
Buffer->Get({lnum}, {lnum}?, ...)
Returns a text string of line {lnum} in the Buffer
for each {lnum} specified. An array can be passed
with a list of {lnum}'s specified.
*perl-Delete*
Buffer->Delete({lnum}, {lnum}?)
Deletes line {lnum} in the Buffer. With the second
{lnum}, deletes the range of lines from the first
{lnum} to the second {lnum}.
*perl-Append*
Buffer->Append({lnum}, {line}, {line}?, ...)
Appends each {line} string after Buffer line {lnum}.
The list of {line}s can be an array.
*perl-Set*
Buffer->Set({lnum}, {line}, {line}?, ...)
Replaces one or more Buffer lines with specified
{lines}s, starting at Buffer line {lnum}. The list of
{line}s can be an array. If the arguments are
invalid, replacement does not occur.
$main::curwin
The current window object.
$main::curbuf
The current buffer object.
*script-here*
When using a script language in-line, you might want to skip this when the
language isn't supported. But this mechanism doesn't work:
if has('perl')
perl << EOF
this will NOT work!
EOF
endif
Instead, put the Perl/Python/Ruby/etc. command in a function and call that
function:
if has('perl')
function DefPerl()
perl << EOF
this works
EOF
endfunction
call DefPerl()
endif
Note that "EOF" must be at the start of the line.
==============================================================================
4. Dynamic loading *perl-dynamic*
On MS-Windows and Unix the Perl library can be loaded dynamically. The
|:version| output then includes |+perl/dyn|.
This means that Vim will search for the Perl DLL or shared library file only
when needed. When you don't use the Perl interface you don't need it, thus
MS-Windows
You can download Perl from http://www.perl.org. The one from ActiveState was
used for building Vim.
To use the Perl interface the Perl DLL must be in your search path.
If Vim reports it cannot find the perl512.dll, make sure your $PATH includes
the directory where it is located. The Perl installer normally does that.
In a console window type "path" to see what directories are used.
The name of the DLL must match the Perl version Vim was compiled with.
Currently the name is "perl512.dll". That is for Perl 5.12. To know for
sure edit "gvim.exe" and search for "perl\d*.dll\c".
==============================================================================
top - main help file
- You can get name collisions from files with the same name but in different
directories (although Vim tries to avoid that by comparing the path name).
This will result in bogus ATTENTION warning messages.
- When you use your home directory, and somebody else tries to edit the same
file, he will not see your swap file and will not get the ATTENTION warning
message.
On the Amiga you can also use a recoverable ram disk, but there is no 100%
guarantee that this works. Putting swap files in a normal ram disk (like RAM:
on the Amiga) or in a place that is cleared when rebooting (like /tmp on Unix)
makes no sense, you will lose the swap file in a crash.
If you want to put swap files in a fixed place, put a command resembling the
following ones in your .vimrc:
:set dir=dh2:tmp (for Amiga)
:set dir=~/tmp (for Unix)
:set dir=c:\\tmp (for MS-DOS and Win32)
This is also very handy when editing files on floppy. Of course you will have
to create that "tmp" directory for this to work!
For read-only files, a swap file is not used. Unless the file is big, causing
the amount of memory used to be higher than given with 'maxmem' or
'maxmemtot'. And when making a change to a read-only file, the swap file is
created anyway.
The 'swapfile' option can be reset to avoid creating a swapfile.
to use the same key for text file and swap file
Enter encryption key:
You can be in one of these two situations:
1. The encryption key was not changed, or after changing the key the text file
was written. You will be prompted for the crypt key twice. The second
time you can simply press Enter. That means the same key is used for the
text file and the swap file.
2. You entered a new encryption key, but did not save the text file. Vim will
then use the new key for the swap file, and the text file will still be
encrypted with the old key. At the second prompt enter the new key.
Note that after recovery the key of the swap file will be used for the text
file. Thus if you write the text file, you need to use that new key.
*:pyfile* *:pyf*
:[range]pyf[ile] {file}
vim.command(str) *python-command*
Executes the vim (ex-mode) command str. Returns None.
Examples:
:py vim.command("set tw=72")
:py vim.command("%s/aaa/bbb/g")
The following definition executes Normal mode commands:
def normal(str):
vim.command("normal "+str)
# Note the use of single quotes to delimit a string containing
# double quotes
normal('"a2dd"aP')
*E659*
The ":python" command cannot be used recursively with Python 2.2 and
vim.eval(str) *python-eval*
Evaluates the expression str using the vim internal expression
evaluator (see |expression|). Returns the expression result as:
- a string if the Vim expression evaluates to a string or number
- a list if the Vim expression evaluates to a Vim list
- a dictionary if the Vim expression evaluates to a Vim dictionary
Dictionaries and lists are recursively expanded.
Examples:
:py text_width = vim.eval("&tw")
:py str = vim.eval("12+12") # NB result is a string! Use
# string.atoi() to convert to
# a number.
:py tagList = vim.eval('taglist("eval_expr")')
The latter will return a python list of python dicts, for instance:
[{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name':
'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}]
vim.error *python-error*
Upon encountering a Vim error, Python raises an exception of type
vim.error.
Example:
try:
vim.command("put a")
except vim.error:
# nothing in register a
Constants of the "vim" module
Note that these are not actually constants - you could reassign them.
But this is silly, as you would then lose access to the vim objects
to which the variables referred.
vim.buffers *python-buffers*
A sequence object providing access to the list of vim buffers. The
object supports the following operations:
:py b = vim.buffers[i] # Indexing (read-only)
:py b in vim.buffers # Membership test
:py n = len(vim.buffers) # Number of elements
:py for b in vim.buffers: # Sequential access
vim.windows *python-windows*
A sequence object providing access to the list of vim windows. The
object supports the following operations:
:py w = vim.windows[i] # Indexing (read-only)
:py w in vim.windows # Membership test
:py n = len(vim.windows) # Number of elements
:py for w in vim.windows: # Sequential access
vim.current *python-current*
An object providing access (via specific attributes) to various
"current" objects available in vim:
vim.current.line The current line (RW) String
vim.current.buffer The current buffer (RO) Buffer
vim.current.window The current window (RO) Window
vim.current.range The current line range (RO) Range
The last case deserves a little explanation. When the :python or
:pyfile command specifies a range, this range of lines becomes the
"current range". A range is a bit like a buffer, but with all access
restricted to a subset of lines. See |python-range| for more details.
error messages.
In implementation terms, this means that all output to sys.stdout
(including the output from print statements) appears as information
messages, and all output to sys.stderr (including error tracebacks)
appears as error messages.
*python-input*
Input (via sys.stdin, including input() and raw_input()) is not
supported, and may cause the program to crash. This should probably be
fixed.
==============================================================================
3. Buffer objects *python-buffer*
Buffer objects represent vim buffers. You can obtain them in a number of ways:
- via vim.current.buffer (|python-current|)
- from indexing vim.buffers (|python-buffers|)
- from the "buffer" attribute of a window (|python-window|)
Buffer objects have one read-only attribute - name - the full file name for
the buffer. They also have three methods (append, mark, and range; see below).
You can also treat buffer objects as sequence objects. In this context, they
act as if they were lists (yes, they are mutable) of strings, with each
element being a line of the buffer. All of the usual sequence operations,
including indexing, index assignment, slicing and slice assignment, work as
you would expect. Note that the result of indexing (slicing) a buffer is a
string (list of strings). This has one unusual consequence - b[:] is different
from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
"b = None" merely updates the variable b, with no effect on the buffer.
Buffer indexes start at zero, as is normal in Python. This differs from vim
line numbers, which start from 1. This is particularly relevant when dealing
with marks (see below) which use vim line numbers.
The buffer object methods are:
b.append(str) Append a line to the buffer
b.append(str, nr) Idem, below line "nr"
b.append(list) Append a list of lines to the buffer
Note that the option of supplying a list of strings to
the append method differs from the equivalent method
for Python's built-in list objects.
b.append(list, nr) Idem, below line "nr"
b.mark(name) Return a tuple (row,col) representing the position
of the named mark (can also get the []"<> marks)
b.range(s,e) Return a range object (see |python-range|) which
represents the part of the given buffer between line
numbers s and e |inclusive|.
Note that when adding a line it must not contain a line break character '\n'.
A trailing '\n' is allowed and ignored, so that you can do:
:py b.append(f.readlines())
Examples (assume b is the current buffer)
:py print b.name # write the buffer file name
:py b[0] = "hello!!!" # replace the top line
:py b[:] = None # delete the whole buffer
:py del b[:] # delete the whole buffer
:py b[0:0] = [ "a line" ] # add a line at the top
:py del b[2] # delete a line (the third)
:py b.append("bottom") # add a line at the bottom
:py n = len(b) # number of lines
:py (row,col) = b.mark('a') # named mark
:py r = b.range(1,5) # a sub-range of the buffer
==============================================================================
4. Range objects *python-range*
Range objects represent a part of a vim buffer. You can obtain them in a
number of ways:
- via vim.current.range (|python-current|)
- from a buffer's range() method (|python-buffer|)
A range object is almost identical in operation to a buffer object. However,
all operations are restricted to the lines within the range (this line range
*:py3* *:python3*
The |:py3| and |:python3| commands work similar to |:python|.
*:py3file*
The |:py3file| command works similar to |:pyfile|.
Vim can be built in four ways (:version output):
1. No Python support (-python, -python3)
2. Python 2 support only (+python or +python/dyn, -python3)
3. Python 3 support only (-python, +python3 or +python3/dyn)
4. Python 2 and 3 support (+python/dyn, +python3/dyn)
Some more details on the special case 4:
When Python 2 and Python 3 are both supported they must be loaded dynamically.
When doing this on Linux/Unix systems and importing global symbols, this leads
to a crash when the second Python version is used. So either global symbols
are loaded but only one Python version is activated, or no global symbols are
loaded. The latter makes Python's "import" fail on libraries that expect the
symbols to be provided by Vim.
*E836* *E837*
Vim's configuration script makes a guess for all libraries based on one
standard Python library (termios). If importing this library succeeds for
both Python versions, then both will be made available in Vim at the same
time. If not, only the version first used in a session will be enabled.
When trying to use the other one you will get the E836 or E837 error message.
Here Vim's behavior depends on the system in which it was configured. In a
system where both versions of Python were configured with --enable-shared,
both versions of Python will be activated at the same time. There will still
be problems with other third party libraries that were not linked to
libPython.
To work around such problems there are these options:
1. The problematic library is recompiled to link to the according
libpython.so.
2. Vim is recompiled for only one Python version.
3. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
may crash Vim though.
==============================================================================
top - main help file
1. Commands |ruby-commands|
2. The VIM module |ruby-vim|
3. VIM::Buffer objects |ruby-buffer|
4. VIM::Window objects |ruby-window|
5. Global variables |ruby-globals|
6. Dynamic loading |ruby-dynamic|
{Vi does not have any of these commands}
*E266* *E267* *E268* *E269* *E270* *E271* *E272* *E273*
The Ruby interface only works when Vim was compiled with the |+ruby| feature.
The home page for ruby is http://www.ruby-lang.org/. You can find links for
downloading Ruby there.
==============================================================================
1. Commands *ruby-commands*
*:ruby* *:rub*
:rub[y] {cmd} Execute Ruby command {cmd}.
:rub[y] << {endpattern}
{script}
{endpattern}
Execute Ruby script {script}.
{endpattern} must NOT be preceded by any white space.
If {endpattern} is omitted, it defaults to a dot '.'
like for the |:append| and |:insert| commands. This
form of the |:ruby| command is mainly useful for
including ruby code in vim scripts.
Note: This command doesn't work when the Ruby feature
wasn't compiled in. To avoid errors, see
|script-here|.
Command to try it out:
:ruby print "Hello" # this is a comment
Example Vim script:
function! RedGem()
ruby << EOF
class Garnet
def initialize(s)
@buffer = VIM::Buffer.current
vimputs(s)
end
def vimputs(s)
@buffer.append(@buffer.count,s)
end
end
gem = Garnet.new("pretty")
EOF
endfunction
*:rubyfile* *:rubyf*
:rubyf[ile] {file} Execute the Ruby script in {file}. This is the same as
":ruby load 'file'"', but allows file name completion.
Executing Ruby commands is not possible in the |sandbox|.
==============================================================================
2. The VIM module *ruby-vim*
Ruby code gets all of its access to vim via the "VIM" module.
Overview
print "Hello" # displays a message
VIM.command(cmd) # execute an Ex command
num = VIM::Window.count # gets the number of windows
w = VIM::Window[n] # gets window "n"
cw = VIM::Window.current # gets the current window
num = VIM::Buffer.count # gets the number of buffers
b = VIM::Buffer[n] # gets buffer "n"
cb = VIM::Buffer.current # gets the current buffer
w.height = lines # sets the window height
w.cursor = [row, col] # sets the window cursor position
pos = w.cursor # gets an array [row, col]
name = b.name # gets the buffer file name
line = b[n] # gets a line from the buffer
num = b.count # gets the number of lines
b[n] = str # sets a line in the buffer
b.delete(n) # deletes a line
b.append(n, str) # appends a line after n
line = VIM::Buffer.current.line # gets the current line
num = VIM::Buffer.current.line_number # gets the current line number
VIM::Buffer.current.line = "test" # sets the current line number
Module Functions:
*ruby-message*
VIM::message({msg})
Displays the message {msg}.
*ruby-set_option*
VIM::set_option({arg})
Sets a vim option. {arg} can be any argument that the ":set" command
accepts. Note that this means that no spaces are allowed in the
argument! See |:set|.
*ruby-command*
VIM::command({cmd})
Executes Ex command {cmd}.
*ruby-evaluate*
VIM::evaluate({expr})
Evaluates {expr} using the vim internal expression evaluator (see
|expression|). Returns the expression result as a string.
A |List| is turned into a string by joining the items and inserting
line breaks.
==============================================================================
When doing file name completion, Vim also finds matches for the short file
name. But Vim will still find and use the corresponding long file name. For
example, if you have the long file name "this_is_a_test" with the short file
name "this_i~1", the command ":e *1" will start editing "this_is_a_test".
==============================================================================
2. Startup *win32-startup*
$PATH *win32-PATH*
The directory of the Vim executable is appended to $PATH. This is mostly to
make "!xxd' work, as it is in the Tools menu. And it also means that when
executable() returns 1 the executable can actually be executed.
==============================================================================
3. Restore screen contents *win32-restore*
When 'restorescreen' is set (which is the default), Vim will restore the
original contents of the console when exiting or when executing external
commands. If you don't want this, use ":set nors" |'restorescreen'|
==============================================================================
4. Using the mouse *win32-mouse*
The Win32 version of Vim supports using the mouse. If you have a two-button
mouse, the middle button can be emulated by pressing both left and right
buttons simultaneously - but note that in the Win32 GUI, if you have the right
mouse button pop-up menu enabled (see 'mouse'), you should err on the side of
pressing the left button first. |mouse-using|
When the mouse doesn't work, try disabling the "Quick Edit Mode" feature of
the console.
==============================================================================
5. Running under Windows 3.1 *win32-win3.1*
*win32s* *windows-3.1*
There is a special version of Gvim that runs under Windows 3.1 and 3.11. You
need the gvim.exe that was compiled with Visual C++ 4.1.
To run the Win32 version under Windows 3.1, you need to install Win32s. You
might have it already from another Win32 application which you have installed.
If Vim doesn't seem to be running properly, get the latest version: 1.30c.
You can find it at:
http://support.microsoft.com/download/support/mslfiles/pw1118.exe
(Microsoft moved it again, we don't know where it is now :-( ).
The reason for having two versions of gvim.exe is that the Win32s version was
compiled with VC++ 4.1. This is the last version of VC++ that supports Win32s
programs. VC++ 5.0 is better, so that one was used for the Win32 version.
Apart from that, there is no difference between the programs. If you are in a
mixed environment, you can use the gvim.exe for Win32s on both.
The Win32s version works the same way as the Win32 version under 95/NT. When
running under Win32s the following differences apply:
- You cannot use long file names, because Windows 3.1 doesn't support them!
- When executing an external command, it doesn't return an exit code. After
doing ":make" you have to do ":cn" yourself.
==============================================================================
6. Win32 mini FAQ *win32-faq*
Q. Why does the Win32 version of Vim update the screen so slowly on Windows 95?
A. The support for Win32 console mode applications is very buggy in Win95.
For some unknown reason, the screen updates very slowly when Vim is run at
one of the standard resolutions (80x25, 80x43, or 80x50) and the 16-bit DOS
version updates the screen much more quickly than the Win32 version.
However, if the screen is set to some other resolution, such as by ":set
columns=100" or ":set lines=40", screen updating becomes about as fast as
it is with the 16-bit version.
WARNING: Changing 'columns' may make Windows 95 crash while updating the
window (complaints --> Microsoft). Since this mostly works, this has not
been disabled, but be careful with changing 'columns'.
Changing the screen resolution makes updates faster, but it brings
additional problems. External commands (e.g., ":!dir") can cause Vim to
freeze when the screen is set to a non-standard resolution, particularly
when 'columns' is not equal to 80. It is not possible for Vim to reliably
set the screen resolution back to the value it had upon startup before
running external commands, so if you change the number of 'lines' or
'columns', be very, very careful. In fact, Vim will not allow you to
execute external commands when 'columns' is not equal to 80, because it is
so likely to freeze up afterwards.
None of the above applies on Windows NT. Screen updates are fast, no
matter how many 'lines' or 'columns' the window has, and external commands
do not cause Vim to freeze.
Q. So if the Win32 version updates the screen so slowly on Windows 95 and the
16-bit DOS version updates the screen quickly, why would I want to run the
Win32 version?
A. Firstly, the Win32 version isn't that slow, especially when the screen is
set to some non-standard number of 'lines' or 'columns'. Secondly, the
16-bit DOS version has some severe limitations: It can't do big changes and
it doesn't know about long file names. The Win32 version doesn't have these
limitations and it's faster overall (the same is true for the 32-bit DJGPP
DOS version of Vim). The Win32 version is smarter about handling the
screen, the mouse, and the keyboard than the DJGPP version is.
Q. And what about the 16-bit DOS version versus the Win32 version on NT?
A. There are no good reasons to run the 16-bit DOS version on NT. The Win32
version updates the screen just as fast as the 16-bit version does when
running on NT. All of the above disadvantages apply. Finally, DOS
applications can take a long time to start up and will run more slowly. On
non-Intel NT platforms, the DOS version is almost unusably slow, because it
runs on top of an 80x86 emulator.
Q. How do I change the font?
A. In the GUI version, you can use the 'guifont' option. Example:
:set guifont=Lucida_Console:h15:cDEFAULT
In the console version, you need to set the font of the console itself.
You cannot do this from within Vim.
Q. When I change the size of the console window with ':set lines=xx' or
similar, the font changes! (Win95)
A. You have the console font set to 'Auto' in Vim's (or your MS-DOS prompt's)
properties. This makes W95 guess (badly!) what font is best. Set an explicit
font instead.
Q. Why can't I paste into Vim when running Windows 95?
A. In the properties dialog box for the MS-DOS window, go to "MS-DOS
Prompt/Misc/Fast pasting" and make sure that it is NOT checked. You should
also do ":set paste" in Vim to avoid unexpected effects. |'paste'|
The result is that the "dir" command updates the "file.bat~" file, instead
of creating a new "file.bat" file. This same behavior is exhibited in Vim
when editing an existing file named "foo.bat" because the default behavior
of Vim is to create a temporary file with a '~' character appended to the
name. When the file is written, it winds up being deleted.
Solution: Add this command to your _vimrc file:
:set backupext=.temporary
Q. How do I change the blink rate of the cursor?
A. You can't! This is a limitation of the NT console. NT 5.0 is reported to
be able to set the blink rate for all console windows at the same time.
*:!start*
Q. How can I run an external command or program asynchronously?
A. When using :! to run an external command, you can run it with "start":
:!start winfile.exe<CR>
Using "start" stops Vim switching to another screen, opening a new console,
or waiting for the program to complete; it indicates that you are running a
program that does not affect the files you are editing. Programs begun
with :!start do not get passed Vim's open file handles, which means they do
not have to be closed before Vim.
To avoid this special treatment, use ":! start".
The optional "/min" argument causes the window to be minimized.
Q. I'm using Win32s, and when I try to run an external command like "make",
Vim doesn't wait for it to finish! Help!
A. The problem is that a 32-bit application (Vim) can't get notification from
Windows that a 16-bit application (your DOS session) has finished. Vim
includes a work-around for this, but you must set up your DOS commands to
run in a window, not full-screen. Unfortunately the default when you
install Windows is full-screen. To change this:
1) Start PIF editor (in the Main program group).
2) Open the file "_DEFAULT.PIF" in your Windows directory.
3) Changes the display option from "Full Screen" to "Windowed".
4) Save and exit.
To test, start Vim and type
:!dir C:\<CR>".
You should see a DOS box window appear briefly with the directory listing.
Q. I use Vim under Win32s and NT. In NT, I can define the console to default to
50 lines, so that I get a 80x50 shell when I ':sh'. Can I do the same in
W3.1x, or am I stuck with 80x25?
A. Edit SYSTEM.INI and add 'ScreenLines=50' to the [NonWindowsApp] section. DOS
prompts and external DOS commands will now run in a 50-line window.
top - main help file
text={text} *E239*
Define the text that is displayed when there is no icon or the
GUI is not being used. Only printable characters are allowed
and they must occupy one or two display cells.
texthl={group}
Highlighting group used for the text item.
{Vi does not have any of these commands} *E275* *E274* *E276* *E278* *E279*
The SNiFF+ interface only works, when Vim was compiled with the |+sniff|
feature.
==============================================================================
1. Introduction *sniff-intro*
The following features for the use with SNiFF+ are available:
* Vim can be used for all editing requests
* SNiFF+ recognizes and updates all browsers when a file is saved in Vim
* SNiFF+ commands can be issued directly from Vim
How to use Vim with SNiFF+
1. Make sure SNiFF+ is running.
2. In the Editor view of the Preferences dialog set the Field named
'External Editor' to 'Emacs/Vim'.
4. Start Vim
5. Connect to SNiFF+ (:sniff connect)
Once a connection is established, SNiFF+ uses Vim for all requests to show or
edit source code. On the other hand, you can send queries to SNiFF+ with the
:sniff command.
==============================================================================
2. Commands *sniff-commands*
*:sniff* *:sni*
:sni[ff] request [symbol] Send request to sniff with optional symbol.
{not in Vi}
:sni[ff] Display all possible requests and the connection
status
Most requests require a symbol (identifier) as parameter. If it is omitted,
Vim will use the current word under the cursor.
The available requests are listed below:
request mapping description
-------------------------------------------------------------------------------
connect sc Establish connection with SNiFF+.
Make sure SNiFF+ is prepared for this in the
Preferences
disconnect sq Disconnect from SNiFF+. You can reconnect any
time with :sniff connect (or 'sc')
*:tabc* *:tabclose*
:tabc[lose][!] Close current tab page.
This command fails when:
- There is only one tab page on the screen. *E784*
- When 'hidden' is not set, [!] is not used, a buffer has
changes, and there is no other window on this buffer.
Changes to the buffer are not written and won't get lost, so
this is a "safe" command.
:tabc[lose][!] {count}
Close tab page {count}. Fails in the same way as ':tabclose"
above.
*:tabo* *:tabonly*
:tabo[nly][!] Close all other tab pages.
When the 'hidden' option is set, all buffers in closed windows
become hidden.
When 'hidden' is not set, and the 'autowrite' option is set,
modified buffers are written. Otherwise, windows that have
buffers that are modified are not removed, unless the [!] is
given, then they become hidden. But modified buffers are
never abandoned, so changes cannot get lost.
*:tabl* *:tablast*
:tabl[ast] Go to the last tab page.
Other commands:
*:tabs*
:tabs List the tab pages and the windows they contain.
Shows a ">" for the current window.
Shows a "+" for modified buffers.
*:tabd* *:tabdo*
:tabd[o] {cmd} Execute {cmd} in each tab page.
It works like doing this:
:tabfirst
:{cmd}
:tabnext
:{cmd}
etc.
This only operates in the current window of each tab page.
When an error is detected on one tab page, further tab pages
will not be visited.
The last tab page (or where an error occurred) becomes the
current tab page.
{cmd} can contain '|' to concatenate several commands.
{cmd} must not open or close tab pages or reorder them.
{not in Vi} {not available when compiled without the
|+listcmds| feature}
Also see |:windo|, |:argdo| and |:bufdo|.
==============================================================================
*tabline-menu*
The GUI tab pages line has a popup menu. It is accessed with a right click.
The entries are:
Close Close the tab page under the mouse pointer. The
current one if there is no label under the mouse
pointer.
New Tab Open a tab page, editing an empty buffer. It appears
to the left of the mouse pointer.
Open Tab... Like "New Tab" and additionally use a file selector to
select a file to edit.
Diff mode works per tab page. You can see the diffs between several files
within one tab page. Other tab pages can show differences between other
files.
Variables local to a tab page start with "t:". |tabpage-variable|
Currently there is only one option local to a tab page: 'cmdheight'.
The TabLeave and TabEnter autocommand events can be used to do something when
switching from one tab page to another. The exact order depends on what you
are doing. When creating a new tab page this works as if you create a new
window on the same buffer and then edit another buffer. Thus ":tabnew"
triggers:
WinLeave leave current window
TabLeave leave current tab page
TabEnter enter new tab page
WinEnter enter window in new tab page
BufLeave leave current buffer
BufEnter enter new empty buffer
When switching to another tab page the order is:
BufLeave
WinLeave
TabLeave
TabEnter
WinEnter
BufEnter
==============================================================================
4. Setting 'tabline' *setting-tabline*
The 'tabline' option specifies what the line with tab pages labels looks like.
It is only used when there is no GUI tab line.
You can use the 'showtabline' option to specify when you want the line with
tab page labels to appear: never, when there is more than one tab page or
always.
The highlighting of the tab pages line is set with the groups TabLine
TabLineSel and TabLineFill. |hl-TabLine| |hl-TabLineSel| |hl-TabLineFill|
A "+" will be shown for a tab page that has a modified window. The number of
windows in a tabpage is also shown. Thus "3+" means three windows and one of
them has a modified buffer.
The 'tabline' option allows you to define your preferred way to tab pages
labels. This isn't easy, thus an example will be given here.
For basics see the 'statusline' option. The same items can be used in the
'tabline' option. Additionally, the |tabpagebuflist()|, |tabpagenr()| and
|tabpagewinnr()| functions are useful.
Since the number of tab labels will vary, you need to use an expression for
the whole option. Something like:
:set tabline=%!MyTabLine()
Then define the MyTabLine() function to list all the tab pages labels. A
convenient method is to split it in two parts: First go over all the tab
pages and define labels for them. Then get the label for each tab page.
function MyTabLine()
let s = ''
for i in range(tabpagenr('$'))
" select the highlighting
if i + 1 == tabpagenr()
let s .= '%#TabLineSel#'
else
let s .= '%#TabLine#'
endif
" set the tab page number (for mouse clicks)
let s .= '%' . (i + 1) . 'T'
" the label is made by MyTabLabel()
let s .= ' %{MyTabLabel(' . (i + 1) . ')} '
endfor
" after the last tab fill with TabLineFill and reset tab page nr
let s .= '%#TabLineFill#%T'
" right-align the label to close the current tab page
if tabpagenr('$') > 1
let s .= '%=%#TabLine#%999Xclose'
endif
return s
endfunction
Now the MyTabLabel() function is called for each tab page to get its label.
function MyTabLabel(n)
let buflist = tabpagebuflist(a:n)
let winnr = tabpagewinnr(a:n)
return bufname(buflist[winnr - 1])
endfunction
This is just a simplistic example that results in a tab pages line that
resembles the default, but without adding a + for a modified buffer or
truncating the names. You will want to reduce the width of labels in a
clever way when there is not enough room. Check the 'columns' option for the
space available.
==============================================================================
5. Setting 'guitablabel' *setting-guitablabel*
When the GUI tab pages line is displayed, 'guitablabel' can be used to
specify the label to display for each tab page. Unlike 'tabline', which
specifies the whole tab pages line at once, 'guitablabel' is used for each
label separately.
'guitabtooltip' is very similar and is used for the tooltip of the same label.
This only appears when the mouse pointer hovers over the label, thus it
usually is longer. Only supported on some systems though.
See the 'statusline' option for the format of the value.
The "%N" item can be used for the current tab page number. The |v:lnum|
variable is also set to this number when the option is evaluated.
The items that use a file name refer to the current window of the tab page.
Note that syntax highlighting is not used for the option. The %T and %X
items are also ignored.
A simple example that puts the tab page number and the buffer name in the
label:
:set guitablabel=%N\ %f
An example that resembles the default 'guitablabel': Show the number of
windows in the tab page and a '+' if there is a modified buffer:
function GuiTabLabel()
let label = ''
let bufnrlist = tabpagebuflist(v:lnum)
" Add '+' if one of the buffers in the tab page is modified
for bufnr in bufnrlist
if getbufvar(bufnr, "&modified")
let label = '+'
break
endif
endfor
" Append the number of windows in the tab page if more than one
let wincount = tabpagewinnr(v:lnum, '$')
if wincount > 1
let label .= wincount
endif
if label != ''
let label .= ' '
endif
" Append the buffer name
return label . bufname(bufnrlist[tabpagewinnr(v:lnum) - 1])
endfunction
set guitablabel=%{GuiTabLabel()}
Note that the function must be defined before setting the option, otherwise
you get an error message for the function not being known.
If you want to fall back to the default label, return an empty string.
If you want to show something specific for a tab page, you might want to use a
tab page local variable. |t:var|
*:tcl* *:tc*
:tc[l] {cmd} Execute Tcl command {cmd}.
:[range]tc[l] << {endmarker}
{script}
{endmarker}
Execute Tcl script {script}.
Note: This command doesn't work when the Tcl feature
wasn't compiled in. To avoid errors, see
|script-here|.
{endmarker} must NOT be preceded by any white space. If {endmarker} is
omitted from after the "<<", a dot '.' must be used after {script}, like for
the |:append| and |:insert| commands.
This form of the |:tcl| command is mainly useful for including tcl code in Vim
scripts.
Example:
function! DefineDate()
tcl << EOF
proc date {} {
return [clock format [clock seconds]]
}
EOF
endfunction
*:tcldo* *:tcld*
:[range]tcld[o] {cmd} Execute Tcl command {cmd} for each line in [range]
*:tclfile* *:tclf*
:tclf[ile] {file} Execute the Tcl script in {file}. This is the same as
":tcl source {file}", but allows file name completion.
{not in Vi}
Note that Tcl objects (like variables) persist from one command to the next,
just as in the Tcl shell.
Executing Tcl commands is not possible in the |sandbox|.
==============================================================================
2. Tcl commands *tcl-commands*
Tcl 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::beep *tcl-beep*
Honk. Does not return a result.
::vim::lbase *tcl-var-lbase*
This variable controls how Tcl treats line numbers. If it is set to
'1', then lines and columns start at 1. This way, line numbers from
Tcl commands and vim expressions are compatible. If this variable is
set to '0', then line numbers and columns start at 0 in Tcl. This is
useful if you want to treat a buffer as a Tcl list or a line as a Tcl
string and use standard Tcl commands that return an index ("lsort" or
"string first", for example). The default value is '1'. Currently,
any non-zero values is treated as '1', but your scripts should not
rely on this. See also |tcl-linenumbers|.
::vim::range *tcl-var-range*
This is an array with three elements, "start", "begin" and "end". It
contains the line numbers of the start and end row of the current
range. "begin" is the same as "start". This variable is read-only.
See |tcl-examples|.
line *tcl-var-line*
lnum *tcl-var-lnum*
These global variables are only available if the ":tcldo" Ex command
is being executed. They contain the text and line number of the
current line. When the Tcl command invoked by ":tcldo" is completed,
the current line is set to the contents of the "line" variable, unless
the variable was unset by the Tcl command. The "lnum" variable is
read-only. These variables are not in the "::vim" namespace so they
can be used in ":tcldo" without much typing (this might be changed in
future versions). See also |tcl-linenumbers|.
==============================================================================
4. Tcl window commands *tcl-window-cmds*
Window commands represent vim windows. They are created by several commands:
::vim::window list |tcl-window|
"windows" option of a buffer command |tcl-buffer-windows|
The ::vim::current(window) variable contains the name of the window command
for the current window. A window command is automatically deleted when the
corresponding vim window is closed.
Let's assume the name of the window command is stored in the Tcl variable "win",
i.e. "$win" calls the command. The following options 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 buffer *tcl-window-buffer*
Creates a Tcl command for the window's buffer, and returns its name as
the result. The name should be stored in a variable:
set buf [$win buffer]
$buf is now a valid Tcl command. See |tcl-buffer-cmds| for the
available options.
*tcl-linenumbers*
Most buffer commands take line numbers as arguments. How Tcl treats these
numbers depends on the "::vim::lbase" variable (see |tcl-var-lbase|). Instead
of line numbers, several keywords can be also used: "top", "start", "begin",
"first", "bottom", "end" and "last".
Options:
$buf append {n} {str} *tcl-buffer-append*
$buf insert {n} {str} *tcl-buffer-insert*
Add a line to the buffer. With the "insert" option, the string
becomes the new line {n}, with "append" it is inserted after line {n}.
Example:
$buf insert top "This is the beginning."
$buf append end "This is the end."
If you want to add some Tcl procedures permanently to vim, just place them in
a file (e.g. "~/.vimrc.tcl" on Unix machines), and add these lines to your
startup file (usually "~/.vimrc" on Unix):
if has("tcl")
tclfile ~/.vimrc.tcl
endif
==============================================================================
9. Dynamic loading *tcl-dynamic*
On MS-Windows the Tcl library can be loaded dynamically. The |:version|
output then includes |+tcl/dyn|.
This means that Vim will search for the Tcl DLL file only when needed. When
you don't use the Tcl interface you don't need it, thus you can use Vim
without this DLL file.
To use the Tcl interface the Tcl DLL must be in your search path. In a
console window type "path" to see what directories are used.
The name of the DLL must match the Tcl version Vim was compiled with.
Currently the name is "tcl83.dll". That is for Tcl 8.3. To know for sure
edit "gvim.exe" and search for "tcl\d*.dll\c".
==============================================================================
top - main help file
*:ws* *:wsverb*
:ws[verb] verb Pass the verb to the verb executor
Pass the verb to a workshop function which gathers some arguments and
sends the verb and data to workshop over an IPC connection.
==============================================================================
3. Compiling vim/gvim for WorkShop *workshop-compiling*
Compiling vim with FEAT_SUN_WORKSHOP turns on all compile time flags necessary
for building a vim to work with Visual WorkShop. The features required for VWS
have been built and tested using the Sun compilers from the VWS release. They
have not been built or tested using Gnu compilers. This does not mean the
features won't build and run if compiled with gcc, just that nothing is
guaranteed with gcc!
==============================================================================
4. Configuring gvim for a WorkShop release tree *workshop-configure*
There are several assumptions which must be met in order to compile a gvim for
use with Sun Visual WorkShop 6.
o You should use the compiler in VWS rather than gcc. We have neither
built nor tested with gcc and cannot guarantee it will build properly.
o You must supply your own XPM library. See |workshop-xpm| below for
details on obtaining the latest version of XPM.
o Edit the Makefile in the src directory and uncomment the lines for Sun
Visual WorkShop. You can easily find these by searching for the string
FEAT_SUN_WORKSHOP
o We also suggest you use Motif for your gui. This will provide gvim with
the same look-and-feel as the rest of Sun Visual WorkShop.
The following configuration line can be used to configure vim to build for use
with Sun Visual WorkShop:
$ CC=cc configure --enable-workshop --enable-gui=motif \
-prefix=<VWS-install-dir>/contrib/contrib6/<vim-version>
The VWS-install-dir should be the base directory where your Sun Visual WorkShop
was installed. By default this is /opt/SUNWspro. It will normally require
root permissions to install the vim release. You will also need to change the
symlink <VWS-install-dir>/bin/gvim to point to the vim in your newly installed
directory. The <vim-version> should be a unique version string. I use "vim"
concatenated with the equivalent of version.h's VIM_VERSION_SHORT.
==============================================================================
5. Obtaining the latest version of the XPM library *workshop-xpm*
The XPM library is required to show images within Vim with Motif or Athena.
Without it the toolbar and signs will be disabled.
The XPM library is provided by Arnaud Le Hors of the French National Institute
for Research in Computer Science and Control. It can be downloaded from
http://cgit.freedesktop.org/xorg/lib/libXpm. The current release, as of this
writing, is xpm-3.4k-solaris.tgz, which is a gzip'ed tar file. If you create
the directory /usr/local/xpm and untar the file there you can use the
uncommented lines in the Makefile without changing them. If you use another
xpm directory you will need to change the XPM_DIR in src/Makefile.
top - main help file
This chapter introduces the manuals available with Vim. Read this to know the
conditions under which the commands are explained.
|01.1| Two manuals
|01.2| Vim installed
|01.3| Using the Vim tutor
|01.4| Copyright
Next chapter: |usr_02.txt| The first steps in Vim
Table of contents: |usr_toc.txt|
==============================================================================
*01.1* Two manuals
The Vim documentation consists of two parts:
1. The User manual
Task oriented explanations, from simple to complex. Reads from start to
end like a book.
2. The Reference manual
Precise description of how everything in Vim works.
The notation used in these manuals is explained here: |notation|
JUMPING AROUND
The text contains hyperlinks between the two parts, allowing you to quickly
jump between the description of an editing task and a precise explanation of
the commands and options used for it. Use these two commands:
Press CTRL-] to jump to a subject under the cursor.
Press CTRL-O to jump back (repeat to go further back).
Many links are in vertical bars, like this: |bars|. The bars themselves may
be hidden or invisible, see below. An option name, like 'number', a command
in double quotes like ":write" and any other word can also be used as a link.
Try it out: Move the cursor to CTRL-] and press CTRL-] on it.
Other subjects can be found with the ":help" command, see |help.txt|.
The bars and stars are usually hidden with the |conceal| feature. They also
use |hl-Ignore|, using the same color for the text as the background. You can
make them visible with:
:set conceallevel=0
:hi link HelpBar Normal
:hi link HelpStar Normal
==============================================================================
*01.2* Vim installed
Most of the manuals assume that Vim has been properly installed. If you
didn't do that yet, or if Vim doesn't run properly (e.g., files can't be found
or in the GUI the menus do not show up) first read the chapter on
installation: |usr_90.txt|.
*not-compatible*
The manuals often assume you are using Vim with Vi-compatibility switched
off. For most commands this doesn't matter, but sometimes it is important,
e.g., for multi-level undo. An easy way to make sure you are using a nice
setup is to copy the example vimrc file. By doing this inside Vim you don't
have to check out where it is located. How to do this depends on the system
you are using:
Unix:
:!cp -i $VIMRUNTIME/vimrc_example.vim ~/.vimrc
MS-DOS, MS-Windows, OS/2:
:!copy $VIMRUNTIME/vimrc_example.vim $VIM/_vimrc
Amiga:
:!copy $VIMRUNTIME/vimrc_example.vim $VIM/.vimrc
If the file already exists you probably want to keep it.
If you start Vim now, the 'compatible' option should be off. You can check it
with this command:
:set compatible?
If it responds with "nocompatible" you are doing well. If the response is
"compatible" you are in trouble. You will have to find out why the option is
still set. Perhaps the file you wrote above is not found. Use this command
to find out:
:scriptnames
If your file is not in the list, check its location and name. If it is in the
list, there must be some other place where the 'compatible' option is switched
back on.
For more info see |vimrc| and |compatible-default|.
Note:
This manual is about using Vim in the normal way. There is an
alternative called "evim" (easy Vim). This is still Vim, but used in
a way that resembles a click-and-type editor like Notepad. It always
stays in Insert mode, thus it feels very different. It is not
explained in the user manual, since it should be mostly self
explanatory. See |evim-keys| for details.
==============================================================================
*01.3* Using the Vim tutor *tutor* *vimtutor*
Instead of reading the text (boring!) you can use the vimtutor to learn your
first Vim commands. This is a 30 minute tutorial that teaches the most basic
Vim functionality hands-on.
On Unix, if Vim has been properly installed, you can start it from the shell:
vimtutor
On MS-Windows you can find it in the Program/Vim menu. Or execute
vimtutor.bat in the $VIMRUNTIME directory.
This will make a copy of the tutor file, so that you can edit it without
the risk of damaging the original.
There are a few translated versions of the tutor. To find out if yours is
available, use the two-letter language code. For French:
vimtutor fr
On Unix, if you prefer using the GUI version of Vim, use "gvimtutor" or
"vimtutor -g" instead of "vimtutor".
For OpenVMS, if Vim has been properly installed, you can start vimtutor from a
VMS prompt with:
@VIM:vimtutor
Optionally add the two-letter language code as above.
1. Copy the tutor file. You can do this with Vim (it knows where to find it):
vim -u NONE -c 'e $VIMRUNTIME/tutor/tutor' -c 'w! TUTORCOPY' -c 'q'
This will write the file "TUTORCOPY" in the current directory. To use a
translated version of the tutor, append the two-letter language code to the
filename. For French:
vim -u NONE -c 'e $VIMRUNTIME/tutor/tutor.fr' -c 'w! TUTORCOPY' -c 'q'
2. Edit the copied file with Vim:
vim -u NONE -c "set nocp" TUTORCOPY
The extra arguments make sure Vim is started in a good mood.
3. Delete the copied file when you are finished with it:
del TUTORCOPY
==============================================================================
*01.4* Copyright *manual-copyright*
The Vim user manual and reference manual are Copyright (c) 1988-2003 by Bram
Moolenaar. This material may be distributed only subject to the terms and
conditions set forth in the Open Publication License, v1.0 or later. The
latest version is presently available at:
http://www.opencontent.org/openpub/
People who contribute to the manuals must agree with the above copyright
notice.
*frombook*
Parts of the user manual come from the book "Vi IMproved - Vim" by Steve
Oualline (published by New Riders Publishing, ISBN: 0735710015). The Open
Publication License applies to this book. Only selected parts are included
and these have been modified (e.g., by removing the pictures, updating the
text for Vim 6.0 and later, fixing mistakes). The omission of the |frombook|
tag does not mean that the text does not come from the book.
Many thanks to Steve Oualline and New Riders for creating this book and
publishing it under the OPL! It has been a great help while writing the user
manual. Not only by providing literal text, but also by setting the tone and
style.
If you make money through selling the manuals, you are strongly encouraged to
donate part of the profit to help AIDS victims in Uganda. See |iccf|.
==============================================================================
Next chapter: |usr_02.txt| The first steps in Vim
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
VIM LICENSE
I) There are no restrictions on distributing unmodified copies of Vim except
that they must include this license text. You can also distribute
unmodified parts of Vim, likewise unrestricted except that they must
include this license text. You are also allowed to include executables
that you made from the unmodified Vim sources, plus your own usage
examples and Vim scripts.
II) It is allowed to distribute a modified (or extended) version of Vim,
including executables and/or source code, when the following four
conditions are met:
1) This license text must be included unmodified.
2) The modified Vim must be distributed in one of the following five ways:
a) If you make changes to Vim yourself, you must clearly describe in
the distribution how to contact you. When the maintainer asks you
(in any way) for a copy of the modified Vim you distributed, you
must make your changes, including source code, available to the
maintainer without fee. The maintainer reserves the right to
include your changes in the official version of Vim. What the
maintainer will do with your changes and under what license they
will be distributed is negotiable. If there has been no negotiation
then this license, or a later version, also applies to your changes.
The current maintainer is Bram Moolenaar <Bram@vim.org>. If this
changes it will be announced in appropriate places (most likely
vim.sf.net, www.vim.org and/or comp.editors). When it is completely
impossible to contact the maintainer, the obligation to send him
your changes ceases. Once the maintainer has confirmed that he has
received your changes they will not have to be sent again.
b) If you have received a modified Vim that was distributed as
mentioned under a) you are allowed to further distribute it
unmodified, as mentioned at I). If you make additional changes the
text under a) applies to those changes.
c) Provide all the changes, including source code, with every copy of
the modified Vim you distribute. This may be done in the form of a
context diff. You can choose what license to use for new code you
add. The changes and their license must not restrict others from
Note:
- If you are happy with Vim, please express that by reading the rest of this
file and consider helping needy children in Uganda.
- If you want to support further Vim development consider becoming a
|sponsor|. The money goes to Uganda anyway.
- According to Richard Stallman the Vim license is GNU GPL compatible.
A few minor changes have been made since he checked it, but that should not
make a difference.
- If you link Vim with a library that goes under the GNU GPL, this limits
further distribution to the GNU GPL. Also when you didn't actually change
anything in Vim.
- Once a change is included that goes under the GNU GPL, this forces all
further changes to also be made under the GNU GPL or a compatible license.
- If you distribute a modified version of Vim, you can include your name and
contact information with the "--with-modified-by" configure argument or the
MODIFIED_BY define.
==============================================================================
Kibaale Children's Centre *kcc* *Kibaale* *charity*
Kibaale Children's Centre (KCC) is located in Kibaale, a small town in the
south of Uganda, near Tanzania, in East Africa. The area is known as Rakai
District. The population is mostly farmers. Although people are poor, there
is enough food. But this district is suffering from AIDS more than any other
part of the world. Some say that it started there. Estimations are that 10
to 30% of the Ugandans are infected with HIV. Because parents die, there are
many orphans. In this district about 60,000 children have lost one or both
parents, out of a population of 350,000. And this is still continuing.
The children need a lot of help. The KCC is working hard to provide the needy
with food, medical care and education. Food and medical care to keep them
healthy now, and education so that they can take care of themselves in the
future. KCC works on a Christian base, but help is given to children of any
religion.
The key to solving the problems in this area is education. This has been
neglected in the past years with president Idi Amin and the following civil
wars. Now that the government is stable again, the children and parents have
to learn how to take care of themselves and how to avoid infections. There is
also help for people who are ill and hungry, but the primary goal is to
prevent people from getting ill and to teach them how to grow healthy food.
Most of the orphans are living in an extended family. An uncle or older
sister is taking care of them. Because these families are big and the income
(if any) is low, a child is lucky if it gets healthy food. Clothes, medical
care and schooling is beyond its reach. To help these needy children, a
sponsorship program was put into place. A child can be financially adopted.
For a few dollars a month KCC sees to it that the child gets indispensable
items, is healthy, goes to school and KCC takes care of anything else that
needs to be done for the child and the family that supports it.
Besides helping the child directly, the environment where the child grows up
needs to be improved. KCC helps schools to improve their teaching methods.
There is a demonstration school at the centre and teacher trainings are given.
Health workers are being trained, hygiene education is carried out and
households are stimulated to build a proper latrine. I helped setting up a
production site for cement slabs. These are used to build a good latrine.
They are sold below cost price.
There is a small clinic at the project, which provides children and their
family with medical help. When needed, transport to a hospital is offered.
Immunization programs are carried out and help is provided when an epidemic is
breaking out (measles and cholera have been a problem).
*donate*
Summer 1994 to summer 1995 I spent a whole year at the centre, working as a
volunteer. I have helped to expand the centre and worked in the area of water
and sanitation. I learned that the help that the KCC provides really helps.
When I came back to Holland, I wanted to continue supporting KCC. To do this
I'm raising funds and organizing the sponsorship program. Please consider one
of these possibilities:
1. Sponsor a child in primary school: 17 euro a month (or more).
2. Sponsor a child in secondary school: 25 euro a month (or more).
3. Sponsor the clinic: Any amount a month or quarter
4. A one-time donation
Compared with other organizations that do child sponsorship the amounts are
very low. This is because the money goes directly to the centre. Less than
5% is used for administration. This is possible because this is a small
organization that works with volunteers. If you would like to sponsor a
child, you should have the intention to do this for at least one year.
How do you know that the money will be spent right? First of all you have my
personal guarantee as the author of Vim. I trust the people that are working
at the centre, I know them personally. Further more, the centre has been
co-sponsored and inspected by World Vision, Save the Children Fund and is now
under the supervision of Pacific Academy Outreach Society. The centre is
visited about once a year to check the progress (at our own cost). I have
visited the centre myself many times, starting in 1993. The visit reports are
on the ICCF web site.
If you have any further questions, send me e-mail: <Bram@vim.org>.
The address of the centre is:
Kibaale Children's Centre
p.o. box 1658
Masaka, Uganda, East Africa
Vim should make it easy for users to work in their preferred styles rather
than coercing its users into particular patterns of work. This can be for
items with a large impact (e.g., the 'compatible' option) or for details. The
defaults are carefully chosen such that most users will enjoy using Vim as it
is. Commands and options can be used to adjust Vim to the desire of the user
and its environment.
NAMES *style-names*
Function names can not be more than 31 characters long (because of VMS).
Don't use "delete" as a variable name, C++ doesn't like it.
Because of the requirement that Vim runs on as many systems as possible, we
need to avoid using names that are already defined by the system. This is a
list of names that are known to cause trouble. The name is given as a regexp
pattern.
is.*() POSIX, ctype.h
to.*() POSIX, ctype.h
VARIOUS *style-various*
Typedef'ed names should end in "_T":
typedef int some_T;
Define'ed names should be uppercase:
#define SOME_THING
Features always start with "FEAT_":
#define FEAT_FOO
Don't use '\"', some compilers can't handle it. '"'' works fine.
Don't use:
#if HAVE_SOME
Some compilers can't handle that and complain that "HAVE_SOME" is not defined.
Use
#ifdef HAVE_SOME
or
#if defined(HAVE_SOME)
STYLE *style-examples*
General rule: One statement per line.
Wrong: if (cond) a = 1;
OK: if (cond)
a = 1;
Wrong: while (cond);
OK: while (cond)
;
Wrong: do a = 1; while (cond);
OK: do
a = 1;
while (cond);
Word frequency
For sorting suggestions it helps to know which words are common. In theory we
could store a word frequency with the word in the dictionary. However, this
requires storing a count per word. That degrades word tree compression a lot.
And maintaining the word frequency for all languages will be a heavy task.
Also, it would be nice to prefer words that are already in the text. This way
the words that appear in the specific text are preferred for suggestions.
What has been implemented is to count words that have been seen during
displaying. A hashtable is used to quickly find the word count. The count is
initialized from words listed in COMMON items in the affix file, so that it
also works when starting a new file.
This isn't ideal, because the longer Vim is running the higher the counts
become. But in practice it is a noticeable improvement over not using the word
count.
==============================================================================
4. Assumptions *design-assumptions*
Size of variables:
char 8 bit signed
char_u 8 bit unsigned
int 32 or 64 bit signed (16 might be possible with limited features)
unsigned 32 or 64 bit unsigned (16 as with ints)
long 32 or 64 bit signed, can hold a pointer
Note that some compilers cannot handle long lines or strings. The C89
standard specifies a limit of 509 characters.
top - main help file
Reference manual
|reference_toc| More detailed information for all commands
The user manual is available as a single, ready to print HTML and PDF file
here:
http://vimdoc.sf.net
==============================================================================
Getting Started
Read this from start to end to learn the essential commands.
This chapter provides just enough information to edit a file with Vim. Not
well or fast, but you can edit. Take some time to practice with these
commands, they form the base for what follows.
|02.1| Running Vim for the First Time
|02.2| Inserting text
|02.3| Moving around
|02.4| Deleting characters
|02.5| Undo and Redo
|02.6| Other editing commands
|02.7| Getting out
|02.8| Finding help
Next chapter: |usr_03.txt| Moving around
Previous chapter: |usr_01.txt| About the manuals
Table of contents: |usr_toc.txt|
==============================================================================
*02.1* Running Vim for the First Time
To start Vim, enter this command:
gvim file.txt
In UNIX you can type this at any command prompt. If you are running Microsoft
Windows, open an MS-DOS prompt window and enter the command.
In either case, Vim starts editing a file called file.txt. Because this
is a new file, you get a blank window. This is what your screen will look
like:
+---------------------------------------+
|# |
|~ |
|~ |
|~ |
|~ |
|"file.txt" [New file] |
+---------------------------------------+
('#" is the cursor position.)
The tilde (~) lines indicate lines not in the file. In other words, when Vim
runs out of file to display, it displays tilde lines. At the bottom of the
screen, a message line indicates the file is named file.txt and shows that you
are creating a new file. The message information is temporary and other
information overwrites it.
running inside an xterm, the editor uses your xterm window. If you are using
an MS-DOS command prompt window under Microsoft Windows, the editing occurs
inside this window. The text in the window will look the same for both
versions, but with gvim you have extra features, like a menu bar. More about
that later.
==============================================================================
*02.2* Inserting text
The Vim editor is a modal editor. That means that the editor behaves
differently, depending on which mode you are in. The two basic modes are
called Normal mode and Insert mode. In Normal mode the characters you type
are commands. In Insert mode the characters are inserted as text.
Since you have just started Vim it will be in Normal mode. To start Insert
mode you type the "i" command (i for Insert). Then you can enter
the text. It will be inserted into the file. Do not worry if you make
mistakes; you can correct them later. To enter the following programmer's
limerick, this is what you type:
iA very intelligent turtle
Found programming UNIX a hurdle
After typing "turtle" you press the <Enter> key to start a new line. Finally
you press the <Esc> key to stop Insert mode and go back to Normal mode. You
now have two lines of text in your Vim window:
+---------------------------------------+
|A very intelligent turtle |
|Found programming UNIX a hurdle |
|~ |
|~ |
| |
+---------------------------------------+
h left *hjkl*
j down
k up
l right
At first, it may appear that these commands were chosen at random. After all,
who ever heard of using l for right? But actually, there is a very good
reason for these choices: Moving the cursor is the most common thing you do in
an editor, and these keys are on the home row of your right hand. In other
words, these commands are placed where you can type them the fastest
(especially when you type with ten fingers).
Note:
You can also move the cursor by using the arrow keys. If you do,
however, you greatly slow down your editing because to press the arrow
keys, you must move your hand from the text keys to the arrow keys.
Considering that you might be doing it hundreds of times an hour, this
can take a significant amount of time.
Also, there are keyboards which do not have arrow keys, or which
locate them in unusual places; therefore, knowing the use of the hjkl
keys helps in those situations.
One way to remember these commands is that h is on the left, l is on the
right and j points down. In a picture:
k
h l
j
The best way to learn these commands is by using them. Use the "i" command to
insert some more lines of text. Then use the hjkl keys to move around and
insert a word somewhere. Don't forget to press <Esc> to go back to Normal
mode. The |vimtutor| is also a nice way to learn by doing.
For Japanese users, Hiroshi Iwatani suggested using this:
Komsomolsk
^
|
Huan Ho <--- ---> Los Angeles
(Yellow river) |
v
Java (the island, not the programming language)
==============================================================================
*02.4* Deleting characters
To delete a character, move the cursor over it and type "x". (This is a
throwback to the old days of the typewriter, when you deleted things by typing
xxxx over them.) Move the cursor to the beginning of the first line, for
example, and type xxxxxxx (seven x's) to delete "A very ". The result should
look like this:
+---------------------------------------+
|intelligent turtle |
|Found programming UNIX a hurdle |
|~ |
|~ |
| |
+---------------------------------------+
Now you can insert new text, for example by typing:
iA young <Esc>
This begins an insert (the i), inserts the words "A young", and then exits
insert mode (the final <Esc>). The result:
+---------------------------------------+
|A young intelligent turtle |
|Found programming UNIX a hurdle |
|~ |
|~ |
| |
+---------------------------------------+
DELETING A LINE
To delete a whole line use the "dd" command. The following line will
then move up to fill the gap:
+---------------------------------------+
|Found programming UNIX a hurdle |
|~ |
|~ |
|~ |
| |
+---------------------------------------+
REDO
If you undo too many times, you can press CTRL-R (redo) to reverse the
preceding command. In other words, it undoes the undo. To see this in
action, press CTRL-R twice. The character A and the space after it disappear:
young intelligent turtle
There's a special version of the undo command, the "U" (undo line) command.
The undo line command undoes all the changes made on the last line that was
edited. Typing this command twice cancels the preceding "U".
A very intelligent turtle
xxxx Delete very
A intelligent turtle
xxxxxx Delete turtle
A intelligent
Restore line with "U"
A very intelligent turtle
Undo "U" with "u"
A intelligent
The "U" command is a change by itself, which the "u" command undoes and CTRL-R
redoes. This might be a bit confusing. Don't worry, with "u" and CTRL-R you
can go to any of the situations you had. More about that in section |32.2|.
==============================================================================
*02.6* Other editing commands
Vim has a large number of commands to change the text. See |Q_in| and below.
Here are a few often used ones.
APPENDING
The "i" command inserts a character before the character under the cursor.
That works fine; but what happens if you want to add stuff to the end of the
line? For that you need to insert text after the cursor. This is done with
the "a" (append) command.
For example, to change the line
and that's not saying much for the turtle.
to
and that's not saying much for the turtle!!!
move the cursor over to the dot at the end of the line. Then type "x" to
delete the period. The cursor is now positioned at the end of the line on the
e in turtle. Now type
a!!!<Esc>
to append three exclamation points after the e in turtle:
and that's not saying much for the turtle!!!
USING A COUNT
Suppose you want to move up nine lines. You can type "kkkkkkkkk" or you can
enter the command "9k". In fact, you can precede many commands with a number.
Earlier in this chapter, for instance, you added three exclamation points to
the end of a line by typing "a!!!<Esc>". Another way to do this is to use the
command "3a!<Esc>". The count of 3 tells the command that follows to triple
its effect. Similarly, to delete three characters, use the command "3x". The
count always comes before the command it applies to.
==============================================================================
*02.7* Getting out
To exit, use the "ZZ" command. This command writes the file and exits.
Note:
Unlike many other editors, Vim does not automatically make a backup
file. If you type "ZZ", your changes are committed and there's no
turning back. You can configure the Vim editor to produce backup
files, see |07.4|.
DISCARDING CHANGES
Sometimes you will make a sequence of changes and suddenly realize you were
better off before you started. Not to worry; Vim has a
quit-and-throw-things-away command. It is:
:q!
Don't forget to press <Enter> to finish the command.
For those of you interested in the details, the three parts of this command
are the colon (:), which enters Command-line mode; the q command, which tells
the editor to quit; and the override command modifier (!).
The override command modifier is needed because Vim is reluctant to throw
away changes. If you were to just type ":q", Vim would display an error
message and refuse to exit:
E37: No write since last change (use ! to override)
By specifying the override, you are in effect telling Vim, "I know that what
I'm doing looks stupid, but I'm a big boy and really want to do this."
If you want to continue editing with Vim: The ":e!" command reloads the
original version of the file.
==============================================================================
*02.8* Finding help
Everything you always wanted to know can be found in the Vim help files.
Don't be afraid to ask!
To get generic help use this command:
:help
You could also use the first function key <F1>. If your keyboard has a <Help>
key it might work as well.
If you don't supply a subject, ":help" displays the general help window.
The creators of Vim did something very clever (or very lazy) with the help
system: They made the help window a normal editing window. You can use all
the normal Vim commands to move through the help information. Therefore h, j,
k, and l move left, down, up and right.
To get out of the help window, use the same command you use to get out of
the editor: "ZZ". This will only close the help window, not exit Vim.
As you read the help text, you will notice some text enclosed in vertical bars
(for example, |help|). This indicates a hyperlink. If you position the
cursor anywhere between the bars and press CTRL-] (jump to tag), the help
system takes you to the indicated subject. (For reasons not discussed here,
the Vim terminology for a hyperlink is tag. So CTRL-] jumps to the location
of the tag given by the word under the cursor.)
After a few jumps, you might want to go back. CTRL-T (pop tag) takes you
back to the preceding position. CTRL-O (jump to older position) also works
nicely here.
At the top of the help screen, there is the notation *help.txt*. This name
between "*" characters is used by the help system to define a tag (hyperlink
destination).
See |29.1| for details about using tags.
To get help on a given subject, use the following command:
:help {subject}
To get help on the "x" command, for example, enter the following:
:help x
To find out how to delete text, use this command:
:help deleting
To get a complete index of all Vim commands, use the following command:
:help index
When you need to get help for a control character command (for example,
CTRL-A), you need to spell it with the prefix "CTRL-".
:help CTRL-A
The Vim editor has many different modes. By default, the help system displays
the normal-mode commands. For example, the following command displays help
for the normal-mode CTRL-H command:
:help CTRL-H
To identify other modes, use a mode prefix. If you want the help for the
insert-mode version of a command, use "i_". For CTRL-H this gives you the
following command:
:help i_CTRL-H
When you start the Vim editor, you can use several command-line arguments.
These all begin with a dash (-). To find what the -t argument does, for
example, use the command:
:help -t
The Vim editor has a number of options that enable you to configure and
customize the editor. If you want help for an option, you need to enclose it
in single quotation marks. To find out what the 'number' option does, for
example, use the following command:
:help 'number'
The table with all mode prefixes can be found here: |help-context|.
Special keys are enclosed in angle brackets. To find help on the up-arrow key
in Insert mode, for instance, use this command:
:help i_<Up>
If you see an error message that you don't understand, for example:
E37: No write since last change (use ! to override)
You can use the error ID at the start to find help about it:
:help E37
Summary: *help-summary*
:help
Gives you very general help. Scroll down to see a list of all
helpfiles, including those added locally (i.e. not distributed
with Vim).
:help user-toc.txt
Table of contents of the User Manual.
:help :subject
Ex-command "subject", for instance the following:
:help :help
Help on getting help.
:help abc
normal-mode command "abc".
:help CTRL-B
Control key <C-B> in Normal mode.
:help i_abc
:help i_CTRL-B
The same in Insert mode.
:help v_abc
:help v_CTRL-B
The same in Visual mode.
:help c_abc
:help c_CTRL-B
The same in Command-line mode.
:help 'subject'
Option 'subject'.
:help subject()
Function "subject".
:help -subject
==============================================================================
Next chapter: |usr_03.txt| Moving around
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
Before you can insert or delete text the cursor has to be moved to the right
place. Vim has a large number of commands to position the cursor. This
chapter shows you how to use the most important ones. You can find a list of
these commands below |Q_lr|.
|03.1| Word movement
|03.2| Moving to the start or end of a line
|03.3| Moving to a character
|03.4| Matching a parenthesis
|03.5| Moving to a specific line
|03.6| Telling where you are
|03.7| Scrolling around
|03.8| Simple searches
|03.9| Simple search patterns
|03.10| Using marks
Next chapter: |usr_04.txt| Making small changes
Previous chapter: |usr_02.txt| The first steps in Vim
Table of contents: |usr_toc.txt|
==============================================================================
*03.1* Word movement
To move the cursor forward one word, use the "w" command. Like most Vim
commands, you can use a numeric prefix to move past multiple words. For
example, "3w" moves three words. This figure shows how it works:
This is a line with example text
--->-->->----------------->
w w w 3w
Notice that "w" moves to the start of the next word if it already is at the
start of a word.
The "b" command moves backward to the start of the previous word:
This is a line with example text
<----<--<-<---------<---
b b b 2b b
There is also the "e" command that moves to the next end of a word and "ge",
which moves to the previous end of a word:
This is a line with example text
<- <--- -----> ---->
ge ge e e
If you are at the last word of a line, the "w" command will take you to the
first word in the next line. Thus you can use this to move through a
paragraph, much faster than using "l". "b" does the same in the other
direction.
A word ends at a non-word character, such as a ".", "-" or ")". To change
what Vim considers to be a word, see the 'iskeyword' option.
It is also possible to move by white-space separated WORDs. This is not a
word in the normal sense, that's why the uppercase is used. The commands for
Sometimes you will start a search, only to realize that you have typed the
wrong command. You type "f" to search backward, for example, only to realize
that you really meant "F". To abort a search, press <Esc>. So "f<Esc>" is an
aborted forward search and doesn't do anything. Note: <Esc> cancels most
operations, not just searches.
==============================================================================
*03.4* Matching a parenthesis
When writing a program you often end up with nested () constructs. Then the
"%" command is very handy: It moves to the matching paren. If the cursor is
on a "(" it will move to the matching ")". If it's on a ")" it will move to
the matching "(".
%
<----->
if (a == (b * c) / d)
<---------------->
%
This also works for [] and {} pairs. (This can be defined with the
'matchpairs' option.)
When the cursor is not on a useful character, "%" will search forward to find
one. Thus if the cursor is at the start of the line of the previous example,
"%" will search forward and find the first "(". Then it moves to its match:
if (a == (b * c) / d)
---+---------------->
%
==============================================================================
*03.5* Moving to a specific line
If you are a C or C++ programmer, you are familiar with error messages such as
the following:
prog.c:33: j undeclared (first use in this function)
This tells you that you might want to fix something on line 33. So how do you
find line 33? One way is to do "9999k" to go to the top of the file and "32j"
to go down thirty two lines. It is not a good way, but it works. A much
better way of doing things is to use the "G" command. With a count, this
command positions you at the given line number. For example, "33G" puts you
on line 33. (For a better way of going through a compiler's error list, see
|usr_30.txt|, for information on the :make command.)
With no argument, "G" positions you at the end of the file. A quick way to
go to the start of a file use "gg". "1G" will do the same, but is a tiny bit
more typing.
| first line of a file ^
| text text text text |
| text text text text | gg
7G | text text text text |
| text text text text
| text text text text
V text text text text |
text text text text | G
text text text text |
last line of a file V
Another way to move to a line is using the "%" command with a count. For
example "50%" moves you to halfway the file. "90%" goes to near the end.
The previous assumes that you want to move to a line in the file, no matter if
it's currently visible or not. What if you want to move to one of the lines
you can see? This figure shows the three commands you can use:
+---------------------------+
H --> | text sample text |
| sample text |
| text sample text |
| sample text |
M --> | text sample text |
| sample text |
| text sample text |
| sample text |
L --> | text sample text |
+---------------------------+
Hints: "H" stands for Home, "M" for Middle and "L" for Last.
==============================================================================
*03.6* Telling where you are
To see where you are in a file, there are three ways:
1. Use the CTRL-G command. You get a message like this (assuming the 'ruler'
option is off):
"usr_03.txt" line 233 of 650 --35%-- col 45-52
This shows the name of the file you are editing, the line number where the
cursor is, the total number of lines, the percentage of the way through
the file and the column of the cursor.
Sometimes you will see a split column number. For example, "col 2-9".
This indicates that the cursor is positioned on the second character, but
because character one is a tab, occupying eight spaces worth of columns,
the screen column is 9.
2. Set the 'number' option. This will display a line number in front of
every line:
:set number
To switch this off again:
:set nonumber
Since 'number' is a boolean option, prepending "no" to its name has the
effect of switching it off. A boolean option has only these two values,
it is either on or off.
Vim has many options. Besides the boolean ones there are options with
a numerical value and string options. You will see examples of this where
they are used.
3. Set the 'ruler' option. This will display the cursor position in the
lower right corner of the Vim window:
:set ruler
Using the 'ruler' option has the advantage that it doesn't take much room,
thus there is more space for your text.
==============================================================================
*03.7* Scrolling around
The CTRL-U command scrolls down half a screen of text. Think of looking
through a viewing window at the text and moving this window up by half the
height of the window. Thus the window moves up over the text, which is
backward in the file. Don't worry if you have a little trouble remembering
which end is up. Most users have the same problem.
The CTRL-D command moves the viewing window down half a screen in the file,
thus scrolls the text up half a screen.
+----------------+
| some text |
| some text |
| some text |
+---------------+ | some text |
| some text | CTRL-U --> | |
| | | 123456 |
| 123456 | +----------------+
| 7890 |
| | +----------------+
| example | CTRL-D --> | 7890 |
+---------------+ | |
| example |
| example |
| example |
| example |
+----------------+
To scroll one line at a time use CTRL-E (scroll up) and CTRL-Y (scroll down).
Think of CTRL-E to give you one line Extra. (If you use MS-Windows compatible
key mappings CTRL-Y will redo a change instead of scroll.)
To scroll forward by a whole screen (except for two lines) use CTRL-F. The
other way is backward, CTRL-B is the command to use. Fortunately CTRL-F is
Forward and CTRL-B is Backward, that's easy to remember.
A common issue is that after moving down many lines with "j" your cursor is at
the bottom of the screen. You would like to see the context of the line with
the cursor. That's done with the "zz" command.
+------------------+ +------------------+
| some text | | some text |
| some text | | some text |
| some text | | some text |
| some text | zz --> | line with cursor |
| some text | | some text |
| some text | | some text |
| line with cursor | | some text |
+------------------+ +------------------+
The "zt" command puts the cursor line at the top, "zb" at the bottom. There
are a few more scrolling commands, see |Q_sc|. To always keep a few lines of
context around the cursor, use the 'scrolloff' option.
==============================================================================
*03.8* Simple searches
To search for a string, use the "/string" command. To find the word include,
for example, use the command:
/include
You will notice that when you type the "/" the cursor jumps to the last line
of the Vim window, like with colon commands. That is where you type the word.
You can press the backspace key (backarrow or <BS>) to make corrections. Use
the <Left> and <Right> cursor keys when necessary.
Pressing <Enter> executes the command.
Note:
The characters .*[]^%/\?~$ have special meanings. If you want to use
them in a search you must put a \ in front of them. See below.
To find the next occurrence of the same string use the "n" command. Use this
to find the first #include after the cursor:
/#include
And then type "n" several times. You will move to each #include in the text.
You can also use a count if you know which match you want. Thus "3n" finds
the third match. Using a count with "/" doesn't work.
The "?" command works like "/" but searches backwards:
?word
The "N" command repeats the last search the opposite direction. Thus using
"N" after a "/" command search backwards, using "N" after "?" searches
forward.
IGNORING CASE
Normally you have to type exactly what you want to find. If you don't care
about upper or lowercase in a word, set the 'ignorecase' option:
:set ignorecase
If you now search for "word", it will also match "Word" and "WORD". To match
case again:
:set noignorecase
HISTORY
Suppose you do three searches:
/one
/two
/three
Now let's start searching by typing a simple "/" without pressing <Enter>. If
you press <Up> (the cursor key), Vim puts "/three" on the command line.
Pressing <Enter> at this point searches for three. If you do not press
<Enter>, but press <Up> instead, Vim changes the prompt to "/two". Another
press of <Up> moves you to "/one".
You can also use the <Down> cursor key to move through the history of
search commands in the other direction.
If you know what a previously used pattern starts with, and you want to use it
again, type that character before pressing <Up>. With the previous example,
you can type "/o<Up>" and Vim will put "/one" on the command line.
The commands starting with ":" also have a history. That allows you to recall
a previous command and execute it again. These two histories are separate.
HIGHLIGHTING MATCHES
While editing a program you see a variable called "nr". You want to check
where it's used. You could move the cursor to "nr" and use the "*" command
and press "n" to go along all the matches.
There is another way. Type this command:
:set hlsearch
If you now search for "nr", Vim will highlight all matches. That is a very
good way to see where the variable is used, without the need to type commands.
To switch this off:
:set nohlsearch
Then you need to switch it on again if you want to use it for the next search
command. If you only want to remove the highlighting, use this command:
:nohlsearch
This doesn't reset the option. Instead, it disables the highlighting. As
soon as you execute a search command, the highlighting will be used again.
Also for the "n" and "N" commands.
TUNING SEARCHES
There are a few options that change how searching works. These are the
essential ones:
:set incsearch
This makes Vim display the match for the string while you are still typing it.
Use this to check if the right match will be found. Then press <Enter> to
really jump to that location. Or type more to change the search string.
:set nowrapscan
This stops the search at the end of the file. Or, when you are searching
backwards, at the start of the file. The 'wrapscan' option is on by default,
thus searching wraps around the end of the file.
INTERMEZZO
If you like one of the options mentioned before, and set it each time you use
Vim, you can put the command in your Vim startup file.
Edit the file, as mentioned at |not-compatible|. Or use this command to
find out where it is:
:scriptnames
Edit the file, for example with:
:edit ~/.vimrc
Then add a line with the command to set the option, just like you typed it in
Vim. Example:
Go:set hlsearch<Esc>
"G" moves to the end of the file. "o" starts a new line, where you type the
":set" command. You end insert mode with <Esc>. Then write the file:
ZZ
If you now start Vim again, the 'hlsearch' option will already be set.
==============================================================================
*03.9* Simple search patterns
The Vim editor uses regular expressions to specify what to search for.
Regular expressions are an extremely powerful and compact way to specify a
search pattern. Unfortunately, this power comes at a price, because regular
expressions are a bit tricky to specify.
In this section we mention only a few essential ones. More about search
patterns and commands in chapter 27 |usr_27.txt|. You can find the full
explanation here: |pattern|.
| example text ^ |
33G | example text | CTRL-O | CTRL-I
| example text | |
V line 33 text ^ V
| example text | |
/^The | example text | CTRL-O | CTRL-I
V There you are | V
example text
Note:
CTRL-I is the same as <Tab>.
The ":jumps" command gives a list of positions you jumped to. The entry which
you used last is marked with a ">".
The command 'mark (single quotation mark, or apostrophe) moves you to the
beginning of the line containing the mark. This differs from the `mark
command, which moves you to marked column.
The marks can be very useful when working on two related parts in a file.
Suppose you have some text near the start of the file you need to look at,
while working on some text near the end of the file.
Move to the text at the start and place the s (start) mark there:
ms
Then move to the text you want to work on and put the e (end) mark there:
me
Now you can move around, and when you want to look at the start of the file,
you use this to jump there:
's
Then you can use '' to jump back to where you were, or 'e to jump to the text
you were working on at the end.
There is nothing special about using s for start and e for end, they are
just easy to remember.
You can use this command to get a list of marks:
:marks
You will notice a few special marks. These include:
'' The cursor position before doing a jump
" The cursor position when last editing the file
[ Start of the last change
] End of the last change
==============================================================================
Next chapter: |usr_04.txt| Making small changes
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
This chapter shows you several ways of making corrections and moving text
around. It teaches you the three basic ways to change text: operator-motion,
Visual mode and text objects.
|04.1| Operators and motions
|04.2| Changing text
|04.3| Repeating a change
|04.4| Visual mode
|04.5| Moving text
|04.6| Copying text
|04.7| Using the clipboard
|04.8| Text objects
|04.9| Replace mode
|04.10| Conclusion
Next chapter: |usr_05.txt| Set your settings
Previous chapter: |usr_03.txt| Moving around
Table of contents: |usr_toc.txt|
==============================================================================
*04.1* Operators and motions
In chapter 2 you learned the "x" command to delete a single character. And
using a count: "4x" deletes four characters.
The "dw" command deletes a word. You may recognize the "w" command as the
move word command. In fact, the "d" command may be followed by any motion
command, and it deletes from the current location to the place where the
cursor winds up.
The "4w" command, for example, moves the cursor over four words. The d4w
command deletes four words.
To err is human. To really foul up you need a computer.
------------------>
d4w
To err is human. you need a computer.
Vim only deletes up to the position where the motion takes the cursor. That's
because Vim knows that you probably don't want to delete the first character
of a word. If you use the "e" command to move to the end of a word, Vim
guesses that you do want to include that last character:
To err is human. you need a computer.
-------->
d2e
To err is human. a computer.
Whether the character under the cursor is included depends on the command you
used to move to that character. The reference manual calls this "exclusive"
when the character isn't included and "inclusive" when it is.
The "$" command moves to the end of a line. The "d$" command deletes from the
cursor to the end of the line. This is an inclusive motion, thus the last
character of the line is included in the delete operation:
MORE CHANGES
Like "dd" deletes a whole line, "cc" changes a whole line. It keeps the
existing indent (leading white space) though.
Just like "d$" deletes until the end of the line, "c$" changes until the end
of the line. It's like doing "d$" to delete the text and then "a" to start
Insert mode and append new text.
SHORTCUTS
Some operator-motion commands are used so often that they have been given a
single letter command:
x stands for dl (delete character under the cursor)
X stands for dh (delete character left of the cursor)
D stands for d$ (delete to end of the line)
C stands for c$ (change to end of the line)
s stands for cl (change one character)
S stands for cc (change a whole line)
SELECTING LINES
If you want to work on whole lines, use "V" to start Visual mode. You will
see right away that the whole line is highlighted, without moving around.
When you move left or right nothing changes. When you move up or down the
selection is extended whole lines at a time.
For example, select three lines with "Vjj":
+------------------------+
| text more text |
>> | more text more text | |
selected lines >> | text text text | | Vjj
>> | text more | V
| more text more |
+------------------------+
SELECTING BLOCKS
If you want to work on a rectangular block of characters, use CTRL-V to start
Visual mode. This is very useful when working on tables.
name Q1 Q2 Q3
pierre 123 455 234
john 0 90 39
steve 392 63 334
To delete the middle "Q2" column, move the cursor to the "Q" of "Q2". Press
CTRL-V to start blockwise Visual mode. Now move the cursor three lines down
with "3j" and to the next word with "w". You can see the first character of
the last column is included. To exclude it, use "h". Now press "d" and the
middle column is gone.
MORE ON PUTTING
The "P" command puts text like "p", but before the cursor. When you deleted a
whole line with "dd", "P" will put it back above the cursor. When you deleted
a word with "dw", "P" will put it back just before the cursor.
You can repeat putting as many times as you like. The same text will be used.
You can use a count with "p" and "P". The text will be repeated as many times
as specified with the count. Thus "dd" and then "3p" puts three copies of the
same deleted line.
If you are not using the GUI, or if you don't like using a menu, you have to
use another way. You use the normal "y" (yank) and "p" (put) commands, but
prepend "* (double-quote star) before it. To copy a line to the clipboard:
"*yy
To put text from the clipboard back into the text:
"*p
This only works on versions of Vim that include clipboard support. More about
the clipboard in section |09.3| and here: |clipboard|.
==============================================================================
*04.8* Text objects
If the cursor is in the middle of a word and you want to delete that word, you
need to move back to its start before you can do "dw". There is a simpler way
to do this: "daw".
this is some example text.
daw
this is some text.
The "d" of "daw" is the delete operator. "aw" is a text object. Hint: "aw"
stands for "A Word". Thus "daw" is "Delete A Word". To be precise, the white
space after the word is also deleted (the white space before the word at the
end of the line).
Using text objects is the third way to make changes in Vim. We already had
operator-motion and Visual mode. Now we add operator-text object.
It is very similar to operator-motion, but instead of operating on the text
between the cursor position before and after a movement command, the text
object is used as a whole. It doesn't matter where in the object the cursor
was.
To change a whole sentence use "cis". Take this text:
Hello there. This
is an example. Just
some text.
Move to the start of the second line, on "is an". Now use "cis":
Hello there. Just
some text.
The cursor is in between the blanks in the first line. Now you type the new
sentence "Another line.":
Hello there. Another line. Just
some text.
"cis" consists of the "c" (change) operator and the "is" text object. This
stands for "Inner Sentence". There is also the "as" (a sentence) object. The
difference is that "as" includes the white space after the sentence and "is"
doesn't. If you would delete a sentence, you want to delete the white space
at the same time, thus use "das". If you want to type new text the white
space can remain, thus you use "cis".
You can also use text objects in Visual mode. It will include the text object
in the Visual selection. Visual mode continues, thus you can do this several
times. For example, start Visual mode with "v" and select a sentence with
"as". Now you can repeat "as" to include more sentences. Finally you use an
operator to do something with the selected sentences.
You can find a long list of text objects here: |text-objects|.
==============================================================================
*04.9* Replace mode
The "R" command causes Vim to enter replace mode. In this mode, each
character you type replaces the one under the cursor. This continues until
you type <Esc>.
In this example you start Replace mode on the first "t" of "text":
This is text.
Rinteresting.<Esc>
This is interesting.
You may have noticed that this command replaced 5 characters in the line with
twelve others. The "R" command automatically extends the line if it runs out
of characters to replace. It will not continue on the next line.
You can switch between Insert mode and Replace mode with the <Insert> key.
When you use <BS> (backspace) to make correction, you will notice that the
old text is put back. Thus it works like an undo command for the last typed
character.
==============================================================================
*04.10* Conclusion
The operators, movement commands and text objects give you the possibility to
make lots of combinations. Now that you know how it works, you can use N
operators with M movement commands to make N * M commands!
You can find a list of operators here: |operator|
For example, there are many other ways to delete pieces of text. Here are a
few often used ones:
x delete character under the cursor (short for "dl")
X delete character before the cursor (short for "dh")
D delete from cursor to end of line (short for "d$")
dw delete from cursor to next start of word
db delete from cursor to previous start of word
diw delete word under the cursor (excluding white space)
daw delete word under the cursor (including white space)
dG delete until the end of the file
dgg delete until the start of the file
If you use "c" instead of "d" they become change commands. And with "y" you
yank the text. And so forth.
There are a few often used commands to make changes that didn't fit somewhere
else:
~ change case of the character under the cursor, and move the
cursor to the next character. This is not an operator (unless
'tildeop' is set), thus you can't use it with a motion
command. It does work in Visual mode and changes case for
all the selected text then.
I Start Insert mode after moving the cursor to the first
non-blank in the line.
A Start Insert mode after moving the cursor to the end of the
line.
==============================================================================
Next chapter: |usr_05.txt| Set your settings
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
Black and white text is boring. With colors your file comes to life. This
not only looks nice, it also speeds up your work. Change the colors used for
the different sorts of text. Print your text, with the colors you see on the
screen.
|06.1| Switching it on
|06.2| No or wrong colors?
|06.3| Different colors
|06.4| With colors or without colors
|06.5| Printing with colors
|06.6| Further reading
Next chapter: |usr_07.txt| Editing more than one file
Previous chapter: |usr_05.txt| Set your settings
Table of contents: |usr_toc.txt|
==============================================================================
*06.1* Switching it on
It all starts with one simple command:
:syntax enable
That should work in most situations to get color in your files. Vim will
automagically detect the type of file and load the right syntax highlighting.
Suddenly comments are blue, keywords brown and strings red. This makes it
easy to overview the file. After a while you will find that black&white text
slows you down!
If you always want to use syntax highlighting, put the ":syntax enable"
command in your |vimrc| file.
If you want syntax highlighting only when the terminal supports colors, you
can put this in your |vimrc| file:
if &t_Co > 1
syntax enable
endif
If you want syntax highlighting only in the GUI version, put the ":syntax
enable" command in your |gvimrc| file.
==============================================================================
*06.2* No or wrong colors?
There can be a number of reasons why you don't see colors:
- Your terminal does not support colors.
Vim will use bold, italic and underlined text, but this doesn't look
very nice. You probably will want to try to get a terminal with
colors. For Unix, I recommend the xterm from the XFree86 project:
|xfree-xterm|.
- Your terminal does support colors, but Vim doesn't know this.
Make sure your $TERM setting is correct. For example, when using an
xterm that supports colors:
setenv TERM xterm-color
or (depending on your shell):
TERM=xterm-color; export TERM
The terminal name must match the terminal you are using. If it
still doesn't work, have a look at |xterm-color|, which shows a few
ways to make Vim display colors (not only for an xterm).
- The file type is not recognized.
Vim doesn't know all file types, and sometimes it's near to impossible
to tell what language a file uses. Try this command:
:set filetype
If the result is "filetype=" then the problem is indeed that Vim
doesn't know what type of file this is. You can set the type
manually:
:set filetype=fortran
To see which types are available, look in the directory
$VIMRUNTIME/syntax. For the GUI you can use the Syntax menu.
Setting the filetype can also be done with a |modeline|, so that the
file will be highlighted each time you edit it. For example, this
line can be used in a Makefile (put it near the start or end of the
file):
# vim: syntax=make
You might know how to detect the file type yourself. Often the file
name extension (after the dot) can be used.
See |new-filetype| for how to tell Vim to detect that file type.
- There is no highlighting for your file type.
You could try using a similar file type by manually setting it as
mentioned above. If that isn't good enough, you can write your own
syntax file, see |mysyntaxfile|.
:colorscheme evening
"evening" is the name of the color scheme. There are several others you might
want to try out. Look in the directory $VIMRUNTIME/colors.
When you found the color scheme that you like, add the ":colorscheme" command
to your |vimrc| file.
You could also write your own color scheme. This is how you do it:
1. Select a color scheme that comes close. Copy this file to your own Vim
directory. For Unix, this should work:
!mkdir ~/.vim/colors
!cp $VIMRUNTIME/colors/morning.vim ~/.vim/colors/mine.vim
This is done from Vim, because it knows the value of $VIMRUNTIME.
2. Edit the color scheme file. These entries are useful:
term attributes in a B&W terminal
cterm attributes in a color terminal
ctermfg foreground color in a color terminal
ctermbg background color in a color terminal
gui attributes in the GUI
guifg foreground color in the GUI
guibg background color in the GUI
For example, to make comments green:
:highlight Comment ctermfg=green guifg=green
Attributes you can use for "cterm" and "gui" are "bold" and "underline".
If you want both, use "bold,underline". For details see the |:highlight|
command.
3. Tell Vim to always use your color scheme. Put this line in your YXXYvimrc|:
colorscheme mine
If you want to see what the most often used color combinations look like, use
this command:
:runtime syntax/colortest.vim
You will see text in various color combinations. You can check which ones are
readable and look nice.
==============================================================================
*06.4* With colors or without colors
Displaying text in color takes a lot of effort. If you find the displaying
too slow, you might want to disable syntax highlighting for a moment:
:syntax clear
When editing another file (or the same one) the colors will come back.
*:syn-off*
If you want to stop highlighting completely use:
:syntax off
This will completely disable syntax highlighting and remove it immediately for
all buffers.
*:syn-manual*
If you want syntax highlighting only for specific files, use this:
:syntax manual
This will enable the syntax highlighting, but not switch it on automatically
when starting to edit a buffer. To switch highlighting on for the current
buffer, set the 'syntax' option:
:set syntax=ON
==============================================================================
*06.5* Printing with colors *syntax-printing*
In the MS-Windows version you can print the current file with this command:
:hardcopy
You will get the usual printer dialog, where you can select the printer and a
few settings. If you have a color printer, the paper output should look the
same as what you see inside Vim. But when you use a dark background the
colors will be adjusted to look good on white paper.
There are several options that change the way Vim prints:
'printdevice'
'printheader'
'printfont'
'printoptions'
To print only a range of lines, use Visual mode to select the lines and then
type the command:
v100j:hardcopy
"v" starts Visual mode. "100j" moves a hundred lines down, they will be
highlighted. Then ":hardcopy" will print those lines. You can use other
commands to move in Visual mode, of course.
This also works on Unix, if you have a PostScript printer. Otherwise, you
will have to do a bit more work. You need to convert the text to HTML first,
and then print it from a web browser.
Convert the current file to HTML with this command:
:TOhtml
In case that doesn't work:
:source $VIMRUNTIME/syntax/2html.vim
You will see it crunching away, this can take quite a while for a large file.
Some time later another window shows the HTML code. Now write this somewhere
(doesn't matter where, you throw it away later):
:write main.c.html
Open this file in your favorite browser and print it from there. If all goes
well, the output should look exactly as it does in Vim. See |2html.vim| for
details. Don't forget to delete the HTML file when you are done with it.
Instead of printing, you could also put the HTML file on a web server, and let
others look at the colored text.
==============================================================================
*06.6* Further reading
|usr_44.txt| Your own syntax highlighted.
|syntax| All the details.
==============================================================================
Next chapter: |usr_07.txt| Editing more than one file
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
No matter how many files you have, you can edit them without leaving Vim.
Define a list of files to work on and jump from one to the other. Copy text
from one file and put it in another one.
|07.1| Edit another file
|07.2| A list of files
|07.3| Jumping from file to file
|07.4| Backup files
|07.5| Copy text between files
|07.6| Viewing a file
|07.7| Changing the file name
Next chapter: |usr_08.txt| Splitting windows
Previous chapter: |usr_06.txt| Using syntax highlighting
Table of contents: |usr_toc.txt|
==============================================================================
*07.1* Edit another file
So far you had to start Vim for every file you wanted to edit. There is a
simpler way. To start editing another file, use this command:
:edit foo.txt
You can use any file name instead of "foo.txt". Vim will close the current
file and open the new one. If the current file has unsaved changes, however,
Vim displays an error message and does not open the new file:
E37: No write since last change (use ! to override)
Note:
Vim puts an error ID at the start of each error message. If you do
not understand the message or what caused it, look in the help system
for this ID. In this case:
:help E37
At this point, you have a number of alternatives. You can write the file
using this command:
:write
Or you can force Vim to discard your changes and edit the new file, using the
force (!) character:
:edit! foo.txt
If you want to edit another file, but not write the changes in the current
file yet, you can make it hidden:
:hide edit foo.txt
The text with changes is still there, but you can't see it. This is further
explained in section |22.4|: The buffer list.
==============================================================================
*07.2* A list of files
You can start Vim to edit a sequence of files. For example:
vim one.c two.c three.c
This command starts Vim and tells it that you will be editing three files.
Vim displays just the first file. After you have done your thing in this
file, to edit the next file you use this command:
:next
If you have unsaved changes in the current file, you will get an error
message and the ":next" will not work. This is the same problem as with
":edit" mentioned in the previous section. To abandon the changes:
:next!
But mostly you want to save the changes and move on to the next file. There
is a special command for this:
:wnext
This does the same as using two separate commands:
:write
:next
WHERE AM I?
To see which file in the argument list you are editing, look in the window
title. It should show something like "(2 of 3)". This means you are editing
the second file out of three files.
If you want to see the list of files, use this command:
:args
This is short for "arguments". The output might look like this:
one.c [two.c] three.c
These are the files you started Vim with. The one you are currently editing,
"two.c", is in square brackets.
AUTOMATIC WRITING
When moving around the files and making changes, you have to remember to use
":write". Otherwise you will get an error message. If you are sure you
always want to write modified files, you can tell Vim to automatically write
them:
:set autowrite
When you are editing a file which you may not want to write, switch it off
again:
:set noautowrite
PREDEFINED MARKS
After jumping to another file, you can use two predefined marks which are very
useful:
`"
This takes you to the position where the cursor was when you left the file.
Another mark that is remembered is the position where you made the last
change:
`.
Suppose you are editing the file "one.txt". Somewhere halfway the file you
use "x" to delete a character. Then you go to the last line with "G" and
write the file with ":w". You edit several other files, and then use ":edit
one.txt" to come back to "one.txt". If you now use `" Vim jumps to the last
line of the file. Using `. takes you to the position where you deleted the
character. Even when you move around in the file `" and `. will take you to
the remembered position. At least until you make another change or leave the
file.
FILE MARKS
In chapter 4 was explained how you can place a mark in a file with "mx" and
jump to that position with "`x". That works within one file. If you edit
another file and place marks there, these are specific for that file. Thus
each file has its own set of marks, they are local to the file.
So far we were using marks with a lowercase letter. There are also marks
with an uppercase letter. These are global, they can be used from any file.
For example suppose that we are editing the file "foo.txt". Go to halfway the
file ("50%") and place the F mark there (F for foo):
50%mF
Now edit the file "bar.txt" and place the B mark (B for bar) at its last line:
GmB
Now you can use the "'F" command to jump back to halfway foo.txt. Or edit yet
another file, type "'B" and you are at the end of bar.txt again.
The file marks are remembered until they are placed somewhere else. Thus you
can place the mark, do hours of editing and still be able to jump back to that
mark.
It's often useful to think of a simple connection between the mark letter
and where it is placed. For example, use the H mark in a header file, M in
a Makefile and C in a C code file.
To see where a specific mark is, give an argument to the ":marks" command:
:marks M
You can also give several arguments:
:marks MCP
Don't forget that you can use CTRL-O and CTRL-I to jump to older and newer
positions without placing marks there.
==============================================================================
*07.4* Backup files
Usually Vim does not produce a backup file. If you want to have one, all you
need to do is execute the following command:
:set backup
The name of the backup file is the original file with a ~ added to the end.
If your file is named data.txt, for example, the backup file name is
data.txt~.
If you do not like the fact that the backup files end with ~, you can
change the extension:
:set backupext=.bak
This will use data.txt.bak instead of data.txt~.
Another option that matters here is 'backupdir'. It specifies where the
backup file is written. The default, to write the backup in the same
directory as the original file, will mostly be the right thing.
Note:
When the 'backup' option isn't set but the 'writebackup' is, Vim will
still create a backup file. However, it is deleted as soon as writing
the file was completed successfully. This functions as a safety
against losing your original file when writing fails in some way (disk
full is the most common cause; being hit by lightning might be
another, although less common).
If you are editing source files, you might want to keep the file before you
make any changes. But the backup file will be overwritten each time you write
the file. Thus it only contains the previous version, not the first one.
To make Vim keep the original file, set the 'patchmode' option. This
specifies the extension used for the first backup of a changed file. Usually
you would do this:
:set patchmode=.orig
When you now edit the file data.txt for the first time, make changes and write
the file, Vim will keep a copy of the unchanged file under the name
"data.txt.orig".
If you make further changes to the file, Vim will notice that
"data.txt.orig" already exists and leave it alone. Further backup files will
then be called "data.txt~" (or whatever you specified with 'backupext').
If you leave 'patchmode' empty (that is the default), the original file
will not be kept.
==============================================================================
*07.5* Copy text between files
This explains how to copy text from one file to another. Let's start with a
simple example. Edit the file that contains the text you want to copy. Move
the cursor to the start of the text and press "v". This starts Visual mode.
Now move the cursor to the end of the text and press "y". This yanks (copies)
the selected text.
To copy the above paragraph, you would do:
:edit thisfile
/This
vjjjj$y
Now edit the file you want to put the text in. Move the cursor to the
character where you want the text to appear after. Use "p" to put the text
there.
:edit otherfile
/There
p
Of course you can use many other commands to yank the text. For example, to
select whole lines start Visual mode with "V". Or use CTRL-V to select a
rectangular block. Or use "Y" to yank a single line, "yaw" to yank-a-word,
etc.
The "p" command puts the text after the cursor. Use "P" to put the text
before the cursor. Notice that Vim remembers if you yanked a whole line or a
block, and puts it back that way.
USING REGISTERS
When you want to copy several pieces of text from one file to another, having
to switch between the files and writing the target file takes a lot of time.
To avoid this, copy each piece of text to its own register.
A register is a place where Vim stores text. Here we will use the
registers named a to z (later you will find out there are others). Let's copy
a sentence to the f register (f for First):
"fyas
The "yas" command yanks a sentence like before. It's the "f that tells Vim
the text should be place in the f register. This must come just before the
yank command.
Now yank three whole lines to the l register (l for line):
"l3Y
The count could be before the "l just as well. To yank a block of text to the
b (for block) register:
CTRL-Vjjww"by
Notice that the register specification "b is just before the "y" command.
This is required. If you would have put it before the "w" command, it would
not have worked.
Now you have three pieces of text in the f, l and b registers. Edit
another file, move around and place the text where you want it:
"fp
Again, the register specification "f comes before the "p" command.
You can put the registers in any order. And the text stays in the register
until you yank something else into it. Thus you can put it as many times as
you like.
When you delete text, you can also specify a register. Use this to move
several pieces of text around. For example, to delete-a-word and write it in
the w register:
"wdaw
Again, the register specification comes before the delete command "d".
APPENDING TO A FILE
When collecting lines of text into one file, you can use this command:
:write >> logfile
This will write the text of the current file to the end of "logfile". Thus it
is appended. This avoids that you have to copy the lines, edit the log file
and put them there. Thus you save two steps. But you can only append to the
end of a file.
To append only a few lines, select them in Visual mode before typing
":write". In chapter 10 you will learn other ways to select a range of lines.
==============================================================================
*07.6* Viewing a file
Sometimes you only want to see what a file contains, without the intention to
ever write it back. There is the risk that you type ":w" without thinking and
overwrite the original file anyway. To avoid this, edit the file read-only.
To start Vim in readonly mode, use this command:
vim -R file
On Unix this command should do the same thing:
view file
You are now editing "file" in read-only mode. When you try using ":w" you
will get an error message and the file won't be written.
When you try to make a change to the file Vim will give you a warning:
W10: Warning: Changing a readonly file
The change will be done though. This allows for formatting the file, for
example, to be able to read it easily.
If you make changes to a file and forgot that it was read-only, you can
still write it. Add the ! to the write command to force writing.
If you really want to forbid making changes in a file, do this:
vim -M file
Now every attempt to change the text will fail. The help files are like this,
for example. If you try to make a change you get this error message:
E21: Cannot make changes, 'modifiable' is off
You could use the -M argument to setup Vim to work in a viewer mode. This is
only voluntary though, since these commands will remove the protection:
:set modifiable
:set write
==============================================================================
*07.7* Changing the file name
A clever way to start editing a new file is by using an existing file that
contains most of what you need. For example, you start writing a new program
to move a file. You know that you already have a program that copies a file,
thus you start with:
:edit copy.c
You can delete the stuff you don't need. Now you need to save the file under
Display two different files above each other. Or view two locations in the
file at the same time. See the difference between two files by putting them
side by side. All this is possible with split windows.
|08.1| Split a window
|08.2| Split a window on another file
|08.3| Window size
|08.4| Vertical splits
|08.5| Moving windows
|08.6| Commands for all windows
|08.7| Viewing differences with vimdiff
|08.8| Various
|08.9| Tab pages
Next chapter: |usr_09.txt| Using the GUI
Previous chapter: |usr_07.txt| Editing more than one file
Table of contents: |usr_toc.txt|
==============================================================================
*08.1* Split a window
The easiest way to open a new window is to use the following command:
:split
This command splits the screen into two windows and leaves the cursor in the
top one:
+----------------------------------+
|/* file one.c */ |
|~ |
|~ |
|one.c=============================|
|/* file one.c */ |
|~ |
|one.c=============================|
| |
+----------------------------------+
What you see here is two windows on the same file. The line with "====" is
that status line. It displays information about the window above it. (In
practice the status line will be in reverse video.)
The two windows allow you to view two parts of the same file. For example,
you could make the top window show the variable declarations of a program, and
the bottom one the code that uses these variables.
The CTRL-W w command can be used to jump between the windows. If you are in
the top window, CTRL-W w jumps to the window below it. If you are in the
bottom window it will jump to the first window. (CTRL-W CTRL-W does the same
thing, in case you let go of the CTRL key a bit later.)
:close
Actually, any command that quits editing a file works, like ":quit" and "ZZ".
But ":close" prevents you from accidentally exiting Vim when you close the
last window.
OPTIONS
The 'winheight' option can be set to a minimal desired height of a window and
'winminheight' to a hard minimum height.
Likewise, there is 'winwidth' for the minimal desired width and
'winminwidth' for the hard minimum width.
The 'equalalways' option, when set, makes Vim equalize the windows sizes
when a window is closed or opened.
==============================================================================
*08.4* Vertical splits
The ":split" command creates the new window above the current one. To make
the window appear at the left side, use:
:vsplit
or:
:vsplit two.c
The result looks something like this:
+--------------------------------------+
|/* file two.c */ |/* file one.c */ ||||
|~ |~ ||||
|~ |~ ||||
|~ |~ ||||
|two.c===============one.c=============|
| |
+--------------------------------------+
Actually, the | lines in the middle will be in reverse video. This is called
the vertical separator. It separates the two windows left and right of it.
There is also the ":vnew" command, to open a vertically split window on a new,
empty file. Another way to do this:
:vertical new
The ":vertical" command can be inserted before another command that splits a
window. This will cause that command to split the window vertically instead
of horizontally. (If the command doesn't split a window, it works
unmodified.)
need a command to move the window somewhere else. For example, you have three
windows like this:
+----------------------------------+
|/* file two.c */ |
|~ |
|~ |
|two.c=============================|
|/* file three.c */ |
|~ |
|~ |
|three.c===========================|
|/* file one.c */ |
|~ |
|one.c=============================|
| |
+----------------------------------+
Clearly the last one should be at the top. Go to that window (using CTRL-W w)
and the type this command:
CTRL-W K
This uses the uppercase letter K. What happens is that the window is moved to
the very top. You will notice that K is again used for moving upwards.
When you have vertical splits, CTRL-W K will move the current window to the
top and make it occupy the full width of the Vim window. If this is your
layout:
+-------------------------------------------+
|/* two.c */ |/* three.c */ |/* one.c */ |
|~ |~ |~ |
|~ |~ |~ |
|~ |~ |~ |
|~ |~ |~ |
|~ |~ |~ |
|two.c=========three.c=========one.c========|
| |
+-------------------------------------------+
Then using CTRL-W K in the middle window (three.c) will result in:
+-------------------------------------------+
|/* three.c */ |
|~ |
|~ |
|three.c====================================|
|/* two.c */ |/* one.c */ ||||
|~ |~ ||||
|two.c==================one.c===============|
| |
+-------------------------------------------+
The other three similar commands (you can probably guess these now):
CTRL-W H move window to the far left
CTRL-W J move window to the bottom
CTRL-W L move window to the far right
==============================================================================
*08.6* Commands for all windows
When you have several windows open and you want to quit Vim, you can close
each window separately. A quicker way is using this command:
:qall
This stands for "quit all". If any of the windows contain changes, Vim will
not exit. The cursor will automatically be positioned in a window with
changes. You can then either use ":write" to save the changes, or ":quit!" to
throw them away.
If you know there are windows with changes, and you want to save all these
changes, use this command:
:wall
This stands for "write all". But actually, it only writes files with
changes. Vim knows it doesn't make sense to write files that were not
changed.
And then there is the combination of ":qall" and ":wall": the "write and
quit all" command:
:wqall
This writes all modified files and quits Vim.
Finally, there is a command that quits Vim and throws away all changes:
:qall!
Be careful, there is no way to undo this command!
The line marked with "<- changed line" is highlighted, and the inserted
text is displayed with another color. This clearly shows what the difference
is between the two files.
The line that was deleted is displayed with "---" in the main.c window.
See the "<- deleted line" marker in the picture. These characters are not
really there. They just fill up main.c, so that it displays the same number
of lines as the other window.
DIFFING IN VIM
Another way to start in diff mode can be done from inside Vim. Edit the
"main.c" file, then make a split and show the differences:
:edit main.c
:vertical diffsplit main.c~
The ":vertical" command is used to make the window split vertically. If you
omit this, you will get a horizontal split.
If you have a patch or diff file, you can use the third way to start diff
mode. First edit the file to which the patch applies. Then tell Vim the name
of the patch file:
:edit main.c
:vertical diffpatch main.c.diff
WARNING: The patch file must contain only one patch, for the file you are
editing. Otherwise you will get a lot of error messages, and some files might
be patched unexpectedly.
The patching will only be done to the copy of the file in Vim. The file on
your harddisk will remain unmodified (until you decide to write the file).
SCROLL BINDING
When the files have more changes, you can scroll in the usual way. Vim will
try to keep both the windows start at the same position, so you can easily see
the differences side by side.
When you don't want this for a moment, use this command:
:set noscrollbind
JUMPING TO CHANGES
When you have disabled folding in some way, it may be difficult to find the
changes. Use this command to jump forward to the next change:
]c
To go the other way use:
[c
Prepended a count to jump further away.
REMOVING CHANGES
You can move text from one window to the other. This either removes
differences or adds new ones. Vim doesn't keep the highlighting updated in
all situations. To update it use this command:
:diffupdate
To remove a difference, you can move the text in a highlighted block from one
window to another. Take the "main.c" and "main.c~" example above. Move the
cursor to the left window, on the line that was deleted in the other window.
Now type this command:
dp
The change will be removed by putting the text of the current window in the
other window. "dp" stands for "diff put".
You can also do it the other way around. Move the cursor to the right
window, to the line where "changed" was inserted. Now type this command:
do
The change will now be removed by getting the text from the other window.
Since there are no changes left now, Vim puts all text in a closed fold.
"do" stands for "diff obtain". "dg" would have been better, but that already
has a different meaning ("dgg" deletes from the cursor until the first line).
For details about diff mode, see |vimdiff|.
==============================================================================
*08.8* Various
The 'laststatus' option can be used to specify when the last window has a
statusline:
0 never
1 only when there are split windows (the default)
2 always
Many commands that edit another file have a variant that splits the window.
For Command-line commands this is done by prepending an "s". For example:
":tag" jumps to a tag, ":stag" splits the window and jumps to a
tag.
For Normal mode commands a CTRL-W is prepended. CTRL-^ jumps to the
alternate file, CTRL-W CTRL-^ splits the window and edits the alternate file.
The 'splitbelow' option can be set to make a new window appear below the
current window. The 'splitright' option can be set to make a vertically split
window appear right of the current window.
When splitting a window you can prepend a modifier command to tell where the
window is to appear:
:leftabove {cmd} left or above the current window
:aboveleft {cmd} idem
:rightbelow {cmd} right or below the current window
:belowright {cmd} idem
:topleft {cmd} at the top or left of the Vim window
:botright {cmd} at the bottom or right of the Vim window
==============================================================================
*08.9* Tab pages
You will have noticed that windows never overlap. That means you quickly run
out of screen space. The solution for this is called Tab pages.
Assume you are editing "thisfile". To create a new tab page use this command:
:tabedit thatfile
This will edit the file "thatfile" in a window that occupies the whole Vim
window. And you will notice a bar at the top with the two file names:
+----------------------------------+
| thisfile | /thatfile/ __________X| (thatfile is bold)
|/* thatfile */ |
|that |
|that |
|~ |
|~ |
|~ |
| |
+----------------------------------+
You now have two tab pages. The first one has a window for "thisfile" and the
second one a window for "thatfile". It's like two pages that are on top of
eachother, with a tab sticking out of each page showing the file name.
Now use the mouse to click on "thisfile" in the top line. The result is
+----------------------------------+
| /thisfile/ | thatfile __________X| (thisfile is bold)
|/* thisfile */ |
|this |
|this |
|~ |
|~ |
|~ |
| |
+----------------------------------+
Thus you can switch between tab pages by clicking on the label in the top
line. If you don't have a mouse or don't want to use it, you can use the "gt"
command. Mnemonic: Goto Tab.
Now let's create another tab page with the command:
:tab split
This makes a new tab page with one window that is editing the same buffer as
the window we were in:
+-------------------------------------+
| thisfile | /thisfile/ | thatfile __X| (thisfile is bold)
|/* thisfile */ |
|this |
|this |
|~ |
|~ |
|~ |
| |
+-------------------------------------+
You can put ":tab" before any Ex command that opens a window. The window will
be opened in a new tab page. Another example:
:tab help gt
Will show the help text for "gt" in a new tab page.
A few more things you can do with tab pages:
- click with the mouse in the space after the last label
The next tab page will be selected, like with "gt".
- click with the mouse on the "X" in the top right corner
The current tab page will be closed. Unless there are unsaved
changes in the current tab page.
- double click with the mouse in the top line
A new tab page will be created.
- the "tabonly" command
Closes all tab pages except the current one. Unless there are unsaved
changes in other tab pages.
For more information about tab pages see |tab-page|.
==============================================================================
Next chapter: |usr_09.txt| Using the GUI
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
Vim works in an ordinary terminal. GVim can do the same things and a few
more. The GUI offers menus, a toolbar, scrollbars and other items. This
chapter is about these extra things that the GUI offers.
|09.1| Parts of the GUI
|09.2| Using the mouse
|09.3| The clipboard
|09.4| Select mode
Next chapter: |usr_10.txt| Making big changes
Previous chapter: |usr_08.txt| Splitting windows
Table of contents: |usr_toc.txt|
==============================================================================
*09.1* Parts of the GUI
You might have an icon on your desktop that starts gVim. Otherwise, one of
these commands should do it:
gvim file.txt
vim -g file.txt
If this doesn't work you don't have a version of Vim with GUI support. You
will have to install one first.
Vim will open a window and display "file.txt" in it. What the window looks
like depends on the version of Vim. It should resemble the following picture
(for as far as this can be shown in ASCII!).
+----------------------------------------------------+
| file.txt + (~/dir) - VIM X | <- window title
+----------------------------------------------------+
| File Edit Tools Syntax Buffers Window Help | <- menubar
+----------------------------------------------------+
| aaa bbb ccc ddd eee fff ggg hhh iii jjj | <- toolbar
| aaa bbb ccc ddd eee fff ggg hhh iii jjj |
+----------------------------------------------------+
| file text | ^ |
| ~ | # |
| ~ | # | <- scrollbar
| ~ | # |
| ~ | # |
| ~ | # |
| | V |
+----------------------------------------------------+
The largest space is occupied by the file text. This shows the file in the
same way as in a terminal. With some different colors and another font
perhaps.
THE MENUBAR
You know how menus work, right? Vim has the usual items, plus a few more.
Browse them to get an idea of what you can use them for. A relevant submenu
is Edit/Global Settings. You will find these entries:
Toggle Toolbar make the toolbar appear/disappear
Toggle Bottom Scrollbar make a scrollbar appear/disappear at the bottom
Toggle Left Scrollbar make a scrollbar appear/disappear at the left
Toggle Right Scrollbar make a scrollbar appear/disappear at the right
On most systems you can tear-off the menus. Select the top item of the menu,
the one that looks like a dashed line. You will get a separate window with
the items of the menu. It will hang around until you close the window.
THE TOOLBAR
This contains icons for the most often used actions. Hopefully the icons are
self-explanatory. There are tooltips to get an extra hint (move the mouse
pointer to the icon without clicking and don't move it for a second).
The "Edit/Global Settings/Toggle Toolbar" menu item can be used to make the
toolbar disappear. If you never want a toolbar, use this command in your
vimrc file:
:set guioptions-=T
This removes the 'T' flag from the 'guioptions' option. Other parts of the
GUI can also be enabled or disabled with this option. See the help for it.
THE SCROLLBARS
By default there is one scrollbar on the right. It does the obvious thing.
When you split the window, each window will get its own scrollbar.
You can make a horizontal scrollbar appear with the menu item
Edit/Global Settings/Toggle Bottom Scrollbar. This is useful in diff mode, or
when the 'wrap' option has been reset (more about that later).
When there are vertically split windows, only the windows on the right side
will have a scrollbar. However, when you move the cursor to a window on the
left, it will be this one the that scrollbar controls. This takes a bit of
time to get used to.
When you work with vertically split windows, consider adding a scrollbar on
the left. This can be done with a menu item, or with the 'guioptions' option:
:set guioptions+=l
This adds the 'l' flag to 'guioptions'.
==============================================================================
*09.2* Using the mouse
Standards are wonderful. In Microsoft Windows, you can use the mouse to
select text in a standard manner. The X Window system also has a standard
system for using the mouse. Unfortunately, these two standards are not the
same.
Fortunately, you can customize Vim. You can make the behavior of the mouse
work like an X Window system mouse or a Microsoft Windows mouse. The following
command makes the mouse behave like an X Window mouse:
:behave xterm
The following command makes the mouse work like a Microsoft Windows mouse:
:behave mswin
The default behavior of the mouse on UNIX systems is xterm. The default
The mouse can be further tuned. Check out these options if you want to change
the way how the mouse works:
'mouse' in which mode the mouse is used by Vim
'mousemodel' what effect a mouse click has
'mousetime' time between clicks for a double-click
'mousehide' hide the mouse while typing
'selectmode' whether the mouse starts Visual or Select mode
==============================================================================
*09.3* The clipboard
In section |04.7| the basic use of the clipboard was explained. There is one
essential thing to explain about X-windows: There are actually two places to
exchange text between programs. MS-Windows doesn't have this.
In X-Windows there is the "current selection". This is the text that is
currently highlighted. In Vim this is the Visual area (this assumes you are
using the default option settings). You can paste this selection in another
application without any further action.
For example, in this text select a few words with the mouse. Vim will
switch to Visual mode and highlight the text. Now start another gVim, without
a file name argument, so that it displays an empty window. Click the middle
mouse button. The selected text will be inserted.
The "current selection" will only remain valid until some other text is
selected. After doing the paste in the other gVim, now select some characters
in that window. You will notice that the words that were previously selected
in the other gVim window are displayed differently. This means that it no
longer is the current selection.
You don't need to select text with the mouse, using the keyboard commands for
Visual mode works just as well.
USING BOTH
This use of both the "current selection" and the "real clipboard" might sound
a bit confusing. But it is very useful. Let's show this with an example.
Use one gVim with a text file and perform these actions:
- Select two words in Visual mode.
- Use the Edit/Copy menu to get these words onto the clipboard.
- Select one other word in Visual mode.
- Use the Edit/Paste menu item. What will happen is that the single selected
word is replaced with the two words from the clipboard.
- Move the mouse pointer somewhere else and click the middle button. You
will see that the word you just overwrote with the clipboard is inserted
here.
If you use the "current selection" and the "real clipboard" with care, you can
do a lot of useful editing with them.
In chapter 4 several ways to make small changes were explained. This chapter
goes into making changes that are repeated or can affect a large amount of
text. The Visual mode allows doing various things with blocks of text. Use
an external program to do really complicated things.
|10.1| Record and playback commands
|10.2| Substitution
|10.3| Command ranges
|10.4| The global command
|10.5| Visual block mode
|10.6| Reading and writing part of a file
|10.7| Formatting text
|10.8| Changing case
|10.9| Using an external program
Next chapter: |usr_11.txt| Recovering from a crash
Previous chapter: |usr_09.txt| Using the GUI
Table of contents: |usr_toc.txt|
==============================================================================
*10.1* Record and playback commands
The "." command repeats the preceding change. But what if you want to do
something more complex than a single change? That's where command recording
comes in. There are three steps:
1. The "q{register}" command starts recording keystrokes into the register
named {register}. The register name must be between a and z.
2. Type your commands.
3. To finish recording, press q (without any extra character).
You can now execute the macro by typing the command "@{register}".
Take a look at how to use these commands in practice. You have a list of
filenames that look like this:
stdio.h
fcntl.h
unistd.h
stdlib.h
And what you want is the following:
#include "stdio.h"
#include "fcntl.h"
#include "unistd.h"
#include "stdlib.h"
You start by moving to the first character of the first line. Next you
execute the following commands:
qa Start recording a macro in register a.
^ Move to the beginning of the line.
i#include "<Esc> Insert the string #include " at the beginning
of the line.
$ Move to the end of the line.
a"<Esc> Append the character double quotation mark (")
to the end of the line.
j Go to the next line.
q Stop recording the macro.
Now that you have done the work once, you can repeat the change by typing the
command "@a" three times.
The "@a" command can be preceded by a count, which will cause the macro to
be executed that number of times. In this case you would type:
3@a
USING REGISTERS
The registers used for recording are the same ones you used for yank and
delete commands. This allows you to mix recording with other commands to
manipulate the registers.
Suppose you have recorded a few commands in register n. When you execute
this with "@n" you notice you did something wrong. You could try recording
again, but perhaps you will make another mistake. Instead, use this trick:
G Go to the end of the file.
o<Esc> Create an empty line.
"np Put the text from the n register. You now see
the commands you typed as text in the file.
{edits} Change the commands that were wrong. This is
just like editing text.
0 Go to the start of the line.
"ny$ Yank the corrected commands into the n
register.
dd Delete the scratch line.
Now you can execute the corrected commands with "@n". (If your recorded
commands include line breaks, adjust the last two items in the example to
include all the lines.)
APPENDING TO A REGISTER
So far we have used a lowercase letter for the register name. To append to a
register, use an uppercase letter.
Suppose you have recorded a command to change a word to register c. It
works properly, but you would like to add a search for the next word to
change. This can be done with:
qC/word<Enter>q
You start with "qC", which records to the c register and appends. Thus
writing to an uppercase register name means to append to the register with
the same letter, but lowercase.
This works both with recording and with yank and delete commands. For
example, you want to collect a sequence of lines into the a register. Yank
the first line with:
"aY
Now move to the second line, and type:
"AY
Repeat this command for all lines. The a register now contains all those
The "from" part of the substitute command is actually a pattern. The same
kind as used for the search command. For example, this command only
substitutes "the" when it appears at the start of a line:
:s/^the/these/
If you are substituting with a "from" or "to" part that includes a slash, you
need to put a backslash before it. A simpler way is to use another character
instead of the slash. A plus, for example:
:s+one/two+one or two+
==============================================================================
*10.3* Command ranges
The ":substitute" command, and many other : commands, can be applied to a
selection of lines. This is called a range.
The simple form of a range is {number},{number}. For example:
:1,5s/this/that/g
Executes the substitute command on the lines 1 to 5. Line 5 is included.
The range is always placed before the command.
A single number can be used to address one specific line:
:54s/President/Fool/
Some commands work on the whole file when you do not specify a range. To make
them work on the current line the "." address is used. The ":write" command
works like that. Without a range, it writes the whole file. To make it write
only the current line into a file:
:.write otherfile
The first line always has number one. How about the last line? The "$"
character is used for this. For example, to substitute in the lines from the
cursor to the end:
:.,$s/yes/no/
The "%" range that we used before, is actually a short way to say "1,$", from
the first to the last line.
USING MARKS
Instead of figuring out the line numbers of certain positions, remembering them
and typing them in a range, you can use marks.
Place the marks as mentioned in chapter 3. For example, use "mt" to mark
the top of an area and "mb" to mark the bottom. Then you can use this range
to specify the lines between the marks (including the lines with the marks):
:'t,'b
A NUMBER OF LINES
When you know how many lines you want to change, you can type the number and
then ":". For example, when you type "5:", you will get:
:.,.+4
Now you can type the command you want to use. It will use the range "."
(current line) until ".+4" (four lines down). Thus it spans five lines.
==============================================================================
*10.4* The global command
The ":global" command is one of the more powerful features of Vim. It allows
you to find a match for a pattern and execute a command there. The general
form is:
:[range]global/{pattern}/{command}
This is similar to the ":substitute" command. But, instead of replacing the
matched text with other text, the command {command} is executed.
Note:
The command executed for ":global" must be one that starts with a
colon. Normal mode commands can not be used directly. The |:normal|
command can do this for you.
Suppose you want to change "foobar" to "barfoo", but only in C++ style
comments. These comments start with "//". Use this command:
:g+//+s/foobar/barfoo/g
This starts with ":g". That is short for ":global", just like ":s" is short
for ":substitute". Then the pattern, enclosed in plus characters. Since the
pattern we are looking for contains a slash, this uses the plus character to
separate the pattern. Next comes the substitute command that changes "foobar"
into "barfoo".
The default range for the global command is the whole file. Thus no range
was specified in this example. This is different from ":substitute", which
works on one line without a range.
The command isn't perfect, since it also matches lines where "//" appears
halfway a line, and the substitution will also take place before the "//".
Just like with ":substitute", any pattern can be used. When you learn more
complicated patterns later, you can use them here.
==============================================================================
INSERTING TEXT
The command "I{string}<Esc>" inserts the text {string} in each line, just
left of the visual block. You start by pressing CTRL-V to enter visual block
mode. Now you move the cursor to define your block. Next you type I to enter
Insert mode, followed by the text to insert. As you type, the text appears on
the first line only.
After you press <Esc> to end the insert, the text will magically be
inserted in the rest of the lines contained in the visual selection. Example:
include one
include two
include three
include four
Move the cursor to the "o" of "one" and press CTRL-V. Move it down with "3j"
to "four". You now have a block selection that spans four lines. Now type:
Imain.<Esc>
The result:
include main.one
include main.two
include main.three
include main.four
If the block spans short lines that do not extend into the block, the text is
not inserted in that line. For example, make a Visual block selection that
includes the word "long" in the first and last line of this text, and thus has
no text selected in the second line:
This is a long line
short
Any other long line
^^^^ selected block
Now use the command "Ivery <Esc>". The result is:
This is a very long line
short
Any other very long line
In the short line no text was inserted.
If the string you insert contains a newline, the "I" acts just like a Normal
insert command and affects only the first line of the block.
The "A" command works the same way, except that it appends after the right
side of the block. And it does insert text in a short line. Thus you can
make a choice whether you do or don't want to append text to a short line.
There is one special case for "A": Select a Visual block and then use "$"
to make the block extend to the end of each line. Using "A" now will append
the text to the end of each line.
Using the same example from above, and then typing "$A XXX<Esc>, you get
this result:
This is a long line XXX
short XXX
Any other long line XXX
This really requires using the "$" command. Vim remembers that it was used.
Making the same selection by moving the cursor to the end of the longest line
with other movement commands will not have the same result.
CHANGING TEXT
The Visual block "c" command deletes the block and then throws you into Insert
mode to enable you to type in a string. The string will be inserted in each
line in the block.
Starting with the same selection of the "long" words as above, then typing
"c_LONG_<Esc>", you get this:
This is a _LONG_ line
short
Any other _LONG_ line
Just like with "I" the short line is not changed. Also, you can't enter a
newline in the new text.
The "C" command deletes text from the left edge of the block to the end of
line. It then puts you in Insert mode so that you can type in a string,
which is added to the end of each line.
Starting with the same text again, and typing "Cnew text<Esc>" you get:
This is a new text
short
Any other new text
Notice that, even though only the "long" word was selected, the text after it
is deleted as well. Thus only the location of the left edge of the visual
block really matters.
Again, short lines that do not reach into the block are excluded.
Other commands that change the characters in the block:
~ swap case (a -> A and A -> a)
U make uppercase (a -> A and A -> A)
u make lowercase (a -> a and A -> a)
Note:
If you want to include characters beyond the end of the line in the
block, check out the 'virtualedit' feature in chapter 25.
SHIFTING
The command ">" shifts the selected text to the right one shift amount,
inserting whitespace. The starting point for this shift is the left edge of
the visual block.
With the same example again, ">" gives this result:
This is a long line
short
Any other long line
The shift amount is specified with the 'shiftwidth' option. To change it to
use 4 spaces:
:set shiftwidth=4
The "<" command removes one shift amount of whitespace at the left
edge of the block. This command is limited by the amount of text that is
there; so if there is less than a shift amount of whitespace available, it
removes what it can.
JOINING LINES
The "J" command joins all selected lines together into one line. Thus it
removes the line breaks. Actually, the line break, leading white space and
trailing white space is replaced by one space. Two spaces are used after a
APPENDING TO A FILE
In the first section of this chapter was explained how to collect a number of
lines into a register. The same can be done to collect lines in a file.
Write the first line with this command:
:.write collection
Now move the cursor to the second line you want to collect, and type this:
:.write >>collection
The ">>" tells Vim the "collection" file is not to be written as a new file,
but the line must be appended at the end. You can repeat this as many times
as you like.
==============================================================================
*10.7* Formatting text
When you are typing plain text, it's nice if the length of each line is
automatically trimmed to fit in the window. To make this happen while
inserting text, set the 'textwidth' option:
:set textwidth=72
You might remember that in the example vimrc file this command was used for
every text file. Thus if you are using that vimrc file, you were already
using it. To check the current value of 'textwidth':
:set textwidth
Now lines will be broken to take only up to 72 characters. But when you
insert text halfway a line, or when you delete a few words, the lines will get
too long or too short. Vim doesn't automatically reformat the text.
To tell Vim to format the current paragraph:
gqap
This starts with the "gq" command, which is an operator. Following is "ap",
the text object that stands for "a paragraph". A paragraph is separated from
the next paragraph by an empty line.
Note:
A blank line, which contains white space, does NOT separate
paragraphs. This is hard to notice!
Instead of "ap" you could use any motion or text object. If your paragraphs
are properly separated, you can use this command to format the whole file:
gggqG
"gg" takes you to the first line, "gq" is the format operator and "G" the
motion that jumps to the last line.
In case your paragraphs aren't clearly defined, you can format just the lines
you manually select. Move the cursor to the first line you want to format.
Start with the command "gqj". This formats the current line and the one below
it. If the first line was short, words from the next line will be appended.
If it was too long, words will be moved to the next line. The cursor moves to
the second line. Now you can use "." to repeat the command. Keep doing this
until you are at the end of the text you want to format.
==============================================================================
*10.8* Changing case
You have text with section headers in lowercase. You want to make the word
"section" all uppercase. Do this with the "gU" operator. Start with the
cursor in the first column:
gUw
section header ----> SECTION header
The "gu" operator does exactly the opposite:
guw
SECTION header ----> section header
You can also use "g~" to swap case. All these are operators, thus they work
with any motion command, with text objects and in Visual mode.
To make an operator work on lines you double it. The delete operator is
"d", thus to delete a line you use "dd". Similarly, "gugu" makes a whole line
lowercase. This can be shortened to "guu". "gUgU" is shortened to "gUU" and
"g~g~" to "g~~". Example:
g~~
Some GIRLS have Fun ----> sOME girls HAVE fUN
==============================================================================
*10.9* Using an external program
Vim has a very powerful set of commands, it can do anything. But there may
still be something that an external command can do better or faster.
The command "!{motion}{program}" takes a block of text and filters it
through an external program. In other words, it runs the system command
represented by {program}, giving it the block of text represented by {motion}
as input. The output of this command then replaces the selected block.
Because this summarizes badly if you are unfamiliar with UNIX filters, take
a look at an example. The sort command sorts a file. If you execute the
following command, the unsorted file input.txt will be sorted and written to
output.txt. (This works on both UNIX and Microsoft Windows.)
sort <input.txt >output.txt
Now do the same thing in Vim. You want to sort lines 1 through 5 of a file.
You start by putting the cursor on line 1. Next you execute the following
command:
!5G
The "!" tells Vim that you are performing a filter operation. The Vim editor
expects a motion command to follow, indicating which part of the file to
filter. The "5G" command tells Vim to go to line 5, so it now knows that it
is to filter lines 1 (the current line) through 5.
In anticipation of the filtering, the cursor drops to the bottom of the
screen and a ! prompt displays. You can now type in the name of the filter
program, in this case "sort". Therefore, your full command is as follows:
!5Gsort<Enter>
The result is that the sort program is run on the first 5 lines. The output
of the program replaces these lines.
line 55 line 11
line 33 line 22
line 11 --> line 33
line 22 line 44
line 44 line 55
last line last line
The "!!" command filters the current line through a filter. In Unix the "date"
command prints the current time and date. "!!date<Enter>" replaces the current
line with the output of "date". This is useful to add a timestamp to a file.
:read !dir
The output of the "ls" or "dir" command is captured and inserted in the text,
below the cursor. This is similar to reading a file, except that the "!" is
used to tell Vim that a command follows.
The command may have arguments. And a range can be used to tell where Vim
should put the lines:
:0read !date -u
This inserts the current time and date in UTC format at the top of the file.
(Well, if you have a date command that accepts the "-u" argument.) Note the
difference with using "!!date": that replaced a line, while ":read !date" will
insert a line.
Did your computer crash? And you just spent hours editing? Don't panic! Vim
stores enough information to be able to restore most of your work. This
chapter shows you how to get your work back and explains how the swap file is
used.
|11.1| Basic recovery
|11.2| Where is the swap file?
|11.3| Crashed or not?
|11.4| Further reading
Next chapter: |usr_12.txt| Clever tricks
Previous chapter: |usr_10.txt| Making big changes
Table of contents: |usr_toc.txt|
==============================================================================
*11.1* Basic recovery
In most cases recovering a file is quite simple, assuming you know which file
you were editing (and the harddisk is still working). Start Vim on the file,
with the "-r" argument added:
vim -r help.txt
Vim will read the swap file (used to store text you were editing) and may read
bits and pieces of the original file. If Vim recovered your changes you will
see these messages (with different file names, of course):
Using swap file ".help.txt.swp"
Original file "~/vim/runtime/doc/help.txt"
Recovery completed. You should check if everything is OK.
(You might want to write out this file under another name
and run diff with the original file to check for changes)
You may want to delete the .swp file now.
To be on the safe side, write this file under another name:
:write help.txt.recovered
Compare the file with the original file to check if you ended up with what you
expected. Vimdiff is very useful for this |08.7|. For example:
:write help.txt.recovered
:edit #
:diffsp help.txt
Watch out for the original file to contain a more recent version (you saved
the file just before the computer crashed). And check that no lines are
missing (something went wrong that Vim could not recover).
If Vim produces warning messages when recovering, read them carefully.
This is rare though.
If the recovery resulted in text that is exactly the same as the file
contents, you will get this message:
Vim cannot always detect that a swap file already exists for a file. This is
the case when the other edit session puts the swap files in another directory
or when the path name for the file is different when editing it on different
machines. Therefore, don't rely on Vim always warning you.
If you really don't want to see this message, you can add the 'A' flag to the
'shortmess' option. But it's very unusual that you need this.
For remarks about encryption and the swap file, see |:recover-crypt|.
==============================================================================
*11.4* Further reading
|swap-file| An explanation about where the swap file will be created and
what its name is.
|:preserve| Manually flushing the swap file to disk.
|:swapname| See the name of the swap file for the current file.
'updatecount' Number of key strokes after which the swap file is flushed to
disk.
'updatetime' Timeout after which the swap file is flushed to disk.
'swapsync' Whether the disk is synced when the swap file is flushed.
'directory' List of directory names where to store the swap file.
'maxmem' Limit for memory usage before writing text to the swap file.
'maxmemtot' Same, but for all files in total.
==============================================================================
Next chapter: |usr_12.txt| Clever tricks
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
By combining several commands you can make Vim do nearly everything. In this
chapter a number of useful combinations will be presented. This uses the
commands introduced in the previous chapters and a few more.
|12.1| Replace a word
|12.2| Change "Last, First" to "First Last"
|12.3| Sort a list
|12.4| Reverse line order
|12.5| Count words
|12.6| Find a man page
|12.7| Trim blanks
|12.8| Find where a word is used
Next chapter: |usr_20.txt| Typing command-line commands quickly
Previous chapter: |usr_11.txt| Recovering from a crash
Table of contents: |usr_toc.txt|
==============================================================================
*12.1* Replace a word
The substitute command can be used to replace all occurrences of a word with
another word:
:%s/four/4/g
The "%" range means to replace in all lines. The "g" flag at the end causes
all words in a line to be replaced.
This will not do the right thing if your file also contains "thirtyfour".
It would be replaced with "thirty4". To avoid this, use the "\<" item to
match the start of a word:
:%s/\<four/4/g
Obviously, this still goes wrong on "fourteen". Use "\>" to match the end of
a word:
:%s/\<four\>/4/g
If you are programming, you might want to replace "four" in comments, but not
in the code. Since this is difficult to specify, add the "c" flag to have the
substitute command prompt you for each replacement:
:%s/\<four\>/4/gc
util.o \
getopt1.o \
inp.o \
patch.o \
backup.o
To sort this list, filter the text through the external sort command:
/^OBJS
j
:.,/^$/-1!sort
This goes to the first line, where "OBJS" is the first thing in the line.
Then it goes one line down and filters the lines until the next empty line.
You could also select the lines in Visual mode and then use "!sort". That's
easier to type, but more work when there are many lines.
The result is this:
OBJS = \
backup.o
getopt.o \
getopt1.o \
inp.o \
patch.o \
pch.o \
util.o \
version.o \
Notice that a backslash at the end of each line is used to indicate the line
continues. After sorting, this is wrong! The "backup.o" line that was at
the end didn't have a backslash. Now that it sorts to another place, it
must have a backslash.
The simplest solution is to add the backslash with "A \<Esc>". You can
keep the backslash in the last line, if you make sure an empty line comes
after it. That way you don't have this problem again.
==============================================================================
*12.4* Reverse line order
The |:global| command can be combined with the |:move| command to move all the
lines before the first line, resulting in a reversed file. The command is:
:global/^/m 0
Abbreviated:
:g/^/m 0
The "^" regular expression matches the beginning of the line (even if the line
is blank). The |:move| command moves the matching line to after the mythical
zeroth line, so the current matching line becomes the first line of the file.
As the |:global| command is not confused by the changing line numbering,
|:global| proceeds to match all remaining lines of the file and puts each as
the first.
This also works on a range of lines. First move to above the first line and
mark it with "mt". Then move the cursor to the last line in the range and
type:
:'t+1,.g/^/m 't
==============================================================================
*12.5* Count words
Sometimes you have to write a text with a maximum number of words. Vim can
count the words for you.
When the whole file is what you want to count the words in, use this
command:
g CTRL-G
Do not type a space after the g, this is just used here to make the command
easy to read.
The output looks like this:
Col 1 of 0; Line 141 of 157; Word 748 of 774; Byte 4489 of 4976
You can see on which word you are (748), and the total number of words in the
file (774).
When the text is only part of a file, you could move to the start of the text,
type "g CTRL-G", move to the end of the text, type "g CTRL-G" again, and then
use your brain to compute the difference in the word position. That's a good
exercise, but there is an easier way. With Visual mode, select the text you
want to count words in. Then type g CTRL-G. The result:
Selected 5 of 293 Lines; 70 of 1884 Words; 359 of 10928 Bytes
For other ways to count words, lines and other items, see |count-items|.
==============================================================================
*12.6* Find a man page *find-manpage*
While editing a shell script or C program, you are using a command or function
that you want to find the man page for (this is on Unix). Let's first use a
simple way: Move the cursor to the word you want to find help on and press
K
Vim will run the external "man" program on the word. If the man page is
found, it is displayed. This uses the normal pager to scroll through the text
(mostly the "more" program). When you get to the end pressing <Enter> will
get you back into Vim.
A disadvantage is that you can't see the man page and the text you are working
on at the same time. There is a trick to make the man page appear in a Vim
window. First, load the man filetype plugin:
:runtime! ftplugin/man.vim
Put this command in your vimrc file if you intend to do this often. Now you
can use the ":Man" command to open a window on a man page:
:Man csh
You can scroll around and the text is highlighted. This allows you to find
the help you were looking for. Use CTRL-W w to jump to the window with the
text you were working on.
To find a man page in a specific section, put the section number first.
For example, to look in section 3 for "echo":
:Man 3 echo
To jump to another man page, which is in the text with the typical form
"word(1)", press CTRL-] on it. Further ":Man" commands will use the same
window.
To display a man page for the word under the cursor, use this:
\K
(If you redefined the <Leader>, use it instead of the backslash).
For example, you want to know the return value of "strstr()" while editing
this line:
if ( strstr (input, "aap") == )
Move the cursor to somewhere on "strstr" and type "\K". A window will open
to display the man page for strstr().
==============================================================================
*12.7* Trim blanks
Some people find spaces and tabs at the end of a line useless, wasteful, and
ugly. To remove whitespace at the end of every line, execute the following
command:
:%s/\s\+$//
The line range "%" is used, thus this works on the whole file. The pattern
that the ":substitute" command matches with is "\s\+$". This finds white
space characters (\s), 1 or more of them (\+), before the end-of-line ($).
Later will be explained how you write patterns like this |usr_27.txt|.
The "to" part of the substitute command is empty: "//". Thus it replaces
Vim has a few generic features that makes it easier to enter commands. Colon
commands can be abbreviated, edited and repeated. Completion is available for
nearly everything.
|20.1| Command line editing
|20.2| Command line abbreviations
|20.3| Command line completion
|20.4| Command line history
|20.5| Command line window
Next chapter: |usr_21.txt| Go away and come back
Previous chapter: |usr_12.txt| Clever tricks
Table of contents: |usr_toc.txt|
==============================================================================
*20.1* Command line editing
When you use a colon (:) command or search for a string with / or ?, Vim puts
the cursor on the bottom of the screen. There you type the command or search
pattern. This is called the Command line. Also when it's used for entering a
search command.
The most obvious way to edit the command you type is by pressing the <BS> key.
This erases the character before the cursor. To erase another character,
typed earlier, first move the cursor with the cursor keys.
For example, you have typed this:
:s/col/pig/
Before you hit <Enter>, you notice that "col" should be "cow". To correct
this, you type <Left> five times. The cursor is now just after "col". Type
<BS> and "w" to correct:
:s/cow/pig/
Now you can press <Enter> directly. You don't have to move the cursor to the
end of the line before executing the command.
The most often used keys to move around in the command line:
<Left> one character left
<Right> one character right
<S-Left> or <C-Left> one word left
<S-Right> or <C-Right> one word right
CTRL-B or <Home> to begin of command line
CTRL-E or <End> to end of command line
Note:
<S-Left> (cursor left key with Shift key pressed) and <C-Left> (cursor
left key with Control pressed) will not work on all keyboards. Same
for the other Shift and Control combinations.
You can also use the mouse to move the cursor.
DELETING
As mentioned, <BS> deletes the character before the cursor. To delete a whole
word use CTRL-W.
/the fine pig
CTRL-W
/the fine
CTRL-U removes all text, thus allows you to start all over again.
OVERSTRIKE
The <Insert> key toggles between inserting characters and replacing the
existing ones. Start with this text:
/the fine pig
Move the cursor to the start of "fine" with <S-Left> twice (or <Left> eight
times, if <S-Left> doesn't work). Now press <Insert> to switch to overstrike
and type "great":
/the greatpig
Oops, we lost the space. Now, don't use <BS>, because it would delete the
"t" (this is different from Replace mode). Instead, press <Insert> to switch
from overstrike to inserting, and type the space:
/the great pig
CANCELLING
You thought of executing a : or / command, but changed your mind. To get rid
of what you already typed, without executing it, press CTRL-C or <Esc>.
Note:
<Esc> is the universal "get out" key. Unfortunately, in the good old
Vi pressing <Esc> in a command line executed the command! Since that
might be considered to be a bug, Vim uses <Esc> to cancel the command.
But with the 'cpoptions' option it can be made Vi compatible. And
when using a mapping (which might be written for Vi) <Esc> also works
Vi compatible. Therefore, using CTRL-C is a method that always works.
If you are at the start of the command line, pressing <BS> will cancel the
command. It's like deleting the ":" or "/" that the line starts with.
==============================================================================
*20.2* Command line abbreviations
Some of the ":" commands are really long. We already mentioned that
":substitute" can be abbreviated to ":s". This is a generic mechanism, all
":" commands can be abbreviated.
How short can a command get? There are 26 letters, and many more commands.
For example, ":set" also starts with ":s", but ":s" doesn't start a ":set"
command. Instead ":set" can be abbreviated to ":se".
When the shorter form of a command could be used for two commands, it
stands for only one of them. There is no logic behind which one, you have to
learn them. In the help files the shortest form that works is mentioned. For
example:
:s[ubstitute]
This means that the shortest form of ":substitute" is ":s". The following
characters are optional. Thus ":su" and ":sub" also work.
In the user manual we will either use the full name of command, or a short
version that is still readable. For example, ":function" can be abbreviated
to ":fu". But since most people don't understand what that stands for, we
will use ":fun". (Vim doesn't have a ":funny" command, otherwise ":fun" would
be confusing too.)
It is recommended that in Vim scripts you write the full command name. That
makes it easier to read back when you make later changes. Except for some
often used commands like ":w" (":write") and ":r" (":read").
CONTEXT
When you type ":set i" instead of ":edit i" and press <Tab> you get:
:set icon
Hey, why didn't you get ":set info.txt"? That's because Vim has context
sensitive completion. The kind of words Vim will look for depends on the
command before it. Vim knows that you cannot use a file name just after a
":set" command, but you can use an option name.
Again, if you repeat typing the <Tab>, Vim will cycle through all matches.
There are quite a few, it's better to type more characters first:
:set isk<Tab>
Gives:
:set iskeyword
Now type "=" and press <Tab>:
:set iskeyword=@,48-57,_,192-255
What happens here is that Vim inserts the old value of the option. Now you
can edit it.
What is completed with <Tab> is what Vim expects in that place. Just try
it out to see how it works. In some situations you will not get what you
want. That's either because Vim doesn't know what you want, or because
completion was not implemented for that situation. In that case you will get
a <Tab> inserted (displayed as ^I).
LIST MATCHES
When there are many matches, you would like to see an overview. Do this by
pressing CTRL-D. For example, pressing CTRL-D after:
:set is
results in:
:set is
incsearch isfname isident iskeyword isprint
:set is
Vim lists the matches and then comes back with the text you typed. You can
now check the list for the item you wanted. If it isn't there, you can use
<BS> to correct the word. If there are many matches, type a few more
characters before pressing <Tab> to complete the rest.
If you have watched carefully, you will have noticed that "incsearch"
doesn't start with "is". In this case "is" stands for the short name of
"incsearch". (Many options have a short and a long name.) Vim is clever
enough to know that you might have wanted to expand the short name of the
option into the long name.
THERE IS MORE
The CTRL-L command completes the word to the longest unambiguous string. If
you type ":edit i" and there are files "info.txt" and "info_backup.txt" you
will get ":edit info".
The 'wildmode' option can be used to change the way completion works.
The 'wildmenu' option can be used to get a menu-like list of matches.
Use the 'suffixes' option to specify files that are less important and appear
at the end of the list of files.
The 'wildignore' option specifies files that are not listed at all.
More about all of this here: |cmdline-completion|
==============================================================================
*20.4* Command line history
In chapter 3 we briefly mentioned the history. The basics are that you can
use the <Up> key to recall an older command line. <Down> then takes you back
to newer commands.
There are actually four histories. The ones we will mention here are for ":"
commands and for "/" and "?" search commands. The "/" and "?" commands share
the same history, because they are both search commands. The two other
histories are for expressions and input lines for the input() function.
|cmdline-history|
Suppose you have done a ":set" command, typed ten more colon commands and then
want to repeat that ":set" command again. You could press ":" and then ten
==============================================================================
Next chapter: |usr_21.txt| Go away and come back
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
This chapter goes into mixing the use of other programs with Vim. Either by
executing program from inside Vim or by leaving Vim and coming back later.
Furthermore, this is about the ways to remember the state of Vim and restore
it later.
|21.1| Suspend and resume
|21.2| Executing shell commands
|21.3| Remembering information; viminfo
|21.4| Sessions
|21.5| Views
|21.6| Modelines
Next chapter: |usr_22.txt| Finding the file to edit
Previous chapter: |usr_20.txt| Typing command-line commands quickly
Table of contents: |usr_toc.txt|
==============================================================================
*21.1* Suspend and resume
Like most Unix programs Vim can be suspended by pressing CTRL-Z. This stops
Vim and takes you back to the shell it was started in. You can then do any
other commands until you are bored with them. Then bring back Vim with the
"fg" command.
CTRL-Z
{any sequence of shell commands}
fg
You are right back where you left Vim, nothing has changed.
In case pressing CTRL-Z doesn't work, you can also use ":suspend".
Don't forget to bring Vim back to the foreground, you would lose any changes
that you made!
Only Unix has support for this. On other systems Vim will start a shell for
you. This also has the functionality of being able to execute shell commands.
But it's a new shell, not the one that you started Vim from.
When you are running the GUI you can't go back to the shell where Vim was
started. CTRL-Z will minimize the Vim window instead.
==============================================================================
*21.2* Executing shell commands
To execute a single shell command from Vim use ":!{command}". For example, to
see a directory listing:
:!ls
:!dir
The first one is for Unix, the second one for MS-Windows.
Vim will execute the program. When it ends you will get a prompt to hit
<Enter>. This allows you to have a look at the output from the command before
returning to the text you were editing.
The "!" is also used in other places where a program is run. Let's take
a look at an overview:
up the window layout, you can go back to the last saved session:
:source ~/.vim/boring.vim
Thus you have complete control over whether you want to continue next time
where you are now, by saving the current setup in a session, or keep the
session file as a starting point.
Another way of using sessions is to create a window layout that you like to
use, and save this in a session. Then you can go back to this layout whenever
you want.
For example, this is a nice layout to use:
+----------------------------------------+
| VIM - main help file |
| |
|Move around: Use the cursor keys, or "h|
|help.txt================================|
|explorer | |
|dir |~ ||||
|dir |~ ||||
|file |~ ||||
|file |~ ||||
|file |~ ||||
|file |~ ||||
|~/=========|[No File]===================|
| |
+----------------------------------------+
This has a help window at the top, so that you can read this text. The narrow
vertical window on the left contains a file explorer. This is a Vim plugin
that lists the contents of a directory. You can select files to edit there.
More about this in the next chapter.
Create this from a just started Vim with:
:help
CTRL-W w
:vertical split ~/
You can resize the windows a bit to your liking. Then save the session with:
:mksession ~/.vim/mine.vim
Now you can start Vim with this layout:
vim -S ~/.vim/mine.vim
Hint: To open a file you see listed in the explorer window in the empty
window, move the cursor to the filename and press "O". Double clicking with
the mouse will also do this.
the top of the file. For text files and other files where the modeline gets
in the way of the normal contents, put it at the end of the file.
The 'modelines' option specifies how many lines at the start and end of the
file are inspected for containing a modeline. To inspect ten lines:
:set modelines=10
The 'modeline' option can be used to switch this off. Do this when you are
working as root on Unix or Administrator on MS-Windows, or when you don't
trust the files you are editing:
:set nomodeline
Use this format for the modeline:
any-text vim:set {option}={value} ... : any-text
The "any-text" indicates that you can put any text before and after the part
that Vim will use. This allows making it look like a comment, like what was
done above with /* and */.
The " vim:" part is what makes Vim recognize this line. There must be
white space before "vim", or "vim" must be at the start of the line. Thus
using something like "gvim:" will not work.
The part between the colons is a ":set" command. It works the same way as
typing the ":set" command, except that you need to insert a backslash before a
colon (otherwise it would be seen as the end of the modeline).
Another example:
// vim:set textwidth=72 dir=c\:\tmp: use c:\tmp here
There is an extra backslash before the first colon, so that it's included in
the ":set" command. The text after the second colon is ignored, thus a remark
can be placed there.
For more details see |modeline|.
==============================================================================
Next chapter: |usr_22.txt| Finding the file to edit
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
Files can be found everywhere. So how do you find them? Vim offers various
ways to browse the directory tree. There are commands to jump to a file that
is mentioned in another. And Vim remembers which files have been edited
before.
|22.1| The file browser
|22.2| The current directory
|22.3| Finding a file
|22.4| The buffer list
Next chapter: |usr_23.txt| Editing other files
Previous chapter: |usr_21.txt| Go away and come back
Table of contents: |usr_toc.txt|
==============================================================================
*22.1* The file browser
Vim has a plugin that makes it possible to edit a directory. Try this:
:edit .
Through the magic of autocommands and Vim scripts, the window will be filled
with the contents of the directory. It looks like this:
" ============================================================================
" Netrw Directory Listing (netrw v109)
" Sorted by name
" Sort sequence: [\/]$,\.h$,\.c$,\.cpp$,*,\.info$,\.swp$,\.o$\.obj$,\.bak$
" Quick Help: <F1>:help -:go up dir D:delete R:rename s:sort-by x:exec
" ============================================================================
../
./
check/
Makefile
autocmd.txt
change.txt
eval.txt~
filetype.txt~
help.txt.info
You can see these items:
1. The name of the browsing tool and its version number
2. The name of the browsing directory
3. The method of sorting (may be by name, time, or size)
4. How names are to be sorted (directories first, then *.h files,
*.c files, etc)
5. How to get help (use the <F1> key), and an abbreviated listing
of available commands
6. A listing of files, including "../", which allows one to list
the parent directory.
If you have syntax highlighting enabled, the different parts are highlighted
so as to make it easier to spot them.
You can use Normal mode Vim commands to move around in the text. For example,
move the cursor atop a file and press <Enter>; you will then be editing that
file. To go back to the browser use ":edit ." again, or use ":Explore".
CTRL-O also works.
Try using <Enter> while the cursor is atop a directory name. The result is
that the file browser moves into that directory and displays the items found
there. Pressing <Enter> on the first directory "../" moves you one level
higher. Pressing "-" does the same thing, without the need to move to the
"../" item first.
You can press <F1> to get help on the things you can do in the netrw file
browser. This is what you get:
9. Directory Browsing netrw-browse netrw-dir netrw-list netrw-help
MAPS netrw-maps
<F1>.............Help.......................................|netrw-help|
<cr>.............Browsing...................................|netrw-cr|
<del>............Deleting Files or Directories..............|netrw-delete|
-................Going Up...................................|netrw--|
a................Hiding Files or Directories................|netrw-a|
mb...............Bookmarking a Directory....................|netrw-mb|
gb...............Changing to a Bookmarked Directory.........|netrw-gb|
c................Make Browsing Directory The Current Dir....|netrw-c|
d................Make A New Directory.......................|netrw-d|
D................Deleting Files or Directories..............|netrw-D|
<c-h>............Edit File/Directory Hiding List............|netrw-ctrl-h|
i................Change Listing Style.......................|netrw-i|
<c-l>............Refreshing the Listing.....................|netrw-ctrl-l|
o................Browsing with a Horizontal Split...........|netrw-o|
p................Use Preview Window.........................|netrw-p|
P................Edit in Previous Window....................|netrw-p|
q................Listing Bookmarks and History..............|netrw-q|
r................Reversing Sorting Order....................|netrw-r|
(etc)
The <F1> key thus brings you to a netrw directory browsing contents help page.
It's a regular help page; use the usual |CTRL-]| to jump to tagged help items
and |CTRL-O| to jump back.
To select files for display and editing: (with the cursor is atop a filename)
<enter> Open the file in the current window. |netrw-cr|
o Horizontally split window and display file |netrw-o|
v Vertically split window and display file |netrw-v|
p Use the |preview-window| |netrw-p|
P Edit in the previous window |netrw-P|
t Open file in a new tab |netrw-t|
The following normal-mode commands may be used to control the browser display:
i Controls listing style (thin, long, wide, and tree).
The long listing includes size and date information.
s Repeatedly pressing s will change the way the files
are sorted; one may sort on name, modification time,
or size.
r Reverse the sorting order.
As a sampling of extra normal-mode commands:
c Change Vim's notion of the current directory to be
the same as the browser directory. (see
|g:netrw_keepdir| to control this, too)
R Rename the file or directory under the cursor; a
prompt will be issued for the new name.
D Delete the file or directory under the cursor; a
confirmation request will be issued.
mb gb Make bookmark/goto bookmark
#include "inits.h"
You want to see what is in that "inits.h" file. Move the cursor on the name
of the file and type:
gf
Vim will find the file and edit it.
What if the file is not in the current directory? Vim will use the 'path'
option to find the file. This option is a list of directory names where to
look for your file.
Suppose you have your include files located in "c:/prog/include". This
command will add it to the 'path' option:
:set path+=c:/prog/include
This directory is an absolute path. No matter where you are, it will be the
same place. What if you have located files in a subdirectory, below where the
file is? Then you can specify a relative path name. This starts with a dot:
:set path+=./proto
This tells Vim to look in the directory "proto", below the directory where the
file in which you use "gf" is. Thus using "gf" on "inits.h" will make Vim
look for "proto/inits.h", starting in the directory of the file.
Without the "./", thus "proto", Vim would look in the "proto" directory
below the current directory. And the current directory might not be where the
file that you are editing is located.
The 'path' option allows specifying the directories where to search for files
in many more ways. See the help on the 'path' option.
The 'isfname' option is used to decide which characters are included in the
file name, and which ones are not (e.g., the " character in the example
above).
When you know the file name, but it's not to be found in the file, you can
type it:
:find inits.h
Vim will then use the 'path' option to try and locate the file. This is the
same as the ":edit" command, except for the use of 'path'.
To open the found file in a new window use CTRL-W f instead of "gf", or use
":sfind" instead of ":find".
A nice way to directly start Vim to edit a file somewhere in the 'path':
vim "+find stdio.h"
This finds the file "stdio.h" in your value of 'path'. The quotes are
necessary to have one argument |-+c|.
==============================================================================
*22.4* The buffer list
The Vim editor uses the term buffer to describe a file being edited.
Actually, a buffer is a copy of the file that you edit. When you finish
changing the buffer, you write the contents of the buffer to the file.
Buffers not only contain file contents, but also all the marks, settings, and
other stuff that goes with it.
HIDDEN BUFFERS
Suppose you are editing the file one.txt and need to edit the file two.txt.
You could simply use ":edit two.txt", but since you made changes to one.txt
that won't work. You also don't want to write one.txt yet. Vim has a
solution for you:
:hide edit two.txt
The buffer "one.txt" disappears from the screen, but Vim still knows that you
are editing this buffer, so it keeps the modified text. This is called a
hidden buffer: The buffer contains text, but you can't see it.
The argument of ":hide" is another command. ":hide" makes that command
behave as if the 'hidden' option was set. You could also set this option
yourself. The effect is that when any buffer is abandoned, it becomes hidden.
Be careful! When you have hidden buffers with changes, don't exit Vim
without making sure you have saved all the buffers.
INACTIVE BUFFERS
When a buffer has been used once, Vim remembers some information about it.
When it is not displayed in a window and it is not hidden, it is still in the
buffer list. This is called an inactive buffer. Overview:
Active Appears in a window, text loaded.
Hidden Not in a window, text loaded.
Inactive Not in a window, no text loaded.
The inactive buffers are remembered, because Vim keeps information about them,
like marks. And remembering the file name is useful too, so that you can see
which files you have edited. And edit them again.
LISTING BUFFERS
View the buffer list with this command:
:buffers
A command which does the same, is not so obvious to list buffers, but is much
shorter to type:
:ls
The output could look like this:
1 #h "help.txt" line 62
2 %a+ "usr_21.txt" line 1
3 "usr_toc.txt" line 1
The first column contains the buffer number. You can use this to edit the
buffer without having to type the name, see below.
After the buffer number come the flags. Then the name of the file
and the line number where the cursor was the last time.
The flags that can appear are these (from left to right):
u Buffer is unlisted |unlisted-buffer|.
% Current buffer.
# Alternate buffer.
a Buffer is loaded and displayed.
h Buffer is loaded but hidden.
= Buffer is read-only.
- Buffer is not modifiable, the 'modifiable' option is off.
+ Buffer has been modified.
EDITING A BUFFER
You can edit a buffer by its number. That avoids having to type the file
name:
:buffer 2
But the only way to know the number is by looking in the buffer list. You can
use the name, or part of it, instead:
:buffer help
Vim will find the best match for the name you type. If there is only one
buffer that matches the name, it will be used. In this case "help.txt".
To open a buffer in a new window:
:sbuffer 3
This works with a name as well.
This chapter is about editing files that are not ordinary files. With Vim you
can edit files that are compressed or encrypted. Some files need to be
accessed over the internet. With some restrictions, binary files can be
edited as well.
|23.1| DOS, Mac and Unix files
|23.2| Files on the internet
|23.3| Encryption
|23.4| Binary files
|23.5| Compressed files
Next chapter: |usr_24.txt| Inserting quickly
Previous chapter: |usr_22.txt| Finding the file to edit
Table of contents: |usr_toc.txt|
==============================================================================
*23.1* DOS, Mac and Unix files
Back in the early days, the old Teletype machines used two characters to
start a new line. One to move the carriage back to the first position
(carriage return, <CR>), another to move the paper up (line feed, <LF>).
When computers came out, storage was expensive. Some people decided that
they did not need two characters for end-of-line. The UNIX people decided
they could use <Line Feed> only for end-of-line. The Apple people
standardized on <CR>. The MS-DOS (and Microsoft Windows) folks decided to
keep the old <CR><LF>.
This means that if you try to move a file from one system to another, you
have line-break problems. The Vim editor automatically recognizes the
different file formats and handles things properly behind your back.
The option 'fileformats' contains the various formats that will be tried
when a new file is edited. The following command, for example, tells Vim to
try UNIX format first and MS-DOS format second:
:set fileformats=unix,dos
You will notice the format in the message you get when editing a file. You
don't see anything if you edit a native file format. Thus editing a Unix file
on Unix won't result in a remark. But when you edit a dos file, Vim will
notify you of this:
"/tmp/test" [dos] 3L, 71C
For a Mac file you would see "[mac]".
The detected file format is stored in the 'fileformat' option. To see
which format you have, execute the following command:
:set fileformat?
The three names that Vim uses are:
unix <LF>
dos <CR><LF>
mac <CR>
CONVERSION
You can use the 'fileformat' option to convert from one file format to
another. Suppose, for example, that you have an MS-DOS file named README.TXT
that you want to convert to UNIX format. Start by editing the MS-DOS format
file:
vim README.TXT
Vim will recognize this as a dos format file. Now change the file format to
UNIX:
:set fileformat=unix
:write
The file is written in Unix format.
==============================================================================
*23.2* Files on the internet
Someone sends you an e-mail message, which refers to a file by its URL. For
example:
You can find the information here:
ftp://ftp.vim.org/pub/vim/README
You could start a program to download the file, save it on your local disk and
then start Vim to edit it.
There is a much simpler way. Move the cursor to any character of the URL.
Then use this command:
gf
With a bit of luck, Vim will figure out which program to use for downloading
the file, download it and edit the copy. To open the file in a new window use
CTRL-W f.
If something goes wrong you will get an error message. It's possible that
the URL is wrong, you don't have permission to read it, the network connection
is down, etc. Unfortunately, it's hard to tell the cause of the error. You
might want to try the manual way of downloading the file.
Accessing files over the internet works with the netrw plugin. Currently URLs
with these formats are recognized:
ftp:// uses ftp
LIMITS ON ENCRYPTION
The encryption algorithm used by Vim is weak. It is good enough to keep out
the casual prowler, but not good enough to keep out a cryptology expert with
lots of time on his hands. Also you should be aware that the swap file is not
encrypted; so while you are editing, people with superuser privileges can read
the unencrypted text from this file.
One way to avoid letting people read your swap file is to avoid using one.
If the -n argument is supplied on the command line, no swap file is used
(instead, Vim puts everything in memory). For example, to edit the encrypted
file "file.txt" without a swap file use the following command:
vim -x -n file.txt
When already editing a file, the swapfile can be disabled with:
:setlocal noswapfile
Since there is no swapfile, recovery will be impossible. Save the file a bit
more often to avoid the risk of losing your changes.
While the file is in memory, it is in plain text. Anyone with privilege can
look in the editor's memory and discover the contents of the file.
If you use a viminfo file, be aware that the contents of text registers are
written out in the clear as well.
If you really want to secure the contents of a file, edit it only on a
portable computer not connected to a network, use good encryption tools, and
keep the computer locked up in a big safe when not in use.
==============================================================================
*23.4* Binary files
You can edit binary files with Vim. Vim wasn't really made for this, thus
there are a few restrictions. But you can read a file, change a character and
write it back, with the result that only that one character was changed and
the file is identical otherwise.
To make sure that Vim does not use its clever tricks in the wrong way, add
the "-b" argument when starting Vim:
vim -b datafile
This sets the 'binary' option. The effect of this is that unexpected side
effects are turned off. For example, 'textwidth' is set to zero, to avoid
automatic formatting of lines. And files are always read in Unix file format.
Binary mode can be used to change a message in a program. Be careful not to
insert or delete any characters, it would stop the program from working. Use
"R" to enter replace mode.
Many characters in the file will be unprintable. To see them in Hex format:
:set display=uhex
Otherwise, the "ga" command can be used to see the value of the character
under the cursor. The output, when the cursor is on an <Esc>, looks like
this:
<^[> 27, Hex 1b, Octal 033
There might not be many line breaks in the file. To get some overview switch
the 'wrap' option off:
:set nowrap
BYTE POSITION
To see on which byte you are in the file use this command:
g CTRL-G
The output is verbose:
Col 9-16 of 9-16; Line 277 of 330; Word 1806 of 2058; Byte 10580 of 12206
The last two numbers are the byte position in the file and the total number of
bytes. This takes into account how 'fileformat' changes the number of bytes
that a line break uses.
To move to a specific byte in the file, use the "go" command. For
example, to move to byte 2345:
2345go
USING XXD
A real binary editor shows the text in two ways: as it is and in hex format.
You can do this in Vim by first converting the file with the "xxd" program.
This comes with Vim.
First edit the file in binary mode:
vim -b datafile
Now convert the file to a hex dump with xxd:
:%!xxd
The text will look like this:
0000000: 1f8b 0808 39d7 173b 0203 7474 002b 4e49 ....9..;..tt.+NI
0000010: 4b2c 8660 eb9c ecac c462 eb94 345e 2e30 K,.`.....b..4^.0
0000020: 373b 2731 0b22 0ca6 c1a2 d669 1035 39d9 7;'1.".....i.59.
You can now view and edit the text as you like. Vim treats the information as
ordinary text. Changing the hex does not cause the printable character to be
changed, or the other way around.
Finally convert it back with:
:%!xxd -r
Only changes in the hex part are used. Changes in the printable text part on
the right are ignored.
See the manual page of xxd for more information.
==============================================================================
*23.5* Compressed files
This is easy: You can edit a compressed file just like any other file. The
"gzip" plugin takes care of decompressing the file when you edit it. And
compressing it again when you write it.
These compression methods are currently supported:
.Z compress
.gz gzip
.bz2 bzip2
Vim uses the mentioned programs to do the actual compression and
decompression. You might need to install the programs first.
==============================================================================
Next chapter: |usr_24.txt| Inserting quickly
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
When entering text, Vim offers various ways to reduce the number of keystrokes
and avoid typing mistakes. Use Insert mode completion to repeat previously
typed words. Abbreviate long words to short ones. Type characters that
aren't on your keyboard.
|24.1| Making corrections
|24.2| Showing matches
|24.3| Completion
|24.4| Repeating an insert
|24.5| Copying from another line
|24.6| Inserting a register
|24.7| Abbreviations
|24.8| Entering special characters
|24.9| Digraphs
|24.10| Normal mode commands
Next chapter: |usr_25.txt| Editing formatted text
Previous chapter: |usr_23.txt| Editing other files
Table of contents: |usr_toc.txt|
==============================================================================
*24.1* Making corrections
The <BS> key was already mentioned. It deletes the character just before the
cursor. The <Del> key does the same for the character under (after) the
cursor.
When you typed a whole word wrong, use CTRL-W:
The horse had fallen to the sky
CTRL-W
The horse had fallen to the
If you really messed up a line and want to start over, use CTRL-U to delete
it. This keeps the text after the cursor and the indent. Only the text from
the first non-blank to the cursor is deleted. With the cursor on the "f" of
"fallen" in the next line pressing CTRL-U does this:
The horse had fallen to the
CTRL-U
fallen to the
When you spot a mistake a few words back, you need to move the cursor there to
correct it. For example, you typed this:
The horse had follen to the ground
You need to change "follen" to "fallen". With the cursor at the end, you
would type this to correct it:
<Esc>4blraA
get out of Insert mode <Esc>
four words back 4b
move on top of the "o" l
replace with "a" ra
OPTIONS
You can customize the search order with the 'complete' option.
The 'ignorecase' option is used. When it is set, case differences are ignored
when searching for matches.
A special option for completion is 'infercase'. This is useful to find
matches while ignoring case ('ignorecase' must be set) but still using the
case of the word typed so far. Thus if you type "For" and Vim finds a match
"fortunately", it will result in "Fortunately".
If the file name starts with / (Unix) or C:\ (MS-Windows) you can find all
files in the file system. For example, type "/u" and CTRL-X CTRL-F. This
will match "/usr" (this is on Unix):
the file is found in /usr/
If you now press CTRL-N you go back to "/u". Instead, to accept the "/usr/"
and go one directory level deeper, use CTRL-X CTRL-F again:
the file is found in /usr/X11R6/
The results depend on what is found in your file system, of course. The
matches are sorted alphabetically.
#include "file.h"
#include "main.h"
/* Main program begins */
The CTRL-@ command does a CTRL-A and then exits Insert mode. That's a quick
way of doing exactly the same insertion again.
==============================================================================
*24.5* Copying from another line
The CTRL-Y command inserts the character above the cursor. This is useful
when you are duplicating a previous line. For example, you have this line of
C code:
b_array[i]->s_next = a_array[i]->s_next;
Now you need to type the same line, but with "s_prev" instead of "s_next".
Start the new line, and press CTRL-Y 14 times, until you are at the "n" of
"next":
b_array[i]->s_next = a_array[i]->s_next;
b_array[i]->s_
Now you type "prev":
b_array[i]->s_next = a_array[i]->s_next;
b_array[i]->s_prev
Continue pressing CTRL-Y until the following "next":
b_array[i]->s_next = a_array[i]->s_next;
b_array[i]->s_prev = a_array[i]->s_
Now type "prev;" to finish it off.
The CTRL-E command acts like CTRL-Y except it inserts the character below the
cursor.
==============================================================================
*24.6* Inserting a register
The command CTRL-R {register} inserts the contents of the register. This is
useful to avoid having to type a long word. For example, you need to type
this:
r = VeryLongFunction(a) + VeryLongFunction(b) + VeryLongFunction(c)
The function name is defined in a different file. Edit that file and move the
cursor on top of the function name there, and yank it into register v:
"vyiw
"v is the register specification, "yiw" is yank-inner-word. Now edit the file
where the new line is to be inserted, and type the first letters:
r =
Now use CTRL-R v to insert the function name:
r = VeryLongFunction
You continue to type the characters in between the function name, and use
CTRL-R v two times more.
You could have done the same with completion. Using a register is useful
when there are many words that start with the same characters.
If the register contains characters such as <BS> or other special characters,
they are interpreted as if they had been typed from the keyboard. If you do
not want this to happen (you really want the <BS> to be inserted in the text),
use the command CTRL-R CTRL-R {register}.
==============================================================================
*24.7* Abbreviations
An abbreviation is a short word that takes the place of a long one. For
example, "ad" stands for "advertisement". Vim enables you to type an
abbreviation and then will automatically expand it for you.
To tell Vim to expand "ad" into "advertisement" every time you insert it,
use the following command:
:iabbrev ad advertisement
Now, when you type "ad", the whole word "advertisement" will be inserted into
the text. This is triggered by typing a character that can't be part of a
word, for example a space:
What Is Entered What You See
I saw the a I saw the a
I saw the ad I saw the ad
I saw the ad<Space> I saw the advertisement<Space>
The expansion doesn't happen when typing just "ad". That allows you to type a
word like "add", which will not get expanded. Only whole words are checked
for abbreviations.
LISTING ABBREVIATIONS
The ":abbreviate" command lists the abbreviations:
:abbreviate
i #e ****************************************/
i #b /****************************************
i JB Jack Benny
i ad advertisement
! teh the
The "i" in the first column indicates Insert mode. These abbreviations are
only active in Insert mode. Other possible characters are:
c Command-line mode :cabbrev
! both Insert and Command-line mode :abbreviate
Since abbreviations are not often useful in Command-line mode, you will mostly
use the ":iabbrev" command. That avoids, for example, that "ad" gets expanded
when typing a command like:
:edit ad
DELETING ABBREVIATIONS
REMAPPING ABBREVIATIONS
There is one thing to watch out for when defining an abbreviation: The
resulting string should not be mapped. For example:
:abbreviate @a adder
:imap dd disk-door
When you now type @a, you will get "adisk-doorer". That's not what you want.
To avoid this, use the ":noreabbrev" command. It does the same as
":abbreviate", but avoids that the resulting string is used for mappings:
:noreabbrev @a adder
Fortunately, it's unlikely that the result of an abbreviation is mapped.
==============================================================================
*24.8* Entering special characters
The CTRL-V command is used to insert the next character literally. In other
words, any special meaning the character has, it will be ignored. For
example:
CTRL-V <Esc>
Inserts an escape character. Thus you don't leave Insert mode. (Don't type
the space after CTRL-V, it's only to make this easier to read).
Note:
On MS-Windows CTRL-V is used to paste text. Use CTRL-Q instead of
CTRL-V. On Unix, on the other hand, CTRL-Q does not work on some
terminals, because it has a special meaning.
You can also use the command CTRL-V {digits} to insert a character with the
decimal number {digits}. For example, the character number 127 is the <Del>
character (but not necessarily the <Del> key!). To insert <Del> type:
CTRL-V 127
You can enter characters up to 255 this way. When you type fewer than two
digits, a non-digit will terminate the command. To avoid the need of typing a
non-digit, prepend one or two zeros to make three digits.
All the next commands insert a <Tab> and then a dot:
CTRL-V 9.
CTRL-V 09.
CTRL-V 009.
To enter a character in hexadecimal, use an "x" after the CTRL-V:
CTRL-V x7f
This also goes up to character 255 (CTRL-V xff). You can use "o" to type a
character as an octal number and two more methods allow you to type up to
a 16 bit and a 32 bit number (e.g., for a Unicode character):
CTRL-V o123
CTRL-V u1234
CTRL-V U12345678
==============================================================================
*24.9* Digraphs
Some characters are not on the keyboard. For example, the copyright character
(©). To type these characters in Vim, you use digraphs, where two characters
represent one. To enter a ©, for example, you press three keys:
CTRL-K Co
To find out what digraphs are available, use the following command:
:digraphs
Vim will display the digraph table. Here are three lines of it:
AC ~_ 159 NS | 160 !I ¡ 161 Ct ¢ 162 Pd £ 163 Cu ¤ 164 Ye ¥ 165
BB ¦ 166 SE § 167 ': ¨ 168 Co © 169 -a ª 170 << « 171 NO ¬ 172
-- 173 Rg ® 174 'm ¯ 175 DG ° 176 +- ± 177 2S ² 178 3S ³ 179
This shows, for example, that the digraph you get by typing CTRL-K Pd is the
character (£). This is character number 163 (decimal).
Pd is short for Pound. Most digraphs are selected to give you a hint about
the character they will produce. If you look through the list you will
understand the logic.
You can exchange the first and second character, if there is no digraph for
that combination. Thus CTRL-K dP also works. Since there is no digraph for
"dP" Vim will also search for a "Pd" digraph.
Note:
The digraphs depend on the character set that Vim assumes you are
using. On MS-DOS they are different from MS-Windows. Always use
":digraphs" to find out which digraphs are currently available.
You can define your own digraphs. Example:
:digraph a" ä
This defines that CTRL-K a" inserts an ä character. You can also specify the
character with a decimal number. This defines the same digraph:
:digraph a" 228
More information about digraphs here: |digraphs|
Another way to insert special characters is with a keymap. More about that
here: |45.5|
==============================================================================
*24.10* Normal mode commands
Insert mode offers a limited number of commands. In Normal mode you have many
more. When you want to use one, you usually leave Insert mode with <Esc>,
execute the Normal mode command, and re-enter Insert mode with "i" or "a".
There is a quicker way. With CTRL-O {command} you can execute any Normal
mode command from Insert mode. For example, to delete from the cursor to the
end of the line:
CTRL-O D
You can execute only one Normal mode command this way. But you can specify a
register or a count. A more complicated example:
CTRL-O "g3dw
This deletes up to the third word into register g.
==============================================================================
Next chapter: |usr_25.txt| Editing formatted text
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
Text hardly ever comes in one sentence per line. This chapter is about
breaking sentences to make them fit on a page and other formatting.
Vim also has useful features for editing single-line paragraphs and tables.
|25.1| Breaking lines
|25.2| Aligning text
|25.3| Indents and tabs
|25.4| Dealing with long lines
|25.5| Editing tables
Next chapter: |usr_26.txt| Repeating
Previous chapter: |usr_24.txt| Inserting quickly
Table of contents: |usr_toc.txt|
==============================================================================
*25.1* Breaking lines
Vim has a number of functions that make dealing with text easier. By default,
the editor does not perform automatic line breaks. In other words, you have
to press <Enter> yourself. This is useful when you are writing programs where
you want to decide where the line ends. It is not so good when you are
creating documentation and want the text to be at most 70 character wide.
If you set the 'textwidth' option, Vim automatically inserts line breaks.
Suppose, for example, that you want a very narrow column of only 30
characters. You need to execute the following command:
:set textwidth=30
Now you start typing (ruler added):
1 2 3
12345678901234567890123456789012345
I taught programming for a whi
If you type "l" next, this makes the line longer than the 30-character limit.
When Vim sees this, it inserts a line break and you get the following:
1 2 3
12345678901234567890123456789012345
I taught programming for a
whil
Continuing on, you can type in the rest of the paragraph:
1 2 3
12345678901234567890123456789012345
I taught programming for a
while. One time, I was stopped
by the Fort Worth police,
because my homework was too
hard. True story.
You do not have to type newlines; Vim puts them in automatically.
Note:
The 'wrap' option makes Vim display lines with a line break, but this
doesn't insert a line break in the file.
REFORMATTING
The Vim editor is not a word processor. In a word processor, if you delete
something at the beginning of the paragraph, the line breaks are reworked. In
Vim they are not; so if you delete the word "programming" from the first line,
all you get is a short line:
1 2 3
12345678901234567890123456789012345
I taught for a
while. One time, I was stopped
by the Fort Worth police,
because my homework was too
hard. True story.
This does not look good. To get the paragraph into shape you use the "gq"
operator.
Let's first use this with a Visual selection. Starting from the first
line, type:
v4jgq
"v" to start Visual mode, "4j' to move to the end of the paragraph and then
the "gq" operator. The result is:
1 2 3
12345678901234567890123456789012345
I taught for a while. One
time, I was stopped by the
Fort Worth police, because my
homework was too hard. True
story.
Note: there is a way to do automatic formatting for specific types of text
layouts, see |auto-format|.
Since "gq" is an operator, you can use one of the three ways to select the
text it works on: With Visual mode, with a movement and with a text object.
The example above could also be done with "gq4j". That's less typing, but
you have to know the line count. A more useful motion command is "}". This
moves to the end of a paragraph. Thus "gq}" formats from the cursor to the
end of the current paragraph.
A very useful text object to use with "gq" is the paragraph. Try this:
gqap
"ap" stands for "a-paragraph". This formats the text of one paragraph
(separated by empty lines). Also the part before the cursor.
If you have your paragraphs separated by empty lines, you can format the
whole file by typing this:
gggqG
"gg" to move to the first line, "gqG" to format until the last line.
Warning: If your paragraphs are not properly separated, they will be joined
together. A common mistake is to have a line with a space or tab. That's a
blank line, but not an empty line.
Vim is able to format more than just plain text. See |fo-table| for how to
change this. See the 'joinspaces' option to change the number of spaces used
after a full stop.
It is possible to use an external program for formatting. This is useful
if your text can't be properly formatted with Vim's builtin command. See the
'formatprg' option.
==============================================================================
*25.2* Aligning text
To center a range of lines, use the following command:
:{range}center [width]
{range} is the usual command-line range. [width] is an optional line width to
RIGHT ALIGNMENT
Similarly, the ":right" command right-justifies the text:
:1,5right 37
gives this result:
I taught for a while. One
time, I was stopped by the
Fort Worth police, because my
homework was too hard. True
story.
LEFT ALIGNMENT
Finally there is this command:
:{range}left [margin]
Unlike ":center" and ":right", however, the argument to ":left" is not the
length of the line. Instead it is the left margin. If it is omitted, the
text will be put against the left side of the screen (using a zero margin
would do the same). If it is 5, the text will be indented 5 spaces. For
example, use these commands:
:1left 5
:2,5left
This results in the following:
I taught for a while. One
time, I was stopped by the
Fort Worth police, because my
homework was too hard. True
story.
JUSTIFYING TEXT
Vim has no built-in way of justifying text. However, there is a neat macro
package that does the job. To use this package, execute the following
command:
:runtime macros/justify.vim
This Vim script file defines a new visual command "_j". To justify a block of
text, highlight the text in Visual mode and then execute "_j".
Look in the file for more explanations. To go there, do "gf" on this name:
$VIMRUNTIME/macros/justify.vim.
An alternative is to filter the text through an external program. Example:
:%!fmt
==============================================================================
*25.3* Indents and tabs
Indents can be used to make text stand out from the rest. The example texts
in this manual, for example, are indented by eight spaces or a tab. You would
normally enter this by typing a tab at the start of each line. Take this
text:
the first line
INCREASING INDENT
To increase the amount of indent in a line, use the ">" operator. Often this
is used as ">>", which adds indent to the current line.
The amount of indent added is specified with the 'shiftwidth' option. The
default value is 8. To make ">>" insert four spaces worth of indent, for
example, type this:
:set shiftwidth=4
When used on the second line of the example text, this is what you get:
the first line
the second line
"4>>" will increase the indent of four lines.
TABSTOP
If you want to make indents a multiple of 4, you set 'shiftwidth' to 4. But
when pressing a <Tab> you still get 8 spaces worth of indent. To change this,
set the 'softtabstop' option:
:set softtabstop=4
This will make the <Tab> key insert 4 spaces worth of indent. If there are
already four spaces, a <Tab> character is used (saving seven characters in the
file). (If you always want spaces and no tab characters, set the 'expandtab'
option.)
Note:
You could set the 'tabstop' option to 4. However, if you edit the
file another time, with 'tabstop' set to the default value of 8, it
will look wrong. In other programs and when printing the indent will
also be wrong. Therefore it is recommended to keep 'tabstop' at eight
all the time. That's the standard value everywhere.
CHANGING TABS
You edit a file which was written with a tabstop of 3. In Vim it looks ugly,
because it uses the normal tabstop value of 8. You can fix this by setting
'tabstop' to 3. But you have to do this every time you edit this file.
Vim can change the use of tabstops in your file. First, set 'tabstop' to
make the indents look good, then use the ":retab" command:
:set tabstop=3
:retab 8
The ":retab" command will change 'tabstop' to 8, while changing the text such
that it looks the same. It changes spans of white space into tabs and spaces
for this. You can now write the file. Next time you edit it the indents will
be right without setting an option.
Warning: When using ":retab" on a program, it may change white space inside
a string constant. Therefore it's a good habit to use "\t" instead of a
real tab.
==============================================================================
*25.4* Dealing with long lines
Sometimes you will be editing a file that is wider than the number of columns
in the window. When that occurs, Vim wraps the lines so that everything fits
on the screen.
If you switch the 'wrap' option off, each line in the file shows up as one
line on the screen. Then the ends of the long lines disappear off the screen
to the right.
When you move the cursor to a character that can't be seen, Vim will scroll
the text to show it. This is like moving a viewport over the text in the
horizontal direction.
By default, Vim does not display a horizontal scrollbar in the GUI. If you
want to enable one, use the following command:
:set guioptions+=b
One horizontal scrollbar will appear at the bottom of the Vim window.
If you don't have a scrollbar or don't want to use it, use these commands to
scroll the text. The cursor will stay in the same place, but it's moved back
into the visible text if necessary.
zh scroll right
4zh scroll four characters right
zH scroll half a window width right
ze scroll right to put the cursor at the end
zl scroll left
4zl scroll four characters left
zL scroll half a window width left
zs scroll left to put the cursor at the start
Let's attempt to show this with one line of text. The cursor is on the "w" of
"which". The "current window" above the line indicates the text that is
currently visible. The "window"s below the text indicate the text that is
visible after the command left of it.
|<-- current window -->|
some long text, part of which is visible in the window
ze |<-- window -->|
zH |<-- window -->|
4zh |<-- window -->|
zh |<-- window -->|
zl |<-- window -->|
4zl |<-- window -->|
zL |<-- window -->|
zs |<-- window -->|
+---------------------------------+
|letter generation program for a |
|bank. They wanted to send out a |
|special, personalized letter to |
|their richest 1000 customers. |
|Unfortunately for the programmer,|
+---------------------------------+
Related options:
'breakat' specifies the characters where a break can be inserted.
'showbreak' specifies a string to show at the start of broken line.
Set 'textwidth' to zero to avoid a paragraph to be split.
COPYING A COLUMN
You want to add a column, which should be a copy of the third column and
placed before the "test 1" column. Do this in seven steps:
1. Move the cursor to the left upper corner of this column, e.g., with
"/test 3".
2. Press CTRL-V to start blockwise Visual mode.
3. Move the cursor down two lines with "2j". You are now in "virtual space":
the "input B" line of the "test 3" column.
4. Move the cursor right, to include the whole column in the selection, plus
the space that you want between the columns. "9l" should do it.
5. Yank the selected rectangle with "y".
6. Move the cursor to "test 1", where the new column must be placed.
7. Press "P".
The result should be:
nice table test 3 test 1 test 2 test 3
input A 0.693 0.534 0.693
input B 0.913
Notice that the whole "test 1" column was shifted right, also the line where
the "test 3" column didn't have text.
Go back to non-virtual cursor movements with:
:set virtualedit=
Suppose you have a lot of files in which you need to change the string
"-person-" to "Jones" and then print it. How do you do that? One way is to
do a lot of typing. The other is to write a shell script to do the work.
The Vim editor does a superb job as a screen-oriented editor when using
Normal mode commands. For batch processing, however, Normal mode commands do
not result in clear, commented command files; so here you will use Ex mode
instead. This mode gives you a nice command-line interface that makes it easy
to put into a batch file. ("Ex command" is just another name for a
command-line (:) command.)
The Ex mode commands you need are as follows:
%s/-person-/Jones/g
write tempfile
quit
You put these commands in the file "change.vim". Now to run the editor in
batch mode, use this shell script:
for file in *.txt; do
vim -e -s $file < change.vim
lpr -r tempfile
done
The for-done loop is a shell construct to repeat the two lines in between,
while the $file variable is set to a different file name each time.
The second line runs the Vim editor in Ex mode (-e argument) on the file
$file and reads commands from the file "change.vim". The -s argument tells
Vim to operate in silent mode. In other words, do not keep outputting the
:prompt, or any other prompt for that matter.
The "lpr -r tempfile" command prints the resulting "tempfile" and deletes
it (that's what the -r argument does).
In chapter 3 a few simple search patterns were mentioned |03.9|. Vim can do
much more complex searches. This chapter explains the most often used ones.
A detailed specification can be found here: |pattern|
|27.1| Ignoring case
|27.2| Wrapping around the file end
|27.3| Offsets
|27.4| Matching multiple times
|27.5| Alternatives
|27.6| Character ranges
|27.7| Character classes
|27.8| Matching a line break
|27.9| Examples
Next chapter: |usr_28.txt| Folding
Previous chapter: |usr_26.txt| Repeating
Table of contents: |usr_toc.txt|
==============================================================================
*27.1* Ignoring case
By default, Vim's searches are case sensitive. Therefore, "include",
"INCLUDE", and "Include" are three different words and a search will match
only one of them.
Now switch on the 'ignorecase' option:
:set ignorecase
Search for "include" again, and now it will match "Include", "INCLUDE" and
"InClUDe". (Set the 'hlsearch' option to quickly see where a pattern
matches.)
You can switch this off again with:
:set noignorecase
But let's keep it set, and search for "INCLUDE". It will match exactly the
same text as "include" did. Now set the 'smartcase' option:
:set ignorecase smartcase
If you have a pattern with at least one uppercase character, the search
becomes case sensitive. The idea is that you didn't have to type that
uppercase character, so you must have done it because you wanted case to
match. That's smart!
With these two options set you find the following matches:
pattern matches
word word, Word, WORD, WoRd, etc.
Word Word
WORD WORD
WoRd WoRd
If you want to ignore case for one specific pattern, you can do this by
prepending the "\c" string. Using "\C" will make the pattern to match case.
This overrules the 'ignorecase' and 'smartcase' options, when "\c" or "\C" is
used their value doesn't matter.
pattern matches
\Cword word
\CWord Word
\cword word, Word, WORD, WoRd, etc.
\cWord word, Word, WORD, WoRd, etc.
A big advantage of using "\c" and "\C" is that it sticks with the pattern.
Thus if you repeat a pattern from the search history, the same will happen, no
matter if 'ignorecase' or 'smartcase' was changed.
Note:
The use of "\" items in search patterns depends on the 'magic' option.
In this chapter we will assume 'magic' is on, because that is the
standard and recommended setting. If you would change 'magic', many
search patterns would suddenly become invalid.
Note:
If your search takes much longer than you expected, you can interrupt
it with CTRL-C on Unix and CTRL-Break on MS-DOS and MS-Windows.
==============================================================================
*27.2* Wrapping around the file end
By default, a forward search starts searching for the given string at the
current cursor location. It then proceeds to the end of the file. If it has
not found the string by that time, it starts from the beginning and searches
from the start of the file to the cursor location.
Keep in mind that when repeating the "n" command to search for the next
match, you eventually get back to the first match. If you don't notice this
you keep searching forever! To give you a hint, Vim displays this message:
search hit BOTTOM, continuing at TOP
If you use the "?" command, to search in the other direction, you get this
message:
search hit TOP, continuing at BOTTOM
Still, you don't know when you are back at the first match. One way to see
this is by switching on the 'ruler' option:
:set ruler
Vim will display the cursor position in the lower righthand corner of the
window (in the status line if there is one). It looks like this:
101,29 84%
The first number is the line number of the cursor. Remember the line number
where you started, so that you can check if you passed this position again.
NOT WRAPPING
To turn off search wrapping, use the following command:
:set nowrapscan
Now when the search hits the end of the file, an error message displays:
E385: search hit BOTTOM without match for: forever
Thus you can find all matches by going to the start of the file with "gg" and
keep searching until you see this message.
If you search in the other direction, using "?", you get:
E384: search hit TOP without match for: forever
==============================================================================
*27.3* Offsets
By default, the search command leaves the cursor positioned on the beginning
of the pattern. You can tell Vim to leave it some other place by specifying
an offset. For the forward search command "/", the offset is specified by
appending a slash (/) and the offset:
/default/2
This command searches for the pattern "default" and then moves to the
beginning of the second line past the pattern. Using this command on the
paragraph above, Vim finds the word "default" in the first line. Then the
cursor is moved two lines down and lands on "an offset".
If the offset is a simple number, the cursor will be placed at the beginning
of the line that many lines from the match. The offset number can be positive
or negative. If it is positive, the cursor moves down that many lines; if
negative, it moves up.
CHARACTER OFFSETS
The "e" offset indicates an offset from the end of the match. It moves the
cursor onto the last character of the match. The command:
/const/e
puts the cursor on the "t" of "const".
From that position, adding a number moves forward that many characters.
This command moves to the character just after the match:
/const/e+1
A positive number moves the cursor to the right, a negative number moves it to
the left. For example:
/const/e-1
moves the cursor to the "s" of "const".
If the offset begins with "b", the cursor moves to the beginning of the
pattern. That's not very useful, since leaving out the "b" does the same
thing. It does get useful when a number is added or subtracted. The cursor
then goes forward or backward that many characters. For example:
/const/b+2
Moves the cursor to the beginning of the match and then two characters to the
right. Thus it lands on the "n".
REPEATING
To repeat searching for the previously used search pattern, but with a
different offset, leave out the pattern:
/that
//e
Is equal to:
/that/e
To repeat with the same offset:
/
"n" does the same thing. To repeat while removing a previously used offset:
//
SEARCHING BACKWARDS
The "?" command uses offsets in the same way, but you must use "?" to separate
the offset from the pattern, instead of "/":
?const?e-2
The "b" and "e" keep their meaning, they don't change direction with the use
of "?".
START POSITION
When starting a search, it normally starts at the cursor position. When you
specify a line offset, this can cause trouble. For example:
/const/-2
This finds the next word "const" and then moves two lines up. If you
use "n" to search again, Vim could start at the current position and find the same
"const" match. Then using the offset again, you would be back where you started.
You would be stuck!
It could be worse: Suppose there is another match with "const" in the next
line. Then repeating the forward search would find this match and move two
lines up. Thus you would actually move the cursor back!
When you specify a character offset, Vim will compensate for this. Thus the
search starts a few characters forward or backward, so that the same match
isn't found again.
==============================================================================
*27.4* Matching multiple times
The "*" item specifies that the item before it can match any number of times.
Thus:
/a*
matches "a", "aa", "aaa", etc. But also "" (the empty string), because zero
times is included.
The "*" only applies to the item directly before it. Thus "ab*" matches
"a", "ab", "abb", "abbb", etc. To match a whole string multiple times, it
must be grouped into one item. This is done by putting "\(" before it and
"\)" after it. Thus this command:
/\(ab\)*
Matches: "ab", "abab", "ababab", etc. And also "".
To avoid matching the empty string, use "\+". This makes the previous item
match one or more times.
/ab\+
Matches "ab", "abb", "abbb", etc. It does not match "a" when no "b" follows.
To match an optional item, use "\=". Example:
/folders\=
Matches "folder" and "folders".
SPECIFIC COUNTS
To match a specific number of items use the form "\{n,m}". "n" and "m" are
numbers. The item before it will be matched "n" to "m" times |inclusive|.
Example:
/ab\{3,5}
matches "abbb", "abbbb" and "abbbbb".
When "n" is omitted, it defaults to zero. When "m" is omitted it defaults
to infinity. When ",m" is omitted, it matches exactly "n" times.
Examples:
pattern match count
\{,4} 0, 1, 2, 3 or 4
\{3,} 3, 4, 5, etc.
\{0,1} 0 or 1, same as \=
\{0,} 0 or more, same as *
\{1,} 1 or more, same as \+
\{3} 3
/ab\{-1,3}
Will match "ab" in "abbb". Actually, it will never match more than one b,
because there is no reason to match more. It requires something else to force
it to match more than the lower limit.
The same rules apply to removing "n" and "m". It's even possible to remove
both of the numbers, resulting in "\{-}". This matches the item before it
zero or more times, as few as possible. The item by itself always matches
zero times. It is useful when combined with something else. Example:
/a.\{-}b
This matches "axb" in "axbxb". If this pattern would be used:
/a.*b
It would try to match as many characters as possible with ".*", thus it
matches "axbxb" as a whole.
==============================================================================
*27.5* Alternatives
The "or" operator in a pattern is "\|". Example:
/foo\|bar
This matches "foo" or "bar". More alternatives can be concatenated:
/one\|two\|three
Matches "one", "two" and "three".
To match multiple times, the whole thing must be placed in "\(" and "\)":
/\(foo\|bar\)\+
This matches "foo", "foobar", "foofoo", "barfoobar", etc.
Another example:
/end\(if\|while\|for\)
This matches "endif", "endwhile" and "endfor".
A related item is "\&". This requires that both alternatives match in the
same place. The resulting match uses the last alternative. Example:
/forever\&...
This matches "for" in "forever". It will not match "fortuin", for example.
==============================================================================
*27.6* Character ranges
To match "a", "b" or "c" you could use "/a\|b\|c". When you want to match all
letters from "a" to "z" this gets very long. There is a shorter method:
/[a-z]
The [] construct matches a single character. Inside you specify which
characters to match. You can include a list of characters, like this:
/[0123456789abcdef]
This will match any of the characters included. For consecutive characters
you can specify the range. "0-3" stands for "0123". "w-z" stands for "wxyz".
Thus the same command as above can be shortened to:
/[0-9a-f]
To match the "-" character itself make it the first or last one in the range.
These special characters are accepted to make it easier to use them inside a
[] range (they can actually be used anywhere in the search pattern):
\e <Esc>
\t <Tab>
\r <CR>
\b <BS>
There are a few more special cases for [] ranges, see |/[]| for the whole
story.
COMPLEMENTED RANGE
To avoid matching a specific character, use "^" at the start of the range.
The [] item then matches everything but the characters included. Example:
/"[^"]*"
" a double quote
[^"] any character that is not a double quote
* as many as possible
" a double quote again
This matches "foo" and "3!x", including the double quotes.
PREDEFINED RANGES
A number of ranges are used very often. Vim provides a shortcut for these.
For example:
/\a
Finds alphabetic characters. This is equal to using "/[a-zA-Z]". Here are a
few more of these:
item matches equivalent
\d digit [0-9]
\D non-digit [^0-9]
\x hex digit [0-9a-fA-F]
\X non-hex digit [^0-9a-fA-F]
\s white space [ ] (<Tab> and <Space>)
\S non-white characters [^ ] (not <Tab> and <Space>)
\l lowercase alpha [a-z]
\L non-lowercase alpha [^a-z]
\u uppercase alpha [A-Z]
\U non-uppercase alpha [^A-Z]
Note:
Using these predefined ranges works a lot faster than the character
range it stands for.
These items can not be used inside []. Thus "[\d\l]" does NOT work to
match a digit or lowercase alpha. Use "\(\d\|\l\)" instead.
See |/\s| for the whole list of these ranges.
==============================================================================
*27.7* Character classes
The character range matches a fixed set of characters. A character class is
similar, but with an essential difference: The set of characters can be
redefined without changing the search pattern.
For example, search for this pattern:
/\f\+
The "\f" items stands for file name characters. Thus this matches a sequence
of characters that can be a file name.
Which characters can be part of a file name depends on the system you are
using. On MS-Windows, the backslash is included, on Unix it is not. This is
specified with the 'isfname' option. The default value for Unix is:
:set isfname
isfname=@,48-57,/,.,-,_,+,,,#,$,%,~,=
For other systems the default value is different. Thus you can make a search
pattern with "\f" to match a file name, and it will automatically adjust to
the system you are using it on.
Note:
Actually, Unix allows using just about any character in a file name,
including white space. Including these characters in 'isfname' would
be theoretically correct. But it would make it impossible to find the
end of a file name in text. Thus the default value of 'isfname' is a
compromise.
simple way you can remember is much faster than the fancy way that you can't.
If you can remember them all, then avoid the last one, because it's both more
typing and slower to execute.
FINDING AN IDENTIFIER
In C programs (and many other computer languages) an identifier starts with a
letter and further consists of letters and digits. Underscores can be used
too. This can be found with:
/\<\h\w*\>
"\<" and "\>" are used to find only whole words. "\h" stands for "[A-Za-z_]"
and "\w" for "[0-9A-Za-z_]".
Note:
"\<" and "\>" depend on the 'iskeyword' option. If it includes "-",
for example, then "ident-" is not matched. In this situation use:
/\w\@<!\h\w*\w\@!
This checks if "\w" does not match before or after the identifier.
See |/\@<!| and |/\@!|.
==============================================================================
Next chapter: |usr_28.txt| Folding
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
created a fold. |zf| is an operator and |ap| a text object selection. You
can use the |zf| operator with any movement command to create a fold for the
text that it moved over. |zf| also works in Visual mode.
To view the text again, open the fold by typing:
zo
And you can close the fold again with:
zc
All the folding commands start with "z". With some fantasy, this looks like a
folded piece of paper, seen from the side. The letter after the "z" has a
mnemonic meaning to make it easier to remember the commands:
zf F-old creation
zo O-pen a fold
zc C-lose a fold
Folds can be nested: A region of text that contains folds can be folded
again. For example, you can fold each paragraph in this section, and then
fold all the sections in this chapter. Try it out. You will notice that
opening the fold for the whole chapter will restore the nested folds as they
were, some may be open and some may be closed.
Suppose you have created several folds, and now want to view all the text.
You could go to each fold and type "zo". To do this faster, use this command:
zr
This will R-educe the folding. The opposite is:
zm
This folds M-ore. You can repeat "zr" and "zm" to open and close nested folds
of several levels.
If you have nested several levels deep, you can open all of them with:
zR
This R-educes folds until there are none left. And you can close all folds
with:
zM
This folds M-ore and M-ore.
You can quickly disable the folding with the |zn| command. Then |zN| brings
back the folding as it was. |zi| toggles between the two. This is a useful
way of working:
- create folds to get overview on your file
- move around to where you want to do your work
- do |zi| to look at the text and edit it
- do |zi| again to go back to moving around
More about manual folding in the reference manual: |fold-manual|
==============================================================================
*28.3* Working with folds
When some folds are closed, movement commands like "j" and "k" move over a
fold like it was a single, empty line. This allows you to quickly move around
over folded text.
You can yank, delete and put folds as if it was a single line. This is very
useful if you want to reorder functions in a program. First make sure that
each fold contains a whole function (or a bit less) by selecting the right
'foldmethod'. Then delete the function with "dd", move the cursor and put it
with "p". If some lines of the function are above or below the fold, you can
use Visual selection:
- put the cursor on the first line to be moved
- hit "V" to start Visual mode
- put the cursor on the last line to be moved
- hit "d" to delete the selected lines.
- move the cursor to the new position and "p"ut the lines there.
It is sometimes difficult to see or remember where a fold is located, thus
where a |zo| command would actually work. To see the defined folds:
:set foldcolumn=4
This will show a small column on the left of the window to indicate folds.
A "+" is shown for a closed fold. A "-" is shown at the start of each open
fold and "|" at following lines of the fold.
You can use the mouse to open a fold by clicking on the "+" in the foldcolumn.
Clicking on the "-" or a "|" below it will close an open fold.
To open all folds at the cursor line use |zO|.
To close all folds at the cursor line use |zC|.
To delete a fold at the cursor line use |zd|.
To delete all folds at the cursor line use |zD|.
When in Insert mode, the fold at the cursor line is never closed. That allows
you to see what you type!
Folds are opened automatically when jumping around or moving the cursor left
or right. For example, the "0" command opens the fold under the cursor
(if 'foldopen' contains "hor", which is the default). The 'foldopen' option
can be changed to open folds for specific commands. If you want the line
under the cursor always to be open, do this:
:set foldopen=all
Warning: You won't be able to move onto a closed fold then. You might want to
use this only temporarily and then set it back to the default:
:set foldopen&
You can make folds close automatically when you move out of it:
:set foldclose=all
This will re-apply 'foldlevel' to all folds that don't contain the cursor.
You have to try it out if you like how this feels. Use |zm| to fold more and
|zr| to fold less (reduce folds).
The folding is local to the window. This allows you to open two windows on
the same buffer, one with folds and one without folds. Or one with all folds
closed and one with all folds open.
==============================================================================
*28.4* Saving and restoring folds
When you abandon a file (starting to edit another one), the state of the folds
is lost. If you come back to the same file later, all manually opened and
closed folds are back to their default. When folds have been created
manually, all folds are gone! To save the folds use the |:mkview| command:
:mkview
This will store the settings and other things that influence the view on the
file. You can change what is stored with the 'viewoptions' option.
When you come back to the same file later, you can load the view again:
:loadview
You can store up to ten views on one file. For example, to save the current
setup as the third view and load the second view:
:mkview 3
:loadview 2
Note that when you insert or delete lines the views might become invalid.
Also check out the 'viewdir' option, which specifies where the views are
stored. You might want to delete old views now and then.
==============================================================================
*28.5* Folding by indent
Defining folds with |zf| is a lot of work. If your text is structured by
giving lower level items a larger indent, you can use the indent folding
method. This will create folds for every sequence of lines with the same
indent. Lines with a larger indent will become nested folds. This works well
with many programming languages.
==============================================================================
*28.9* Folding unchanged lines
This is useful when you set the 'diff' option in the same window. The
|vimdiff| command does this for you. Example:
:setlocal diff foldmethod=diff scrollbind nowrap foldlevel=1
Do this in every window that shows a different version of the same file. You
will clearly see the differences between the files, while the text that didn't
change is folded.
For more details see |fold-diff|.
==============================================================================
*28.10* Which fold method to use?
All these possibilities make you wonder which method you should choose.
Unfortunately, there is no golden rule. Here are some hints.
If there is a syntax file with folding for the language you are editing, that
is probably the best choice. If there isn't one, you might try to write it.
This requires a good knowledge of search patterns. It's not easy, but when
it's working you will not have to define folds manually.
Typing commands to manually fold regions can be used for unstructured text.
Then use the |:mkview| command to save and restore your folds.
The marker method requires you to change the file. If you are sharing the
files with other people or you have to meet company standards, you might not
be allowed to add them.
The main advantage of markers is that you can put them exactly where you
want them. That avoids that a few lines are missed when you cut and paste
folds. And you can add a comment about what is contained in the fold.
Folding by indent is something that works in many files, but not always very
well. Use it when you can't use one of the other methods. However, it is
very useful for outlining. Then you specifically use one 'shiftwidth' for
each nesting level.
Folding with expressions can make folds in almost any structured text. It is
quite simple to specify, especially if the start and end of a fold can easily
be recognized.
If you use the "expr" method to define folds, but they are not exactly how
you want them, you could switch to the "manual" method. This will not remove
the defined folds. Then you can delete or add folds manually.
==============================================================================
Next chapter: |usr_29.txt| Moving through programs
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
+-----------|-------------------------+
|
CTRL-] |
| +----------------------------+
+--> |void write_line(char *s) |
|{ |
| while (*s != 0) |
| write_char(*s++); |
|} | |
+--------|-------------------+
|
CTRL-] |
| +------------------------------------+
+--> |void write_char(char c) |
|{ |
| putchar((int)(unsigned char)c); |
|} |
+------------------------------------+
The ":tags" command shows the list of tags that you traversed through:
:tags
# TO tag FROM line in file/text
1 1 write_line 8 write_block.c
2 1 write_char 7 write_line.c
>
Now to go back. The CTRL-T command goes to the preceding tag. In the example
above you get back to the "write_line" function, in the call to "write_char".
This command takes a count argument that indicates how many tags to jump
back. You have gone forward, and now back. Let's go forward again. The
following command goes to the tag on top of the list:
:tag
You can prefix it with a count and jump forward that many tags. For example:
":3tag". CTRL-T also can be preceded with a count.
These commands thus allow you to go down a call tree with CTRL-] and back
up again with CTRL-T. Use ":tags" to find out where you are.
SPLIT WINDOWS
The ":tag" command replaces the file in the current window with the one
containing the new function. But suppose you want to see not only the old
function but also the new one? You can split the window using the ":split"
command followed by the ":tag" command. Vim has a shorthand command that does
both:
:stag tagname
To split the current window and jump to the tag under the cursor use this
command:
CTRL-W ]
If a count is specified, the new window will be that many lines high.
rattling. It may get a bit slow. In that case it's better to spend this
time while generating one big tags file. You might do this overnight.
This requires the Exuberant ctags program, mentioned above. It offers an
argument to search a whole directory tree:
cd ~/proj
ctags -R .
The nice thing about this is that Exuberant ctags recognizes various file
types. Thus this doesn't work just for C and C++ programs, also for Eiffel
and even Vim scripts. See the ctags documentation to tune this.
Now you only need to tell Vim where your big tags file is:
:set tags=~/proj/tags
MULTIPLE MATCHES
When a function is defined multiple times (or a method in several classes),
the ":tag" command will jump to the first one. If there is a match in the
current file, that one is used first.
You can now jump to other matches for the same tag with:
:tnext
Repeat this to find further matches. If there are many, you can select which
one to jump to:
:tselect tagname
Vim will present you with a list of choices:
# pri kind tag file
1 F f mch_init os_amiga.c
mch_init()
2 F f mch_init os_mac.c
mch_init()
3 F f mch_init os_msdos.c
mch_init(void)
4 F f mch_init os_riscos.c
mch_init()
Enter nr of choice (<CR> to abort):
You can now enter the number (in the first column) of the match that you would
like to jump to. The information in the other columns give you a good idea of
where the match is defined.
To move between the matching tags, these commands can be used:
:tfirst go to first match
:[count]tprevious go to [count] previous match
:[count]tnext go to [count] next match
:tlast go to last match
If [count] is omitted then one is used.
:tselect /^write_
The "^" specifies that the tag starts with "write_". Otherwise it would also
be found halfway a tag name. Similarly "$" at the end makes sure the pattern
matches until the end of a tag.
A TAGS BROWSER
Since CTRL-] takes you to the definition of the identifier under the cursor,
you can use a list of identifier names as a table of contents. Here is an
example.
First create a list of identifiers (this requires Exuberant ctags):
ctags --c-types=f -f functions *.c
Now start Vim without a file, and edit this file in Vim, in a vertically split
window:
vim
:vsplit functions
The window contains a list of all the functions. There is some more stuff,
but you can ignore that. Do ":setlocal ts=99" to clean it up a bit.
In this window, define a mapping:
:nnoremap <buffer> <CR> 0ye<C-W>w:tag <C-R>"<CR>
Move the cursor to the line that contains the function you want to go to.
Now press <Enter>. Vim will go to the other window and jump to the selected
function.
RELATED ITEMS
You can set 'ignorecase' to make case in tag names be ignored.
The 'tagbsearch' option tells if the tags file is sorted or not. The default
is to assume a sorted tags file, which makes a tags search a lot faster, but
doesn't work if the tags file isn't sorted.
The 'taglength' option can be used to tell Vim the number of significant
characters in a tag.
When you use the SNiFF+ program, you can use the Vim interface to it |sniff|.
SNiFF+ is a commercial program.
Cscope is a free program. It does not only find places where an identifier is
declared, but also where it is used. See |cscope|.
==============================================================================
*29.2* The preview window
When you edit code that contains a function call, you need to use the correct
arguments. To know what values to pass you can look at how the function is
defined. The tags mechanism works very well for this. Preferably the
definition is displayed in another window. For this the preview window can be
used.
To open a preview window to display the function "write_char":
:ptag write_char
Vim will open a window, and jumps to the tag "write_char". Then it takes you
back to the original position. Thus you can continue typing without the need
to use a CTRL-W command.
If the name of a function appears in the text, you can get its definition
in the preview window with:
CTRL-W }
There is a script that automatically displays the text where the word under
the cursor was defined. See |CursorHold-example|.
To close the preview window use this command:
:pclose
To edit a specific file in the preview window, use ":pedit". This can be
MOVING IN BRACES
The "[(" and "])" commands work similar to "[{" and "]}", except that they
work on () pairs instead of {} pairs.
[(
<--------------------------------
<-------
if (a == b && (c == d || (e > f)) && x > y)
-------------->
-------------------------------->
])
MOVING IN COMMENTS
To move back to the start of a comment use "[/". Move forward to the end of a
comment with "]/". This only works for /* - */ comments.
+-> +-> /*
| [/ | * A comment about --+
[/ | +-- * wonderful life. | ]/
| */ <-+
|
+-- foo = bar * 3; --+
| ]/
/* a short comment */ <-+
==============================================================================
*29.4* Finding global identifiers
You are editing a C program and wonder if a variable is declared as "int" or
"unsigned". A quick way to find this is with the "[I" command.
Suppose the cursor is on the word "column". Type:
[I
Vim will list the matching lines it can find. Not only in the current file,
but also in all included files (and files included in them, etc.). The result
looks like this:
structs.h
1: 29 unsigned column; /* column number */
The advantage over using tags or the preview window is that included files are
JUMPING TO A MATCH
"[I" produces a list with only one line of text. When you want to have a
closer look at the first item, you can jump to that line with the command:
[<Tab>
You can also use "[ CTRL-I", since CTRL-I is the same as pressing <Tab>.
The list that "[I" produces has a number at the start of each line. When you
want to jump to another item than the first one, type the number first:
3[<Tab>
Will jump to the third item in the list. Remember that you can use CTRL-O to
jump back to where you started from.
RELATED COMMANDS
[i only lists the first match
]I only lists items below the cursor
]i only lists the first item below the cursor
Vim has various commands that aid in writing computer programs. Compile a
program and directly jump to reported errors. Automatically set the indent
for many languages and format comments.
|30.1| Compiling
|30.2| Indenting C files
|30.3| Automatic indenting
|30.4| Other indenting
|30.5| Tabs and spaces
|30.6| Formatting comments
Next chapter: |usr_31.txt| Exploiting the GUI
Previous chapter: |usr_29.txt| Moving through programs
Table of contents: |usr_toc.txt|
==============================================================================
*30.1* Compiling
Vim has a set of so called "quickfix" commands. They enable you to compile a
program from within Vim and then go through the errors generated and fix them
(hopefully). You can then recompile and fix any new errors that are found
until finally your program compiles without any error.
The following command runs the program "make" (supplying it with any argument
you give) and captures the results:
:make {arguments}
If errors were generated, they are captured and the editor positions you where
the first error occurred.
Take a look at an example ":make" session. (Typical :make sessions generate
far more errors and fewer stupid ones.) After typing ":make" the screen looks
like this:
:!make | &tee /tmp/vim215953.err
gcc -g -Wall -o prog main.c sub.c
main.c: In function 'main':
main.c:6: too many arguments to function 'do_sub'
main.c: At top level:
main.c:10: parse error before '}'
make: *** [prog] Error 1
2 returned
"main.c" 11L, 111C
(3 of 6): too many arguments to function 'do_sub'
Press ENTER or type command to continue
From this you can see that you have errors in the file "main.c". When you
press <Enter>, Vim displays the file "main.c", with the cursor positioned on
line 6, the first line with an error. You did not need to specify the file or
the line number, Vim knew where to go by looking in the error messages.
+---------------------------------------------------+
|int main() |
|{ |
| int i=3; |
cursor -> | do_sub("foo"); |
| ++i; |
| return (0); |
|} |
|} |
| ~ |
|(3 of 12): too many arguments to function 'do_sub' |
+---------------------------------------------------+
The following command goes to where the next error occurs:
:cnext
Vim jumps to line 10, the last line in the file, where there is an extra '}'.
When there is not enough room, Vim will shorten the error message. To see
the whole message use:
:cc
You can get an overview of all the error messages with the ":clist" command.
The output looks like this:
:clist
3 main.c: 6:too many arguments to function 'do_sub'
5 main.c: 10:parse error before '}'
Only the lines where Vim recognized a file name and line number are listed
here. It assumes those are the interesting lines and the rest is just boring
messages. However, sometimes unrecognized lines do contain something you want
to see. Output from the linker, for example, about an undefined function.
To see all the messages add a "!" to the command:
:clist!
1 gcc -g -Wall -o prog main.c sub.c
2 main.c: In function 'main':
3 main.c:6: too many arguments to function 'do_sub'
4 main.c: At top level:
5 main.c:10: parse error before '}'
6 make: *** [prog] Error 1
Vim will highlight the current error. To go back to the previous error, use:
:cprevious
Other commands to move around in the error list:
:cfirst to first error
:clast to last error
:cc 3 to error nr 3
SWITCHING COMPILERS
You have to tell Vim what format the error messages are that your compiler
produces. This is done with the 'errorformat' option. The syntax of this
option is quite complicated and it can be made to fit almost any compiler.
You can find the explanation here: |errorformat|.
You might be using various different compilers. Setting the 'makeprg' option,
and especially the 'errorformat' each time is not easy. Vim offers a simple
method for this. For example, to switch to using the Microsoft Visual C++
compiler:
:compiler msvc
This will find the Vim script for the "msvc" compiler and set the appropriate
options.
You can write your own compiler files. See |write-compiler-plugin|.
OUTPUT REDIRECTION
The ":make" command redirects the output of the executed program to an error
file. How this works depends on various things, such as the 'shell'. If your
":make" command doesn't capture the output, check the 'makeef' and
'shellpipe' options. The 'shellquote' and 'shellxquote' options might also
matter.
In case you can't get ":make" to redirect the file for you, an alternative is
to compile the program in another window and redirect the output into a file.
Then have Vim read this file with:
:cfile {filename}
Jumping to errors will work like with the ":make" command.
==============================================================================
*30.2* Indenting C style text
A program is much easier to understand when the lines have been properly
indented. Vim offers various ways to make this less work. For C or C style
programs like Java or C++, set the 'cindent' option. Vim knows a lot about C
programs and will try very hard to automatically set the indent for you. Set
the 'shiftwidth' option to the amount of spaces you want for a deeper level.
Four spaces will work fine. One ":set" command will do it:
:set cindent shiftwidth=4
With this option enabled, when you type something such as "if (x)", the next
line will automatically be indented an additional level.
if (flag)
Automatic indent ---> do_the_work();
Automatic unindent <-- if (other_flag) {
If you don't like the indenting for one specific type of file, this is how you
avoid it. Create a file with just this one line:
:let b:did_indent = 1
Now you need to write this in a file with a specific name:
{directory}/indent/{filetype}.vim
The {filetype} is the name of the file type, such as "cpp" or "java". You can
see the exact name that Vim detected with this command:
:set filetype
In this file the output is:
filetype=help
Thus you would use "help" for {filetype}.
For the {directory} part you need to use your runtime directory. Look at
the output of this command:
set runtimepath
Now use the first item, the name before the first comma. Thus if the output
looks like this:
runtimepath=~/.vim,/usr/local/share/vim/vim60/runtime,~/.vim/after
You use "~/.vim" for {directory}. Then the resulting file name is:
~/.vim/indent/help.vim
Instead of switching the indenting off, you could write your own indent file.
How to do that is explained here: |indent-expression|.
==============================================================================
*30.4* Other indenting
The most simple form of automatic indenting is with the 'autoindent' option.
It uses the indent from the previous line. A bit smarter is the 'smartindent'
option. This is useful for languages where no indent file is available.
'smartindent' is not as smart as 'cindent', but smarter than 'autoindent'.
With 'smartindent' set, an extra level of indentation is added for each {
and removed for each }. An extra level of indentation will also be added for
any of the words in the 'cinwords' option. Lines that begin with # are
treated specially: all indentation is removed. This is done so that
preprocessor directives will all start in column 1. The indentation is
restored for the next line.
CORRECTING INDENTS
When you are using 'autoindent' or 'smartindent' to get the indent of the
previous line, there will be many times when you need to add or remove one
'shiftwidth' worth of indent. A quick way to do this is using the CTRL-D and
CTRL-T commands in Insert mode.
For example, you are typing a shell script that is supposed to look like
this:
if test -n a; then
echo a
echo "-------"
fi
Start off by setting these options:
:set autoindent shiftwidth=3
You start by typing the first line, <Enter> and the start of the second line:
if test -n a; then
echo
Now you see that you need an extra indent. Type CTRL-T. The result:
if test -n a; then
echo
The CTRL-T command, in Insert mode, adds one 'shiftwidth' to the indent, no
matter where in the line you are.
You continue typing the second line, <Enter> and the third line. This time
the indent is OK. Then <Enter> and the last line. Now you have this:
if test -n a; then
echo a
echo "-------"
fi
To remove the superfluous indent in the last line press CTRL-D. This deletes
one 'shiftwidth' worth of indent, no matter where you are in the line.
When you are in Normal mode, you can use the ">>" and "<<" commands to
shift lines. ">" and "<" are operators, thus you have the usual three ways to
specify the lines you want to indent. A useful combination is:
>i{
This adds one indent to the current block of lines, inside {}. The { and }
lines themselves are left unmodified. ">a{" includes them. In this example
the cursor is on "printf":
original text after ">i{" after ">a{"
if (flag) if (flag) if (flag)
{ { {
printf("yes"); printf("yes"); printf("yes");
flag = 0; flag = 0; flag = 0;
} } }
==============================================================================
*30.5* Tabs and spaces
'tabstop' is set to eight by default. Although you can change it, you quickly
run into trouble later. Other programs won't know what tabstop value you
used. They probably use the default value of eight, and your text suddenly
looks very different. Also, most printers use a fixed tabstop value of eight.
Thus it's best to keep 'tabstop' alone. (If you edit a file which was written
with a different tabstop setting, see |25.3| for how to fix that.)
For indenting lines in a program, using a multiple of eight spaces makes
you quickly run into the right border of the window. Using a single space
doesn't provide enough visual difference. Many people prefer to use four
spaces, a good compromise.
Since a <Tab> is eight spaces and you want to use an indent of four spaces,
you can't use a <Tab> character to make your indent. There are two ways to
handle this:
1. Use a mix of <Tab> and space characters. Since a <Tab> takes the place of
eight spaces, you have fewer characters in your file. Inserting a <Tab>
is quicker than eight spaces. Backspacing works faster as well.
2. Use spaces only. This avoids the trouble with programs that use a
different tabstop value.
Fortunately, Vim supports both methods quite well.
JUST SPACES
If you want absolutely no tabs in your file, you can set the 'expandtab'
option:
:set expandtab
When this option is set, the <Tab> key inserts a series of spaces. Thus you
get the same amount of white space as if a <Tab> character was inserted, but
there isn't a real <Tab> character in your file.
The backspace key will delete each space by itself. Thus after typing one
<Tab> you have to press the <BS> key up to eight times to undo it. If you are
in the indent, pressing CTRL-D will be a lot quicker.
DEFINING A COMMENT
The 'comments' option defines what a comment looks like. Vim distinguishes
between a single-line comment and a comment that has a different start, end
and middle part.
Many single-line comments start with a specific character. In C++ // is
used, in Makefiles #, in Vim scripts ". For example, to make Vim understand
C++ comments:
:set comments=://
The colon separates the flags of an item from the text by which the comment is
recognized. The general form of an item in 'comments' is:
{flags}:{text}
The {flags} part can be empty, as in this case.
Several of these items can be concatenated, separated by commas. This
allows recognizing different types of comments at the same time. For example,
let's edit an e-mail message. When replying, the text that others wrote is
preceded with ">" and "!" characters. This command would work:
:set comments=n:>,n:!
There are two items, one for comments starting with ">" and one for comments
that start with "!". Both use the flag "n". This means that these comments
nest. Thus a line starting with ">" may have another comment after the ">".
This allows formatting a message like this:
> ! Did you see that site?
> ! It looks really great.
> I don't like it. The
> colors are terrible.
What is the URL of that
site?
Try setting 'textwidth' to a different value, e.g., 80, and format the text by
Visually selecting it and typing "gq". The result is:
> ! Did you see that site? It looks really great.
> I don't like it. The colors are terrible.
What is the URL of that site?
You will notice that Vim did not move text from one type of comment to
another. The "I" in the second line would have fit at the end of the first
line, but since that line starts with "> !" and the second line with ">", Vim
knows that this is a different kind of comment.
Vim works well in a terminal, but the GUI has a few extra items. A file
browser can be used for commands that use a file. A dialog to make a choice
between alternatives. Use keyboard shortcuts to access menu items quickly.
|31.1| The file browser
|31.2| Confirmation
|31.3| Menu shortcuts
|31.4| Vim window position and size
|31.5| Various
Next chapter: |usr_32.txt| The undo tree
Previous chapter: |usr_30.txt| Editing programs
Table of contents: |usr_toc.txt|
==============================================================================
*31.1* The file browser
When using the File/Open... menu you get a file browser. This makes it easier
to find the file you want to edit. But what if you want to split a window to
edit another file? There is no menu entry for this. You could first use
Window/Split and then File/Open..., but that's more work.
Since you are typing most commands in Vim, opening the file browser with a
typed command is possible as well. To make the split command use the file
browser, prepend "browse":
:browse split
Select a file and then the ":split" command will be executed with it. If you
cancel the file dialog nothing happens, the window isn't split.
You can also specify a file name argument. This is used to tell the file
browser where to start. Example:
:browse split /etc
The file browser will pop up, starting in the directory "/etc".
The ":browse" command can be prepended to just about any command that opens a
file.
If no directory is specified, Vim will decide where to start the file
browser. By default it uses the same directory as the last time. Thus when
you used ":browse split" and selected a file in "/usr/local/share", the next
time you use a ":browse" it will start in "/usr/local/share" again.
This can be changed with the 'browsedir' option. It can have one of three
values:
last Use the last directory browsed (default)
buffer Use the same directory as the current buffer
current use the current directory
For example, when you are in the directory "/usr", editing the file
"/usr/local/share/readme", then the command:
:set browsedir=buffer
:browse edit
with the underlined letter of a menu. For example, <A-w> (<Alt> and w) pops
up the Window menu.
In the Window menu, the "split" item has the p underlined. To select it,
let go of the <Alt> key and press p.
After the first selection of a menu with the <Alt> key, you can use the cursor
keys to move through the menus. <Right> selects a submenu and <left> closes
it. <Esc> also closes a menu. <Enter> selects a menu item.
There is a conflict between using the <Alt> key to select menu items, and
using <Alt> key combinations for mappings. The 'winaltkeys' option tells Vim
what it should do with the <Alt> key.
The default value "menu" is the smart choice: If the key combination is a
menu shortcut it can't be mapped. All other keys are available for mapping.
The value "no" doesn't use any <Alt> keys for the menus. Thus you must use
the mouse for the menus, and all <Alt> keys can be mapped.
The value "yes" means that Vim will use any <Alt> keys for the menus. Some
<Alt> key combinations may also do other things than selecting a menu.
==============================================================================
*31.4* Vim window position and size
To see the current Vim window position on the screen use:
:winpos
This will only work in the GUI. The output may look like this:
Window position: X 272, Y 103
The position is given in screen pixels. Now you can use the numbers to move
Vim somewhere else. For example, to move it to the left a hundred pixels:
:winpos 172 103
Note:
There may be a small offset between the reported position and where
the window moves. This is because of the border around the window.
This is added by the window manager.
You can use this command in your startup script to position the window at a
specific position.
The size of the Vim window is computed in characters. Thus this depends on
the size of the font being used. You can see the current size with this
command:
:set lines columns
To change the size set the 'lines' and/or 'columns' options to a new value:
:set lines=50
:set columns=80
Obtaining the size works in a terminal just like in the GUI. Setting the size
is not possible in most terminals.
You can start the X-Windows version of gvim with an argument to specify the
size and position of the window:
gvim -geometry {width}x{height}+{x_offset}+{y_offset}
{width} and {height} are in characters, {x_offset} and {y_offset} are in
pixels. Example:
gvim -geometry 80x25+100+300
==============================================================================
*31.5* Various
You can use gvim to edit an e-mail message. In your e-mail program you must
select gvim to be the editor for messages. When you try that, you will
see that it doesn't work: The mail program thinks that editing is finished,
while gvim is still running!
What happens is that gvim disconnects from the shell it was started in.
That is fine when you start gvim in a terminal, so that you can do other work
in that terminal. But when you really want to wait for gvim to finish, you
must prevent it from disconnecting. The "-f" argument does this:
gvim -f file.txt
The "-f" stands for foreground. Now Vim will block the shell it was started
in until you finish editing and exit.
Vim provides multi-level undo. If you undo a few changes and then make a new
change you create a branch in the undo tree. This text is about moving
through the branches.
|32.1| Undo up to a file write
|32.2| Numbering changes
|32.3| Jumping around the tree
|32.4| Time travelling
Next chapter: |usr_40.txt| Make new commands
Previous chapter: |usr_31.txt| Exploiting the GUI
Table of contents: |usr_toc.txt|
==============================================================================
*32.1* Undo up to a file write
Sometimes you make several changes, and then discover you want to go back to
when you have last written the file. You can do that with this command:
:earlier 1f
The "f" stands for "file" here.
You can repeat this command to go further back in the past. Or use a count
different from 1 to go back faster.
If you go back too far, go forward again with:
:later 1f
Note that these commands really work in time sequence. This matters if you
made changes after undoing some changes. It's explained in the next section.
Also note that we are talking about text writes here. For writing the undo
information in a file see |undo-persistence|.
==============================================================================
*32.2* Numbering changes
In section |02.5| we only discussed one line of undo/redo. But it is also
possible to branch off. This happens when you undo a few changes and then
make a new change. The new changes become a branch in the undo tree.
Let's start with the text "one". The first change to make is to append
" too". And then move to the first 'o' and change it into 'w'. We then have
two changes, numbered 1 and 2, and three states of the text:
one
|
change 1
|
one too
|
change 2
|
one two
If we now undo one change, back to "one too", and change "one" to "me" we
create a branch in the undo tree:
one
|
change 1
|
one too
/ \
change 2 change 3
| |
one two me too
You can now use the |u| command to undo. If you do this twice you get to
"one". Use |CTRL-R| to redo, and you will go to "one too". One more |CTRL-R|
takes you to "me too". Thus undo and redo go up and down in the tree, using
the branch that was last used.
What matters here is the order in which the changes are made. Undo and redo
are not considered changes in this context. After each change you have a new
state of the text.
Note that only the changes are numbered, the text shown in the tree above has
no identifier. They are mostly referred to by the number of the change above
it. But sometimes by the number of one of the changes below it, especially
when moving up in the tree, so that you know which change was just undone.
==============================================================================
*32.3* Jumping around the tree
So how do you get to "one two" now? You can use this command:
:undo 2
The text is now "one two", you are below change 2. You can use the |:undo|
command to jump to below any change in the tree.
Now make another change: change "one" to "not":
one
|
change 1
|
one too
/ \
change 2 change 3
| |
one two me too
|
change 4
|
not two
Now you change your mind and want to go back to "me too". Use the |g-|
command. This moves back in time. Thus it doesn't walk the tree upwards or
downwards, but goes to the change made before.
You can repeat |g-| and you will see the text change:
me too
one two
one too
one
Use |g+| to move forward in time:
one
one too
one two
me too
not two
Using |:undo| is useful if you know what change you want to jump to. |g-| and
|g+| are useful if you don't know exactly what the change number is.
You can type a count before |g-| and |g+| to repeat them.
==============================================================================
*32.4* Time travelling
When you have been working on text for a while the tree grows to become big.
Then you may want to go to the text of some minutes ago.
To see what branches there are in the undo tree use this command:
:undolist
number changes time
3 2 16 seconds ago
4 3 5 seconds ago
Here you can see the number of the leaves in each branch and when the change
was made. Assuming we are below change 4, at "not two", you can go back ten
seconds with this command:
:earlier 10s
Depending on how much time you took for the changes you end up at a certain
position in the tree. The |:earlier| command argument can be "m" for minutes,
"h" for hours and "d" for days. To go all the way back use a big number:
:earlier 100d
To travel forward in time again use the |:later| command:
:later 1m
The arguments are "s", "m" and "h", just like with |:earlier|.
If you want even more details, or want to manipulate the information, you can
use the |undotree()| function. To see what it returns:
:echo undotree()
==============================================================================
Next chapter: |usr_40.txt| Make new commands
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
Vim is an extensible editor. You can take a sequence of commands you use
often and turn it into a new command. Or redefine an existing command.
Autocommands make it possible to execute commands automatically.
|40.1| Key mapping
|40.2| Defining command-line commands
|40.3| Autocommands
Next chapter: |usr_41.txt| Write a Vim script
Previous chapter: |usr_32.txt| The undo tree
Table of contents: |usr_toc.txt|
==============================================================================
*40.1* Key mapping
A simple mapping was explained in section |05.3|. The principle is that one
sequence of key strokes is translated into another sequence of key strokes.
This is a simple, yet powerful mechanism.
The simplest form is that one key is mapped to a sequence of keys. Since
the function keys, except <F1>, have no predefined meaning in Vim, these are
good choices to map. Example:
:map <F2> GoDate: <Esc>:read !date<CR>kJ
This shows how three modes are used. After going to the last line with "G",
the "o" command opens a new line and starts Insert mode. The text "Date: " is
inserted and <Esc> takes you out of insert mode.
Notice the use of special keys inside <>. This is called angle bracket
notation. You type these as separate characters, not by pressing the key
itself. This makes the mappings better readable and you can copy and paste
the text without problems.
The ":" character takes Vim to the command line. The ":read !date" command
reads the output from the "date" command and appends it below the current
line. The <CR> is required to execute the ":read" command.
At this point of execution the text looks like this:
Date:
Fri Jun 15 12:54:34 CEST 2001
Now "kJ" moves the cursor up and joins the lines together.
To decide which key or keys you use for mapping, see |map-which-keys|.
LISTING MAPPINGS
To see the currently defined mappings, use ":map" without arguments. Or one
of the variants that include the mode in which they work. The output could
look like this:
_g :call MyGrep(1)<CR>
v <F2> :s/^/> /<CR>:noh<CR>``
n <F2> :.,$s/^/> /<CR>:noh<CR>``
<xHome> <Home>
<xEnd> <End>
The first column of the list shows in which mode the mapping is effective.
This is "n" for Normal mode, "i" for Insert mode, etc. A blank is used for a
mapping defined with ":map", thus effective in both Normal and Visual mode.
One useful purpose of listing the mapping is to check if special keys in <>
form have been recognized (this only works when color is supported). For
example, when <Esc> is displayed in color, it stands for the escape character.
When it has the same color as the other text, it is five characters.
REMAPPING
The result of a mapping is inspected for other mappings in it. For example,
the mappings for <F2> above could be shortened to:
:map <F2> G<F3>
:imap <F2> <Esc><F3>
:map <F3> oDate: <Esc>:read !date<CR>kJ
For Normal mode <F2> is mapped to go to the last line, and then behave like
<F3> was pressed. In Insert mode <F2> stops Insert mode with <Esc> and then
also uses <F3>. Then <F3> is mapped to do the actual work.
Suppose you hardly ever use Ex mode, and want to use the "Q" command to format
text (this was so in old versions of Vim). This mapping will do it:
:map Q gq
But, in rare cases you need to use Ex mode anyway. Let's map "gQ" to Q, so
that you can still go to Ex mode:
:map gQ Q
What happens now is that when you type "gQ" it is mapped to "Q". So far so
good. But then "Q" is mapped to "gq", thus typing "gQ" results in "gq", and
you don't get to Ex mode at all.
To avoid keys to be mapped again, use the ":noremap" command:
:noremap gQ Q
Now Vim knows that the "Q" is not to be inspected for mappings that apply to
it. There is a similar command for every mode:
:noremap Normal, Visual and Operator-pending
:vnoremap Visual
:nnoremap Normal
:onoremap Operator-pending
:noremap! Insert and Command-line
:inoremap Insert
:cnoremap Command-line
RECURSIVE MAPPING
When a mapping triggers itself, it will run forever. This can be used to
repeat an action an unlimited number of times.
For example, you have a list of files that contain a version number in the
first line. You edit these files with "vim *.txt". You are now editing the
first file. Define this mapping:
:map ,, :s/5.1/5.2/<CR>:wnext<CR>,,
Now you type ",,". This triggers the mapping. It replaces "5.1" with "5.2"
in the first line. Then it does a ":wnext" to write the file and edit the
next one. The mapping ends in ",,". This triggers the same mapping again,
thus doing the substitution, etc.
This continues until there is an error. In this case it could be a file
where the substitute command doesn't find a match for "5.1". You can then
make a change to insert "5.1" and continue by typing ",," again. Or the
":wnext" fails, because you are in the last file in the list.
When a mapping runs into an error halfway, the rest of the mapping is
discarded. CTRL-C interrupts the mapping (CTRL-Break on MS-Windows).
DELETE A MAPPING
To remove a mapping use the ":unmap" command. Again, the mode the unmapping
applies to depends on the command used:
:unmap Normal, Visual and Operator-pending
:vunmap Visual
:nunmap Normal
:ounmap Operator-pending
:unmap! Insert and Command-line
:iunmap Insert
:cunmap Command-line
There is a trick to define a mapping that works in Normal and Operator-pending
mode, but not in Visual mode. First define it for all three modes, then
delete it for Visual mode:
:map <C-A> /---><CR>
:vunmap <C-A>
Notice that the five characters "<C-A>" stand for the single key CTRL-A.
To remove all mappings use the |:mapclear| command. You can guess the
variations for different modes by now. Be careful with this command, it can't
be undone.
SPECIAL CHARACTERS
The ":map" command can be followed by another command. A | character
separates the two commands. This also means that a | character can't be used
inside a map command. To include one, use <Bar> (five characters). Example:
:map <F8> :write <Bar> !checkin %<CR>
The same problem applies to the ":unmap" command, with the addition that you
have to watch out for trailing white space. These two commands are different:
:unmap a | unmap b
:unmap a| unmap b
The first command tries to unmap "a ", with a trailing space.
When using a space inside a mapping, use <Space> (seven characters):
:map <Space> W
This makes the spacebar move a blank-separated word forward.
It is not possible to put a comment directly after a mapping, because the "
character is considered to be part of the mapping. You can use |", this
starts a new, empty command with a comment. Example:
:map <Space> W| " Use spacebar to move forward a word
ADDITIONALLY...
The <script> keyword can be used to make a mapping local to a script. See
|:map-<script>|.
The <buffer> keyword can be used to make a mapping local to a specific buffer.
See |:map-<buffer>|
The <unique> keyword can be used to make defining a new mapping fail when it
already exists. Otherwise a new mapping simply overwrites the old one. See
|:map-<unique>|.
To make a key do nothing, map it to <Nop> (five characters). This will make
the <F7> key do nothing at all:
:map <F7> <Nop>| map! <F7> <Nop>
There must be no space after <Nop>.
==============================================================================
*40.2* Defining command-line commands
The Vim editor enables you to define your own commands. You execute these
commands just like any other Command-line mode command.
To define a command, use the ":command" command, as follows:
:command DeleteFirst 1delete
Now when you execute the command ":DeleteFirst" Vim executes ":1delete", which
deletes the first line.
Note:
User-defined commands must start with a capital letter. You cannot
use ":X", ":Next" and ":Print". The underscore cannot be used! You
can use digits, but this is discouraged.
To list the user-defined commands, execute the following command:
:command
Just like with the builtin commands, the user defined commands can be
abbreviated. You need to type just enough to distinguish the command from
another. Command line completion can be used to get the full name.
NUMBER OF ARGUMENTS
User-defined commands can take a series of arguments. The number of arguments
must be specified by the -nargs option. For instance, the example
:DeleteFirst command takes no arguments, so you could have defined it as
follows:
:command -nargs=0 DeleteFirst 1delete
However, because zero arguments is the default, you do not need to add
"-nargs=0". The other values of -nargs are as follows:
-nargs=0 No arguments
-nargs=1 One argument
-nargs=* Any number of arguments
-nargs=? Zero or one argument
-nargs=+ One or more arguments
LINE RANGE
Some commands take a range as their argument. To tell Vim that you are
defining such a command, you need to specify a -range option. The values for
this option are as follows:
-range Range is allowed; default is the current line.
-range=% Range is allowed; default is the whole file.
-range={count} Range is allowed; the last number in it is used as a
single number whose default is {count}.
When a range is specified, the keywords <line1> and <line2> get the values of
the first and last line in the range. For example, the following command
defines the SaveIt command, which writes out the specified range to the file
"save_file":
:command -range=% SaveIt :<line1>,<line2>write! save_file
OTHER OPTIONS
Some of the other options and keywords are as follows:
EVENTS
One of the most useful events is BufReadPost. It is triggered after a new
file is being edited. It is commonly used to set option values. For example,
you know that "*.gsm" files are GNU assembly language. To get the syntax file
right, define this autocommand:
:autocmd BufReadPost *.gsm set filetype=asm
If Vim is able to detect the type of file, it will set the 'filetype' option
for you. This triggers the Filetype event. Use this to do something when a
certain type of file is edited. For example, to load a list of abbreviations
for text files:
:autocmd Filetype text source ~/.vim/abbrevs.vim
When starting to edit a new file, you could make Vim insert a skeleton:
:autocmd BufNewFile *.[ch] 0read ~/skeletons/skel.c
See |autocmd-events| for a complete list of events.
PATTERNS
The {file_pattern} argument can actually be a comma-separated list of file
patterns. For example: "*.c,*.h" matches files ending in ".c" and ".h".
The usual file wildcards can be used. Here is a summary of the most often
used ones:
* Match any character any number of times
? Match any character once
[abc] Match the character a, b or c
. Matches a dot
a{b,c} Matches "ab" and "ac"
When the pattern includes a slash (/) Vim will compare directory names.
Without the slash only the last part of a file name is used. For example,
"*.txt" matches "/home/biep/readme.txt". The pattern "/home/biep/*" would
also match it. But "home/foo/*.txt" wouldn't.
When including a slash, Vim matches the pattern against both the full path
of the file ("/home/biep/readme.txt") and the relative path (e.g.,
"biep/readme.txt").
Note:
When working on a system that uses a backslash as file separator, such
as MS-Windows, you still use forward slashes in autocommands. This
makes it easier to write the pattern, since a backslash has a special
meaning. It also makes the autocommands portable.
DELETING
To delete an autocommand, use the same command as what it was defined with,
but leave out the {command} at the end and use a !. Example:
:autocmd! FileWritePre *
This will delete all autocommands for the "FileWritePre" event that use the
"*" pattern.
LISTING
To list all the currently defined autocommands, use this:
:autocmd
The list can be very long, especially when filetype detection is used. To
list only part of the commands, specify the group, event and/or pattern. For
example, to list all BufNewFile autocommands:
:autocmd BufNewFile
GROUPS
The {group} item, used when defining an autocommand, groups related autocommands
together. This can be used to delete all the autocommands in a certain group,
for example.
When defining several autocommands for a certain group, use the ":augroup"
command. For example, let's define autocommands for C programs:
:augroup cprograms
: autocmd BufReadPost *.c,*.h :set sw=4 sts=4
: autocmd BufReadPost *.cpp :set sw=3 sts=3
:augroup END
This will do the same as:
:autocmd cprograms BufReadPost *.c,*.h :set sw=4 sts=4
:autocmd cprograms BufReadPost *.cpp :set sw=3 sts=3
To delete all autocommands in the "cprograms" group:
:autocmd! cprograms
NESTING
Generally, commands executed as the result of an autocommand event will not
trigger any new events. If you read a file in response to a FileChangedShell
event, it will not trigger the autocommands that would set the syntax, for
example. To make the events triggered, add the "nested" argument:
:autocmd FileChangedShell * nested edit
EXECUTING AUTOCOMMANDS
It is possible to trigger an autocommand by pretending an event has occurred.
This is useful to have one autocommand trigger another one. Example:
:autocmd BufReadPost *.new execute "doautocmd BufReadPost " . expand("<afile>:r")
This defines an autocommand that is triggered when a new file has been edited.
The file name must end in ".new". The ":execute" command uses expression
evaluation to form a new command and execute it. When editing the file
"tryout.c.new" the executed command will be:
:doautocmd BufReadPost tryout.c
The expand() function takes the "<afile>" argument, which stands for the file
name the autocommand was executed for, and takes the root of the file name
with ":r".
":doautocmd" executes on the current buffer. The ":doautoall" command works
like "doautocmd" except it executes on all the buffers.
it.
The ":normal" command uses all the text after it as commands. Thus there
can be no | and another command following. To work around this, put the
":normal" command inside an ":execute" command. This also makes it possible
to pass unprintable characters in a convenient way. Example:
:autocmd BufReadPost *.chg execute "normal ONew entry:\<Esc>" |
\ 1read !date
This also shows the use of a backslash to break a long command into more
lines. This can be used in Vim scripts (not at the command line).
When you want the autocommand do something complicated, which involves jumping
around in the file and then returning to the original position, you may want
to restore the view on the file. See |restore-position| for an example.
IGNORING EVENTS
At times, you will not want to trigger an autocommand. The 'eventignore'
option contains a list of events that will be totally ignored. For example,
the following causes events for entering and leaving a window to be ignored:
:set eventignore=WinEnter,WinLeave
To ignore all events, use the following command:
:set eventignore=all
To set it back to the normal behavior, make 'eventignore' empty:
:set eventignore=
==============================================================================
Next chapter: |usr_41.txt| Write a Vim script
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
By now you know that Vim is very flexible. This includes the menus used in
the GUI. You can define your own menu entries to make certain commands easily
accessible. This is for mouse-happy users only.
|42.1| Introduction
|42.2| Menu commands
|42.3| Various
|42.4| Toolbar and popup menus
Next chapter: |usr_43.txt| Using filetypes
Previous chapter: |usr_41.txt| Write a Vim script
Table of contents: |usr_toc.txt|
==============================================================================
*42.1* Introduction
The menus that Vim uses are defined in the file "$VIMRUNTIME/menu.vim". If
you want to write your own menus, you might first want to look through that
file.
To define a menu item, use the ":menu" command. The basic form of this
command is as follows:
:menu {menu-item} {keys}
The {menu-item} describes where on the menu to put the item. A typical
{menu-item} is "File.Save", which represents the item "Save" under the
"File" menu. A dot is used to separate the names. Example:
:menu File.Save :update<CR>
The ":update" command writes the file when it was modified.
You can add another level: "Edit.Settings.Shiftwidth" defines a submenu
"Settings" under the "Edit" menu, with an item "Shiftwidth". You could use
even deeper levels. Don't use this too much, you need to move the mouse quite
a bit to use such an item.
The ":menu" command is very similar to the ":map" command: the left side
specifies how the item is triggered and the right hand side defines the
characters that are executed. {keys} are characters, they are used just like
you would have typed them. Thus in Insert mode, when {keys} is plain text,
that text is inserted.
ACCELERATORS
The ampersand character (&) is used to indicate an accelerator. For instance,
you can use Alt-F to select "File" and S to select "Save". (The 'winaltkeys'
option may disable this though!). Therefore, the {menu-item} looks like
"&File.&Save". The accelerator characters will be underlined in the menu.
You must take care that each key is used only once in each menu. Otherwise
you will not know which of the two will actually be used. Vim doesn't warn
you for this.
PRIORITIES
SPECIAL CHARACTERS
The {menu-item} in this example is "&File.&Save<Tab>:w". This brings up an
important point: {menu-item} must be one word. If you want to put a dot,
space or tabs in the name, you either use the <> notation (<Space> and <Tab>,
for instance) or use the backslash (\) escape.
:menu 10.305 &File.&Do\ It\.\.\. :exit<CR>
In this example, the name of the menu item "Do It..." contains a space and the
command is ":exit<CR>".
The <Tab> character in a menu name is used to separate the part that defines
the menu name from the part that gives a hint to the user. The part after the
<Tab> is displayed right aligned in the menu. In the File.Save menu the name
used is "&File.&Save<Tab>:w". Thus the menu name is "File.Save" and the hint
is ":w".
SEPARATORS
The separator lines, used to group related menu items together, can be defined
by using a name that starts and ends in a '-'. For example "-sep-". When
using several separators the names must be different. Otherwise the names
don't matter.
The command from a separator will never be executed, but you have to define
one anyway. A single colon will do. Example:
:amenu 20.510 Edit.-sep3- :
==============================================================================
*42.2* Menu commands
You can define menu items that exist for only certain modes. This works just
like the variations on the ":map" command:
:menu Normal, Visual and Operator-pending mode
:nmenu Normal mode
:vmenu Visual mode
:omenu Operator-pending mode
:menu! Insert and Command-line mode
:imenu Insert mode
:cmenu Command-line mode
:amenu All modes
To avoid that the commands of a menu item are being mapped, use the command
":noremenu", ":nnoremenu", ":anoremenu", etc.
USING :AMENU
The ":amenu" command is a bit different. It assumes that the {keys} you
give are to be executed in Normal mode. When Vim is in Visual or Insert mode
when the menu is used, Vim first has to go back to Normal mode. ":amenu"
inserts a CTRL-C or CTRL-O for you. For example, if you use this command:
:amenu 90.100 Mine.Find\ Word *
Then the resulting menu commands will be:
Normal mode: *
Visual mode: CTRL-C *
Operator-pending mode: CTRL-C *
Insert mode: CTRL-O *
Command-line mode: CTRL-C *
When in Command-line mode the CTRL-C will abandon the command typed so far.
In Visual and Operator-pending mode CTRL-C will stop the mode. The CTRL-O in
Insert mode will execute the command and then return to Insert mode.
CTRL-O only works for one command. If you need to use two or more
commands, put them in a function and call that function. Example:
:amenu Mine.Next\ File :call <SID>NextFile()<CR>
:function <SID>NextFile()
: next
: 1/^Code
:endfunction
This menu entry goes to the next file in the argument list with ":next". Then
it searches for the line that starts with "Code".
The <SID> before the function name is the script ID. This makes the
function local to the current Vim script file. This avoids problems when a
function with the same name is defined in another script file. See |<SID>|.
SILENT MENUS
The menu executes the {keys} as if you typed them. For a ":" command this
means you will see the command being echoed on the command line. If it's a
long command, the hit-Enter prompt will appear. That can be very annoying!
To avoid this, make the menu silent. This is done with the <silent>
argument. For example, take the call to NextFile() in the previous example.
When you use this menu, you will see this on the command line:
:call <SNR>34_NextFile()
To avoid this text on the command line, insert "<silent>" as the first
argument:
:amenu <silent> Mine.Next\ File :call <SID>NextFile()<CR>
Don't use "<silent>" too often. It is not needed for short commands. If you
make a menu for someone else, being able the see the executed command will
give him a hint about what he could have typed, instead of using the mouse.
LISTING MENUS
When a menu command is used without a {keys} part, it lists the already
defined menus. You can specify a {menu-item}, or part of it, to list specific
menus. Example:
:amenu
This lists all menus. That's a long list! Better specify the name of a menu
to get a shorter list:
:amenu Edit
This lists only the "Edit" menu items for all modes. To list only one
specific menu item for Insert mode:
:imenu Edit.Undo
Take care that you type exactly the right name. Case matters here. But the
'&' for accelerators can be omitted. The <Tab> and what comes after it can be
left out as well.
DELETING MENUS
To delete a menu, the same command is used as for listing, but with "menu"
changed to "unmenu". Thus ":menu" becomes, ":unmenu", ":nmenu" becomes
":nunmenu", etc. To delete the "Tools.Make" item for Insert mode:
:iunmenu Tools.Make
You can delete a whole menu, with all its items, by using the menu name.
Example:
:aunmenu Syntax
This deletes the Syntax menu and all the items in it.
==============================================================================
*42.3* Various
You can change the appearance of the menus with flags in 'guioptions'. In the
default value they are all included, except "M". You can remove a flag with a
command like:
:set guioptions-=m
m When removed the menubar is not displayed.
M When added the default menus are not loaded.
g When removed the inactive menu items are not made grey
but are completely removed. (Does not work on all
systems.)
t When removed the tearoff feature is not enabled.
The dotted line at the top of a menu is not a separator line. When you select
this item, the menu is "teared-off": It is displayed in a separate window.
This is called a tearoff menu. This is useful when you use the same menu
often.
For translating menu items, see |:menutrans|.
Since the mouse has to be used to select a menu item, it is a good idea to use
the ":browse" command for selecting a file. And ":confirm" to get a dialog
instead of an error message, e.g., when the current buffer contains changes.
These two can be combined:
:amenu File.Open :browse confirm edit<CR>
The ":browse" makes a file browser appear to select the file to edit. The
":confirm" will pop up a dialog when the current buffer has changes. You can
then select to save the changes, throw them away or cancel the command.
For more complicated items, the confirm() and inputdialog() functions can
be used. The default menus contain a few examples.
==============================================================================
*42.4* Toolbar and popup menus
There are two special menus: ToolBar and PopUp. Items that start with these
names do not appear in the normal menu bar.
TOOLBAR
The toolbar appears only when the "T" flag is included in the 'guioptions'
option.
The toolbar uses icons rather than text to represent the command. For
example, the {menu-item} named "ToolBar.New" causes the "New" icon to appear
on the toolbar.
The Vim editor has 28 built-in icons. You can find a table here:
|builtin-tools|. Most of them are used in the default toolbar. You can
redefine what these items do (after the default menus are setup).
You can add another bitmap for a toolbar item. Or define a new toolbar
item with a bitmap. For example, define a new toolbar item with:
:tmenu ToolBar.Compile Compile the current file
:amenu ToolBar.Compile :!cc % -o %:r<CR>
Now you need to create the icon. For MS-Windows it must be in bitmap format,
with the name "Compile.bmp". For Unix XPM format is used, the file name is
"Compile.xpm". The size must be 18 by 18 pixels. On MS-Windows other sizes
can be used as well, but it will look ugly.
Put the bitmap in the directory "bitmaps" in one of the directories from
'runtimepath'. E.g., for Unix "~/.vim/bitmaps/Compile.xpm".
You can define tooltips for the items in the toolbar. A tooltip is a short
text that explains what a toolbar item will do. For example "Open file". It
appears when the mouse pointer is on the item, without moving for a moment.
This is very useful if the meaning of the picture isn't that obvious.
Example:
:tmenu ToolBar.Make Run make in the current directory
Note:
Pay attention to the case used. "Toolbar" and "toolbar" are different
from "ToolBar"!
To remove a tooltip, use the |:tunmenu| command.
The 'toolbar' option can be used to display text instead of a bitmap, or both
text and a bitmap. Most people use just the bitmap, since the text takes
quite a bit of space.
POPUP MENU
The popup menu pops up where the mouse pointer is. On MS-Windows you activate
it by clicking the right mouse button. Then you can select an item with the
left mouse button. On Unix the popup menu is used by pressing and holding the
right mouse button.
The popup menu only appears when the 'mousemodel' has been set to "popup"
or "popup_setpos". The difference between the two is that "popup_setpos"
moves the cursor to the mouse pointer position. When clicking inside a
selection, the selection will be used unmodified. When there is a selection
but you click outside of it, the selection is removed.
There is a separate popup menu for each mode. Thus there are never grey
items like in the normal menus.
When you are editing a file of a certain type, for example a C program or a
shell script, you often use the same option settings and mappings. You
quickly get tired of manually setting these each time. This chapter explains
how to do it automatically.
|43.1| Plugins for a filetype
|43.2| Adding a filetype
Next chapter: |usr_44.txt| Your own syntax highlighted
Previous chapter: |usr_42.txt| Add new menus
Table of contents: |usr_toc.txt|
==============================================================================
*43.1* Plugins for a filetype *filetype-plugin*
How to start using filetype plugins has already been discussed here:
|add-filetype-plugin|. But you probably are not satisfied with the default
settings, because they have been kept minimal. Suppose that for C files you
want to set the 'softtabstop' option to 4 and define a mapping to insert a
three-line comment. You do this with only two steps:
*your-runtime-dir*
1. Create your own runtime directory. On Unix this usually is "~/.vim". In
this directory create the "ftplugin" directory:
mkdir ~/.vim
mkdir ~/.vim/ftplugin
When you are not on Unix, check the value of the 'runtimepath' option to
see where Vim will look for the "ftplugin" directory:
set runtimepath
You would normally use the first directory name (before the first comma).
You might want to prepend a directory name to the 'runtimepath' option in
your |vimrc| file if you don't like the default value.
2. Create the file "~/.vim/ftplugin/c.vim", with the contents:
setlocal softtabstop=4
noremap <buffer> <LocalLeader>c o/**************<CR><CR>/<Esc>
Try editing a C file. You should notice that the 'softtabstop' option is set
to 4. But when you edit another file it's reset to the default zero. That is
because the ":setlocal" command was used. This sets the 'softtabstop' option
only locally to the buffer. As soon as you edit another buffer, it will be
set to the value set for that buffer. For a new buffer it will get the
default value or the value from the last ":set" command.
Likewise, the mapping for "\c" will disappear when editing another buffer.
The ":map <buffer>" command creates a mapping that is local to the current
buffer. This works with any mapping command: ":map!", ":vmap", etc. The
|<LocalLeader>| in the mapping is replaced with the value of the
"maplocalleader" variable.
RECOGNIZING BY CONTENTS
If your file cannot be recognized by its file name, you might be able to
recognize it by its contents. For example, many script files start with a
line like:
#!/bin/xyz
To recognize this script create a file "scripts.vim" in your runtime directory
(same place where filetype.vim goes). It might look like this:
if did_filetype()
finish
endif
if getline(1) =~ '^#!.*[/\\]xyz\>'
setf xyz
endif
The first check with did_filetype() is to avoid that you will check the
contents of files for which the filetype was already detected by the file
name. That avoids wasting time on checking the file when the "setf" command
won't do anything.
The scripts.vim file is sourced by an autocommand in the default
filetype.vim file. Therefore, the order of checks is:
1. filetype.vim files before $VIMRUNTIME in 'runtimepath'
2. first part of $VIMRUNTIME/filetype.vim
3. all scripts.vim files in 'runtimepath'
4. remainder of $VIMRUNTIME/filetype.vim
5. filetype.vim files after $VIMRUNTIME in 'runtimepath'
If this is not sufficient for you, add an autocommand that matches all files
and sources a script or executes a function to check the contents of the file.
==============================================================================
Next chapter: |usr_44.txt| Your own syntax highlighted
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
Vim comes with highlighting for a couple of hundred different file types. If
the file you are editing isn't included, read this chapter to find out how to
get this type of file highlighted. Also see |:syn-define| in the reference
manual.
|44.1| Basic syntax commands
|44.2| Keywords
|44.3| Matches
|44.4| Regions
|44.5| Nested items
|44.6| Following groups
|44.7| Other arguments
|44.8| Clusters
|44.9| Including another syntax file
|44.10| Synchronizing
|44.11| Installing a syntax file
|44.12| Portable syntax file layout
Next chapter: |usr_45.txt| Select your language
Previous chapter: |usr_43.txt| Using filetypes
Table of contents: |usr_toc.txt|
==============================================================================
*44.1* Basic syntax commands
Using an existing syntax file to start with will save you a lot of time. Try
finding a syntax file in $VIMRUNTIME/syntax for a language that is similar.
These files will also show you the normal layout of a syntax file. To
understand it, you need to read the following.
Let's start with the basic arguments. Before we start defining any new
syntax, we need to clear out any old definitions:
:syntax clear
This isn't required in the final syntax file, but very useful when
experimenting.
There are more simplifications in this chapter. If you are writing a syntax
file to be used by others, read all the way through the end to find out the
details.
This also can be used to list clusters (explained in |44.8|). Just include
the @ in the name.
MATCHING CASE
Some languages are not case sensitive, such as Pascal. Others, such as C, are
case sensitive. You need to tell which type you have with the following
commands:
:syntax case match
:syntax case ignore
The "match" argument means that Vim will match the case of syntax elements.
Therefore, "int" differs from "Int" and "INT". If the "ignore" argument is
used, the following are equivalent: "Procedure", "PROCEDURE" and "procedure".
The ":syntax case" commands can appear anywhere in a syntax file and affect
the syntax definitions that follow. In most cases, you have only one ":syntax
case" command in your syntax file; if you work with an unusual language that
contains both case-sensitive and non-case-sensitive elements, however, you can
scatter the ":syntax case" command throughout the file.
==============================================================================
*44.2* Keywords
The most basic syntax elements are keywords. To define a keyword, use the
following form:
:syntax keyword {group} {keyword} ...
The {group} is the name of a syntax group. With the ":highlight" command you
can assign colors to a {group}. The {keyword} argument is an actual keyword.
Here are a few examples:
:syntax keyword xType int long char
:syntax keyword xStatement if then else endif
This example uses the group names "xType" and "xStatement". By convention,
each group name is prefixed by the filetype for the language being defined.
This example defines syntax for the x language (eXample language without an
interesting name). In a syntax file for "csh" scripts the name "cshType"
would be used. Thus the prefix is equal to the value of 'filetype'.
These commands cause the words "int", "long" and "char" to be highlighted
one way and the words "if", "then", "else" and "endif" to be highlighted
another way. Now you need to connect the x group names to standard Vim
names. You do this with the following commands:
:highlight link xType Type
:highlight link xStatement Statement
This tells Vim to highlight "xType" like "Type" and "xStatement" like
"Statement". See |group-name| for the standard names.
UNUSUAL KEYWORDS
The characters used in a keyword must be in the 'iskeyword' option. If you
use another character, the word will never match. Vim doesn't give a warning
message for this.
The x language uses the '-' character in keywords. This is how it's done:
:setlocal iskeyword+=-
:syntax keyword xStatement when-not
The ":setlocal" command is used to change 'iskeyword' only for the current
buffer. Still it does change the behavior of commands like "w" and "*". If
that is not wanted, don't define a keyword but use a match (explained in the
next section).
The x language allows for abbreviations. For example, "next" can be
abbreviated to "n", "ne" or "nex". You can define them by using this command:
:syntax keyword xStatement n[ext]
This doesn't match "nextone", keywords always match whole words only.
==============================================================================
*44.3* Matches
Consider defining something a bit more complex. You want to match ordinary
identifiers. To do this, you define a match syntax item. This one matches
any word consisting of only lowercase letters:
:syntax match xIdentifier /\<\l\+\>/
Note:
Keywords overrule any other syntax item. Thus the keywords "if",
"then", etc., will be keywords, as defined with the ":syntax keyword"
commands above, even though they also match the pattern for
xIdentifier.
The part at the end is a pattern, like it's used for searching. The // is
used to surround the pattern (like how it's done in a ":substitute" command).
You can use any other character, like a plus or a quote.
Now define a match for a comment. In the x language it is anything from # to
the end of a line:
:syntax match xComment /#.*/
Since you can use any search pattern, you can highlight very complex things
with a match item. See |pattern| for help on search patterns.
==============================================================================
*44.4* Regions
In the example x language, strings are enclosed in double quotation marks (").
To highlight strings you define a region. You need a region start (double
quote) and a region end (double quote). The definition is as follows:
:syntax region xString start=/"/ end=/"/
The "start" and "end" directives define the patterns used to find the start
and end of the region. But what about strings that look like this?
"A string with a double quote (\") in it"
This creates a problem: The double quotation marks in the middle of the string
will end the region. You need to tell Vim to skip over any escaped double
quotes in the string. Do this with the skip keyword:
:syntax region xString start=/"/ skip=/\\"/ end=/"/
The double backslash matches a single backslash, since the backslash is a
special character in search patterns.
When to use a region instead of a match? The main difference is that a match
item is a single pattern, which must match as a whole. A region starts as
soon as the "start" pattern matches. Whether the "end" pattern is found or
not doesn't matter. Thus when the item depends on the "end" pattern to match,
you cannot use a region. Otherwise, regions are often simpler to define. And
it is easier to use nested items, as is explained in the next section.
==============================================================================
*44.5* Nested items
Take a look at this comment:
%Get input TODO: Skip white space
You want to highlight TODO in big yellow letters, even though it is in a
comment that is highlighted blue. To let Vim know about this, you define the
following syntax groups:
:syntax keyword xTodo TODO contained
:syntax match xComment /%.*/ contains=xTodo
In the first line, the "contained" argument tells Vim that this keyword can
exist only inside another syntax item. The next line has "contains=xTodo".
This indicates that the xTodo syntax element is inside it. The result is that
the comment line as a whole is matched with "xComment" and made blue. The
word TODO inside it is matched by xTodo and highlighted yellow (highlighting
for xTodo was setup for this).
RECURSIVE NESTING
The x language defines code blocks in curly braces. And a code block may
contain other code blocks. This can be defined this way:
:syntax region xBlock start=/{/ end=/}/ contains=xBlock
Suppose you have this text:
while i < b {
if a {
b = c;
}
}
First a xBlock starts at the { in the first line. In the second line another
{ is found. Since we are inside a xBlock item, and it contains itself, a
nested xBlock item will start here. Thus the "b = c" line is inside the
second level xBlock region. Then a } is found in the next line, which matches
with the end pattern of the region. This ends the nested xBlock. Because the
} is included in the nested region, it is hidden from the first xBlock region.
Then at the last } the first xBlock region ends.
You want to highlight the three items differently. But "(condition)" and
"then" might also appear in other places, where they get different
highlighting. This is how you can do this:
:syntax match xIf /if/ nextgroup=xIfCondition skipwhite
:syntax match xIfCondition /([^)]*)/ contained nextgroup=xThen skipwhite
:syntax match xThen /then/ contained
The "nextgroup" argument specifies which item can come next. This is not
required. If none of the items that are specified are found, nothing happens.
For example, in this text:
if not (condition) then
The "if" is matched by xIf. "not" doesn't match the specified nextgroup
xIfCondition, thus only the "if" is highlighted.
The "skipwhite" argument tells Vim that white space (spaces and tabs) may
appear in between the items. Similar arguments are "skipnl", which allows a
line break in between the items, and "skipempty", which allows empty lines.
Notice that "skipnl" doesn't skip an empty line, something must match after
the line break.
==============================================================================
*44.7* Other arguments
MATCHGROUP
When you define a region, the entire region is highlighted according to the
group name specified. To highlight the text enclosed in parentheses () with
the group xInside, for example, use the following command:
:syntax region xInside start=/(/ end=/)/
Suppose, that you want to highlight the parentheses differently. You can do
this with a lot of convoluted region statements, or you can use the
"matchgroup" argument. This tells Vim to highlight the start and end of a
region with a different highlight group (in this case, the xParen group):
:syntax region xInside matchgroup=xParen start=/(/ end=/)/
The "matchgroup" argument applies to the start or end match that comes after
it. In the previous example both start and end are highlighted with xParen.
To highlight the end with xParenEnd:
:syntax region xInside matchgroup=xParen start=/(/
\ matchgroup=xParenEnd end=/)/
A side effect of using "matchgroup" is that contained items will not match in
the start or end of the region. The example for "transparent" uses this.
TRANSPARENT
In a C language file you would like to highlight the () text after a "while"
differently from the () text after a "for". In both of these there can be
nested () items, which should be highlighted in the same way. You must make
sure the () highlighting stops at the matching ). This is one way to do this:
:syntax region cWhile matchgroup=cWhile start=/while\s*(/ end=/)/
\ contains=cCondNest
:syntax region cFor matchgroup=cFor start=/for\s*(/ end=/)/
\ contains=cCondNest
:syntax region cCondNest start=/(/ end=/)/ contained transparent
Now you can give cWhile and cFor different highlighting. The cCondNest item
can appear in either of them, but take over the highlighting of the item it is
contained in. The "transparent" argument causes this.
Notice that the "matchgroup" argument has the same group as the item
itself. Why define it then? Well, the side effect of using a matchgroup is
that contained items are not found in the match with the start item then.
This avoids that the cCondNest group matches the ( just after the "while" or
"for". If this would happen, it would span the whole text until the matching
) and the region would continue after it. Now cCondNest only matches after
the match with the start pattern, thus after the first (.
OFFSETS
Suppose you want to define a region for the text between ( and ) after an
"if". But you don't want to include the "if" or the ( and ). You can do this
by specifying offsets for the patterns. Example:
:syntax region xCond start=/if\s*(/ms=e+1 end=/)/me=s-1
The offset for the start pattern is "ms=e+1". "ms" stands for Match Start.
This defines an offset for the start of the match. Normally the match starts
where the pattern matches. "e+1" means that the match now starts at the end
of the pattern match, and then one character further.
The offset for the end pattern is "me=s-1". "me" stands for Match End.
"s-1" means the start of the pattern match and then one character back. The
result is that in this text:
if (foo == bar)
Only the text "foo == bar" will be highlighted as xCond.
More about offsets here: |:syn-pattern-offset|.
ONELINE
The "oneline" argument indicates that the region does not cross a line
boundary. For example:
:syntax region xIfThen start=/if/ end=/then/ oneline
This defines a region that starts at "if" and ends at "then". But if there is
no "then" after the "if", the region doesn't match.
Note:
When using "oneline" the region doesn't start if the end pattern
doesn't match in the same line. Without "oneline" Vim does _not_
check if there is a match for the end pattern. The region starts even
when the end pattern doesn't match in the rest of the file.
Suppose you have a language that contains for loops, if statements, while
loops, and functions. Each of them contains the same syntax elements: numbers
and identifiers. You define them like this:
:syntax match xFor /^for.*/ contains=xNumber,xIdent
:syntax match xIf /^if.*/ contains=xNumber,xIdent
:syntax match xWhile /^while.*/ contains=xNumber,xIdent
You have to repeat the same "contains=" every time. If you want to add
another contained item, you have to add it three times. Syntax clusters
simplify these definitions by enabling you to have one cluster stand for
several syntax groups.
To define a cluster for the two items that the three groups contain, use
the following command:
:syntax cluster xState contains=xNumber,xIdent
Clusters are used inside other syntax items just like any syntax group.
Their names start with @. Thus, you can define the three groups like this:
:syntax match xFor /^for.*/ contains=@xState
:syntax match xIf /^if.*/ contains=@xState
:syntax match xWhile /^while.*/ contains=@xState
You can add new group names to this cluster with the "add" argument:
:syntax cluster xState add=xString
You can remove syntax groups from this list as well:
:syntax cluster xState remove=xNumber
==============================================================================
*44.9* Including another syntax file
The C++ language syntax is a superset of the C language. Because you do not
want to write two syntax files, you can have the C++ syntax file read in the
one for C by using the following command:
:runtime! syntax/c.vim
The ":runtime!" command searches 'runtimepath' for all "syntax/c.vim" files.
This makes the C parts of the C++ syntax be defined like for C files. If you
have replaced the c.vim syntax file, or added items with an extra file, these
will be loaded as well.
After loading the C syntax items the specific C++ items can be defined.
For example, add keywords that are not used in C:
:syntax keyword cppStatement new delete this friend using
This works just like in any other syntax file.
Now consider the Perl language. A Perl script consists of two distinct parts:
a documentation section in POD format, and a program written in Perl itself.
The POD section starts with "=head" and ends with "=cut".
You want to define the POD syntax in one file, and use it from the Perl
syntax file. The ":syntax include" command reads in a syntax file and stores
the elements it defined in a syntax cluster. For Perl, the statements are as
follows:
:syntax include @Pod <sfile>:p:h/pod.vim
:syntax region perlPOD start=/^=head/ end=/^=cut/ contains=@Pod
When "=head" is found in a Perl file, the perlPOD region starts. In this
region the @Pod cluster is contained. All the items defined as top-level
items in the pod.vim syntax files will match here. When "=cut" is found, the
region ends and we go back to the items defined in the Perl file.
The ":syntax include" command is clever enough to ignore a ":syntax clear"
command in the included file. And an argument such as "contains=ALL" will
only contain items defined in the included file, not in the file that includes
it.
The "<sfile>:p:h/" part uses the name of the current file (<sfile>),
expands it to a full path (:p) and then takes the head (:h). This results in
the directory name of the file. This causes the pod.vim file in the same
directory to be included.
==============================================================================
*44.10* Synchronizing
Compilers have it easy. They start at the beginning of a file and parse it
straight through. Vim does not have it so easy. It must start in the middle,
where the editing is being done. So how does it tell where it is?
The secret is the ":syntax sync" command. This tells Vim how to figure out
where it is. For example, the following command tells Vim to scan backward
for the beginning or end of a C-style comment and begin syntax coloring from
there:
:syntax sync ccomment
You can tune this processing with some arguments. The "minlines" argument
tells Vim the minimum number of lines to look backward, and "maxlines" tells
the editor the maximum number of lines to scan.
For example, the following command tells Vim to look at least 10 lines
before the top of the screen:
:syntax sync ccomment minlines=10 maxlines=500
If it cannot figure out where it is in that space, it starts looking farther
and farther back until it figures out what to do. But it looks no farther
back than 500 lines. (A large "maxlines" slows down processing. A small one
might cause synchronization to fail.)
To make synchronizing go a bit faster, tell Vim which syntax items can be
skipped. Every match and region that only needs to be used when actually
displaying text can be given the "display" argument.
By default, the comment to be found will be colored as part of the Comment
syntax group. If you want to color things another way, you can specify a
different syntax group:
:syntax sync ccomment xAltComment
If your programming language does not have C-style comments in it, you can try
another method of synchronization. The simplest way is to tell Vim to space
back a number of lines and try to figure out things from there. The following
command tells Vim to go back 150 lines and start parsing from there:
:syntax sync minlines=150
A large "minlines" value can make Vim slower, especially when scrolling
backwards in the file.
Finally, you can specify a syntax group to look for by using this command:
:syntax sync match {sync-group-name}
\ grouphere {group-name} {pattern}
This tells Vim that when it sees {pattern} the syntax group named {group-name}
begins just after the pattern given. The {sync-group-name} is used to give a
name to this synchronization specification. For example, the sh scripting
language begins an if statement with "if" and ends it with "fi":
if [ --f file.txt ] ; then
echo "File exists"
fi
To define a "grouphere" directive for this syntax, you use the following
command:
:syntax sync match shIfSync grouphere shIf "\<if\>"
The "groupthere" argument tells Vim that the pattern ends a group. For
example, the end of the if/fi group is as follows:
:syntax sync match shIfSync groupthere NONE "\<fi\>"
In this example, the NONE tells Vim that you are not in any special syntax
region. In particular, you are not inside an if block.
You also can define matches and regions that are with no "grouphere" or
"groupthere" arguments. These groups are for syntax groups skipped during
synchronization. For example, the following skips over anything inside {},
even if it would normally match another synchronization method:
:syntax sync match xSpecial /{.*}/
More about synchronizing in the reference manual: |:syn-sync|.
==============================================================================
If you want your syntax file to work with Vim 5.x, add a check for v:version.
See yacc.vim for an example.
Do not include anything that is a user preference. Don't set 'tabstop',
'expandtab', etc. These belong in a filetype plugin.
Do not include mappings or abbreviations. Only include setting 'iskeyword' if
it is really necessary for recognizing keywords.
To allow users select their own preferred colors, make a different group name
for every kind of highlighted item. Then link each of them to one of the
standard highlight groups. That will make it work with every color scheme.
If you select specific colors it will look bad with some color schemes. And
don't forget that some people use a different background color, or have only
eight colors available.
For the linking use "hi def link", so that the user can select different
highlighting before your syntax file is loaded. Example:
hi def link nameString String
hi def link nameNumber Number
hi def link nameCommand Statement
... etc ...
Add the "display" argument to items that are not used when syncing, to speed
up scrolling backwards and CTRL-L.
==============================================================================
Next chapter: |usr_45.txt| Select your language
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
The messages in Vim can be given in several languages. This chapter explains
how to change which one is used. Also, the different ways to work with files
in various languages is explained.
|45.1| Language for Messages
|45.2| Language for Menus
|45.3| Using another encoding
|45.4| Editing files with a different encoding
|45.5| Entering language text
Next chapter: |usr_90.txt| Installing Vim
Previous chapter: |usr_44.txt| Your own syntax highlighted
Table of contents: |usr_toc.txt|
==============================================================================
*45.1* Language for Messages
When you start Vim, it checks the environment to find out what language you
are using. Mostly this should work fine, and you get the messages in your
language (if they are available). To see what the current language is, use
this command:
:language
If it replies with "C", this means the default is being used, which is
English.
Note:
Using different languages only works when Vim was compiled to handle
it. To find out if it works, use the ":version" command and check the
output for "+gettext" and "+multi_lang". If they are there, you are
OK. If you see "-gettext" or "-multi_lang" you will have to find
another Vim.
What if you would like your messages in a different language? There are
several ways. Which one you should use depends on the capabilities of your
system.
The first way is to set the environment to the desired language before
starting Vim. Example for Unix:
env LANG=de_DE.ISO_8859-1 vim
This only works if the language is available on your system. The advantage is
that all the GUI messages and things in libraries will use the right language
as well. A disadvantage is that you must do this before starting Vim. If you
want to change language while Vim is running, you can use the second method:
:language fr_FR.ISO_8859-1
This way you can try out several names for your language. You will get an
error message when it's not supported on your system. You don't get an error
when translated messages are not available. Vim will silently fall back to
using English.
To find out which languages are supported on your system, find the
directory where they are listed. On my system it is "/usr/share/locale". On
language. For many European languages this is "latin1". Then each byte is
one character. That means there are 256 different characters possible. For
Asian languages this is not sufficient. These mostly use a double-byte
encoding, providing for over ten thousand possible characters. This still
isn't enough when a text is to contain several different languages. This is
where Unicode comes in. It was designed to include all characters used in
commonly used languages. This is the "Super encoding that replaces all
others". But it isn't used that much yet.
Fortunately, Vim supports these three kinds of encodings. And, with some
restrictions, you can use them even when your environment uses another
language than the text.
Nevertheless, when you only edit files that are in the encoding of your
language, the default should work fine and you don't need to do anything. The
following is only relevant when you want to edit different languages.
Note:
Using different encodings only works when Vim was compiled to handle
it. To find out if it works, use the ":version" command and check the
output for "+multi_byte". If it's there, you are OK. If you see
"-multi_byte" you will have to find another Vim.
Start the xterm with the "-u8" argument. You might also need so specify a
font. Example:
xterm -u8 -fn -misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1
Now you can run Vim inside this terminal. Set 'encoding' to "utf-8" as
before. That's all.
See |encoding-values| for suggested values. Other values may work as well.
This depends on the conversion available.
FORCING AN ENCODING
If the automatic detection doesn't work you must tell Vim what encoding the
file is. Example:
:edit ++enc=koi8-r russian.txt
The "++enc" part specifies the name of the encoding to be used for this file
only. Vim will convert the file from the specified encoding, Russian in this
example, to 'encoding'. 'fileencoding' will also be set to the specified
encoding, so that the reverse conversion can be done when writing the file.
The same argument can be used when writing the file. This way you can
actually use Vim to convert a file. Example:
:write ++enc=utf-8 russian.txt
Note:
Conversion may result in lost characters. Conversion from an encoding
to Unicode and back is mostly free of this problem, unless there are
illegal characters. Conversion from Unicode to other encodings often
loses information when there was more than one language in the file.
==============================================================================
*45.5* Entering language text
Computer keyboards don't have much more than a hundred keys. Some languages
have thousands of characters, Unicode has ten thousands. So how do you type
these characters?
First of all, when you don't use too many of the special characters, you
can use digraphs. This was already explained in |24.9|.
When you use a language that uses many more characters than keys on your
keyboard, you will want to use an Input Method (IM). This requires learning
the translation from typed keys to resulting character. When you need an IM
you probably already have one on your system. It should work with Vim like
with other programs. For details see |mbyte-XIM| for the X Window system and
|mbyte-IME| for MS-Windows.
KEYMAPS
For some languages the character set is different from latin, but uses a
similar number of characters. It's possible to map keys to characters. Vim
uses keymaps for this.
Suppose you want to type Hebrew. You can load the keymap like this:
:set keymap=hebrew
Vim will try to find a keymap file for you. This depends on the value of
'encoding'. If no matching file was found, you will get an error message.
Now you can type Hebrew in Insert mode. In Normal mode, and when typing a ":"
command, Vim automatically switches to English. You can use this command to
switch between Hebrew and English:
CTRL-^
This only works in Insert mode and Command-line mode. In Normal mode it does
something completely different (jumps to alternate file).
The usage of the keymap is indicated in the mode message, if you have the
'showmode' option set. In the GUI Vim will indicate the usage of keymaps with
a different cursor color.
You can also change the usage of the keymap with the 'iminsert' and
'imsearch' options.
To see the list of mappings, use this command:
:lmap
To find out which keymap files are available, in the GUI you can use the
Edit/Keymap menu. Otherwise you can use this command:
:echo globpath(&rtp, "keymap/*.vim")
DO-IT-YOURSELF KEYMAPS
You can create your own keymap file. It's not very difficult. Start with
a keymap file that is similar to the language you want to use. Copy it to the
"keymap" directory in your runtime directory. For example, for Unix, you
would use the directory "~/.vim/keymap".
The name of the keymap file must look like this:
keymap/{name}.vim
or
keymap/{name}_{encoding}.vim
{name} is the name of the keymap. Chose a name that is obvious, but different
from existing keymaps (unless you want to replace an existing keymap file).
{name} cannot contain an underscore. Optionally, add the encoding used after
an underscore. Examples:
keymap/hebrew.vim
keymap/hebrew_utf-8.vim
The contents of the file should be self-explanatory. Look at a few of the
keymaps that are distributed with Vim. For the details, see |mbyte-keymap|.
LAST RESORT
If all other methods fail, you can enter any character with CTRL-V:
encoding type range
8-bit CTRL-V 123 decimal 0-255
8-bit CTRL-V x a1 hexadecimal 00-ff
16-bit CTRL-V u 013b hexadecimal 0000-ffff
31-bit CTRL-V U 001303a4 hexadecimal 00000000-7fffffff
Don't type the spaces. See |i_CTRL-V_digit| for the details.
==============================================================================
Next chapter: |usr_90.txt| Installing Vim
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
*install*
Before you can use Vim you have to install it. Depending on your system it's
simple or easy. This chapter gives a few hints and also explains how
upgrading to a new version is done.
|90.1| Unix
|90.2| MS-Windows
|90.3| Upgrading
|90.4| Common installation issues
|90.5| Uninstalling Vim
Previous chapter: |usr_45.txt| Select your language
Table of contents: |usr_toc.txt|
==============================================================================
*90.1* Unix
First you have to decide if you are going to install Vim system-wide or for a
single user. The installation is almost the same, but the directory where Vim
is installed in differs.
For a system-wide installation the base directory "/usr/local" is often
used. But this may be different for your system. Try finding out where other
packages are installed.
When installing for a single user, you can use your home directory as the
base. The files will be placed in subdirectories like "bin" and "shared/vim".
FROM A PACKAGE
You can get precompiled binaries for many different UNIX systems. There is a
long list with links on this page:
http://www.vim.org/binaries.html
Volunteers maintain the binaries, so they are often out of date. It is a
good idea to compile your own UNIX version from the source. Also, creating
the editor from the source allows you to control which features are compiled.
This does require a compiler though.
If you have a Linux distribution, the "vi" program is probably a minimal
version of Vim. It doesn't do syntax highlighting, for example. Try finding
another Vim package in your distribution, or search on the web site.
FROM SOURCES
To compile and install Vim, you will need the following:
- A C compiler (GCC preferred)
- The GZIP program (you can get it from www.gnu.org)
- The Vim source and runtime archives
To get the Vim archives, look in this file for a mirror near you, this should
provide the fastest download:
ftp://ftp.vim.org/pub/vim/MIRRORS
Or use the home site ftp.vim.org, if you think it's fast enough. Go to the
"unix" directory and you'll find a list of files there. The version number is
embedded in the file name. You will want to get the most recent version.
You can get the files for Unix in two ways: One big archive that contains
everything, or four smaller ones that each fit on a floppy disk. For version
6.1 the single big one is called:
vim-6.1.tar.bz2
You need the bzip2 program to uncompress it. If you don't have it, get the
four smaller files, which can be uncompressed with gzip. For Vim 6.1 they are
called:
vim-6.1-src1.tar.gz
vim-6.1-src2.tar.gz
vim-6.1-rt1.tar.gz
vim-6.1-rt2.tar.gz
COMPILING
First create a top directory to work in, for example:
mkdir ~/vim
cd ~/vim
Then unpack the archives there. If you have the one big archive, you unpack
it like this:
bzip2 -d -c path/vim-6.1.tar.bz2 | tar xf -
Change "path" to where you have downloaded the file.
gzip -d -c path/vim-6.1-src1.tar.gz | tar xf -
gzip -d -c path/vim-6.1-src2.tar.gz | tar xf -
gzip -d -c path/vim-6.1-rt1.tar.gz | tar xf -
gzip -d -c path/vim-6.1-rt2.tar.gz | tar xf -
If you are satisfied with getting the default features, and your environment
is setup properly, you should be able to compile Vim with just this:
cd vim61/src
make
The make program will run configure and compile everything. Further on we
will explain how to compile with different features.
If there are errors while compiling, carefully look at the error messages.
There should be a hint about what went wrong. Hopefully you will be able to
correct it. You might have to disable some features to make Vim compile.
Look in the Makefile for specific hints for your system.
TESTING
Now you can check if compiling worked OK:
make test
This will run a sequence of test scripts to verify that Vim works as expected.
Vim will be started many times and all kinds of text and messages flash by.
If it is alright you will finally see:
test results:
ALL DONE
If you get "TEST FAILURE" some test failed. If there are one or two messages
about failed tests, Vim might still work, but not perfectly. If you see a lot
of error messages or Vim doesn't finish until the end, there must be something
wrong. Either try to find out yourself, or find someone who can solve it.
You could look in the |maillist-archive| for a solution. If everything else
fails, you could ask in the vim |maillist| if someone can help you.
INSTALLING
*install-home*
If you want to install in your home directory, edit the Makefile and search
for a line:
#prefix = $(HOME)
Remove the # at the start of the line.
When installing for the whole system, Vim has most likely already selected
a good installation directory for you. You can also specify one, see below.
You need to become root for the following.
To install Vim do:
make install
That should move all the relevant files to the right place. Now you can try
running vim to verify that it works. Use two simple tests to check if Vim can
find its runtime files:
:help
:syntax enable
If this doesn't work, use this command to check where Vim is looking for the
runtime files:
:echo $VIMRUNTIME
You can also start Vim with the "-V" argument to see what happens during
startup:
vim -V
Don't forget that the user manual assumes you Vim in a certain way. After
installing Vim, follow the instructions at |not-compatible| to make Vim work
as assumed in this manual.
SELECTING FEATURES
Vim has many ways to select features. One of the simple ways is to edit the
Makefile. There are many directions and examples. Often you can enable or
disable a feature by uncommenting a line.
An alternative is to run "configure" separately. This allows you to
specify configuration options manually. The disadvantage is that you have to
figure out what exactly to type.
Some of the most interesting configure arguments follow. These can also be
enabled from the Makefile.
--prefix={directory} Top directory where to install Vim.
--with-features=tiny Compile with many features disabled.
--with-features=small Compile with some features disabled.
--with-features=big Compile with more features enabled.
--with-features=huge Compile with most features enabled.
See |+feature-list| for which feature
is enabled in which case.
--enable-perlinterp Enable the Perl interface. There are
similar arguments for ruby, python and
tcl.
--disable-gui Do not compile the GUI interface.
--without-x Do not compile X-windows features.
When both of these are used, Vim will
not connect to the X server, which
makes startup faster.
To see the whole list use:
./configure --help
You can find a bit of explanation for each feature, and links for more
information here: |feature-list|.
For the adventurous, edit the file "feature.h". You can also change the
source code yourself!
==============================================================================
*90.2* MS-Windows
There are two ways to install the Vim program for Microsoft Windows. You can
uncompress several archives, or use a self-installing big archive. Most users
with fairly recent computers will prefer the second method. For the first
one, you will need:
- An archive with binaries for Vim.
- The Vim runtime archive.
- A program to unpack the zip files.
To get the Vim archives, look in this file for a mirror near you, this should
provide the fastest download:
ftp://ftp.vim.org/pub/vim/MIRRORS
Or use the home site ftp.vim.org, if you think it's fast enough. Go to the
"pc" directory and you'll find a list of files there. The version number is
embedded in the file name. You will want to get the most recent version.
We will use "61" here, which is version 6.1.
gvim61.exe The self-installing archive.
This is all you need for the second method. Just launch the executable, and
follow the prompts.
For the first method you must chose one of the binary archives. These are
available:
gvim61.zip The normal MS-Windows GUI version.
gvim61ole.zip The MS-Windows GUI version with OLE support.
Uses more memory, supports interfacing with
other OLE applications.
vim61w32.zip 32 bit MS-Windows console version. For use in
a Win NT/2000/XP console. Does not work well
on Win 95/98.
vim61d32.zip 32 bit MS-DOS version. For use in the
Win 95/98 console window.
vim61d16.zip 16 bit MS-DOS version. Only for old systems.
Does not support long filenames.
You only need one of them. Although you could install both a GUI and a
console version. You always need to get the archive with runtime files.
vim61rt.zip The runtime files.
Use your un-zip program to unpack the files. For example, using the "unzip"
program:
cd c:\
unzip path\gvim61.zip
unzip path\vim61rt.zip
This will unpack the files in the directory "c:\vim\vim61". If you already
have a "vim" directory somewhere, you will want to move to the directory just
above it.
Now change to the "vim\vim61" directory and run the install program:
install
Carefully look through the messages and select the options you want to use.
If you finally select "do it" the install program will carry out the actions
you selected.
The install program doesn't move the runtime files. They remain where you
unpacked them.
In case you are not satisfied with the features included in the supplied
binaries, you could try compiling Vim yourself. Get the source archive from
the same location as where the binaries are. You need a compiler for which a
makefile exists. Microsoft Visual C works, but is expensive. The Free
Borland command-line compiler 5.5 can be used, as well as the free MingW and
Cygwin compilers. Check the file src/INSTALLpc.txt for hints.
==============================================================================
*90.3* Upgrading
If you are running one version of Vim and want to install another, here is
what to do.
UNIX
When you type "make install" the runtime files will be copied to a directory
which is specific for this version. Thus they will not overwrite a previous
version. This makes it possible to use two or more versions next to
each other.
The executable "vim" will overwrite an older version. If you don't care
about keeping the old version, running "make install" will work fine. You can
delete the old runtime files manually. Just delete the directory with the
version number in it and all files below it. Example:
rm -rf /usr/local/share/vim/vim58
There are normally no changed files below this directory. If you did change
the "filetype.vim" file, for example, you better merge the changes into the
new version before deleting it.
If you are careful and want to try out the new version for a while before
switching to it, install the new version under another name. You need to
specify a configure argument. For example:
./configure --with-vim-name=vim6
Before running "make install", you could use "make -n install" to check that
no valuable existing files are overwritten.
When you finally decide to switch to the new version, all you need to do is
to rename the binary to "vim". For example:
mv /usr/local/bin/vim6 /usr/local/bin/vim
MS-WINDOWS
Upgrading is mostly equal to installing a new version. Just unpack the files
in the same place as the previous version. A new directory will be created,
e.g., "vim61", for the files of the new version. Your runtime files, vimrc
file, viminfo, etc. will be left alone.
If you want to run the new version next to the old one, you will have to do
some handwork. Don't run the install program, it will overwrite a few files
of the old version. Execute the new binaries by specifying the full path.
The program should be able to automatically find the runtime files for the
right version. However, this won't work if you set the $VIMRUNTIME variable
somewhere.
If you are satisfied with the upgrade, you can delete the files of the
previous version. See |90.5|.
==============================================================================
*90.4* Common installation issues
This section describes some of the common problems that occur when installing
Vim and suggests some solutions. It also contains answers to many
installation questions.
:set t_kb=^V<BS>
:set t_kD=^V<Del>
In the first line you need to press CTRL-V and then hit the backspace key.
In the second line you need to press CTRL-V and then hit the Delete key.
You can put these lines in your vimrc file, see |05.1|. A disadvantage is
that it won't work when you use another terminal some day. Look here for
alternate solutions: |:fixdel|.
Q: I Am Using RedHat Linux. Can I Use the Vim That Comes with the System?
By default RedHat installs a minimal version of Vim. Check your RPM packages
for something named "Vim-enhanced-version.rpm" and install that.
UNIX
When you installed Vim as a package, check your package manager to find out
how to remove the package again.
If you installed Vim from sources you can use this command:
make uninstall
However, if you have deleted the original files or you used an archive that
someone supplied, you can't do this. Do delete the files manually, here is an
example for when "/usr/local" was used as the root:
rm -rf /usr/local/share/vim/vim61
rm /usr/local/bin/eview
rm /usr/local/bin/evim
rm /usr/local/bin/ex
rm /usr/local/bin/gview
rm /usr/local/bin/gvim
rm /usr/local/bin/gvim
rm /usr/local/bin/gvimdiff
rm /usr/local/bin/rgview
rm /usr/local/bin/rgvim
rm /usr/local/bin/rview
rm /usr/local/bin/rvim
rm /usr/local/bin/rvim
rm /usr/local/bin/view
rm /usr/local/bin/vim
rm /usr/local/bin/vimdiff
rm /usr/local/bin/vimtutor
rm /usr/local/bin/xxd
rm /usr/local/man/man1/eview.1
rm /usr/local/man/man1/evim.1
rm /usr/local/man/man1/ex.1
rm /usr/local/man/man1/gview.1
rm /usr/local/man/man1/gvim.1
rm /usr/local/man/man1/gvimdiff.1
rm /usr/local/man/man1/rgview.1
rm /usr/local/man/man1/rgvim.1
rm /usr/local/man/man1/rview.1
rm /usr/local/man/man1/rvim.1
rm /usr/local/man/man1/view.1
rm /usr/local/man/man1/vim.1
rm /usr/local/man/man1/vimdiff.1
rm /usr/local/man/man1/vimtutor.1
rm /usr/local/man/man1/xxd.1
MS-WINDOWS
If you installed Vim with the self-installing archive you can run
the "uninstall-gui" program located in the same directory as the other Vim
programs, e.g. "c:\vim\vim61". You can also launch it from the Start menu if
installed the Vim entries there. This will remove most of the files, menu
entries and desktop shortcuts. Some files may remain however, as they need a
Windows restart before being deleted.
You will be given the option to remove the whole "vim" directory. It
probably contains your vimrc file and other runtime files that you created, so
be careful.
Else, if you installed Vim with the zip archives, the preferred way is to use
the "uninstal" program (note the missing l at the end). You can find it in
the same directory as the "install" program, e.g., "c:\vim\vim61". This
should also work from the usual "install/remove software" page.
However, this only removes the registry entries for Vim. You have to
delete the files yourself. Simply select the directory "vim\vim61" and delete
it recursively. There should be no files there that you changed, but you
might want to check that first.
The "vim" directory probably contains your vimrc file and other runtime
files that you created. You might want to keep that.
==============================================================================
Table of contents: |usr_toc.txt|
Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
top - main help file
'compatible'.
------------------------------------------------------------------------------
top
terminfo. This can cause differences when the entries differ AND when of
the programs in question one uses terminfo and the other uses termcap
(also see |+terminfo|).
In your particular problem, you are looking for the control sequences
^[[?47h and ^[[?47l. These switch between xterms alternate and main screen
buffer. As a quick workaround a command sequence like
echo -n "^[[?47h"; vim ... ; echo -n "^[[?47l"
may do what you want. (My notation ^[ means the ESC character, further down
you'll see that the databases use \E instead).
On startup, vim echoes the value of the termcap variable ti (terminfo:
smcup) to the terminal. When exiting, it echoes te (terminfo: rmcup). Thus
these two variables are the correct place where the above mentioned control
sequences should go.
Compare your xterm termcap entry (found in /etc/termcap) with your xterm
terminfo entry (retrieved with "infocmp -C xterm"). Both should contain
entries similar to:
:te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:
PS: If you find any difference, someone (your sysadmin?) should better check
the complete termcap and terminfo database for consistency.
NOTE 1: If you recompile Vim with FEAT_XTERM_SAVE defined in feature.h, the
builtin xterm will include the mentioned "te" and "ti" entries.
NOTE 2: If you want to disable the screen switching, and you don't want to
change your termcap, you can add these lines to your .vimrc:
:set t_ti= t_te=
==============================================================================
Scrolling in Insert mode *scroll-insert*
If you are in insert mode and you want to see something that is just off the
screen, you can use CTRL-X CTRL-E and CTRL-X CTRL-Y to scroll the screen.
|i_CTRL-X_CTRL-E|
To make this easier, you could use these mappings:
:inoremap <C-E> <C-X><C-E>
:inoremap <C-Y> <C-X><C-Y>
(Type this literally, make sure the '<' flag is not in 'cpoptions').
You then lose the ability to copy text from the line above/below the cursor
|i_CTRL-E|.
Also consider setting 'scrolloff' to a larger value, so that you can always see
some context around the cursor. If 'scrolloff' is bigger than half the window
height, the cursor will always be in the middle and the text is scrolled when
the cursor is moved up/down.
==============================================================================
Smooth scrolling *scroll-smooth*
If you like the scrolling to go a bit smoother, you can use these mappings:
:map <C-U> <C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-
Y><C-Y>
:map <C-D> <C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-
E><C-E>
(Type this literally, make sure the '<' flag is not in 'cpoptions').
==============================================================================
Correcting common typing mistakes *type-mistakes*
When there are a few words that you keep on typing in the wrong way, make
abbreviations that correct them. For example:
:ab teh the
:ab fro for
==============================================================================
Counting words, lines, etc. *count-items*
To count how often any pattern occurs in the current buffer use the substitute
command and add the 'n' flag to avoid the substitution. The reported number
of substitutions is the number of items. Examples:
:%s/./&/gn characters
:%s/\i\+/&/gn words
:%s/^//n lines
:%s/the/&/gn "the" anywhere
:%s/\<the\>/&/gn "the" as a word
You might want to reset 'hlsearch' or do ":nohlsearch".
Add the 'e' flag if you don't want an error when there are no matches.
An alternative is using |v_g_CTRL-G| in Visual mode.
If you want to find matches in multiple files use |:vimgrep|.
*count-bytes*
If you want to count bytes, you can use this:
Visually select the characters (block is also possible)
Use "y" to yank the characters
Use the strlen() function:
:echo strlen(@")
A line break is counted for one byte.
==============================================================================
Restoring the cursor position *restore-position*
Sometimes you want to write a mapping that makes a change somewhere in the
file and restores the cursor position, without scrolling the text. For
example, to change the date mark in a file:
:map <F2> msHmtgg/Last [cC]hange:\s*/e+1<CR>"_D"=strftime("%Y %b %d")<CR>p'tzt`s
Breaking up saving the position:
ms store cursor position in the 's' mark
H go to the first line in the window
mt store this position in the 't' mark
Breaking up restoring the position:
't go to the line previously at the top of the window
zt scroll to move this line to the top of the window
`s jump to the original position of the cursor
For something more advanced see |winsaveview()| and |winrestview()|.
==============================================================================
Renaming files *rename-files*
Say I have a directory with the following files in them (directory picked at
random :-):
buffer.c
charset.c
digraph.c
...
and I want to rename *.c *.bla. I'd do it like this:
$ vim
:r !ls *.c
:%s/\(.*\).c/mv & \1.bla
:w !sh
:q!
==============================================================================
Change a name in multiple files *change-name*
Example for using a script file to change a name in several files:
Create a file "subs.vim" containing substitute commands and a :update
command:
:%s/Jones/Smith/g
:%s/Allen/Peter/g
:update
Execute Vim on all files you want to change, and source the script for
each argument:
vim *.let
argdo source subs.vim
See |:argdo|.
==============================================================================
Speeding up external commands *speed-up*
In some situations, execution of an external command can be very slow. This
can also slow down wildcard expansion on Unix. Here are a few suggestions to
increase the speed.
If your .cshrc (or other file, depending on the shell used) is very long, you
should separate it into a section for interactive use and a section for
non-interactive use (often called secondary shells). When you execute a
command from Vim like ":!ls", you do not need the interactive things (for
example, setting the prompt). Put the stuff that is not needed after these
lines:
if ($?prompt == 0) then
exit 0
endif
Another way is to include the "-f" flag in the 'shell' option, e.g.:
:set shell=csh\ -f
(the backslash is needed to include the space in the option).
This will make csh completely skip the use of the .cshrc file. This may cause
some things to stop working though.
==============================================================================
Useful mappings *useful-mappings*
Here are a few mappings that some people like to use.
*map-backtick*
:map ' `
Make the single quote work like a backtick. Puts the cursor on the column of
a mark, instead of going to the first non-blank character in the line.
*emacs-keys*
For Emacs-style editing on the command-line:
" start of line
:cnoremap <C-A> <Home>
" back one character
:cnoremap <C-B> <Left>
" delete character under cursor
:cnoremap <C-D> <Del>
" end of line
:cnoremap <C-E> <End>
" forward one character
:cnoremap <C-F> <Right>
" recall newer command-line
:cnoremap <C-N> <Down>
" recall previous (older) command-line
:cnoremap <C-P> <Up>
" back one word
:cnoremap <Esc><C-B> <S-Left>
" forward one word
:cnoremap <Esc><C-F> <S-Right>
NOTE: This requires that the '<' flag is excluded from 'cpoptions'. |<>|
*format-bullet-list*
This mapping will format any bullet list. It requires that there is an empty
line above and below each list entry. The expression commands are used to
be able to give comments to the parts of the mapping.
:let m = ":map _f :set ai<CR>" " need 'autoindent' set
:let m = m . "{O<Esc>" " add empty line above item
:let m = m . "}{)^W" " move to text after bullet
*collapse*
These two mappings reduce a sequence of empty (;b) or blank (;n) lines into a
single line
:map ;b GoZ<Esc>:g/^$/.,/./-j<CR>Gdd
:map ;n GoZ<Esc>:g/^[ <Tab>]*$/.,/[^ <Tab>]/-j<CR>Gdd
==============================================================================
Compressing the help files *gzip-helpfile*
For those of you who are really short on disk space, you can compress the help
files and still be able to view them with Vim. This makes accessing the help
files a bit slower and requires the "gzip" program.
(1) Compress all the help files: "gzip doc/*.txt".
(2) Edit "doc/tags" and change the ".txt" to ".txt.gz":
:%s=\(\t.*\.txt\)\t=\1.gz\t=
(3) Add this line to your vimrc:
set helpfile={dirname}/help.txt.gz
Where {dirname} is the directory where the help files are. The |gzip| plugin
will take care of decompressing the files.
You must make sure that $VIMRUNTIME is set to where the other Vim files are,
when they are not in the same location as the compressed "doc" directory. See
|$VIMRUNTIME|.
==============================================================================
Executing shell commands in a window *shell-window*
There have been questions for the possibility to execute a shell in a window
inside Vim. The answer: you can't! Including this would add a lot of code to
Vim, which is a good reason not to do this. After all, Vim is an editor, it
is not supposed to do non-editing tasks. However, to get something like this,
you might try splitting your terminal screen or display window with the
"splitvt" program. You can probably find it on some ftp server. The person
that knows more about this is Sam Lantinga <slouken@cs.ucdavis.edu>.
An alternative is the "window" command, found on BSD Unix systems, which
supports multiple overlapped windows. Or the "screen" program, found at
www.uni-erlangen.de, which supports a stack of windows.
==============================================================================
Hex editing *hex-editing* *using-xxd*
See section |23.4| of the user manual.
If one has a particular extension that one uses for binary files (such as exe,
bin, etc), you may find it helpful to automate the process with the following
bit of autocmds for your <.vimrc>. Change that "*.bin" to whatever
comma-separated list of extension(s) you find yourself wanting to edit:
" vim -b : edit binary using xxd-format!
augroup Binary
au!
*map-self-destroy*
" This is for automatically adding the name of the file to the menu list.
" It uses a self-destroying mapping!
" 1. use a line in the buffer to convert the 'dots' in the file name to \.
" 2. store that in register '"'
" 3. add that name to the Buffers menu list
" WARNING: this does have some side effects, like overwriting the
" current register contents and removing any mapping for the "i" command.
"
autocmd BufNewFile,BufReadPre * nmap i :nunmap i<CR>O<C-R>%<Esc>:.g/\./s/\./\\./g<CR>0"9y$u:menu
Buffers.<C-R>9 :buffer <C-R>%<C-V><CR><CR>
autocmd BufNewFile,BufReadPre * normal i
Another method, perhaps better, is to use the ":execute" command. In the
string you can use the <> notation by preceding it with a backslash. Don't
forget to double the number of existing backslashes and put a backslash before
'"''.
autocmd BufNewFile,BufReadPre * exe "normal O\<C-R>%\<Esc>:.g/\\./s/\\./\\\\./g\<CR>0\"9y$u:menu
Buffers.\<C-R>9 :buffer \<C-R>%\<C-V>\<CR>\<CR>"
For a real buffer menu, user functions should be used (see |:function|), but
then the <> notation isn't used, which defeats using it as an example here.
==============================================================================
Highlighting matching parens *match-parens*
This example shows the use of a few advanced tricks:
- using the |CursorMoved| autocommand event
- using |searchpairpos()| to find a matching paren
- using |synID()| to detect whether the cursor is in a string or comment
- using |:match| to highlight something
- using a |pattern| to match a specific position in the file.
This should be put in a Vim script file, since it uses script-local variables.
It skips matches in strings or comments, unless the cursor started in string
or comment. This requires syntax highlighting.
A slightly more advanced version is used in the |matchparen| plugin.
let s:paren_hl_on = 0
function s:Highlight_Matching_Paren()
if s:paren_hl_on
match none
let s:paren_hl_on = 0
endif
let c_lnum = line('.')
let c_col = col('.')
let c = getline(c_lnum)[c_col - 1]
let plist = split(&matchpairs, ':\|,')
let i = index(plist, c)
if i < 0
return
endif
if i % 2 == 0
let s_flags = 'nW'
let c2 = plist[i + 1]
else
let s_flags = 'nbW'
let c2 = c
let c = plist[i - 1]
endif
if c == '['
let c = '\['
let c2 = '\]'
endif
let s_skip ='synIDattr(synID(line("."), col("."), 0), "name") ' .
\ '=~? "string\\|comment"'
execute 'if' s_skip '| let s_skip = 0 | endif'
let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip)
if m_lnum > 0 && m_lnum >= line('w0') && m_lnum <= line('w$')
exe 'match Search /\(\%' . c_lnum . 'l\%' . c_col .
\ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
let s:paren_hl_on = 1
endif
endfunction
autocmd CursorMoved,CursorMovedI * call s:Highlight_Matching_Paren()
autocmd InsertEnter * match none
*votes-for-changes*
See |develop.txt| for development plans. You can vote for which items should
be worked on, but only if you sponsor Vim development. See |sponsor|.
*known-bugs*
Improvement patch for filetype.vim. (Thilo Six, 2011 Mar 19)
Patch to recognize more files as log files. (Mathieu Parent, 2011 Jan 14)
Two patches for xxd. (Florian Zumbiehl, 2011 Jan 11)
Two updates for second one Jan 12.
Go through new coverity reports.
When 'colorcolumn' is set locally to a window, ":new" opens a window with the
same highlighting but 'colorcolumn' is empty. (Tyru, 2010 Nov 15)
Patch by Christian Brabandt, 2011 Feb 13 (but move further down).
Patch for configure related to Ruby on Mac OS X. (Bjorn Winckler, 2011 Jan 14)
Patch to set v:register on startup. (Ingo Karkat, 2011 Jan 16)
Patch to set v:register default depending on "unnamed" in 'clipboard'. (Ingo
Karkat, 2011 Jan 16)
Patch for:
InsertCharPre - user typed character Insert mode, before inserting the
char. Pattern is matched with text before the cursor.
Set v:char to the character, can be changed.
(not triggered when 'paste' is set).
(Jakson A. Aquino, 2011 Jan 29)
Patch for "No errors" showing up after QuickfixCmdPost. (Mike Lundy, 2011 Feb
3)
64 bits value. Change all number options to use nropt_T and define it to the
right type.
string() can't parse back "inf" and "nan". Fix documentation or fix code?
(ZyX, 2010 Aug 23)
When doing "redir => s:foo" in a script and then "redir END" somewhere else
(e.g. in a function) it can't find s:foo.
maparg() does not show the <script> flag. When temporarily changing a
mapping, how to restore the script ID?
Patch to fix \%V item in regexp. (Christian Brabandt, 2010 Nov 8)
Update Nov 19. James Vega: still not right. Christian: it's difficult.
Patch to add up to 99 match groups. (Christian Brabandt, 2010 Dec 22)
Also add named groups: \%{name}(re) and \%{name}g
Bug in try/catch: return with invalid compare throws error that isn't caught.
(ZyX, 2011 Jan 26)
Highlighting stops working after changing it many times. Script to reproduce
it: Pablo Contreras, 2010 Oct 12 Windows XP and 7. Font is never freed?
After patch 7.3.097 still get E15. (Yukihiro Nakadaira, 2011 Jan 18)
Also for another example (ZyX, 2011 Jan 24)
Build problem with small features on Mac OS X 10.6. (Rainer, 2011 Jan 24)
"0g@$" puts '] on last byte of multi-byte. (ZyX, 2011 Jan 22)
Deleting a linewise selection that includes the last line of the file leaves
an empty line. (Ben Schmidt, 2011 Mar 17)
Patch by Christian Brabandt, 2011 Mar 19.
Patch to support sorting on floating point number. (Alex Jakushev, 2010 Oct
30)
When a script contains "redir => s:foo" but doesn't end redirection, a
following "redir" command gives an error for not being able to access s:foo.
(ZyX, 2011 Mar 27)
Problem with "syn sync gouphere". (Gustavo Niemeyer, 2011 Jan 27)
Loading autoload script even when usage is inside "if 0". (Christian Brabandt,
2010 Dec 18)
In the sandbox it's not allowed to do many things, but it's possible to change
or set variables. Add a way to prevent variables from being changed in the
sandbox? E.g.: ":protect g:restore_settings".
GTK: drawing a double-width combining character over single-width characters
doesn't look right. (Dominique Pelle, 2010 Aug 8)
GTK: tear-off menu does not work. (Kurt Sonnenmoser, 2010 Oct 25)
Win32: tear-off menu does not work when menu language is German. (Markus
Bossler, 2011 Mar 2) Fixed by 7.3.095?
Version of netbeans.c for use with MacVim. (Kazuki Sakamoto, 2010 Nov 18)
7.3.014 changed how backslash at end of line works, but still get a NUL when
there is one backslash. (Ray Frush, 2010 Nov 18) What does the original ex
do?
":find" completion does not escape space in directory name. (Isz, 2010 Nov 2)
Searching mixed with Visual mode doesn't redraw properly. (James Vega, 2010 Nov
22)
New esperanto spell file can't be processed. (Dominique Pelle, 2011 Jan 30)
- move compflags to separate growarray?
- instead of a regexp use a hashtable. Expand '?', '*", '+'. What would be
the maximum repeat for * and +?
"L'Italie" noted as a spell error at start of the sentence. (Dominique Pelle,
2011 Feb 27)
Copy/paste between Vim and Google chrome doesn't work well for multi-byte
characters. (Ben Haskell, 2010 Sep 17)
When putting text in the cut buffer (when exiting) and conversion doesn't work
Patch to support :undo absolute jump to file save number. (Christian Brabandt,
2010 Nov 5)
Patch to use 'foldnextmax' also for "marker" foldmethod. (Arnaud Lacombe, 2011
Jan 7)
When setting 'undofile' while the file is already loaded, but unchanged, try
to read the undo file. Requires computing a checksum of the text. (Andy
Wokula)
Bug with 'incsearch' going to wrong line. (Wolfram Kresse, 2009 Aug 17)
Only with "vim -u NONE".
Problem with editing file in binary mode. (Ingo Krabbe, 2009 Oct 8)
With 'wildmode' set to "longest:full,full" and pressing Tab once the first
entry in wildmenu is highlighted, that shouldn't happen. (Yuki Watanabe, 2011
Feb 12)
Display error when 'tabline' that includes a file name with double-width
characters. (2010 Aug 14, bootleq)
Problem with stop directory in findfile(). (Adam Simpkins, 2009 Aug 26)
Undo problem: line not removed as expected when using setline() from Insert
mode. (Israel Chauca, 2010 May 13, more in second msg)
Break undo when CTRL-R = changes the text? Or save more lines?
Patch for static code analysis errors in riscOS. (Dominique Pelle, 2010 Dec 3)
Patch for better #if 0 syntax highlighting for C code. (Ben Schmidt, 2011 Jan
20)
Change to C syntax folding to make it work much faster, but a bit less
reliable. (Lech Lorens, 2009 Nov 9) Enable with an option?
Most time is spent in in_id_list().
Slow combination of folding and PHP syntax highlighting. Script to reproduce
it. Caused by "syntax sync fromstart" in combination with patch 7.2.274.
(Christian Brabandt, 2010 May 27)
Generally, folding with 'foldmethod' set to "syntax" is slow. Do profiling to
find out why.
When completion inserts the first match, it may trigger the line to be folded.
Disable updating folds while completion is active? (Peter Odding, 2010 Jun 9)
Using ":call foo#d.f()" doesn't autoload the "foo.vim" file. Works OK for
echo, just not for ":call" and ":call call()". (Ted, 2011 Mar 17)
In command line window ":close" doesn't work properly. (Tony Mechelynck, 2009
Jun 1)
Cannot use getchar() inside :normal and using an expression mapping. Is this
supposed to work? (XyX, 2010 Sep 22)
When using an expression mapping with a multi-byte character each byte is
converted to a utf-8 character. (ZyX, 2011 Jan 4)
Patch for possible solution. (Yukihiro Nakadaira, 2011 Jan 5)
When a:base in 'completefunc' starts with a number it's passed as a number,
not a string. (Sean Ma) Need to add flag to call_func_retlist() to force a
string value.
There is no command line completion for ":lmap".
":e ~br<Tab>" does not complete to ":e /home/bram/". Would need to use
getpwent() to find all the matches.
Invalid read error in Farsi mode. (Dominique Pelle, 2009 Aug 2)
For running gvim on an USB stick: avoid the OLE registration. Use a command
line argument -noregister.
When using an expression in 'statusline' leading white space sometimes goes
missing (but not always). (ZyX, 2010 Nov 1)
When a mapping exists both for insert mode and lang-insert mode, the last one
doesn't work. (Tyru, 2010 May 6) Or is this intended?
Still a problem with ":make" in the wrong directory. Caused by ":bufdo".
When 'foldmethod' is "indent", using >> on a line just above a fold makes the
cursor line folded. (Evan Laforge, 2009 Oct 17)
When 'foldmethod' is "indent", adding an empty line below a fold and then
indented text, creates a new fold instead of joining it with the previous one.
(Evan Laforge, 2009 Oct 17)
Bug: When reloading a buffer changed outside of Vim, BufRead autocommands
are applied to the wrong buffer/window. (Ben Fritz, 2009 Apr 2, May 11)
Ignore window options when not in the right window?
Perhaps we need to use a hidden window for applying autocommands to a buffer
that doesn't have a window.
When "b" is a symlink to directory "a", resolve("b/") doesn't result in "a/".
(ZyX, 2011 Feb 12)
When using "ab foo bar" and mapping <Tab> to <Esc>, pressing <Tab> after foo
doesn't trigger the abbreviation like <Esc> would. (Ramana Kumar, 2009 Sep 6)
getbufvar() to get a window-local option value for a buffer that's not
displayed in a window should return the value that's stored for that buffer.
":he ctrl_u" can be auto-corrected to ":he ctrl-u".
There should be a way after an abbreviation has expanded to go back to what
was typed. CTRL-G h ? Would also undo last word or line break inserted
perhaps. And undo CTRL-W. CTRL-G l would redo.
Diff mode out of sync. (Gary Johnson, 2010 Aug 4)
Support a 'systemencoding' option (for Unix). It specifies the encoding of
file names. (Kikuchan, 2010 Oct 5). Useful on a latin1 or double-byte Asian
system when 'encoding' is "utf-8".
Win32: A --remote command that has a directory name starting with a ( doesn't
work, the backslash is removed, assuming that it escapes the (. (Valery
Kondakoff, 2009 May 13)
Win32 GUI: Changing manifest helps for dpi changes (Joe Castro, 2009 Mar 27)
Win32 GUI: last message from startup doesn't show up when there is an echoerr
command. (Cyril Slobin, 2009 Mar 13)
Win32: use different args for SearchPath()? (Yasuhiro Matsumoto, 2009 Jan 30)
Win32: completion of file name ":e c:\!test" results in ":e c:\\!test", which
does not work. (Nieko Maatjes, 2009 Jan 8, Ingo Karkat, 2009 Jan 22)
opening/closing window causes other window with 'winfixheight' to change
height. Also happens when there is another window in the frame, if it's not
very high. (Yegappan Lakshmanan, 2010 Jul 22, Michael Peeters, 2010 Jul 22)
Directory wrong in session file, caused by ":lcd" in BufEnter autocommand.
(Felix Kater, 2009 Mar 3)
Session file generates error upon loading, cause bu --remote-silent-tab.
(7tommm (ytommm) 2010 Nov 24)
Using ~ works OK on 'a' with composing char, but not on 0x0418 with composing
char 0x0301. (Tony Mechelynck, 2009 Mar 4)
A function on a dictionary is not profiled. (Zyx, 2010 Dec 25)
Inconsistent: starting with $LANG set to es_ES.utf-8 gives Spanish
messages, even though locale is not supported. But ":lang messages
es_ES.utf-8" gives an error and doesn't switch messages. (Dominique Pelle,
2009 Jan 26)
When $HOME contains special characters, such as a comma, escape them when used
in an option. (Michael Hordijk, 2009 May 5)
Turn "esc" argument of expand_env_esc() into string of chars to be escaped.
Should make 'ignorecase' global-local, so that it makes sense setting it from
a modeline.
Add cscope target to Makefile. (Tony Mechelynck, 2009 Jun 18, replies by
Sergey Khorev)
Consider making YankRing or something else that keeps a list of yanked text
part of standard Vim. The "1 to "9 registers are not sufficient.
netrw: dragging status line causes selection of entry. Should check row
number to be below last visible line.
After doing "su" $HOME can be the old user's home, thus ~root/file is not
correct. Don't use it in the swap file.
Completion for ":buf" doesn't work properly on Win32 when 'shellslash' is off.
(Henrik Ohman, 2009, Jan 29)
shellescape() depends on 'shellshash' for quoting. That doesn't work when
'shellslash' is set but using cmd.exe. (Ben Fritz)
Use a different option or let it depend on whether 'shell' looks like a
unix-like shell?
Allow patches to add something to version.c, like with an official patch, so
that :version output shows which patches have been applied.
Bug: in Ex mode (after "Q") backslash before line break, when yanked into a
register and executed, results in <Nul>: instead of line break.
(Konrad Schwarz, 2010 Apr 16)
Have a look at patch for utf-8 line breaking. (Yongwei Wu, 2008 Mar 1, Mar 23)
Now at: http://vimgadgets.sourceforge.net/liblinebreak/
Greek sigma character should be lower cased depending on the context. Can we
make this work? (Dominique Pelle, 2009 Sep 24)
When changing 'encoding' convert all the swap file names, so that we can
still delete them. Also convert all buffer file names?
"gqip" in Insert mode has an off-by-one error, causing it to reflow text.
(Raul Coronado, 2009 Nov 2)
Update src/testdir/main.aap.
"vim -c 'sniff connect'"' hangs Vim. (Dominique Pelle, 2008 Dec 7)
Something wrong with session that has "cd" commands and "badd", in such a way
that Vim doesn't find the edited file in the buffer list, causing the
ATTENTION message? (Tony Mechelynck, 2008 Dec 1)
Also: swap files are in ~/tmp/ One has relative file name ".mozilla/...".
Add v:motion_force. (Kana Natsuno, 2008 Dec 6)
Runtime files for Clojure. (Toralf Wittner, 2008 Jun 25)
MS-Windows: editing the first, empty buffer, 'ffs' set to "unix,dos", ":enew"
doesn't set 'ff' to "unix". (Ben Fritz, 2008 Dec 5) Reusing the old buffer
probably causes this.
'scrollbind' is not respected when deleting lines or undo. (Milan Vancura,
2009 Jan 16)
Document that default font in Athena can be set with resources:
XtDefaultFont: "9x15"
XtDefaultFontSet: "9x15"
(Richard Sherman, 2009 Apr 12)
Having "Syntax" in 'eventignore' for :bufdo may cause problems, e.g. for
":bufdo e" when buffers are open in windows. ex_listdo(eap) could set the
option only for when jumping to another buffer, not when the command argument
is executed.
":pedit %" with a BufReadPre autocommand causes the cursor to move to the
first line. (Ingo Karkat, 2008 Jul 1) Ian Kelling is working on this.
Wildmenu not deleted: "gvim -u NONE", ":set nocp wildmenu cmdheight=3
laststatus=2", CTRL-D CTRL-H CTRL-H CTRL-H. (A.Politz, 2008 April 1)
Works OK with Vim in an xterm.
Cursor line moves in other window when using CTRL-W J that doesn't change
anything. (Dasn, 2009 Apr 7)
On Unix "glob('does not exist~')" returns the string. Without the "~" it
doesn't. (John Little, 2008 Nov 9)
Shell expansion returns unexpanded string?
Don't use shell when "~" is not at the start?
":unlet $VAR" doesn't work.
When using ":e ++enc=foo file" and the file is already loaded with
'fileencoding' set to "bar", then do_ecmd() uses that buffer, even though the
fileencoding differs. Reload the buffer in this situation? Need to check for
the buffer to be unmodified.
Unfinished patch by Ian Kelling, 2008 Jul 11. Followup Jul 14, need to have
another look at it.
Patch for c.vim and cpp.vim syntax files. (Chung-chieh Shan, 2008 Nov 26)
c.vim: XXX in a comment is colored yellow, but not when it's after "#if 0".
(Ilya Dogolazky, 2009 Aug 7)
You can type ":w ++bad=x fname", but the ++bad argument is ignored. Give an
error message? Or is this easy to implement? (Nathan Stratton Treadway, 2008
Aug 20) This is in ucs2bytes(), search for 0xBF. Using the ++bad argument is
at the other match for 0xBF.
Fix for matchparen HL doesn't work. beep.
When adding "-complete=file" to a user command this also changes how the
argument is processed for <f-args>. (Ivan Tishchenko, 2008 Aug 19)
Win32: associating a type with Vim doesn't take care of space after a
backslash? (Robert Vibrant, 2008 Jun 5)
Win32: bold font doesn't work when 'guifontwide' has been set. (Yue Wu, 2010
Aug 23)
When 'rightleft' is set, cursorcolumn isn't highlighted after the end of a
line. It's also wrong in folds. (Dominique Pelle, 2010 Aug 21)
Using an insert mode expression mapping, cursor is not in the expected
position. (ZyX, 2010 Aug 29)
After using <Tab> for command line completion after ":ta blah" and getting E33
(no tags file), further editing the command to e.g., ":echo 'blah'"', the
command is not executed. Fix by Ian Kelling?
":help s/~" jumps to *s/\~*, while ":help s/\~" doesn't find anything. (Tim
Chase) Fix by Ian Kelling, 2008 Jul 14.
Use "\U12345678" for 32 bit Unicode characters? (Tony Mechelynck, 2009
Apr 6) Or use "\u(123456)", similar to Perl.
When mapping : to ; and ; to :, @; doesn't work like @: and @: doesn't work
either. Matt Wozniski: nv_at() calls do_execreg() which uses
put_in_typebuf(). Char mapped twice?
Despite adding save_subexpr() this still doesn't work properly:
Regexp: matchlist('12a4aaa', '^\(.\{-}\)\(\%5c\@<=a\+\)\(.\+\)\?')
Returns ['12a4', 'aaa', '4aaa'], should be ['12a4', 'aaa', '']
Backreference not cleared when retrying after \@<= fails?
(Brett Stahlman, 2008 March 8)
Problem with remote_send(). (Charles Campbell, 2008 Aug 12)
ftplugin for help file should set 'isk' to help file value.
Win32: remote editing fails when the current directory name contains "[".
(Ivan Tishchenko, Liu Yubao) Suggested patch by Chris Lubinski: Avoid
escaping characters where the backslash is not removed later. Asked Chris for
an alternate solution, also for src/ex_getln.c.
This also fails when the file or directory name contains "%". (Thoml, 2008
July 7)
The str2special() function doesn't handle multi-byte characters properly.
Patch from Vladimir Vichniakov, 2007 Apr 24.
Should clean up the whole function. Also allow modifiers like <S-Char-32>?
find_special_key() also has this problem.
Problem with 'langmap' being used on the rhs of a mapping. (Nikolai Weibull,
2008 May 14)
Problem with CTRL-F. (Charles Campbell, 2008 March 21)
Only happens with "gvim -geometry "160x26+4+27" -u NONE -U NONE prop.c".
'lines' is 54. (2008 March 27)
Problem with pointer wrapping around in getvcol(). (Wolfgang Kroworsch, 2008
Oct 19) Check for "col" being "MAXCOL" separately?
Unexpectedly inserting a double quote. (Anton Woellert, 2008 Mar 23)
Windows 98: pasting from the clipboard with text from another application has
a trailing NUL. (Joachim Hofmann) Perhaps the length specified for CF_TEXT
isn't right?
When a register contains illegal bytes, writing viminfo in utf-8 and reading
it back doesn't result in utf-8. (Devin Bayer)
Command line completion: Scanning for tags doesn't check for typed key now and
then? Hangs for about 5 seconds. Appears to be caused by finding include
files with "foo/**" in 'path'. (Kalisiak, 2006 July 15)
Additional info: When using the |wildcards| globing, vim hangs
indefinitely on lots of directories. The |file-searching| globing, like in
":set path=/**" does not hang as often as with globing with |wildcards|, like
in ":1find /**/file". This is for a files that unix "find" can find very
quick. Merging the 2 kinds of globing might make this an easier fix. (Ian
Kelling, 2008 July 4)
When the file name has parenthesis, e.g., "foo (bar).txt", ":!ls '%'"' has the
parenthesis escaped but not the space. That's inconsistent. Either escape
neither or both. No escaping might be best, because it doesn't depend on
particularities of the shell. (Zvi Har'El, 2007 Nov 10) (Teemu Likonen, 2008
Jun 3)
However, for backwards compatibility escaping might be necessary. Check if
the user put quotes around the expanded item?
Error E324 can be given when a cron script has wiped out our temp directory.
Give a clear error message about this (and tell them not to wipe out /tmp).
Color for cUserLabel should differ from case label, so that a mistake in a
switch list is noticed:
switch (i)
{
case 1:
foobar:
}
Look at http://www.gtk-server.org/ . It has a Vim script implementation.
Netbeans problem. Use "nc -l 127.0.0.1 55555" for the server, then run gvim
with "gvim -nb:localhost:55555:foo". From nc do: '1:editFile!0 "foo"'. Then
go to Insert mode and add a few lines. Then backspacing every other time
moves the cursor instead of deleting. (Chris Kaiser, 2007 Sep 25)
Patch to use Modern UI 2.0 for the Nsis installer. (Guopeng Wen, 2010 Jul 30)
8 Windows install with NSIS: make it possible to do a silent install, see
http://nsis.sourceforge.net/Docs/Chapter4.html#4.12
Version from Guopeng Wen that does this (2010 Dec 27)
Changes for Win32 makefile. (Mike Williams, 2007 Jan 22, Alexei Alexandrov,
2007 Feb 8)
Patch for Win32 clipboard under Cygwin. (Frodak Baksik, Feb 15)
Sutcliffe says it works well.
Update 2007 May 22 for Vim 7.1
Update 2008 Dec 2008 for Vim 7.2.xx (Sharonov)
Win32: Can't complete shell command names. Why is setting xp_context in
set_one_cmd_context() inside #ifndef BACKSLASH_IN_FILENAME?
Win32: Patch for convert_filterW(). (Taro Muraoka, 2007 Mar 2)
Win32: Patch for cscope external command. (Mike Williams, 2007 Aug 7)
Win32: XPM support only works with path without spaces. Patch by Mathias
Michaelis, 2006 Jun 9. Another patch for more path names, 2006 May 31.
New version: http://members.tcnet.ch/michaelis/vim/patches.zip also for other
patches by Mathias, see mail Feb 22)
Win32: compiling with normal features and OLE fails. Patch by Mathias
Michaelis, 2006 Jun 4.
Win32: echo doesn't work for gvim.exe.mnf. Use inline file. Patch by Mathias
Michaelis. http://groups.yahoo.com/group/vimdev/message/43765
Patch that includes this and does more by George Reilly, 2007 Feb 12
Win16: include patches to make Win16 version work. (Vince Negri, 2006 May 22)
Win32: after "[I" showing matches, scroll wheel messes up screen. (Tsakiridis,
2007 Feb 18)
Patch by Alex Dobrynin, 2007 Jun 3. Also fixes other scroll wheel problems.
Win32: using CTRL-S in Insert mode doesn't remove the "+" from the tab pages
label. (Tsakiridis, 2007 Feb 18) Patch from Ian Kelling, 2008 Aug 6.
Win32: using "gvim --remote-tab-silent fname" sometimes gives an empty screen
with the more prompt. Caused by setting the guitablabel? (Thomas Michael
Engelke, 2007 Dec 20 - 2008 Jan 17)
Win64: Seek error in swap file for a very big file (3 Gbyte). Check storing
pointer in long and seek offset in 64 bit var.
Win32: patch for fullscreen mode. (Liushaolin, 2008 April 17)
Win32: When 'shell' is cmd.exe this command fails:
echo system('"'c:/path/echo.exe" "foo bar"')
Should we set the default for 'shellxquote' to a double quote, when 'shell'
contains "cmd" in the tail? (Benjamin Fritz, 2008 Oct 13)
Also set 'shellcmdflag' to include /s.
Win32: When there is 4 Gbyte of memory mch_avail_mem() doesn't work properly.
Unfinished patch by Jelle Geerts, 2008 Aug 24.
Let mch_avail_mem() return Kbyte instead?
Win32: When 'shell' is bash shellescape() doesn't always do the right thing.
Depends on 'shellslash', 'shellquote' and 'shellxquote', but shellescape()
only takes 'shellslash' into account.
Pressing the 'pastetoggle' key doesn't update the statusline. (Jan Christoph
Ebersbach, 2008 Feb 1)
Menu item that does "xxd -r" doesn't work when 'fileencoding' is utf-16.
Check for this and use iconv? (Edward L. Fox, 2007 Sep 12)
Does the conversion in the other direction work when 'filenecodings' is set
properly?
Cursor displayed in the wrong position when using 'numberwidth'. (James Vega,
2007 Jun 21)
When $VAR contains a backslash expand('$VAR') removes it. (Teemu Likonen, 2008
Jun 18)
If the variable "g:x#y#z" exists completion after ":echo g:x#" doesn't work.
Feature request: Command to go to previous tab, like what CTRL-W p does for
windows. (Adam George)
When using input() in a loop and then ":echo" the display column isn't right.
(Benjamin Fritz, 2008 Aug 28) Patch by Ben Schmidt, 2008 Sep 2.
F1 - F4 in an xterm produce a different escape sequence when used with a
modifier key. Need to catch three different sequences. Use K_ZF1, like
K_ZHOME? (Dickey, 2007 Dec 2)
UTF-8: mapping a multi-byte key where the second byte is 0x80 doesn't appear
to work. (Tony Mechelynck, 2007 March 2)
In debug mode, using CTRL-R = to evaluate a function causes stepping through
the function. (Hari Krishna Dara, 2006 Jun 28)
C++ indenting wrong with "=". (James Kanze, 2007 Jan 26)
":lockvar" should use copyID to avoid endless loop.
When using --remote-silent and the file name matches 'wildignore' get an E479
error. without --remote-silent it works fine. (Ben Fritz, 2008 Jun 20)
Gvim: dialog for closing Vim should check if Vim is busy writing a file. Then
use a different dialog: "busy saving, really quit? yes / no".
Check other interfaces for changing curbuf in a wrong way. Patch like for
if_ruby.c.
":helpgrep" should use the directory from 'helpfile'.
Patch to dynamically load Python on Solaris. (Danek Duvall, 2009 Feb 16)
Needs more work.
Python3 interface doesn't handle utf-8 correctly? (Nov 2010, lilydjwg)
The need_fileinfo flag is messy. Instead make the message right away and put
it in keep msg?
Mac: Using gvim: netrw window disappears. (Nick Lo, 2006 Jun 21)
Mac: OS/X 10.4 with Python 2.5 installed: configure finds an extra argument
that breaks the build. (Brian Victor, 2008 Sep 1)
Add an option to specify the character to use when a double-width character is
moved to the next line. Default '>', set to a space to blank it out. Check
that char is single width when it's set (compare with 'listchars').
The generated vim.bat can avoid the loop for NT. (Carl Zmola, 2006 Sep 3)
Session file creation: 'autochdir' causes trouble. Keep it off until after
loading all files.
Win32: When 'autochdir' is on and 'encoding' is changed, files on the command
line are opened again, but from the wrong directory. Apply 'autochdir' only
after starting up?
When showing a diff between a non-existent file and an existing one, with the
cursor in the empty buffer, the other buffer only shows the last line. Change
the "insert" into a change from one line to many? (Yakov Lerner, 2008 May 27)
Add autocommand for when a tabpage is being closed. Also for when a tab page
has been created.
Using ":make" blocks Vim. Allow running one make in the background (if the
shell supports it), catch errors in a file and update the error list on the
fly. A bit like "!make > file&" and repeating ":cf file". ":bgmake",
background make. ":bgcancel" interrupts it.
A.Politz may work on this.
These two abbreviations don't give the same result:
let asdfasdf = "xyz\<Left>"
cabbr XXX <C-R>=asdfasdf<CR>
cabbr YYY xyz<Left>
Michael Dietrich: maximized gvim sometimes displays output of external command
partly. (2006 Dec 7)
In FileChangedShell command it's no longer allowed to switch to another
buffer. But the changed buffer may differ from the current buffer, how to
reload it then?
New syntax files for fstab and resolv from Radu Dineiu, David Necas did
previous version.
For Aap: include a config.arg.example file with hints how to use config.arg.
Command line completion when 'cmdheight' is maximum and 'wildmenu' is set,
only one buffer line displayed, causes display errors.
Completing with 'wildmenu' and using <Up> and <Down> to move through directory
tree stops unexpectedly when using ":cd " and entering a directory that
doesn't contain other directories.
Setting 'background' resets the Normal background color:
highlight Normal ctermbg=DarkGray
set background=dark
This is undesired, 'background' is supposed to tell Vim what the background
color is, not reset it.
Linux distributions:
- Suggest compiling xterm with --enable-tcap-query, so that nr of colors is
known to Vim. 88 colors instead of 16 works better. See ":help
xfree-xterm".
- Suggest including bare "vi" and "vim" with X11, syntax, etc.
Completion menu: For a wrapping line, completing a long file name, only the
start of the path is shown in the menu. Should move the menu to the right to
show more text of the completions. Shorten the items that don't fit in the
middle?
When running inside screen it's possible to kill the X server and restart it
(using pty's the program can keep on running). Vim dies because it loses the
connection to the X server. Can Vim simply quit using the X server instead of
dying? Also relevant when running in a console.
Accessing file#var in a function should not need the g: prepended.
When exiting detects a modified buffer, instead of opening the buffer in the
current tab, use an existing tab, if possible. Like finding a window where
Write "making vim work better" for the docs (mostly pointers): *nice*
- sourcing $VIMRUNTIME/vimrc_example.vim
- setting 'mouse' to "a"
- getting colors in xterm
- compiling Vim with X11, GUI, etc.
Problem with ":call" and dictionary function. Hari Krishna Dara, Charles
Campbell 2006 Jul 06.
Syntax HL error caused by "containedin". (Peter Hodge, 2006 Oct 6)
A custom completion function in a ":command" cannot be a Funcref. (Andy
Wokula, 2007 Aug 25)
Problem with using :redir in user command completion function? (Hari Krishna
Dara, 2006 June 21)
Another resizing problem when setting 'columns' and 'lines' to a very large
number. (Tony Mechelynck, 2007 Feb 6)
After starting Vim, using '0 to jump somewhere in a file, ":sp" doesn't center
the cursor line. It works OK after some other commands.
Win32: Is it possible to have both postscript and Win32 printing?
Does multi-byte printing with ":hardcopy" work? Add remark in documentation
about this.
Check: Running Vim in a console and still having connect to the X server for
copy/paste: is stopping the X server handled gracefully? Should catch the X
error and stop using the connection to the server.
Problem with 'cdpath' on MS-Windows when a directory is equal to $HOME. (2006
Jul 26, Gary Johnson)
Using UTF-8 character with ":command" does not work properly. (Matt Wozniski,
2008 Sep 29)
In the Netbeans interface add a "vimeval" function, so that the other side can
check the result of has("patch13").
Cursor line at bottom of window instead of halfway after saving view and
restoring. Only with 'nowrap'. (Robert Webb, 2008 Aug 25)
Netrw has trouble executing autocommands only for a directory. Add <isdir>
and <notisdir> to autocommand patterns? Also <isfile>?
Add command modifier that skips wildcard expansion, so that you don't need to
put backslashes before special chars, only for white space.
Syntax HL: open two windows on the same C code, delete a ")" in one window,
resulting in highlighted "{" in that window, not in the other.
In mswin.vim: Instead of mapping <C-V> for Insert mode in a complicated way,
can it be done like ":imap <C-V> <MiddleMouse>" without negative side effects?
GTK: when the Tab pages bar appears or disappears while the window is
maximized the window is no longer maximized. Patch that has some idea but
doesn't work from Geoffrey Antos, 2008 May 5.
Also: the window may no longer fit on the screen, thus the command line is not
visible.
When right after "vim file", "M" then CTRL-W v the windows are scrolled
differently and unexpectedly. Caused by patch 7.2.398?
The magic clipboard format "VimClipboard2" appears in several places. Should
be only one.
"vim -C" often has 'nocompatible', because it's set somewhere in a startup
script. Do "set compatible" after startup?
It's difficult to debug numbered functions (function in a Dictionary). Print
the function name before resolving it to a number?
let d = {}
fun! d.foo()
echo "here"
endfun
call d.foo(9)
Add a mark for the other end of the Visual area (VIsual pos). '< and '> are
only set after Visual moded is ended.
Also add a variable for the Visual mode. So that this mode and '< '> can be
used to set what "gv" selects. (Ben Schmidt)
Win32: When running ":make" and 'encoding' differs from the system locale, the
output should be converted. Esp. when 'encoding' is "utf-8". (Yongwei Wu)
Should we use 'termencoding' for this?
Win32, NTFS: When editing a specific infostream directly and 'backupcopy' is
"auto" should detect this situation and work like 'backupcopy' is "yes". File
name is something like "c:\path\foo.txt:bar", includes a colon. (Alex
Jakushev, 2008 Feb 1)
Small problem displaying diff filler line when opening windows with a script.
(David Luyer, 2007 Mar 1 ~/Mail/oldmail/mool/in.15872 )
Is it allowed that 'backupext' is empty? Problems when backup is in same dir
as original file? If it's OK don't compare with 'patchmode'. (Thierry Closen)
Patch for supporting count before CR in quickfix window. (AOYAMA Shotaro, 2007
Jan 1)
Patch for adding ":lscscope". (Navdeep Parhar, 2007 Apr 26; update 2008 Apr
23)
":mkview" isn't called with the right buffer argument. Happens when using
tabs and the autocommand "autocmd BufWinLeave * mkview". (James Vega, 2007
Jun 18)
xterm should be able to pass focus changes to Vim, so that Vim can check for
buffers that changed. Perhaps in misc.c, function selectwindow().
Xterm 224 supports it!
When completing from another file that uses a different encoding completion
text has the wrong encoding. E.g., when 'encoding' is utf-8 and file is
latin1. Example from Gombault Damien, 2007 Mar 24.
Is it possible to use "foo#var" instead of "g:foo#var" inside a function?
Syntax HL: When using "nextgroup" and the group has an empty match, there is
no search at that position for another match. (Lukas Mai, 2008 April 11)
In gvim the backspace key produces a backspace character, but on Linux the
VERASE key is Delete. Set VERASE to Backspace? (patch by Stephane Chazelas,
2007 Oct 16)
When entering a C /* comment, after typing <Enter> for 70 times the indent
disappears. (Vincent Beffara, 2008 Jul 3)
TermResponse autocommand isn't always triggered when using vimdiff. (Aron
Griffis, 2007 Sep 19)
Create a gvimtutor.1 file and change Makefiles to install it.
When 'encoding' is utf-8 typing text at the end of the line causes previously
typed characters to be redrawn. Caused by patch 7.1.329. (Tyler Spivey, 2008
Sep 3, 11)
When Vim in an xterm owns the selection and the user does ":shell" Vim doesn't
respond to selection requests. Invoking XtDisownSelection() before executing
the shell doesn't help. Would require forking and doing a message loop, like
what happens for the GUI.
X11: Putting more than about 262040 characters of text on the clipboard and
pasting it in another Vim doesn't work. (Dominique Pelle, 2008 Aug 21-23)
clip_x11_request_selection_cb() is called with zero value and length.
Also: Get an error message from free() in the process that owns the selection.
Seems to happen when the selection is requested the second time, but before
clip_x11_convert_selection_cb() is invoked, thus in X library code.
":vimgrep" does not recognize a recursive symlink. Is it possible to detect
this, at least for Unix (using device/inode)?
When switching between windows the cursor is often put in the middle.
Remember the relative position and restore that, just like lnum and col are
restored. (Luc St-Louis)
At next release:
- Rename src/Makefile and create a new one like toplevel Makefile that
creates auto/config.mk when it's not there? (Ben Schmidt, 2011 Feb 11)
More patches:
- Another patch for Javascript indenting. (Hari Kumar, 2010 Jul 11)
Needs a few tests.
- Add 'cscopeignorecase' option. (Liang Wenzhi, 2006 Sept 3)
- Argument for feedkeys() to prepend to typeahead (Yakov Lerner, 2006 Oct
21)
- Load intl.dll too, not only libintl.dll. (Mike Williams, 2006 May 9, docs
patch May 10)
- Extra argument to strtrans() to translate special keys to their name (Eric
Arnold, 2006 May 22)
- 'threglookexp' option: only match with first word in thesaurus file.
(Jakson A. Aquino, 2006 Jun 14)
- Mac: indicate whether a buffer was modified. (Nicolas Weber, 2006 Jun 30)
- Allow negative 'nrwidth' for left aligning. (Nathan Laredo, 2006 Aug 16)
- ml_append_string(): efficiently append to an existing line. (Brad
Beveridge, 2006 Aug 26) Use in some situations, e.g., when pasting a
character at a time?
- recognize hex numbers better. (Mark Manning, 2006 Sep 13)
- Add <AbbrExpand> key, to expand an abbreviation in a mapping. (Kana
Natsuno, 2008 Jul 17)
- Add 'wspara' option, also accept blank lines like empty lines for "{" and
"}". (Mark Lundquist, 2008 Jul 18)
- Patch to add CTRL-T to delete part of a path on cmdline. (Adek, 2008 Jul
21)
- Instead of creating a copy of the tutor in all the shell scripts, do it in
vimtutor.vim. (Jan Minar, 2008 Jul 20)
- When fsync() fails there is no hint about what went wrong. Patch by Ben
Schmidt, 2008 Jul 22.
- testdir/Make_dos_sh.mak for running tests with MingW. (Bill Mccarthy, 2008
Sep 13)
- Patch for adding "space" item in 'listchars'. (Jérémie Roquet, 2009 Oct 29,
Docs patch Oct 30)
- Replace ccomplete.vim by cppcomplete.vim from www.vim.org? script 1520 by
Vissale Neang. (Martin Stubenschrott) Asked Vissale to make the scripts
more friendly for the Vim distribution.
New version received 2008 Jan 6.
No maintenance in two years...
- Patch to access screen under Python. (Marko Mahni, 2010 Jul 18)
- Patch to open dropped files in new tabs. (Michael Trim, 2010 Aug 3)
Awaiting updated patches:
9 Mac unicode patch (Da Woon Jung, Eckehard Berns):
8 Add patch from Muraoka Taro (Mar 16) to support input method on Mac?
New patch 2004 Jun 16
- selecting proportional font breaks display
- UTF-8 text causes display problems. Font replacement causes this.
- Command-key mappings do not work. (Alan Schmitt)
- With 'nopaste' pasting is wrong, with 'paste' Command-V doesn't work.
(Alan Schmitt)
- remove 'macatsui' option when this has been fixed.
- when 'macatsui' is off should we always convert to "macroman" and ignore
'termencoding'?
9 HTML indenting can be slow. Caused by using searchpair(). Can search()
be used instead? A.Politz is looking into a solution.
8 Win32: Add minidump generation. (George Reilly, 2006 Apr 24)
8 Add ":n" to fnamemodify(): normalize path, remove "../" when possible.
Aric Blumer has a patch for this. He will update the patch for 6.3.
7 Completion of network shares, patch by Yasuhiro Matsumoto.
Update 2004 Sep 6.
How does this work? Missing comments.
- Patch for 'breakindent' option: repeat indent for wrapped line. (Vaclav
Smilauer, 2004 Sep 13, fix Oct 31, update 2007 May 30)
Version for latest MacVim: Tobia Conforto, 2009 Nov 23
8 Add a few more command names to the menus. Patch from Jiri Brezina
(28 feb 2002). Will mess the translations...
7 ATTENTION dialog choices are more logical when "Delete it' appears
before "Quit". Patch by Robert Webb, 2004 May 3.
- Include flipcase patch: ~/vim/patches/wall.flipcase2 ? Make it work
for multi-byte characters.
- Win32: add options to print dialog. Patch from Vipin Aravind.
- Patch to add highlighting for whitespace. (Tom Schumm, 2003 Jul 5)
use the patch that keeps using HLF 8 if HLF WS has not
Vi incompatibility:
- Try new POSIX tests, made after my comments. (Geoff Clare, 2005 April 7)
Version 1.5 is in ~/src/posix/1.5. (Lynne Canal)
8 With undo/redo only marks in the changed lines should be changed. Other
marks should be kept. Vi keeps each mark at the same text, even when it
is deleted or restored. (Webb)
Also: A mark is lost after: make change, undo, redo and undo.
Example: "{d''"' then "u" then "d''"': deletes an extra line, because the ''
position is one line down. (Veselinovic)
8 When stdin is not a tty, and Vim reads commands from it, an error should
make Vim exit.
7 Unix Vim (not gvim): Typing CTRL-C in Ex mode should finish the line
(currently you can continue typing, but it's truncated later anyway).
Requires a way to make CTRL-C interrupt select() when in cooked input.
8 When loading a file in the .exrc, Vi loads the argument anyway. Vim skips
loading the argument if there is a file already. When no file argument
given, Vi starts with an empty buffer, Vim keeps the loaded file. (Bearded)
6 In Insert mode, when using <BS> or <Del>, don't wipe out the text, but
only move back the cursor. Behaves like '$' in 'cpoptions'. Use a flag
in 'cpoptions' to switch this on/off.
8 When editing a file which is a symbolic link, and then opening another
symbolic link on the same file, Vim uses the name of the first one.
Adjust the file name in the buffer to the last one used? Use several file
names in one buffer???
Also: When first editing file "test", which is symlink to "test2", and
then editing "test2", you end up editing buffer "test" again. It's not
logical that the name that was first used sticks with the buffer.
7 The ":undo" command works differently in Ex mode. Edit a file, make some
changes, "Q", "undo" and _all_ changes are undone, like the ":visual"
command was one command.
On the other hand, an ":undo" command in an Ex script only undoes the last
change (e.g., use two :append commands, then :undo).
7 The ":map" command output overwrites the command. Perhaps it should keep
the ":map" when it's used without arguments?
7 CTRL-L is not the end of a section? It is for Posix! Make it an option.
7 Implement 'prompt' option. Init to off when stdin is not a tty.
7 CTRL-T in Insert mode inserts 'shiftwidth' of spaces at the cursor. Add a
flag in 'cpoptions' for this.
7 Add a way to send an email for a crashed edit session. Create a file when
making changes (containing name of the swap file), delete it when writing
the file. Supply a program that can check for crashed sessions (either
all, for a system startup, or for one user, for in a .login file).
7 Vi doesn't do autoindenting when input is not from a tty (in Ex mode).
7 "z3<CR>" should still use the whole window, but only redisplay 3 lines.
7 ":tag xx" should move the cursor to the first non-blank. Or should it go
to the match with the tag? Option?
7 Implement 'autoprint'/'ap' option.
7 Add flag in 'cpoptions' that makes <BS> after a count work like <Del>
(Sayre).
7 Add flag in 'cpoptions' that makes operator (yank, filter) not move the
cursor, at least when cancelled. (default Vi compatible).
7 This Vi-trick doesn't work: "Q" to go to Ex mode, then "g/pattern/visual".
In Vi you can edit in visual mode, and when doing "Q" you jump to the next
match. Nvi can do it too.
7 Support '\' for line continuation in Ex mode for these commands: (Luebking)
g/./a\ g/pattern1/ s/pattern2/rep1\\
line 1\ line 2\\
line 2\ line 3\\
. line4/
6 ":e /tmp/$tty" doesn't work. ":e $uid" does. Is $tty not set because of
the way the shell is started?
6 Vi compatibility (optional): make "ia<CR><ESC>10." do the same strange
thing. (only repeat insert for the first line).
Athena GUI:
9 The first event for any button in the menu or toolbar appears to get lost.
The second click on a menu does work.
9 When dragging the scrollbar thumb very fast, focus is only obtained in
the scrollbar itself. And the thumb is no longer updated when moving
through files.
7 The file selector is not resizable. With a big font it is difficult to
read long file names. (Schroeder)
4 Re-write the widget attachments and code so that we will not have to go
through and calculate the absolute position of every widget every time the
window is refreshed/changes size. This will help the "flashing-widgets"
problem during a refresh.
5 When starting gvim with all the default colors and then typing
":hi Menu guibg=cyan", the menus change color but the background of the
pullright pixmap doesn't change colors.
If you type ":hi Menu guibg=cyan font=anyfont", then the pixmap changes
colors as it should.
Allocating a new pixmap and setting the resource doesn't change the
pullright pixmap's colors. Why? Possible Athena bug?
Motif GUI:
- gui_mch_browsedir() is missing, browsedir() doesn't work nicely.
7 Use XmStringCreateLocalized() instead of XmStringCreateSimple()?
David Harrison says it's OK (it exists in Motif 1.2).
8 Lesstif: When deleting a menu that's torn off, the torn off menu becomes
very small instead of disappearing. When closing it, Vim crashes.
(Phillipps)
GUI:
9 On Solaris, creating the popup menu causes the right mouse button no
longer to work for extending the selection. (Halevy)
9 When running an external program, it can't always be killed with CTRL-C.
e.g., on Solaris 5.5, when using "K" (Keech). Other 'guipty' problems on
Solaris 2.6. (Marley)
9 On Solaris: Using a "-geometry" argument, bigger than the window where Vim
is started from, causes empty lines below the cmdline. (raf)
8 X11 GUI: When menu is disabled by excluding 'm' from 'guioptions', ALT key
should not be used to trigger a menu (like the Win32 version).
8 When setting 'langmenu', it should be effective immediately. Store both
the English and the translated text in the menu structure. Re-generate
the translation when 'langmenu' has changed.
8 Basic flaw in the GUI code: NextScreen is updated before calling
gui_write(), but the GUI code relies on NextScreen to represent the state
of where it is processing the output.
Need better separation of Vim core and GUI code.
8 When fontset support is enabled, setting 'guifont' to a single font
doesn't work.
8 Menu priority for sub-menus for: Amiga, BeOS.
8 When translating menus ignore the part after the Tab, the shortcut. So
that the same menu item with a different shortcut (e.g., for the Mac) are
still translated.
8 Add menu separators for Amiga, RISCOS.
8 Add way to specify the file filter for the browse dialog. At least for
browse().
8 Add dialog for search/replace to other GUIs? Tk has something for this,
use that code? Or use console dialog.
8 When selecting a font with the font dialog and the font is invalid, the
error message disappears too quick.
7 More features in the find/replace dialog:
- regexp on/off
- search in selection/buffer/all buffers/directory
when all buffers/directory is used:
- filter for file name
when directory is used:
- subdirectory on/off
- top directory browser
8 gui_check_colors() is not called at the right moment. Do it much later,
to avoid problems.
8 gui_update_cursor() is called for a cursor shape change, even when there
are mappings to be processed. Only do something when going to wait for
input. Or maybe every 100 ms?
8 X11: When the window size is reduced to fit on screen, there are blank
lines below the text and bottom scrollbar. "gvim -geometry 80x78+0+0".
When the "+0+0" is omitted it works.
8 When starting an external command, and 'guipty' set, BS and DEL are mixed
up. Set erase character somehow?
8 A dead circumflex followed by a space should give the '^' character
(Rommel). Look how xterm does this.
Also: Bednar has some code for dead key handling.
Also: Nedit 5.0.2 with USE_XMIM does it right. (Gaya)
8 The compose key doesn't work properly (Cepas). Both for Win32 and X11.
7 The cursor in an inactive window should be hollow. Currently it's not
visible.
7 GUI on Solaris 2.5.1, using /usr/dt/..: When gvim starts, cursor is
hollow, after window lowered/raised it's OK. (Godfrey)
7 When starting GUI with ":gui", and window is made smaller because it
doesn't fit on the screen, there is an extra redraw.
8 When setting font with .Xdefaults, there is an extra empty line at the
bottom, which disappears when using ":set guifont=<Tab>". (Chadzelek)
8 When font shape changes, but not the size, doing ":set font=" does not
redraw the screen with the new font. Also for Win32.
When the size changes, on Solaris 2.5 there isn't a redraw for the
remaining part of the window (Phillipps).
- Flashes really badly in certain cases when running remotely from a Sun.
4 Re-write the code so that the highlighting isn't changed multiple times
when doing a ":hi clear". The color changes happen three or more times
currently. This is very obvious on a 66Mhz 486.
MSDOS/DJGPP:
9 Pressing CTRL-C often crashes the console Vim runs in. (Ken Liao)
When 'bioskey' isn't set it doesn't happen. Could be a problem with the
BIOS emulation of the console. Version 5.6 already had this problem.
8 DJGPP: "cd c:" can take us to a directory that no longer exists.
change_drive() doesn't check this. How to check for this error?
9 The 16 bit version runs out of memory very quickly. Should find unused
code and reduce static data. Resetting 'writebackup' helps to be able to
write a file.
9 Crash when running on Windows 98 in a console window and pressing CTRL-C.
Happens now and then. When debugging Vim in gdb this also happens. Since
the console crashes, might be a bug in the DOS console. Resetting
'bioskey' avoids it, but then CTRL-C doesn't work.
9 DOS: Make CTRL-Fx and ALT-Fx work.
CTRL-F1 = CE-5E, CTRL-F2 = CE-5F, .., CTRL-F10 = CE-67
ALT-F1 = CE-68, ALT-F2 = CE-69, .., ALT-F10 = CE-71
Shifted cursor keys produce same codes as unshifted keys. Use bioskey(2)
to get modifier mask for <S-C-M-Fx>.
Use K_SPECIAL/KS_MODIFIER codes to insert modifier mask in input stream?
Make this work like in Win32 console.
Mapping things like <M-A> doesn't work, because it generates an extended
key code. Use a translation table?
9 Can't read an opened swap file when the "share" command has not been used.
At least ignore the swap files that Vim has opened itself.
8 Use DJGPP 2.03.
8 The Dos32 version (DJGPP) can't use long file names on Windows NT.
Check if new package can be used (v2misc/ntlfn08[bs].zip).
8 setlocale() is bogus.
8 Vim busy waits for new characters or mouse clicks. Should put in some
sort of sleep, to avoid eating 50% of the CPU time. Test on an unpatched
Windows 95 system!
8 DJGPP: when shell is bash, make fails. (Donahoe)
7 Hitting CTRL-P twice quickly (e.g., in keyword completion) on a 8088
machine, starts printer echo! (John Mullin).
7 MSDOS 16 bit version can't work with COMSPEC that has an argument, e.g.:
COMSPEC=C:\WINDOWS\COMMAND.COM /E:4096 (Bradley)
Caused by BCC system() function (Borland "make" has the same problem).
8 Mouse: handle left&right button pressed as middle button pressed. Add
Windows 95:
8 Editing a file by its short file name and writing it, makes the long file
name disappear. Setting 'backupcopy' helps.
Use FindFirstFile()->cAlternateFileName in fname_case() (George Reilly).
8 Doing wildcard expansion, will match the short filename, but result in the
long filename (both DJGPP and Win32).
Win32 console:
9 When editing a file by its short file name, it should be expanded into its
long file name, to avoid problems like these: (Mccollister)
1) Create a file called ".bashrc" using some other editor.
2) Drag that file onto a shortcut or the actual executable.
3) Note that the file name is something like BASHRC~1
4) Go to File->Save As menu item and type ".bashrc" as the file name.
5) Press "Yes" to indicate that I want to overwrite the file.
6) Note that the message "File exists (add ! to override)" is displayed
and the file is not saved.
Use FindFirstFile() to expand a file name and directory in the path to its
long name.
8 Also implement 'conskey' option for the Win32 console version? Look at
how Xvi does console I/O under Windows NT.
7 Re-install the use of $TERM and support the use of different terminals,
besides the console.
8 Use of <altgr> modifier doesn't work? 5.3 was OK. (Garcia-Suarez/Guckes)
9 Mapping <C-S-Tab> doesn't work correctly. How to see the difference with
<C-S-i>?
9 tmpnam() uses file in root of file system: "\asdf". That doesn't work on
a Netware network drive. Use same function as for Win32 GUI?
8 In os_win32.h, HAVE_STRICMP and HAVE_STRNICMP are defined only if __GNUC__
is not defined. Shouldn't that be the other way around?
7 Use SetConsoleCP() and SetConsoleOutputCP() to implement 'termencoding'?
Avoids that input and output work differently. Need to be restored when
exiting.
Amiga:
8 In mch_inchar() should use convert_input_safe() to handle incomplete byte
sequences.
9 In mch_expandpath() a "*" is to be expanded, but "\*" isn't. Remove
backslashes in result.
8 Executing a shell, only one option for 'shell' is separated. Should do
all options, using white space separation.
Macintosh:
- GUI: gui_mch_browsedir() is missing.
7 Loading the Perl library only works on OS/X 10.2 or 10.3, never on both.
Load the Perl library dynamically see Python sources file dynload_mac
(Jack)
dynamic linking: http://developer.apple.com/technotes/tn2002/tn2064.html
8 inputdialog() doesn't resize when giving more text lines. (David Fishburn,
2006 Sept 28)
8 Define vim_mkdir() for Macintosh.
8 Define mch_writable() for Macintosh.
9 When DiskLock is running, using a swap file causes a crash. Appears to be
a problem with writing a file that starts with a dot. (Giacalone)
9 In mac_expandpath() check that handling of backslashes is done properly.
"Small" problems:
- Can't disable terminal flow control, to enable the use of CTRL-S and
CTRL-Q. Add an option for it?
- When using e_secure in do_one_cmd() mention the command being executed,
otherwise it's not clear where it comes from.
- When the quickfix window is open and executing ":echo 'hello'"' using the
Command-line window, the text is immediately removed by the redrawing.
(Michael Henry, 2008 Nov 1)
Generic solution: When redrawing while there is a message on the
cmdline, don't erase the display but draw over the existing text.
Other solution, redraw after closing the cmdline window, before executing
the command.
9 For Turkish vim_tolower() and vim_toupper() also need to use utf_
functions for characters below 0x80. (Sertacyildiz)
9 When the last edited file is a help file, using '0 in a new Vim doesn't
edit the file as a help file. 'filetype' is OK, but 'iskeyword' isn't,
file isn't readonly, etc.
8 When an ":edit" is inside a try command and the ATTENTION prompt is used,
the :catch commands are always executed, also when the file is edited
normally. Should reset did_emsg and undo side effects. Also make sure
the ATTENTION message shows up. Servatius Brandt works on this.
8 ":g//" gives "Pattern not found error" with E486. Should not use the
error number, it's not a regular error message.
7 Vimtutor leaves escape sequence in terminal. This is the xterm response to
requesting the version number. (Yasuhiro Matsumoto)
8 When redirecting and using ":silent" the current column for displaying and
redirection can be different. Use a separate variable to hold the column
for redirection.
7 The messages for "vim --help" and "vim --version" don't use
'termencoding'.
- Could the hit-enter prompt be avoided when a message only overlaps the
'showcmd' area? Clear that area when the next cmd is typed.
8 When 'scrollbind' is set, a window won't scroll horizontally if the cursor
line is too short. Add a word in 'scrollopt' to allow moving the cursor
to longer line that is visible. A similar thing is done for the GUI when
using the horizontal scrollbar.
7 VisVim can only open one file. Hard to solve: each opened file is passed
with a separate invocation, would need to use timestamps to know the
invocations belong together.
8 When giving a ":bwipeout" command a file-changed dialog may popup for this
buffer, which is pointless. (Mike Williams)
8 On MS-Windows ":make" doesn't show output while it is working. Use the
tee.exe from http://unxutils.sourceforge.net/ ? About 16 Kbyte in the
UnxUtils.zip archive.
Alternate one: http://www.pramodx.20m.com/tee_for_win32.htm, but Walter
Briscoe says it's not as good.
8 "stl" and "stlnc" in 'fillchars' don't work for multi-byte characters.
8 When doing Insert mode completion a mapping cannot recursively call
edit(), because the completion information is global. Put everything in
an allocated structure?
6 Python: ":py raw_input('prompt')" doesn't work. (Manu Hack)
8 Command line completion: buffers "foo.txt" and "../b/foo.txt", completing
":buf foo<Tab>" doesn't find the second one. (George V. Reilly)
7 Output for ":scriptnames" and ":breaklist" should shorten the file names:
use "~/" when possible.
7 mb off2cells() doesn't work correctly on the tail byte of a double-byte
9 dosinst.c: The DJGPP version can't uninstall the Uninstall registry key on
Windows NT. How to install a .inf file on Windows NT and how to detect
that Windows NT is being used?
8 When 'virtualedit' is "block,insert" and encoding is "utf-8", selecting a
block of one double-wide character, then "d" deletes only half of it.
8 When 'virtualedit' is set, should "I" in blockwise visual mode also insert
in lines that don't extend into the block?
8 With 'virtualedit' set, in Insert mode just after the end of line, CTRL-O
yh does not yank the last character of the line. (Pavel Papushev)
Doing "hl" first appears to make it work.
8 With 'virtualedit' set it's possible to move into the blank area from
'linebreak'.
8 With 'virtualedit' set and 'selection' "exclusive", a Visual selection
that ends in or after a tab, "d" doesn't delete (part of) the tab.
(Helmut Stiegler)
9 When jumping to a tag, the search pattern is put in the history. When
'magic' is on, the pattern may not work. Translate the pattern depending
on p_magic when putting it in the history? Alternative: Store value of
'magic' in history. (Margo)
9 optwin.vim: Restoring a mapping for <Space> or <CR> is not correct for
":noremap". Add "mapcmd({string}, {mode})? Use code from ":mkexrc".
9 incsearch is incorrect for "/that/<Return>/this/;//" (last search pattern
isn't updated).
9 term_console is used before it is set (msdos, Amiga).
9 Get out-of-memory for ":g/^/,$s//@/" on 1000 lines, this is not handled
correctly. Get many error messages while redrawing the screen, which
cause another redraw, etc.
8 [<C-I> doesn't work when '*' is in 'iskeyword'. find_pattern_in_path()
must escape special characters in the pattern.
8 Vim can overwrite a read-only file with ":w!". ":w" can't overwrite an
existing file, "w!" can, but perhaps not a read-only file? Then use
":w!!" for that.
Or ask for permission to overwrite it (if file can be made writable) and
restore file to readonly afterwards.
Overwriting a file for which a swap file exists is similar issue.
7 When compiled with "xterm_clipboard", startup can be slower and might get
error message for invalid $DISPLAY. Try connecting to the X server in the
background (forked), so that Vim starts up quicker? Connect as soon as
the clipboard is to be used (Visual select mode starts, paste from
clipboard)
7 X11: Some people prefer to use CLIPBOARD instead of PRIMARY for the normal
selection. Add an "xclipboard" argument to the 'clipboard' option? (Mark
Waggoner)
8 For xterm need to open a connection to the X server to get the window
title, which can be slow. Can also get the title with "<Esc>[21t", no
need to use X11 calls. This returns "<Esc>]l{title}<Esc>\".
6 When the xterm reports the number of colors, a redraw occurs. This is
annoying on a slow connection. Wait for the xterm to report the number of
colors before drawing the screen. With a timeout.
8 When the builtin xterm termcap contains codes that are not wanted, need a
way to avoid using the builtin termcap.
8 Xterm sends ^[[H for <Home> and ^[[F for <End> in some mode. Also
recognize these keys? Mostly useful for xterm simulators, like gnometerm.
See http://dickey.his.com/xterm/xterm.faq.html#xterm_pc_style.
8 For xterm also recognize keypad up/down/left/right and insert.
8 '[ and '] should be set to start/end of line when using a linewise operator
(e.g., ":w").
8 CTRL-A can't handle big "long" numbers, they become negative. Check for
"-" character, if not present, use unsigned long.
8 Make it possible to disable the special meaning of "#" in the first column
for ">>".
8 Add suspending with CTRL-Z at the "more" prompt, and when executing a long
script in do_cmdline().
8 When using 'hidden', many swap files will be open. When Vim runs into the
maximum number of open files, error messages will appear. Detect that
this problem is present, and close any hidden files that don't have
changes.
8 With 'viminfo' set such that the ".viminfo" file is written on a FAT
filesystem, an illegal file name may be created: ".vim".
8 For each buffer that is opened, the viminfo file is opened and read to
check for file marks. This can be slow.
7 In xterm, recognize both vt100 and vt220 cursor keys. Change
add_termcode() to not remove an existing entry for a name, when it's
needed.
Need a generic solution to recognize different codes for the same key.
8 Core dump within signal function: gdb doesn't show stack backtrace! Option
to skip catch_signals()?
9 Repeating a "cw" with "." doesn't work if the text was pasted from the
clipboard. (Thomas Jones) It's because the menu/toolbar item exits Insert
mode and uses "gP". How to fix this without breaking inserting a block of
text?
8 In Replace mode pasting from the clipboard (using menu or toolbar) inserts
all the text. Add ":rmenu"?
8 Pasting with the mouse in Replace mode inserts the text, instead of
overwriting, when it is more than one line. Same for using <C-R>.
9 CTRL-E and CTRL-Y don't work in small window when 'so' is 4 and lines are
wrapping (Acevedo/in.226). E.g., when using CTRL-E, window height 7,
window might actually scroll down when last line of buffer is displayed.
--> Remember if the previous command was "cursor follows screen" or
"screen follow cursor" and use this in cursupdate().
7 tilde_replace() can only handle "~/", should also do "~user/".
Get the list of home directories (from /etc/passwd? Use getpwent()) and
use some clever algorithm to match a path with that. Find common strings
in the list?
8 When dragging status line with mouse, sometimes a jump when first clicking
on the status line (caused by 'winheight'). Select window on button up,
instead of on button down.
8 Dragging the status line doesn't scroll but redraw.
9 Evaluating 'statusline' in build_stl_str_hl() does not properly check for
reaching the end of the available buffer.
Patch to dynamically allocate the buffer for % items. (Eric Arnold, 2006
May 14)
8 When performing incremental search, should abort searching as soon as a
character is typed.
8 When the value of $MAKE contains a path, configure can't handle this.
It's an autoconf bug. Remove the path from $MAKE to work around it.
8 How to set VIMRC_FILE to \"something\" for configure? Why does this not
work: CFLAGS='-DVIMRC_FILE=\"/mydir/myfile\"' ./configure
8 The temporary file is sometimes not writable. Check for this, and use an
alternate name when it isn't. Or add the 'temptemplate' option: template
for the temp file name ":set temptemplate=/usr/tmp/?????.tmp".
Also: Win32 version uses Windows temp directory, which might not work for
cygwin bash.
7 Get error "*, \+ or \( operand could be empty" for pattern "\(.\)\1\{3}".
Remember flags for backreferences.
7 When switching to Daylight Saving Time, Vim complains that a file has been
changed since last read. Can we use a function that uses GMT?
7 When completing an environment variable after a '$', check for file names
that contain a '$' after all have been found.
8 When "cm" termcap entry is missing, starting gvim shouldn't complain about
it. (Lohner) Try out with "vt100" entry, cm replaced with cX.
7 When an include file starts with "../", the check for already visiting
this file doesn't work. Need to simplify the file name.
7 The names and comments for the arguments of do_browse() are confusing.
"dflt" isn't the default file name when "initdir" is not NULL and
"initdir" is the default path to be used.
7 When 'scrolloff' is exactly half the window height, "j" causes a scroll of
two lines at a time. "k" doesn't do this. (Cory T. Echols)
8 When write_viminfo() is used while there are many orphaned viminfo
tempfiles writing the viminfo file fails. Give a clear error message so
that the user knows he has to delete the files.
7 It's possible to redefine a script-local function with ":func
<SNR>123_Test()". (Krishna) Disallow this.
- On Windows NT 4.0 the number of files passed to Vim with drag&drop and
"Edit with Vim" is limited. The maximum command line length is 255 chars.
*extensions-improvements*
Most interesting new features to be added when all bugs have been fixed:
- Using ":exe edit fname" has escaping problems. Use ":edit ++(fname)".
Thus use "++=" to give arguments as expressions, comma separated as if
calling a function.
With options: ":edit ++(['!', '++enc=abc'], ['+/pat'], fname)".
Alternative: Make a function for Ex commands: cmd_edit().
- Add COLUMN NUMBERS to ":" commands ":line1,line2[col1,col2]cmd". Block
can be selected with CTRL-V. Allow '$' (end of line) for col2.
- Add DEBUGGER INTERFACE. Implementation for gdb by Xavier de Gaye.
Should work like an IDE. Try to keep it generic. Now found here:
http://clewn.sf.net.
And the idevim plugin/script.
To be able to start the debugger from inside Vim: For GUI run a program
with a netbeans connection; for console: start a program that splits the
terminal, runs the debugger in one window and reconnect Vim I/O to the
other window.
Wishes for NetBeans commands:
- make it possible to have 'defineAnnoType' also handle terminal colors.
- send 'balloonText' events for the cursor position (using CursorHold ?)
in terminal mode.
- ECLIPSE plugin. Problem is: the interface is very complicated. Need to
implement part in Java and then connect to Vim. Some hints from Alexandru
Roman, 2004 Dec 15. Should then also work with Oracle Jdeveloper, see JSR
198 standard http://www.jcp.org/en/jsr/detail?id=198.
Eclim does it: http://eclim.sourceforge.net/ Eric Van Dewoestine
Plugin that uses a terminal emulator: http://vimplugin.sf.net
And another one: http://www.satokar.com/viplugin/index.php
- STICKY CURSOR: Add a way of scrolling that leaves the cursor where it is.
Especially when using the scrollbar. Typing a cursor-movement command
scrolls back to where the cursor is.
- Scroll commands by screen line. g CTRL-E and g CTRL-Y ? Requires the
first line to be able to start halfway.
- Running a shell command from the GUI still has limitations. Look into how
the terminal emulator of the Vim shell project can help:
http://vimshell.wana.at
8 Add a command to jump to a certain kind of tag. Allow the user to specify
values for the optional fields. E.g., ":tag size type=m".
Also allow specifying the file and command, so that the result of
taglist() can be used.
- X11: Make it possible to run Vim inside a window of another program.
This can be done with XReparentWindow(). But how exactly?
Documentation:
8 List of Vim runtime directories. dotvim.txt from Charles Campbell, 2007
Feb 20.
8 The GUI help should explain the Find and Find/Replace dialogs. Add a link
to it from ":promptrepl" and ":promptfind".
8 List of options should mention whether environment variables are expanded
or not.
8 Extend usr_27.txt a bit. (Adam Seyfarth)
7 Add a section on debugging scripts in the user manual.
9 Make the Reference Manual more precise. For each command mention:
- change to cursor position and curswant
- if it can be undone (u/CTRL-R) and redone (.)
- how it works for folded lines
- how it works with multi-byte characters
9 In change.txt, remark about Javadoc isn't right. Right alignment would
work too.
8 Spread the windows commands over the other files. For example, ":stag"
should be with ":tag". Cross-link with tags to avoid too much double
text.
8 Add tags for all features, e.g. "gui_running".
7 MS-Windows: When a wrong command is typed with an ALT key, give a hint to
look at the help for 'winaltkeys'.
7 Add a help.vim plugin that maps <Tab> to jump to the next tag in || and
<C-Tab> (and <S-Tab>) to the previous tag.
Patch by Balazs Kezes, 2007 Dec 30. Remark from A. Politz.
- Check text editor compendium for vi and Vim remarks.
Help:
- First try using the ":help" argument literally, before using it as a
pattern. And then match it as part of a tag.
- When a help item has multiple matches make it possible to use ":tn" to go
to the other matches.
- Support a way to view (and edit) .info files.
- Default mapping for help files: <Tab> to position cursor on next |:tag|.
- Implement a "sticky" help window, some help text lines that are always
displayed in a window with fixed height. (Guckes) Use "~/.vimhelp" file,
user can edit it to insert his favorite commands, new account can contain a
default contents.
- Make 'winminheight' a local option, so that the user can set a minimal
height for the help window (and other windows).
- ":help :s^I" should expand to ":help :substitute".
- Make the help key (<F1>) context sensitive?
- Learn mode: show short help while typing commands.
User Friendlier:
8 Windows install with install.exe: Use .exe instead of .bat files for
links, so that command line arguments are passed on unmodified? (Walter
Briscoe)
8 Windows install: Be able to associate Vim with a selection of file types?
8 Windows uninstall: Have uninstal.c delete the vimfiles directories that
dosinst.c creates. List the contents of the directory (recursively) if
the user asks for it. Requires an implementation of "rm -rf".
8 Remember the name of the vimrc file that was used (~/.vimrc, $VIM/_vimrc,
$HOME/_vimrc, etc.) and add "edit vimrc" to the File menu.
- Add a way to save local settings and mappings into a new plugin file.
":mkplugin <file>"?
8 Add ":plugininstall" command. Can be used to install a plugin file that
includes documentation. Let the user select a directory from
'runtimepath'.
" Vim plugin
<main plugin code>
" >>> plugin help start <<<
<plugin docs>
- Add mappings local to a window: ":map <window> ..."?
9 Add buffer-local menu. Should offer a choice between removing the menu or
disabling it. Be careful that tear-offs don't disappear (keep one empty
item?).
Alternative: use BufEnter and BufLeave autocommands.
8 make a vimtutor script for Amiga and other systems.
7 Add the arguments for configure to the ":version" output?
7 When Vim detects a file is being edited elsewhere and it's a gvim session
of the same user it should offer a "Raise" button, so that the other gvim
window can be displayed. (Eduard)
8 Support saving and restoring session for X windows? It should work to do
":mksession" and use "-S fname" for the restart command. The
gui_x11_wm_protocol_handler() already takes care of the rest.
global_event_filter() for GTK.
Tab pages:
9 GUI implementation for the tab pages line for other systems.
7 GUI: Control over the appearance of the text in the labels (bold, color,
font, etc.)
8 Make GUI menu in tab pages line configurable. Like the popup menu.
8 balloons for the tab page labels that are shortened to show the full path.
8 :tabmove +N move tab page N pages forward
8 :tabmove -N move tab page N pages backward
7 :tabdup duplicate the tab with all its windows.
7 Option to put tab line at the left or right? Need an option to specify
its width. It's like a separate window with ":tabs" output.
7 Add local variables for each tab page?
8 Add local options for each tab page? E.g., 'diffopt' could differ between
tab pages.
7 Add local highlighting for each tab page?
7 Add local directory for tab pages? How would this interfere with
window-local directories?
Spell checking:
- have some way not to give spelling errors for a range of characters.
E.g. for Chinese and other languages with specific characters for which we
don't have a spell file. Useful when there is also text in other
languages in the file.
- Support more regions? Caolan McNamara argues it's needed for es_XX.
https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=219777
- Unicode defines another quote character: 0x2019. Use it as an equivalent
of a single quote, thus use it as a word character like a quote and match
with words, replacing the curly quote with a single quote.
- Could filter é things for HTML before doing spell checking.
Similarly for TeX.
- The Hungarian spell file uses four extra characters in the FOL/UPP/LOW
items than other spell files with the ISO-8859-2 encoding, that causes
problem when changing 'spelllang'. There is no obvious way to fix this.
- Considering Hunspell 1.1.4:
What does MAXNGRAMSUGS do?
Is COMPLEXPREFIXES necessary when we have flags for affixes?
- Support spelling words in CamelCase as if they were two separate words.
Requires some option to enable it. (Timothy Knox)
- There is no Finnish spell checking file. For openoffice Voikko is now
used, which is based on Malaga: http://home.arcor.de/bjoern-beutel/malaga/
(Teemu Likonen)
8 ":mkspell" still takes much too long in Hungarian dictionary from
hunspell. Only solution appears to be to postpone secondary suffixes.
8 Handle postponed prefix with COMPOUNDPERMITFLAG or COMPOUNDFORBIDFLAG.
WFP_COMPPERMIT and WFP_COMPFORBID
8 implement use of <compoptions> in .spl file:
implement CHECKCOMPOUNDREP: when a compound word seems to be OK apply REP
items and check if the result is a valid word.
implement CHECKCOMPOUNDDUP
implement CHECKCOMPOUNDTRIPLE
Add CHECKCOMPOUNDCASE: when compounding make leading capital lower case.
How is it supposed to work?
- Add a command the repeats ]s and z=, showing the misspelled word in its
context. Thus to spell-check a whole file.
- suggestion for "KG" to "kg" when it's keepcase.
- For flags on affixes: Use a "AFFCOMPSET" flag; means the compound flags of
the word are not used.
- Support breakpoint character ? 0xb7 and ignore it? Makes it possible to
use same wordlist for hyphenation.
- Compound word is accepted if nr of words is <= COMPOUNDWORDMAX OR nr of
syllables <= COMPOUNDSYLMAX. Specify using AND in the affix file?
- NEEDCOMPOUND also used for affix? Or is this called ONLYINCOMPOUND now?
Or is ONLYINCOMPOUND only for inside a compound, not at start or end?
- Do we need a flag for the rule that when compounding is done the following
word doesn't have a capital after a word character, even for Onecap words?
- New hunspell home page: http://hunspell.sourceforge.net/
- Version 1.1.0 is out now, look into that.
- Lots of code depends on LANG, that isn't right. Enable each mechanism
in the affix file separately.
- Example with compounding dash is bad, gets in the way of setting
COMPOUNDMIN and COMPOUNDWORDMAX to a reasonable value.
- PSEUDOROOT == NEEDAFFIX
- COMPOUNDROOT -> COMPOUNDED? For a word that already is a compound word
Or use COMPOUNDED2, COMPOUNDED3, etc.
- CIRCUMFIX: when a word uses a prefix marked with the CIRCUMFIX flag, then
the word must also have a suffix marked with the CIRCUMFIX flag. It's a
bit primitive, since only one flag is used, which doesn't allow matching
specific prefixes with suffixes.
Alternative:
PSFX {flag} {pchop} {padd} {pcond} {schop} {sadd}[/flags] {scond}
We might not need this at all, you can use the NEEDAFFIX flag and the
affix which is required.
- When a suffix has more than one syllable, it may count as a word for
COMPOUNDWORDMAX.
- Add flags to count extra syllables in a word. SYLLABLEADD1 SYLLABLEADD2,
etc.? Or make it possible to specify the syllable count of a word
directly, e.g., after another slash: /abc/3
- MORPHO item in affix file: ignore TAB and morphological field after
word/flags and affix.
- Implement multiple flags for compound words and CMP item?
Await comments from other spell checking authors.
- Also see tklspell: http://tkltrans.sourceforge.net/
8 Charles Campbell asks for method to add "contained" groups to existing
syntax items (to add @Spell).
Add ":syntax contains {pattern} add=@Spell" command? A bit like ":syn
cluster" but change the contains list directly for matching syntax items.
- References: MySpell library (in OpenOffice.org).
http://spellchecker.mozdev.org/source.html
http://whiteboard.openoffice.org/source/browse/whiteboard/lingucomponent/source/spellcheck/myspell/
author: Kevin Hendricks <kevin.hendricks@sympatico.ca>
8 It is currently not possible to mark "can not" as rare, because "can" and
"not" are good words. Find a way to let "rare" overrule "good"?
8 Make "en-rare" spell file? Ask Charles Campbell.
8 The English dictionaries for different regions are not consistent in their
use of words with a dash.
7 Insert mode completion mechanism that uses the spell word lists.
8 Add hl groups to 'spelllang'?
:set spelllang=en_us,en-rare/SpellRare,en-math/SpellMath
More complicated: Regions with different languages? E.g., comments
in English, strings in German (po file).
Diff mode:
9 Instead invoking an external diff program, use builtin code. One can be
found here: http://www.ioplex.com/~miallen/libmba/dl/src/diff.c
It's quite big and badly documented though.
8 Use diff mode to show the changes made in a buffer (compared to the file).
Use an unnamed buffer, like doing:
new | set bt=nofile | r # | 0d_ | diffthis | wincmd p | diffthis
Also show difference with the file when editing started? Should show what
can be undone. (Tom Popovich)
7 Add cursor-binding: when moving the cursor in one diff'ed buffer, also
move it in other diff'ed buffers, so that CTRL-W commands go to the same
location.
Folding:
(commands still available: zI zJ zK zp zP zq zQ zV zy zY;
secondary: zB zS zT zZ, z=)
8 Vertical folds: looks like vertically split windows, but the cursor moves
through the vertical separator, separator moves when scrolling.
8 Add "z/" and "z?" for searching in not folded text only.
9 Add search pattern item to only match in closed or open fold and/or fold
with certain level. Allows doing ":g/pat/cmd" to work on closed folds.
7 Use "++--", "+++--" for different levels instead of "+---" "+----".
8 When a closed fold is displayed open because of 'foldminlines', the
behavior of commands is still like the fold is closed. How to make the
user aware of this?
8 Add an option 'foldskip' with values like 'foldopen' that specifies which
commands skip over a closed fold.
8 "H" and "L" count buffer lines instead of window lines. (Servatius Brandt)
8 Add a way to add fold-plugins. Johannes Zellner has one for VB.
7 When using manual folding, the undo command should also restore folds.
- Allow completely hiding a closed fold. E.g., by setting 'foldtext' to an
empty string. Require showing a character in 'foldcolumn' to avoid the
missing line goes unnoticed.
How to implement this?
- When pressing the down arrow of a scrollbar, a closed fold doesn't scroll
until after a long time. How to make scrolling with closed folds
smoother?
- When creating a session, also store folds for buffers in the buffer list,
using the wininfo in wi_folds.
- When currently editing the first file in the argument list the session
file can contain:
args version.c main.c
edit version.c
Can editing version.c twice be avoided?
- 'foldmethod' "textobject": fold on sections and paragraph text objects.
- "zuf": undo change in manual fold. "zUf" redo change in manual fold. How
to implement this?
- "zJ" command: add the line or fold below the fold in the fold under the
cursor.
- 'foldmethod' "syntax": "fold=3" argument: set fold level for a region or
match.
- Apply a new foldlevel to a range of lines. (Steve Litt)
8 Have some way to restrict commands to not folded text. Also commands like
searches.
Multi-byte characters:
- When editing a file with both utf-8 and latin1 text Vim always falls back
to latin1. Add a command to convert the latin1 characters to utf-8?
:unmix utf-8,latin1 filename
Would only work when 'encoding' is utf-8.
9 When the tail byte of a double-byte character is illegal (e.g., a CR), the
display is messed up (Yasuhiro Matsumoto). Should check for illegal
double-byte characters and display them differently (display each single
byte).
9 'fenc' in modeline problem: add option to reload the file when 'fenc' is
set to a different value in a modeline? Option can be default on. Could
it be done with an autocommand?
8 Add an item in 'fileencodings' to check the first lines of a file for
the encoding. See Python PEP: http://www.python.org/peps/pep-0263.html.
To avoid getting a wrong encoding only accept something Emacs-like:
"-*- coding: enc-na_me.foo -*-" and "-*- coding= enc-na_me.foo -*-"
Match with "-\*-\s*coding[:=]\s*\([::word::-_.]\+\)\s*-\*-" and use first
item.
8 Add an item in 'fileencodings' to check the first line of an XML file for
the encoding. <?xml version="1.0" encoding="UTF-8"?> Or "charset=UTF-8"?
For HTML look for "charset=utf-8".
8 The quickfix file is read without conversion, thus in 'encoding'. Add an
option to specify the encoding of the errorfile and convert it. Also for
":grep" and ":helpgrep".
More generic solution: support a filter (e.g., by calling a function).
8 When a file was converted from 'fileencoding' to 'encoding', a tag search
should also do this on the search pattern. (Andrzej M. Ostruszka)
8 When filtering changes the encoding 'fileencoding' may not work. E.g.,
when using xxd and 'fileencoding' is "utf-16". Add an option to set a
different fileencoding for filter output?
7 When converting a file fails, mention which byte could not be converted,
so that the user can fix the problem.
8 Add configure option to be able to disable using the iconv library. (Udo
Schweigert)
9 'aleph' should be set to 1488 for Unicode. (Zvi Har'El)
8 Should add test for using various commands with multi-byte characters.
8 'infercase' doesn't work with multi-byte characters.
8 toupper() function doesn't handle byte count changes.
7 Searching and composing characters:
When searching, should order of composing characters be ignored?
Add special item to match with a composing character, zero-width, so that
one can replace a base character and keep the composing characters.
Add a special item to match with a composing character, so that composing
characters can be manipulated.
Add a modifier to ignore composing characters, only compare base
characters. Useful for Hebrew (Ron Aaron)
8 Should implement 'delcombine' for command line editing.
8 Detect overlong UTF-8 sequences and handle them like illegal bytes.
8 ":s/x/\u\1/" doesn't work, making uppercase isn't done for multi-byte
characters.
8 UTF-8: "r" in Visual mode doesn't take composing characters.
8 UTF-8: When there is a precomposed character in the font, use it instead
of a character and a composing character. See xterm for an example.
7 When a character can't be displayed, display its digraph instead.
'display' option to specify this.
7 Use ideas for nl_langinfo() from Markus Kuhn in enc_default():
(www.cl.cam.ac.uk/~mgk25/ucs/langinfo.c)
- GTK and Win32: Allow selecting fonts for 'guifontset' with the
fontselector somehow.
- GTK and Win32: make it possible to set the font for the menu to make it
possible to have 'encoding' different from the current locale.
- dbcs_class() only works for Japanese and Korean. Implement this for
other encodings. The "euc-jp" and "euc-kr" choices might be wrong.
- Find some way to automatically select the right GUI font or fontset,
depending on the default value of 'encoding'.
Irrelevant in the GTK+ 2 GUI so long as UTF-8 is used.
For Windows, the charset_pairs[] table could be used. But how do we know
if a font exists?
- Do keyboard conversion from 'termencoding' to 'encoding' with
convert_input() for Mac GUI and RiscOS GUI.
- Add mnemonics from RFC1345 longer than two characters.
Support CTRL-K _{mnemonic}_
7 In "-- INSERT (lang) --" show the name of the keymap used instead of
"lang". (Ilya Dogolazky)
- Make 'breakat' accept multi-byte characters. Problem: can't use a lookup
table anymore (breakat_flags[]).
Simplistic solution: when 'formatoptions' contains "m" also break a line
at a multi-byte character >= 0x100.
- Add the possibility to enter mappings which are used whenever normal text
could be entered. E.g., for "f" command. But not in Normal mode. Sort
of opposite of 'langmap'. Use ":tmap" command?
- When breaking a line, take properties of multi-byte characters into
account. The "linebreak" program from Bruno Haible can do it:
ftp://ftp.ilog.fr/pub/Users/haible/gnu/linebreak-0.1.tar.gz
But it's very complicated...
Printing:
7 Implement "undercurl" for printing.
- Add "page width" to wrap long lines.
- Win32: use a font dialog for setting 'printfont'. Can reuse the code for
the 'guifont' dialog, put the common code in a separate function.
- Add the file timestamp to the page header (with an option). (George
Reilly)
- Win32: when 'printfont' is empty use 'guifont'.
- Unix: Use some dialog box to do the obvious settings (paper size, printer
name, portrait/landscape, etc).
- PostScript: Only works for text that can be converted to an 8-bit
character set. How to support Unicode fully?
- Allow specifying the paper size, instead of using a standard size. Same
units as for the margins.
- Support right-to-left text?
8 Make the foreground color darkening function preserve the hue of the
color.
Syntax highlighting:
8 Make ":syn off" use 'runtimepath' instead of $VIMRUNTIME. (Gary Johnson)
Should do the same for ":syn on" and ":syn manual".
8 Support "containedin" argument for ":syn include", so that the defined
cluster can be added to existing syntax items.
8 C syntax: Don't highlight {} as errors inside () when used like this:
"({ something })", often used in GCC code.
7 Add a "startgroup" to a region. Used like "nextgroup" inside the region,
preferred item at the start of the region. (Charles Campbell)
8 When editing a new file without a name and giving it a name (by writing
it) and 'filetype' is not set, detect the filetype. Avoid doing it for
":wq file".
7 For "nextgroup" we have skipwhite, skipnl and skipempty. It would be
really nice to be able to skip with a pattern. Or skip with a syntax
group. (Nikolai Weibull, 2007 Feb 27)
8 Make conversion to HTML faster (Write it in C or pre-compile the script).
9 There is still a redraw bug somewhere. Probably because a cached state is
used in a wrong way. I can't reproduce it...
7 Be able to change only the background highlighting. Useful for Diff* and
Search highlighting.
7 When 'number' is set highlight the number of the current line.
Must be enabled with an option, because it slows down display updating.
8 Allow the user to add items to the Syntax menu sorted, without having to
change this for each release.
8 Add a "matchcontains" for regions: items contained in the start or end
pattern, but not in the body.
8 Add a "keepend-contained" argument: Don't change the end of an item this
one is contained in. Like "keepend" but specified on the contained item,
instead of the containing item.
8 cpp.vim: In C++ it's allowed to use {} inside ().
8 Some syntax files set 'iskeyword'. When switching to another filetype
this isn't reset. Add a special keyword definition for the syntax rules?
When this is done, use vim.vim syntax highlighting for help file examples,
but without ":" in 'iskeyword' for syntax.
8 Add specific syntax item to match with parens/braces that don't have a
"%" match. :syntax nomatch cMatchError (,{,[,),},] [contained]
8 Highlight the text between two matching parens (e.g., with a grey
background) when on one of the parens or in between them.
Option for the matchparen plugin?
8 Add a command to jump to the next character highlighted with "Error".
8 When using a cterm, and no ctermfg or ctermbg are defined, use start/stop
sequences. Add remark in docs that :if 'term' == "term-name" should be
used.
8 Add @spell cluster to String and Comment groups for many languages. Will
allow spell checking. (Fleiner)
8 When listing syntax items, try to sort the keywords alphabetically. And
re-insert the [] if possible.
8 Make it possible to use color of text for Visual highlight group (like for
the Cursor).
8 It would be useful to make the highlight group name an expression. Then
when there is a match, the expression would be evaluated to find out what
highlight group to use. Could be used to check if the shell used in a
password file appears in /etc/shells. (Nikolai Weibull)
syn match =s:checkShell(v:match) contained 'pattern'
8 Make it possible to only highlight a sub-expression of a match. Like
using "\1" in a ":s" command.
8 Support for deleting syntax items:
:syn keyword cTodo remove this
:syn match cTodo remove "pattern"
:syn region cString remove start="this" end="that"
8 Add possibility to sync on something else, when the syncing in one way
doesn't find match. For HTML: When no {script} is found, try looking for
a '<'. (Fleiner)
7 Replace the synchronizing method with a state machine specification?
Should be able to start at any line in the file, search forwards or
backwards, and use the result of matching a pattern.
7 Use parsing like awk, so that e.g., a ( without a matching ) can be
detected.
8 Make it possible to use "inverted" highlighting, invert the original
character. For Visual mode. (xterm-selection already does this).
8 Highlight non-printable characters with "SpecialChar", linked to
"Special". Display them with the digraph characters, if possible.
8 Highlight the clipboard-selection with a highlight group.
8 Be able to reset highlighting to its original (default) values.
7 Be able to write current highlighting to a file as commands, similar to
":mkvimrc".
8 Improve c.vim:
- Add check for unterminated strings, with a variable to switch it on:
"c_strict_ansi".
- Detect unbalanced "#endif". Requires looking back a long way...
8 Add an option to restrict the updating of syntax highlighting to the
current line while in Insert mode.
8 When guessing value of 'background', the syntax file has already been
loaded (from the .gvimrc). After changing 'background', load it again?
8 Add ":syn resync" command, to re-parse the whole file until the current
display position.
8 Should support "me" offset for a region start pattern. To be used to
allow searching for the end pattern inside the match of the end pattern.
Example: syn region pikeXX start="([^{]" end=")" should work on "()".
8 When using a regexp for "contains=", should delay matching with it until
redrawing happens. Set a flag when a group is added, check this flag when
highlighting starts.
8 Some terminals can display colors like the GUI. Add some setting to use
GUI colors for the terminal? With something to define the escape
sequence.
7 It's possible for an item to be transparent, so that the colors of an item
lower on the stack is used. Also do this with highlighting, so that the
user can set transparent highlighting? E.g. a number in a C comment would
get the color of a comment, a number in an assignment Normal. (Nikolai
Weibull)
7 Add "semitrans": Add highlighting. E.g., make the text bold, but keep the
colors. And add colors, so that Green+Red becomes Yellow.
E.g. for this html:
<B> bold text <I> italic+bold text </B> italic text </I>
7 CTRL-] checks the highlight group for finding out what the tag is.
7 Add an explanation how a list of words can be used to highlight misspelled
words.
8 Add more command line completion for :syntax.
8 Add more command line completion for :highlight.
7 Should find a better way to parse the :syntax and :highlight commands.
Use tables or lists that can be shared by parsing for execution and
completion?
8 Add ColorSchemePost autocommand event, so that scripts can set up their
highlighting. (Salman Halim)
7 Add a few sets of colors (e.g. Borland Turbo C one). With a menu to
select one of the sets.
8 Add offsets to sub-matches: "\(a*\) *"he=e1-1
'e' is end of match 'e1' is end of sub-match 1, 's2' is start of submatch
2, etc.
8 In Insert mode, when there are typeahead characters, postpone the
highlighting (for "." command).
8 Syncing on comments isn't 100% correct when / / lines mix with / * and * /.
For example: What about a line that starts with / / and contains * /?
8 Ignore / * and * / inside strings, when syncing.
7 Build a few more syntax files from the file "/usr/share/misc/vgrindefs":
ISP, LDL, Icon, ratfor. And check "nedit/source/highlight.c".
6 Add possibility to have background color continue until the right edge of
the window. Useful for comment blocks and function headings. (Rogall)
- Make it possible to add "contains" items for all items in a group. Useful
when extending an already existing syntax file.
- Add line-continuation pattern for non-syncing items too?
- Add possibility to highlight the whole line, including the right margin
(for comment blocks).
- Add 'hlmatch' option: List of flags:
'c': highlight match for character under the cursor.
'b': highlight the previous (, and its match.
'a': highlight all text from the previous ( until its match.
Also for {}, <>, etc.?
'e': highlight all braces without a match (slow?)
OR: add an argument "cursor" to the syntax command, which means that the
region/match/keyword is only highlighted when the cursor is on it.
(Campbell)