Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
{expr}
) abs(){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)
echo abs(-5.456)
echo abs(-4)
{expr}
(number
)
number
){expr}
) acos(){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].
Returns NaN if {expr}
is outside the range [-1, 1]. Returns
0.0 if {expr}
is not a Float or a Number.
Examples:echo acos(0)
echo acos(-0.5)
{expr}
(number
)
number
){object}
, {expr}
) add(){expr}
to List or Blob {object}
. Returns
the resulting List or Blob. Examples:let alist = add([1, 2, 3], item)
call add(mylist, "woodstock")
{expr}
is a List it is appended as a single
item. Use extend() to concatenate Lists.
When {object}
is a Blob then {expr}
must be a number.
Use insert() to add an item at another position.
Returns 1 if {object}
is not a List or a Blob.{object}
(any
)
{expr}
(any
)
{expr}
, {expr}
) and()or()
and xor()
.
Example:let flag = and(bits, 0x80)
{expr}
(number
)
{expr1}
(number
)
integer
)lua vim.print(vim.fn.api_info())
table
){lnum}
, {text}
) append(){text}
is a List: Append each item of the List as a
text line below line {lnum}
in the current buffer.
Otherwise append {text}
as one text line below line {lnum}
in
the current buffer.
Any type of item is accepted and converted to a String.
{lnum}
can be zero to insert a line before the first one.
{lnum}
is used like with getline().
Returns 1 for failure ({lnum}
out of range or out of memory),
0 for success. When {text}
is an empty list zero is returned,
no matter the value of {lnum}
. Example:let failed = append(line('$'), "# THE END")
let failed = append(0, ["Chapter 1", "the beginning"])
{lnum}
(integer
)
{text}
(string|string[]
)
0|1
){buf}
, {lnum}
, {text}
) appendbufline(){expr}
.{buf}
, see bufname().{lnum}
is the line number to append below. Note that using
line() would use the current buffer, not the one appending
to. Use "$" to append at the end of the buffer. Other string
values are not supported.{buf}
is not a valid buffer or {lnum}
is not valid, an
error message is given. Example:let failed = appendbufline(13, 0, "# THE START")
{text}
is an empty list then no error is given
for an invalid {lnum}
, since {lnum}
isn't actually used.{buf}
(integer|string
)
{lnum}
(integer
)
{text}
(string
)
0|1
){winid}
]) argc(){winid}
is not supplied, the argument list of the current
window is used.
If {winid}
is -1, the global argument list is used.
Otherwise {winid}
specifies the window of which the argument
list is used: either the window number or the window ID.
Returns -1 if the {winid}
argument is invalid.{winid}
(integer?
)
integer
)integer
){winnr}
[, {tabnr}
]]) arglistid(){winnr}
only use this window in the current tab page.
With {winnr}
and {tabnr}
use the window in the specified tab
page.
{winnr}
can be the window number or the window-ID.{winnr}
(integer?
)
{tabnr}
(integer?
)
integer
){nr}
[, {winid}
]]) argv(){nr}
th file in the argument list. 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
{winid}
argument specifies the window ID, see argc().
For the Vim command line arguments see v:argv.{nr}
th argument is not present in
the argument list. Returns an empty List if the {winid}
argument is invalid.{nr}
(integer?
)
{winid}
(integer?
)
string|string[]
){expr}
) asin(){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].
Returns NaN if {expr}
is outside the range [-1, 1]. Returns
0.0 if {expr}
is not a Float or a Number.
Examples:echo asin(0.8)
echo asin(-0.5)
{expr}
(any
)
number
){cmd}
) assert_beeps(){cmd}
and add an error message to v:errors if it does
NOT produce a beep or visual bell.
Also see assert_fails(), assert_nobeep() and
assert-return.{cmd}
(string
)
0|1
){expected}
, {actual}
[, {msg}
]) assert_equal(){expected}
and {actual}
are not equal an error message is
added to v:errors and 1 is returned. Otherwise zero is
returned. assert-return
The error is in the form "Expected {expected}
but got
{actual}
". When {msg}
is present it is prefixed to that,
along with the location of the assert when run from a script.call assert_equal('foo', 'bar', 'baz')
{expected}
(any
)
{actual}
(any
)
{msg}
(any?
)
0|1
){fname_one}
, {fname_two}
) assert_equalfile(){fname_one}
and {fname_two}
do not contain
exactly the same text an error message is added to v:errors.
Also see assert-return.
When {fname_one}
or {fname_two}
does not exist the error will
mention that.{fname_one}
(string
)
{fname_two}
(string
)
0|1
){error}
[, {msg}
]) assert_exception(){error}
an error
message is added to v:errors. Also see assert-return.
This can be used to assert that a command throws an exception.
Using the error number, followed by a colon, avoids problems
with translations:try
commandthatfails
call assert_false(1, 'command should have failed')
catch
call assert_exception('E492:')
endtry
{error}
(any
)
{msg}
(any?
)
0|1
){cmd}
[, {error}
[, {msg}
[, {lnum}
[, {context}
]]]])
Run {cmd}
and add an error message to v:errors if it does
NOT produce an error or when {error}
is not found in the
error message. Also see assert-return.{error}
is a string it must be found literally in the
first reported error. Most often this will be the error code,
including the colon, e.g. "E123:".call assert_fails('bad cmd', 'E987:')
{error}
is a List with one or two strings, these are
used as patterns. The first pattern is matched against the
first reported error:call assert_fails('cmd', ['E987:.*expected bool'])
call assert_fails('cmd', ['', 'E987:'])
{msg}
is empty then it is not used. Do this to get the
default message when passing the {lnum}
argument.
E1115 {lnum}
is present and not negative, and the {error}
argument is present and matches, then this is compared with
the line number at which the error was reported. That can be
the line number in a function or in a script.
E1116 {context}
is present it is used as a pattern and matched
against the context (script name or function name) where
{lnum}
is located in.{cmd}
(string
)
{error}
(any?
)
{msg}
(any?
)
{lnum}
(integer?
)
{context}
(any?
)
0|1
){actual}
[, {msg}
]) assert_false(){actual}
is not false an error message is added to
v:errors, like with assert_equal().
The error is in the form "Expected False but got {actual}
".
When {msg}
is present it is prefixed to that, along with the
location of the assert when run from a script.
Also see assert-return.{actual}
is not a
number the assert fails.{actual}
(any
)
{msg}
(any?
)
0|1
){lower}
, {upper}
, {actual}
[, {msg}
]) assert_inrange(){actual}
is lower
than {lower}
or higher than {upper}
an error message is added
to v:errors. Also see assert-return.
The error is in the form "Expected range {lower}
- {upper}
,
but got {actual}
". When {msg}
is present it is prefixed to
that.{lower}
(number
)
{upper}
(number
)
{actual}
(number
)
{msg}
(string?
)
0|1
){pattern}
, {actual}
[, {msg}
]) assert_match(){pattern}
does not match {actual}
an error message is
added to v:errors. Also see assert-return.
The error is in the form "Pattern {pattern}
does not match
{actual}
". When {msg}
is present it is prefixed to that,
along with the location of the assert when run from a script.{pattern}
is used as with expr-=~: The matching is always done
like 'magic' was set and 'cpoptions' is empty, no matter what
the actual value of 'magic' or 'cpoptions' is.{actual}
is used as a string, automatic conversion applies.
Use "^" and "$" to match with the start and end of the text.
Use both to match the whole text.call assert_match('^f.*o$', 'foobar')
{pattern}
(string
)
{actual}
(string
)
{msg}
(string?
)
0|1
){cmd}
) assert_nobeep(){cmd}
and add an error message to v:errors if it
produces a beep or visual bell.
Also see assert_beeps().{cmd}
(string
)
0|1
){expected}
, {actual}
[, {msg}
]) assert_notequal()assert_equal()
: add an error message to
v:errors when {expected}
and {actual}
are equal.
Also see assert-return.{expected}
(any
)
{actual}
(any
)
{msg}
(any?
)
0|1
){pattern}
, {actual}
[, {msg}
]) assert_notmatch()assert_match()
: add an error message to
v:errors when {pattern}
matches {actual}
.
Also see assert-return.{pattern}
(string
)
{actual}
(string
)
{msg}
(string?
)
0|1
){msg}
) assert_report(){msg}
.
Always returns one.{msg}
(string
)
0|1
){actual}
[, {msg}
]) assert_true(){actual}
is not true an error message is added to
v:errors, like with assert_equal().
Also see assert-return.
A value is TRUE when it is a non-zero number or v:true.
When {actual}
is not a number or v:true the assert fails.
When {msg}
is given it is prefixed to the default message,
along with the location of the assert when run from a script.{actual}
(any
)
{msg}
(string?
)
0|1
){expr}
) atan(){expr}
, in
the range [-pi/2, +pi/2] radians, as a Float.
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo atan(100)
echo atan(-4.01)
{expr}
(number
)
number
){expr1}
, {expr2}
) atan2(){expr1}
/ {expr2}
, measured in
radians, as a Float in the range [-pi, pi].
{expr1}
and {expr2}
must evaluate to a Float or a Number.
Returns 0.0 if {expr1}
or {expr2}
is not a Float or a
Number.
Examples:echo atan2(-1, 1)
echo atan2(1, -1)
{expr1}
(number
)
{expr2}
(number
)
number
){blob}
) blob2list(){blob}
. Examples:blob2list(0z0102.0304) " returns [1, 2, 3, 4]
blob2list(0z) " returns []
{blob}
(any
)
any[]
){save}
, {title}
, {initdir}
, {default}
) browse(){save}
when TRUE, select file to write
{title}
title for the requester
{initdir}
directory to start browsing in
{default}
default file name
An empty string is returned when the "Cancel" button is hit,
something went wrong, or browsing is not possible.{save}
(any
)
{title}
(string
)
{initdir}
(string
)
{default}
(string
)
0|1
){title}
, {initdir}
) browsedir(){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.{title}
(string
)
{initdir}
(string
)
0|1
){name}
) bufadd(){name}
(must be a
String).
If a buffer for file {name}
already exists, return that buffer
number. Otherwise return the buffer number of the newly
created buffer. When {name}
is an empty string then a new
buffer is always created.
The buffer will not have 'buflisted' set and not be loaded
yet. To add some text to the buffer use this:let bufnr = bufadd('someName')
call bufload(bufnr)
call setbufline(bufnr, 1, ['some', 'text'])
{name}
(string
)
integer
){buf}
) bufexists(){buf}
exists.
If the {buf}
argument is a number, buffer numbers are used.
Number zero is the alternate buffer for the current window.{buf}
argument is a string it must match a buffer name
exactly. The name can be:
{buf}
(any
)
0|1
){buf}
) buflisted(){buf}
exists and is listed (has the 'buflisted' option set).
The {buf}
argument is used like with bufexists().{buf}
(any
)
0|1
){buf}
) bufload(){buf}
is loaded. When the buffer name
refers to an existing file then the file is read. Otherwise
the buffer will be empty. If the buffer was already loaded
then there is no change. If the buffer is not related to a
file then no file is read (e.g., when 'buftype' is "nofile").
If there is an existing swap file for the file of the buffer,
there will be no dialog, the buffer will be loaded anyway.
The {buf}
argument is used like with bufexists().{buf}
(any
)
{buf}
) bufloaded(){buf}
exists and is loaded (shown in a window or hidden).
The {buf}
argument is used like with bufexists().{buf}
(any
)
0|1
){buf}
]) bufname():ls
command, but not using special names such as
"[No Name]".
If {buf}
is omitted the current buffer is used.
If {buf}
is a Number, that buffer number's name is given.
Number zero is the alternate buffer for the current window.
If {buf}
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 {buf}
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)
echo bufname("#") " alternate buffer name
echo bufname(3) " name of buffer 3
echo bufname("%") " name of current buffer
echo bufname("file2") " name of buffer where "file2" matches.
{buf}
(integer|string?
)
string
){buf}
[, {create}
]]) bufnr():ls
command. For the use of {buf}
, see bufname()
above.
If the buffer doesn't exist, -1 is returned. Or, if the
{create}
argument is present and TRUE, a new, unlisted,
buffer is created and its number is returned.
bufnr("$") is the last buffer:let last_buffer = bufnr("$")
{buf}
(integer|string?
)
{create}
(any?
)
integer
){buf}
) bufwinid(){buf}
. For the use of {buf}
,
see bufname() above. If buffer {buf}
doesn't exist or
there is no such window, -1 is returned. Example:echo "A window containing buffer 1 is " .. (bufwinid(1))
{buf}
(any
)
integer
){buf}
) bufwinnr(){buf}
doesn't exist or there is no such window, -1
is returned. Example:echo "A window containing buffer 1 is " .. (bufwinnr(1))
{buf}
(any
)
integer
){byte}
) byte2line(){byte}
in the current buffer. This includes the
end-of-line character, depending on the 'fileformat' option
for the current buffer. The first character has byte count
one.
Also see line2byte(), go and :goto.{byte}
value is invalid.{byte}
(any
)
integer
){expr}
, {nr}
[, {utf16}
]) byteidx(){nr}
th character in the String
{expr}
. Use zero for the first character, it then returns
zero.
If there are no multibyte characters the returned value is
equal to {nr}
.
Composing characters are not counted separately, their byte
length is added to the preceding base character. See
byteidxcomp() below for counting composing characters
separately.
When {utf16}
is present and TRUE, {nr}
is used as the UTF-16
index in the String {expr}
instead of as the character index.
The UTF-16 index is the index in the string when it is encoded
with 16-bit words. If the specified UTF-16 index is in the
middle of a character (e.g. in a 4-byte character), then the
byte index of the first byte in the character is returned.
Refer to string-offset-encoding for more information.
Example :echo matchstr(str, ".", byteidx(str, 3))
let s = strpart(str, byteidx(str, 3))
echo strpart(s, 0, byteidx(s, 1))
{nr}
characters -1 is returned.
If there are exactly {nr}
characters the length of the string
in bytes is returned.
See charidx() and utf16idx() for getting the character and
UTF-16 index respectively from the byte index.
Examples:echo byteidx('a😊😊', 2) " returns 5
echo byteidx('a😊😊', 2, 1) " returns 1
echo byteidx('a😊😊', 3, 1) " returns 5
{expr}
(any
)
{nr}
(integer
)
{utf16}
(any?
)
integer
){expr}
, {nr}
[, {utf16}
]) byteidxcomp()let s = 'e' .. nr2char(0x301)
echo byteidx(s, 1)
echo byteidxcomp(s, 1)
echo byteidxcomp(s, 2)
{expr}
(any
)
{nr}
(integer
)
{utf16}
(any?
)
integer
){func}
, {arglist}
[, {dict}
]) call() E699
Call function {func}
with the items in List {arglist}
as
arguments.
{func}
can either be a Funcref or the name of a function.
a:firstline and a:lastline are set to the cursor line.
Returns the return value of the called function.
{dict}
is for functions with the "dict" attribute. It will be
used to set the local variable "self". Dictionary-function{func}
(any
)
{arglist}
(any
)
{dict}
(any?
)
any
){expr}
) ceil(){expr}
as a Float (round up).
{expr}
must evaluate to a Float or a Number.
Examples:echo ceil(1.456)
echo ceil(-5.456)
echo ceil(4.0)
{expr}
(number
)
number
){id}
[, {stream}
]) chanclose(){stream}
can be one of "stdin", "stdout",
"stderr" or "rpc" (closes stdin/stdout for a job started
with "rpc":v:true
) If {stream}
is omitted, all streams
are closed. If the channel is a pty, this will then close the
pty master, sending SIGHUP to the job process.
For a socket, there is only one stream, and {stream}
should be
omitted.{id}
(integer
)
{stream}
(string?
)
0|1
)integer
){id}
, {data}
) chansend(){id}
. For a job, it writes it to the
stdin of the process. For the stdio channel channel-stdio,
it writes to Nvim's stdout. Returns the number of bytes
written if the write succeeded, 0 otherwise.
See channel-bytes for more information.{data}
may be a string, string convertible, Blob, or a list.
If {data}
is a list, the items will be joined by newlines; any
newlines in an item will be sent as NUL. To send a final
newline, include a final empty string. Example:call chansend(id, ["abc", "123\n456", ""])
"rpc":v:true
then the channel expects RPC
messages, use rpcnotify() and rpcrequest() instead.{id}
(number
)
{data}
(string|string[]
)
0|1
){string}
[, {utf8}
]) char2nr(){string}
.
Examples:echo char2nr(" ") " returns 32
echo char2nr("ABC") " returns 65
echo char2nr("á") " returns 225
echo char2nr("á"[0]) " returns 195
echo char2nr("\<M-x>") " returns 128
{utf8}
is ignored, it exists only for backwards-compatibility.
A combining character is a separate character.
nr2char() does the opposite.{string}
is not a String.{string}
(string
)
{utf8}
(any?
)
0|1
){string}
) charclass(){string}
.
The character class is one of:
0 blank
1 punctuation
2 word character (depends on 'iskeyword')
3 emoji
other specific Unicode class
The class is used in patterns and word motions.
Returns 0 if {string}
is not a String.{string}
(string
)
0|1|2|3|'other'
){expr}
[, {winid}
]) charcol(){expr}
instead of the byte position.echo charcol('.') " returns 3
echo col('.') " returns 7
{expr}
(string|any[]
)
{winid}
(integer?
)
integer
){string}
, {idx}
[, {countcc}
[, {utf16}
]]) charidx(){idx}
in {string}
.
The index of the first character is zero.
If there are no multibyte characters the returned value is
equal to {idx}
.{countcc}
is omitted or FALSE, then composing characters
are not counted separately, their byte length is added to the
preceding base character.
When {countcc}
is TRUE, then composing characters are
counted as separate characters.{utf16}
is present and TRUE, {idx}
is used as the UTF-16
index in the String {expr}
instead of as the byte index.{idx}
bytes. If there are exactly {idx}
bytes the length
of the string in characters is returned.echo charidx('áb́ć', 3) " returns 1
echo charidx('áb́ć', 6, 1) " returns 4
echo charidx('áb́ć', 16) " returns -1
echo charidx('a😊😊', 4, 0, 1) " returns 2
{string}
(string
)
{idx}
(integer
)
{countcc}
(boolean?
)
{utf16}
(boolean?
)
integer
){dir}
) chdir(){dir}
. The scope of
the directory change depends on the directory of the current
window:
{dir}
must be a String.
If successful, returns the previous working directory. Pass
this to another chdir() to restore the directory.
On failure, returns an empty string.
let save_dir = chdir(newdir)
if save_dir != ""
" ... do some work
call chdir(save_dir)
endif
{dir}
(string
)
string
){lnum}
) cindent(){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 -1 is returned.
See C-indenting.{lnum}
(integer
)
integer
){win}
]) clearmatches(){win}
is specified, use the window with this number or
window ID instead of the current window.{win}
(integer?
)
{expr}
[, {winid}
]) col(){expr}
.
For accepted positions see getpos().
When {expr}
is "$", it means the end of the cursor line, so
the result is the number of bytes in the cursor line plus one.
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.{winid}
argument the values are obtained for
that window instead of the current window.echo col(".") " column of cursor
echo col("$") " length of cursor line plus one
echo col("'t") " column of mark t
echo col("'" .. markname) " column of mark markname
{expr}
is invalid or when
the window with ID {winid}
is not found.
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. Also, when using a <Cmd>
mapping the cursor isn't
moved, this can be used to obtain the column in Insert mode:imap <F2> <Cmd>echo col(".").."\n"<CR>
{expr}
(string|any[]
)
{winid}
(integer?
)
integer
){startcol}
, {matches}
) complete() E785
Set the matches for Insert mode completion.
Can only be used in Insert mode. You need to use a mapping
with CTRL-R
= (see i_CTRL-R). It does not work after CTRL-O
or with an expression mapping.
{startcol}
is the byte offset in the line where the completed
text start. The text up to the cursor is the original text
that will be replaced by the matches. Use col('.') for an
empty string. "col('.') - 1" will replace one character by a
match.
{matches}
must be a List. Each List item is one match.
See complete-items for the kind of items that are possible.
"longest" in 'completeopt' is ignored.
Note that the after calling this function you need to avoid
inserting anything that would cause completion to stop.
The match can be selected with CTRL-N
and CTRL-P
as usual with
Insert mode completion. The popup menu will appear if
specified, see ins-completion-menu.
Example:inoremap <F5> <C-R>=ListMonths()<CR>
func ListMonths()
call complete(col('.'), ['January', 'February', 'March',
\ 'April', 'May', 'June', 'July', 'August', 'September',
\ 'October', 'November', 'December'])
return ''
endfunc
{startcol}
(integer
)
{matches}
(any[]
)
{expr}
) complete_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.{expr}
(any
)
0|1|2
)0|1
){what}
]) complete_info()<Up>
or
<Down>
keys)
completed Return a dictionary containing the entries of
the currently selected index item.
preview_winid Info floating preview window id.
preview_bufnr Info floating preview buffer id.CTRL-X
i_CTRL-X
"scroll" Scrolling with i_CTRL-X_CTRL-E or
i_CTRL-X_CTRL-Y
"whole_line" Whole lines i_CTRL-X_CTRL-L
"files" File names i_CTRL-X_CTRL-F
"tags" Tags i_CTRL-X_CTRL-]
"path_defines" Definition completion i_CTRL-X_CTRL-D
"path_patterns" Include completion i_CTRL-X_CTRL-I
"dictionary" Dictionary i_CTRL-X_CTRL-K
"thesaurus" Thesaurus i_CTRL-X_CTRL-T
"cmdline" Vim Command line i_CTRL-X_CTRL-V
"function" User defined completion i_CTRL-X_CTRL-U
"omni" Omni completion i_CTRL-X_CTRL-O
"spell" Spelling suggestions i_CTRL-X_s
"eval" complete() completion
"unknown" Other internal modes{what}
list argument is supplied, then only
the items listed in {what}
are returned. Unsupported items in
{what}
are silently ignored." Get all items
call complete_info()
" Get only 'mode'
call complete_info(['mode'])
" Get only 'mode' and 'pum_visible'
call complete_info(['mode', 'pum_visible'])
{what}
(any[]?
)
table
){msg}
[, {choices}
[, {default}
[, {type}
]]]) confirm(){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")
confirm("file has been modified", "&Save\nSave &All")
{type}
String argument gives the type of dialog.
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.{type}
argument gives the type of dialog. This
is only used for the icon of the 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.<Esc>
, CTRL-C
,
or another valid interrupt key, confirm() returns 0.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
{msg}
(string
)
{choices}
(string?
)
{default}
(integer?
)
{type}
(string?
)
integer
){expr}
) copy(){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.
A Dictionary is copied in a similar way as a List.
Also see deepcopy().{expr}
(T
)
T
){expr}
) cos(){expr}
, measured in radians, as a Float.
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo cos(100)
echo cos(-4.01)
{expr}
(number
)
number
){expr}
) cosh(){expr}
as a Float in the range
[1, inf].
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo cosh(0.5)
echo cosh(-0.5)
{expr}
(number
)
number
){comp}
, {expr}
[, {ic}
[, {start}
]]) count() E706
Return the number of times an item with value {expr}
appears
in String, List or Dictionary {comp}
.{ic}
is given and it's TRUE then case is ignored.{comp}
is a string then the number of not overlapping
occurrences of {expr}
is returned. Zero is returned when
{expr}
is an empty string.{comp}
(string|table|any[]
)
{expr}
(any
)
{ic}
(boolean?
)
{start}
(integer?
)
integer
){index}
]) ctxget(){index}
from the top of the context-stack (see context-dict).
If {index}
is not given, it is assumed to be 0 (i.e.: top).{index}
(integer?
)
table
)any
){types}
]) ctxpush(){types}
is given and is a List of Strings, it specifies
which context-types to include in the pushed context.
Otherwise, all context types are included.{types}
(string[]?
)
any
){context}
[, {index}
]) ctxset(){index}
from the top of the
context-stack to that represented by {context}
.
{context}
is a Dictionary with context data (context-dict).
If {index}
is not given, it is assumed to be 0 (i.e.: top).{context}
(table
)
{index}
(integer?
)
integer
)any
){lnum}
, {col}
[, {off}
]) cursor(){list}
)
Positions the cursor at the column (byte count) {col}
in the
line {lnum}
. The first column is one.{list}
this is used as a List
with two, three or four item:
[{lnum}
, {col}
]
[{lnum}
, {col}
, {off}
]
[{lnum}
, {col}
, {off}
, {curswant}
]
This is like the return value of getpos() or getcurpos(),
but without the first item.{col}
as the character count, use
setcursorcharpos().{lnum}
is used like with getline(), except that if {lnum}
is
zero, the cursor will stay in the current line.
If {lnum}
is greater than the number of lines in the buffer,
the cursor will be positioned at the last line in the buffer.
If {col}
is greater than the number of bytes in the line,
the cursor will be positioned at the last character in the
line.
If {col}
is zero, the cursor will stay in the current column.
If {curswant}
is given it is used to set the preferred column
for vertical movement. Otherwise {col}
is used.{off}
specifies 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.{list}
(integer[]
)
any
){pid}
) debugbreak(){pid}
to get a SIGTRAP. Behavior for other
processes is undefined. See terminal-debug.
(Sends a SIGINT to a process {pid}
other than MS-Windows){pid}
(integer
)
any
){expr}
[, {noref}
]) deepcopy() E698
Make a copy of {expr}
. For Numbers and Strings this isn't
different from using {expr}
directly.
When {expr}
is a List a full copy is created. This means
that the original List can be changed without changing the
copy, and vice versa. When an item is a List, a copy for it
is made, recursively. Thus changing an item in the copy does
not change the contents of the original List.{noref}
is omitted or zero a contained List or
Dictionary is only copied once. All references point to
this single copy. With {noref}
set to 1 every occurrence of a
List or Dictionary results in a new copy. This also means
that a cyclic reference causes deepcopy() to fail.
E724 {noref}
set to 1 will fail.
Also see copy().{expr}
(T
)
{noref}
(boolean?
)
T
){fname}
[, {flags}
]) delete(){flags}
or with {flags}
empty: Deletes the file by the
name {fname}
.{fname}
is a symbolic link. The symbolic
link itself is deleted, not what it points to.{flags}
is "d": Deletes the directory by the name
{fname}
. This fails when directory {fname}
is not empty.{flags}
is "rf": Deletes the directory by the name
{fname}
and everything in it, recursively. BE CAREFUL!
Note: on MS-Windows it is not possible to delete a directory
that is being used.{fname}
(string
)
{flags}
(string?
)
integer
){buf}
, {first}
[, {last}
]) deletebufline(){first}
to {last}
(inclusive) from buffer {buf}
.
If {last}
is omitted then delete line {first}
only.
On success 0 is returned, on failure 1 is returned.{buf}
, see bufname() above.{first}
and {last}
are used like with getline(). Note that
when using line() this refers to the current buffer. Use "$"
to refer to the last line in buffer {buf}
.{buf}
(integer|string
)
{first}
(integer|string
)
{last}
(integer|string?
)
any
){dict}
, {pattern}
, {callback}
) dictwatcheradd(){dict}
);
{pattern}
).
{callback}
).
{dict}
and on keys
matching {pattern}
will result in {callback}
being invoked.silent! call dictwatcherdel(g:, '*', 'OnDictChanged')
function! OnDictChanged(d,k,z)
echomsg string(a:k) string(a:z)
endfunction
call dictwatcheradd(g:, '*', 'OnDictChanged')
{pattern}
only accepts very simple patterns that can
contain a "*" at the end of the string, in which case it will
match every key that begins with the substring before the "*".
That means if "*" is not the last character of {pattern}
, only
keys that are exactly equal as {pattern}
will be matched.{callback}
receives three arguments:old
and new
, the key was updated.
new
, the key was added.
old
, the key was deleted.
{dict}
(table
)
{pattern}
(string
)
{callback}
(function
)
any
){dict}
, {pattern}
, {callback}
) dictwatcherdel(){dict}
(any
)
{pattern}
(string
)
{callback}
(function
)
any
):setf FALLBACK
was used.
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.integer
){lnum}
) diff_filler(){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.{lnum}
(integer
)
integer
){lnum}
, {col}
) diff_hlID(){lnum}
column
{col}
(byte index). When the current line does not have a
diff change zero is returned.
{lnum}
is used like with getline(). Thus "." is the current
line, "'m" mark m, etc.
{col}
is 1 for the leftmost column, {lnum}
is 1 for the first
line.
The highlight ID can be used with synIDattr() to obtain
syntax information about the highlighting.{lnum}
(integer
)
{col}
(integer
)
any
){chars}
) digraph_get() E1214
Return the digraph of {chars}
. This should be a string with
exactly two characters. If {chars}
are not just two
characters, or the digraph of {chars}
does not exist, an error
is given and an empty string is returned." Get a built-in digraph
echo digraph_get('00') " Returns '∞'
" Get a user-defined digraph
call digraph_set('aa', 'あ')
echo digraph_get('aa') " Returns 'あ'
{chars}
(string
)
string
){listall}
]) digraph_getlist(){listall}
argument is given
and it is TRUE, return all digraphs, including the default
digraphs. Otherwise, return only user-defined digraphs." Get user-defined digraphs
echo digraph_getlist()
" Get all the digraphs, including default digraphs
echo digraph_getlist(1)
{listall}
(boolean?
)
string[][]
){chars}
, {digraph}
) digraph_set(){chars}
to the list. {chars}
must be a string
with two characters. {digraph}
is a string with one UTF-8
encoded character. E1215
Be careful, composing characters are NOT ignored. This
function is similar to :digraphs command, but useful to add
digraphs start with a white space.call digraph_set(' ', 'あ')
{chars}
(string
)
{digraph}
(string
)
any
){digraphlist}
) digraph_setlist(){digraphlist}
is a list composed of lists,
where each list contains two strings with {chars}
and
{digraph}
as in digraph_set(). E1216
Example:call digraph_setlist([['aa', 'あ'], ['ii', 'い']])
for [chars, digraph] in [['aa', 'あ'], ['ii', 'い']]
call digraph_set(chars, digraph)
endfor
{digraphlist}
(table<integer,string[]>
)
any
){expr}
) empty(){expr}
is empty, zero otherwise.
{expr}
(any
)
integer
)echo has_key(environ(), 'HOME')
echo index(keys(environ()), 'HOME', 0, 1) != -1
any
){string}
, {chars}
) escape(){chars}
that occur in {string}
with a
backslash. Example:echo escape('c:\program files\vim', ' \')
c:\\program\ files\\vim
{string}
(string
)
{chars}
(string
)
string
){string}
) eval(){string}
and return the result. Especially useful to
turn the result of string() back into the original value.
This works for Numbers, Floats, Strings, Blobs and composites
of them. Also works for Funcrefs that refer to existing
functions.{string}
(string
)
any
)any
){expr}
) executable(){expr}
exists. {expr}
must be the name of the program without any
arguments.{expr}
(string
)
0|1
){command}
[, {silent}
]) execute(){command}
and capture its output.
If {command}
is a String, returns {command}
output.
If {command}
is a List, returns concatenated outputs.
Line continuations in {command}
are not recognized.
Examples:echo execute('echon "foo"')
echo execute(['echon "foo"', 'echon "bar"'])
{silent}
argument can have these values:
"" no :silent
used
"silent" :silent
used
"silent!" :silent!
used
The default is "silent". Note that with "silent!", unlike
:redir
, error messages are dropped.split()
on the result:execute('args')->split("\n")
win_execute()
.{command}
(string|string[]
)
{silent}
(''|'silent'|'silent!'?
)
string
){expr}
) exepath(){expr}
if it is an executable and
given as a (partial or full) path or is found in $PATH.
Returns empty string otherwise.
If {expr}
starts with "./" the current-directory is used.{expr}
(string
)
string
){expr}
argument is a string, which contains one of these:
varname internal variable (see
dict.key internal-variables). Also works
list[i] 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]")
echo exists("l[xx]")
*funcname
built-in function (see functions)
or user defined function (see
user-function). Also works for a
variable that is a Funcref.
:cmdname Ex command: built-in command, user
command or command modifier :command.
Returns:
1 for match with start of a command
2 full match with a command
3 matches several user commands
To check for a supported command
always check the return value to be 2.
:2match The :2match command.
:3match The :3match command (but you
probably should not use it, it is
reserved for internal usage)
#event autocommand defined for this event
#event#pattern autocommand defined for this event and
pattern (the pattern is taken
literally and compared to the
autocommand patterns character by
character)
#group autocommand group exists
#group#event autocommand defined for this group and
event.
#group#event#pattern
autocommand defined for this group,
event and pattern.
##event autocommand for this event is
supported.echo exists("&mouse")
echo exists("$HOSTNAME")
echo exists("*strftime")
echo exists("*s:MyFunc")
echo exists("*MyFunc")
echo exists("*v:lua.Func")
echo exists("bufcount")
echo exists(":Make")
echo exists("#CursorHold")
echo exists("#BufReadPre#*.gz")
echo exists("#filetypeindent")
echo exists("#filetypeindent#FileType")
echo exists("#filetypeindent#FileType#*")
echo exists("##ColorScheme")
echo exists(":make")
echo exists(":make install")
echo exists(bufcount)
{expr}
(string
)
0|1
){expr}
) exp(){expr}
as a Float in the range
[0, inf].
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo exp(2)
echo exp(-1)
{expr}
(number
)
any
){string}
[, {nosuf}
[, {list}
]]) expand(){string}
. 'wildignorecase' applies.{list}
is given and it is TRUE, a List will be returned.
Otherwise the result is a String and when there are several
matches, they are separated by <NL>
characters.{string}
does
not start with '%', '#' or '<', see below.{string}
starts with '%', '#' or '<', the expansion is
done like for the cmdline-special variables with their
associated modifiers. Here is a short overview:<cfile>
file name under the cursor
<afile>
autocmd file name
<abuf>
autocmd buffer number (as a String!)
<amatch>
autocmd matched name
<cexpr>
C expression under the cursor
<sfile>
sourced script file or function name
<slnum>
sourced script line number or function
line number
<sflnum>
script file line number, also when in
a function
<SID>
"<SNR>123_" where "123" is the
current script ID <SID>
<script>
sourced script file, or script file
where the current function was defined
<stack>
call stack
<cword>
word under the cursor
<cWORD>
WORD under the cursor
<client>
the {clientid}
of the last received
message
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 onlylet &tags = expand("%:p:h") .. "/tags"
let doesntwork = expand("%:h.bak")
let doeswork = expand("%:h") .. ".bak"
echo expand(expand("<cfile>"))
{string}
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
{nosuf}
argument is given and it is TRUE.
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")
{string}
(string
)
{nosuf}
(boolean?
)
{list}
(nil|false?
)
string
){string}
[, {options}
]) expandcmd(){string}
like what is done for
an Ex command such as :edit
. This expands special keywords,
like with expand(), and environment variables, anywhere in
{string}
. "~user" and "~/path" are only expanded at the
start.{options}
Dict
argument:
errmsg If set to TRUE, error messages are displayed
if an error is encountered during expansion.
By default, error messages are not displayed.{string}
is returned.echo expandcmd('make %<.o')
make /path/runtime/doc/builtin.o
echo expandcmd('make %<.o', {'errmsg': v:true})
{string}
(string
)
{options}
(table?
)
any
){expr1}
, {expr2}
[, {expr3}
]) extend(){expr1}
and {expr2}
must be both Lists or both
Dictionaries.{expr2}
to {expr1}
.
If {expr3}
is given insert the items of {expr2}
before the
item with index {expr3}
in {expr1}
. When {expr3}
is zero
insert before the first item. When {expr3}
is equal to
len({expr1}
) then {expr2}
is appended.
Examples:echo sort(extend(mylist, [7, 5]))
call extend(mylist, [2, 3], 1)
{expr1}
is the same List as {expr2}
then the number of
items copied is equal to the original length of the List.
E.g., when {expr3}
is 1 you get N new copies of the first item
(where N is the original length of the List).
Use add() to concatenate one item to a list. To concatenate
two lists into a new list use the + operator:let newlist = [1, 2, 3] + [4, 5]
{expr2}
to {expr1}
.
If a key exists in both {expr1}
and {expr2}
then {expr3}
is
used to decide what to do:
{expr3}
= "keep": keep the value of {expr1}
{expr3}
= "force": use the value of {expr2}
{expr3}
= "error": give an error message E737 {expr3}
is omitted then "force" is assumed.{expr1}
is changed when {expr2}
is not empty. If necessary
make a copy of {expr1}
first.
{expr2}
remains unchanged.
When {expr1}
is locked and {expr2}
is not empty the operation
fails.
Returns {expr1}
. Returns 0 on error.{expr1}
(table
)
{expr2}
(table
)
{expr3}
(table?
)
any
){expr1}
, {expr2}
[, {expr3}
]) extendnew(){expr1}
a new
List or Dictionary is created and returned. {expr1}
remains
unchanged.{expr1}
(table
)
{expr2}
(table
)
{expr3}
(table?
)
any
){string}
[, {mode}
]) feedkeys(){string}
are queued for processing as if they
come from a mapping or were typed by the user.{string}
.{string}
, use double-quotes
and "\..." notation expr-quote. For example,
feedkeys("\<CR>") simulates pressing of the <Enter>
key. But
feedkeys('\<CR>
') pushes 5 characters.
The <Ignore> keycode may be used to exit the
wait-for-character without doing anything.{mode}
is a String, which can contain these character flags:
'm' Remap keys. This is default. If {mode}
is absent,
keys are remapped.
'n' Do not remap keys.
't' Handle keys as if typed; otherwise they are handled as
if coming from a mapping. This matters for undo,
opening folds, etc.
'L' Lowlevel input. Other flags are not used.
'i' Insert the string instead of appending (see above).
'x' Execute commands until typeahead is empty. This is
similar to using ":normal!". You can call feedkeys()
several times without 'x' and then one time with 'x'
(possibly with an empty {string}
) to execute all the
typeahead. Note that when Vim ends in Insert mode it
will behave as if <Esc>
is typed, to avoid getting
stuck, waiting for a character to be typed before the
script continues.
Note that if you manage to call feedkeys() while
executing commands, thus calling it recursively, then
all typeahead will be consumed by the last call.
'!' When used with 'x' will not end Insert mode. Can be
used in a test when a timer is set to exit Insert mode
a little later. Useful for testing CursorHoldI.{string}
(string
)
{mode}
(string?
)
any
){from}
, {to}
) filecopy(){from}
to {to}
. The
result is a Number, which is TRUE if the file was copied
successfully, and FALSE when it failed.
If a file with name {to}
already exists, it will fail.
Note that it does not handle directories (yet).{from}
(string
)
{to}
(string
)
0|1
){file}
) filereadable(){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}
is used as-is, you may want to expand wildcards first:echo filereadable('~/.vimrc')
0
echo filereadable(expand('~/.vimrc'))
1
{file}
(string
)
0|1
){file}
) filewritable(){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.{file}
(string
)
0|1
){expr1}
, {expr2}
) filter(){expr1}
must be a List, String, Blob or Dictionary.
For each item in {expr1}
evaluate {expr2}
and when the result
is zero or false remove the item from the List or
Dictionary. Similarly for each byte in a Blob and each
character in a String.{expr2}
is a string, inside {expr2}
v:val has the value
of the current item. For a Dictionary v:key has the key
of the current item and for a List v:key has the index of
the current item. For a Blob v:key has the index of the
current byte. For a String v:key has the index of the
current character.
Examples:call filter(mylist, 'v:val !~ "OLD"')
call filter(mydict, 'v:key >= 8')
call filter(var, 0)
{expr2}
is the result of expression and is then
used as an expression again. Often it is good to use a
literal-string to avoid having to double backslashes.{expr2}
is a Funcref it must take two arguments:
1. the key or the index of the current item.
2. the value of the current item.
The function must return TRUE if the item should be kept.
Example that keeps the odd items of a list:func Odd(idx, val)
return a:idx % 2 == 1
endfunc
call filter(mylist, function('Odd'))
call filter(myList, {idx, val -> idx * val <= 42})
call filter(myList, {idx -> idx % 2 == 1})
let l = filter(copy(mylist), 'v:val =~ "KEEP"')
{expr1}
, the List or Dictionary that was filtered,
or a new Blob or String.
When an error is encountered while evaluating {expr2}
no
further items in {expr1}
are processed.
When {expr2}
is a Funcref errors inside a function are ignored,
unless it was defined with the "abort" flag.{expr1}
(string|table
)
{expr2}
(string|function
)
any
){name}
[, {path}
[, {count}
]]) finddir(){name}
in {path}
. Supports both downwards and
upwards recursive directory searches. See file-searching
for the syntax of {path}
.{path}
is omitted or empty then 'path' is used.{count}
is given, find {count}
's occurrence of
{name}
in {path}
instead of the first one.
When {count}
is negative return all the matches in a List.:find
.{name}
(string
)
{path}
(string?
)
{count}
(integer?
)
any
){name}
[, {path}
[, {count}
]]) findfile()echo findfile("tags.vim", ".;")
{name}
(string
)
{path}
(string?
)
{count}
(any?
)
any
){list}
[, {maxdepth}
]) flatten(){list}
up to {maxdepth}
levels. Without {maxdepth}
the result is a List without nesting, as if {maxdepth}
is
a very large number.
The {list}
is changed in place, use flattennew() if you do
not want that.
E900 {maxdepth}
means how deep in nested lists changes are made.
{list}
is not modified when {maxdepth}
is 0.
{maxdepth}
must be positive number.echo flatten([1, [2, [3, 4]], 5])
echo flatten([1, [2, [3, 4]], 5], 1)
{list}
(any[]
)
{maxdepth}
(integer?
)
any[]|0
){list}
(any[]
)
{maxdepth}
(integer?
)
any[]|0
){expr}
) float2nr(){expr}
to a Number by omitting the part after the
decimal point.
{expr}
must evaluate to a Float or a Number.
Returns 0 if {expr}
is not 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 (or when
64-bit Number support is enabled, 0x7fffffffffffffff or
-0x7fffffffffffffff). NaN results in -0x80000000 (or when
64-bit Number support is enabled, -0x8000000000000000).
Examples:echo float2nr(3.95)
echo float2nr(-23.45)
echo float2nr(1.0e100)
echo float2nr(-1.0e150)
echo float2nr(1.0e-100)
{expr}
(number
)
any
){expr}
) floor(){expr}
as a Float (round down).
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo floor(1.856)
echo floor(-5.456)
echo floor(4.0)
{expr}
(number
)
any
){expr1}
, {expr2}
) fmod(){expr1}
/ {expr2}
, even if the
division is not representable. Returns {expr1}
- i * {expr2}
for some integer i such that if {expr2}
is non-zero, the
result has the same sign as {expr1}
and magnitude less than
the magnitude of {expr2}
. If {expr2}
is zero, the value
returned is zero. The value returned is a Float.
{expr1}
and {expr2}
must evaluate to a Float or a Number.
Returns 0.0 if {expr1}
or {expr2}
is not a Float or a
Number.
Examples:echo fmod(12.33, 1.22)
echo fmod(-12.33, 1.22)
{expr1}
(number
)
{expr2}
(number
)
any
){string}
) fnameescape(){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).
Returns an empty string on error.
Example:let fname = '+some str%nge|name'
exe "edit " .. fnameescape(fname)
edit \+some\ str\%nge\|name
{string}
(string
)
string
){fname}
, {mods}
) fnamemodify(){fname}
according to {mods}
. {mods}
is a
string of characters like it is used for file names on the
command line. See filename-modifiers.
Example:echo fnamemodify("main.c", ":p:h")
/home/user/vim/vim/src
{mods}
is empty or an unsupported modifier is used then
{fname}
is returned.
When {fname}
is empty then with {mods}
":h" returns ".", so
that :cd
can be used with it. This is different from
expand('%:h') without a buffer name, which returns an empty
string.
Note: Environment variables don't work in {fname}
, use
expand() first then.{fname}
(string
)
{mods}
(string
)
string
){lnum}
) foldclosed(){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.
{lnum}
is used like with getline(). Thus "." is the current
line, "'m" mark m, etc.{lnum}
(integer
)
integer
){lnum}
) foldclosedend(){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.
{lnum}
is used like with getline(). Thus "." is the current
line, "'m" mark m, etc.{lnum}
(integer
)
integer
){lnum}
) foldlevel(){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.
{lnum}
is used like with getline(). Thus "." is the current
line, "'m" mark m, etc.{lnum}
(integer
)
integer
)+-- 45 lines: abcdef
string
){lnum}
) foldtextresult(){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.{lnum}
(integer
)
string
){expr1}
, {expr2}
) foreach(){expr1}
must be a List, String, Blob or Dictionary.
For each item in {expr1}
execute {expr2}
. {expr1}
is not
modified; its values may be, as with :lockvar 1. E741
See map() and filter() to modify {expr1}
.{expr2}
is a string, inside {expr2}
v:val has the value
of the current item. For a Dictionary v:key has the key
of the current item and for a List v:key has the index of
the current item. For a Blob v:key has the index of the
current byte. For a String v:key has the index of the
current character.
Examples:call foreach(mylist, 'let used[v:val] = v:true')
{expr1}
list.{expr2}
is the result of expression and is then used
as a command. Often it is good to use a literal-string to
avoid having to double backslashes.{expr2}
is a Funcref it must take two arguments:
1. the key or the index of the current item.
2. the value of the current item.
With a lambda you don't get an error if it only accepts one
argument.
If the function returns a value, it is ignored.{expr1}
in all cases.
When an error is encountered while executing {expr2}
no
further items in {expr1}
are processed.
When {expr2}
is a Funcref errors inside a function are ignored,
unless it was defined with the "abort" flag.{expr1}
(string|table
)
{expr2}
(string|function
)
string|table
){name}
) fullcommand(){name}
may start with a :
and can
include a [range], these are skipped and not returned.
Returns an empty string if a command doesn't exist or if it's
ambiguous (for user-defined commands).fullcommand('s')
, fullcommand('sub')
,
fullcommand(':%substitute')
all return "substitute".{name}
(string
)
string
){name}
[, {arglist}
] [, {dict}
]) funcref(){name}
is redefined later.{name}
must be an existing user function.
It only works for an autoloaded function if it has already
been loaded (to avoid mistakenly loading the autoload script
when only intending to use the function name, use function()
instead). {name}
cannot be a builtin function.
Returns 0 on error.{name}
(string
)
{arglist}
(any?
)
{dict}
(any?
)
any
){name}
[, {arglist}
] [, {dict}
]) function() partial E700 E923
Return a Funcref variable that refers to function {name}
.
{name}
can be the name of a user defined function or an
internal function.{name}
can also be a Funcref or a partial. When it is a
partial the dict stored in it will be used and the {dict}
argument is not allowed. E.g.:let FuncWithArg = function(dict.Func, [arg])
let Broken = function(dict.Func, [arg], dict)
{name}
,
also when it was redefined later. Use funcref() to keep the
same function.{arglist}
or {dict}
is present this creates a partial.
That means the argument list and/or the dictionary is stored in
the Funcref and will be used when the Funcref is called.func Callback(arg1, arg2, name)
"...
endfunc
let Partial = function('Callback', ['one', 'two'])
"...
call Partial('name')
call Callback('one', 'two', 'name')
func Callback(one, two, three)
"...
endfunc
let Partial = function('Callback', ['two'])
"...
eval 'one'->Partial('three')
call Callback('one', 'two', 'three')
func Callback(arg1, arg2, name)
"...
endfunc
let Func = function('Callback', ['one'])
let Func2 = function(Func, ['two'])
"...
call Func2('name')
call Callback('one', 'two', 'name')
{dict}
is passed in as "self". Example:function Callback() dict
echo "called for " .. self.name
endfunction
"...
let context = {"name": "example"}
let Func = function('Callback', context)
"...
call Func() " will echo: called for example
let Func = function('Callback', context)
let Func = context.Callback
function Callback(arg1, count) dict
"...
endfunction
let context = {"name": "example"}
let Func = function('Callback', ['one'], context)
"...
call Func(500)
call context.Callback('one', 500)
{name}
(string
)
{arglist}
(any?
)
{dict}
(any?
)
any
){atexit}
]) garbagecollect(){atexit}
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.{atexit}
(boolean?
)
any
){list}
, {idx}
[, {default}
]) get() get()-list
Get item {idx}
from List {list}
. When this item is not
available return {default}
. Return zero when {default}
is
omitted.{list}
(any[]
)
{idx}
(integer
)
{default}
(any?
)
any
){blob}
, {idx}
[, {default}
]) get()-blob{idx}
from Blob {blob}
. When this byte is not
available return {default}
. Return -1 when {default}
is
omitted.{blob}
(string
)
{idx}
(integer
)
{default}
(any?
)
any
){dict}
, {key}
[, {default}
]) get()-dict{key}
from Dictionary {dict}
. When this
item is not available return {default}
. Return zero when
{default}
is omitted. Useful example:let val = get(g:, 'var_name', 'default')
{dict}
(table<string,any>
)
{key}
(string
)
{default}
(any?
)
any
){func}
, {what}
) get()-func{what}
from Funcref {func}
. Possible values for
{what}
are:
"name" The function name
"func" The function
"dict" The dictionary
"args" The list with arguments
"arity" A dictionary with information about the number of
arguments accepted by the function (minus the
{arglist}
) with the following fields:
required the number of positional arguments
optional the number of optional arguments,
in addition to the required ones
varargs TRUE if the function accepts a
variable number of arguments ...{arglist}
of
the Funcref contains more arguments than the
Funcref expects, it's not validated.{func}
(function
)
{what}
(string
)
any
){buf}
]) getbufinfo(){dict}
])
Get information about buffers as a List of Dictionaries.{dict}
:
buflisted include only listed buffers.
bufloaded include only loaded buffers.
bufmodified include only modified buffers.{buf}
specifies a particular buffer to return
information for. For the use of {buf}
, see bufname()
above. If the buffer is found the returned List has one item.
Otherwise the result is an empty list.echo line('.', {winid})
for buf in getbufinfo()
echo buf.name
endfor
for buf in getbufinfo({'buflisted':1})
if buf.changed
" ....
endif
endfor
getbufvar({bufnr}, '&option_name')
{dict}
(vim.fn.getbufinfo.dict?
)
vim.fn.getbufinfo.ret.item[]
){buf}
, {lnum}
[, {end}
]) getbufline(){lnum}
to {end}
(inclusive) in the buffer {buf}
. If {end}
is omitted, a
List with only the line {lnum}
is returned. See
getbufoneline()
for only getting the line.{buf}
, see bufname() above.{lnum}
and {end}
"$" can be used for the last line of the
buffer. Otherwise a number must be used.{lnum}
is smaller than 1 or bigger than the number of
lines in the buffer, an empty List is returned.{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.let lines = getbufline(bufnr("myfile"), 1, "$")
{buf}
(integer|string
)
{lnum}
(integer
)
{end}
(integer?
)
string[]
){buf}
, {lnum}
) getbufoneline()getbufline()
but only get one line and return it
as a string.{buf}
(integer|string
)
{lnum}
(integer
)
string
){buf}
, {varname}
[, {def}
]) getbufvar(){varname}
in buffer {buf}
. Note that the name without "b:"
must be used.
The {varname}
argument is a string.
When {varname}
is empty returns a Dictionary with all the
buffer-local variables.
When {varname}
is equal to "&" returns a Dictionary with all
the buffer-local options.
Otherwise, when {varname}
starts with "&" returns the value of
a buffer-local option.
This also works for a global or buffer-local option, but it
doesn't work for a global variable, window-local variable or
window-local option.
For the use of {buf}
, see bufname() above.
When the buffer or variable doesn't exist {def}
or an empty
string is returned, there is no error message.
Examples: let bufmodified = getbufvar(1, "&mod")
echo "todo myvar = " .. getbufvar("todo", "myvar")
Parameters: ~
• {buf} (`integer|string`)
• {varname} (`string`)
• {def} (`any?`)
Return: ~
(`any`)
getcellwidths() getcellwidths()any
){buf}
]) getchangelist(){buf}
. For the use
of {buf}
, see bufname() above. If buffer {buf}
doesn't
exist, an empty list is returned.{buf}
is the current buffer, then the current
position refers to the position in the list. For other
buffers, it is set to the length of the list.{buf}
(integer|string?
)
table[]
){expr}
]) getchar(){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.
If you prefer always getting a string use getcharstr().{expr}
and when {expr}
is 0 a whole character or
special key is returned. If it is a single 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 String with 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.{expr}
is 0 and Esc is typed, there will be a short delay
while Vim waits to see if this is the start of an escape
sequence.{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.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
<Del>
key you get the code for the <Del>
key, not the raw character
sequence. Examples:getchar() == "\<Del>"
getchar() == "\<S-Left>"
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
{expr}
(0|1?
)
integer
)integer
){expr}
) getcharpos(){expr}
. Same as getpos() but the
column number in the returned List is a character index
instead of a byte index.
If getpos() returns a very large column number, equal to
v:maxcol, then getcharpos() will return the character index
of the last character.getcharpos('.') returns [0, 5, 3, 0]
getpos('.') returns [0, 5, 7, 0]
{expr}
(string
)
integer[]
){dict}
with the following entries:nnoremap <expr> ; getcharsearch().forward ? ';' : ','
nnoremap <expr> , getcharsearch().forward ? ',' : ';'
table
){expr}
]) getcharstr(){expr}
is omitted, wait until a character is available.
If {expr}
is 0 or false, only get a character when one is
available. Return an empty string otherwise.
If {expr}
is 1 or true, only check if a character is
available, it is not consumed. Return an empty string
if no character is available.
Otherwise this works like getchar(), except that a number
result is converted to a string.{expr}
(0|1?
)
string
)string
)string
)cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
string
)integer
)string
)integer
)-
:insert or :append command
= i_CTRL-R_=
Only works when editing the command line, thus requires use of
c_CTRL-\_e or c_CTRL-R_= or an expression mapping.
Returns an empty string otherwise.
Also see getcmdpos(), setcmdpos() and getcmdline().':'|'>'|'/'|'?'|'@'|'-'|'='
)':'|'>'|'/'|'?'|'@'|'-'|'='
){pat}
, {type}
[, {filtered}
]) getcompletion(){type}
argument specifies what for. The following completion
types are supported:{func}
customlist,{func} custom completion, defined via {func}
diff_buffer :diffget and :diffput completion
dir directory names
dir_in_path directory names in 'cdpath'
environment environment variable names
event autocommand events
expression Vim expression
file file and directory names
file_in_path file and directory names in 'path'
filetype filetype names 'filetype'
function function name
help help subjects
highlight highlight groups
history :history suboptions
keymap keyboard mappings
locale locale names (as output of locale -a)
mapclear buffer argument
mapping mapping name
menu menus
messages :messages suboptions
option options
packadd optional package pack-add names
runtime :runtime completion
scriptnames sourced script names :scriptnames
shellcmd Shell command
shellcmdline Shell command line with filename arguments
sign :sign suboptions
syntax syntax file names 'syntax'
syntime :syntime suboptions
tag tags
tag_listfiles tags, file names
user user names
var user variables{pat}
is an empty string, then all the matches are
returned. Otherwise only items matching {pat}
are returned.
See wildcards for the use of special characters in {pat}
.{filtered}
flag is set to 1, then 'wildignore'
is applied to filter the results. Otherwise all the matches
are returned. The 'wildignorecase' option always applies.{type}
is "cmdline", then the cmdline-completion result is
returned. For example, to complete the possible values after
a ":call" command:echo getcompletion('call ', 'cmdline')
{type}
produces an error.{pat}
(string
)
{type}
(string
)
{filtered}
(boolean?
)
string[]
){winid}
]) getcurpos(){winid}
argument can specify the window. It can
be the window number or the window-ID. The last known
cursor position is returned, this may be invalid for the
current value of the buffer if it is not the current window.
If {winid}
is invalid a list with zeroes is returned.let save_cursor = getcurpos()
MoveTheCursorAround
call setpos('.', save_cursor)
{winid}
(integer?
)
any
){winid}
]) getcursorcharpos()getcursorcharpos() " returns [0, 3, 2, 0, 3]
getcurpos() " returns [0, 3, 4, 0, 3]
{winid}
(integer?
)
any
){winnr}
[, {tabnr}
]]) getcwd(){winnr}
or {tabnr}
the working
directory of that scope is returned, and 'autochdir' is
ignored.
Tabs and windows are identified by their respective numbers,
0 means current tab or window. Missing tab number implies 0.
Thus the following are equivalent:getcwd(0)
getcwd(0, 0)
{winnr}
is -1 it is ignored, only the tab is resolved.
{winnr}
can be the window number or the window-ID.
If both {winnr}
and {tabnr}
are -1 the global working
directory is returned.
Throw error if the arguments are invalid. E5000 E5001 E5002{winnr}
(integer?
)
{tabnr}
(integer?
)
string
){name}
) getenv(){name}
. The {name}
argument is a string, without a leading '$'. Example:myHome = getenv('HOME')
{name}
(string
)
string
){name}
]) getfontname(){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.{name}
(string?
)
string
){fname}
) getfperm(){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 "-". Examples:echo getfperm("/etc/passwd")
echo getfperm(expand("~/.config/nvim/init.vim"))
{fname}
(string
)
string
){fname}
) getfsize(){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.{fname}
(string
)
integer
){fname}
) getftime(){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.{fname}
(string
)
integer
){fname}
) getftype(){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")
{fname}
(string
)
'file'|'dir'|'link'|'bdev'|'cdev'|'socket'|'fifo'|'other'
){winnr}
only use this window in the current tab page.
{winnr}
can also be a window-ID.
With {winnr}
and {tabnr}
use the window in the specified tab
page. If {winnr}
or {tabnr}
is invalid, an empty list is
returned.{winnr}
(integer?
)
{tabnr}
(integer?
)
vim.fn.getjumplist.ret
){lnum}
[, {end}
]) getline(){end}
the result is a String, which is line {lnum}
from the current buffer. Example:getline(1)
{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(".")
{lnum}
is a number smaller than 1 or bigger than the
number of lines in the buffer, an empty string is returned.{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)
{lnum}
(integer|string
)
{end}
(nil|false?
)
string
){nr}
[, {what}
]) getloclist(){nr}
. {nr}
can be the window number or the window-ID.
When {nr}
is zero the current window is used.{nr}
, an empty list is
returned. Otherwise, same as getqflist().{what}
dictionary argument is supplied, then
returns the items listed in {what}
as a dictionary. Refer to
getqflist() for the supported items in {what}
.{what}
,
the following item is supported by getloclist():{nr}
.
Returns an empty Dictionary if window {nr}
does not exist.echo getloclist(3, {'all': 0})
echo getloclist(5, {'filewinid': 0})
{nr}
(integer
)
{what}
(table?
)
any
){buf}
]) getmarklist(){buf}
argument returns a List with information
about all the global marks. mark{buf}
argument is specified, returns the
local marks defined in buffer {buf}
. For the use of {buf}
,
see bufname(). If {buf}
is invalid, an empty list is
returned.{buf}
(integer??
)
vim.fn.getmarklist.ret.item[]
){win}
]) getmatches(){win}
is specified, use the window with this number or
window ID instead of the current window. If {win}
is invalid,
an empty list is returned.
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
{win}
(integer?
)
any
)vim.fn.getmousepos.ret
)integer
){expr}
) getpos(){expr}
.
The accepted values for {expr}
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 for all values).
w0 First line visible in current window (one if the
display isn't updated, e.g. in silent Ex mode).
w$ Last line visible in current window (this is one
less than "w0" if no lines are visible).
v When not in Visual mode, returns the cursor
position. In Visual mode, returns the other end
of the Visual area. A good way to think about
this is that in Visual mode "v" and "." complement
each other. While "." refers to the cursor
position, "v" refers to where v_o would move the
cursor. As a result, you can use "v" and "."
together to work on all of a selection in
characterwise Visual mode. If the cursor is at
the end of a characterwise Visual area, "v" refers
to the start of the same Visual area. And if the
cursor is at the start of a characterwise Visual
area, "v" refers to the end of the same Visual
area. "v" differs from '< and '> 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.<Tab>
or after the last
character.{expr}
is invalid, returns a list with all zeros.let save_a_mark = getpos("'a")
" ...
call setpos("'a", save_a_mark)
{expr}
(string
)
integer[]
){what}
]) getqflist()vimgrep /theword/jg *.c
for d in getqflist()
echo bufname(d.bufnr) ':' d.lnum '=' d.text
endfor
{what}
dictionary argument is supplied, then
returns only the items listed in {what}
as a dictionary. The
following string items are supported in {what}
:
changedtick get the total number of changes made
to the list quickfix-changedtick
context get the quickfix-context
efm errorformat to use when parsing "lines". If
not present, then the 'errorformat' option
value is used.
id get information for the quickfix list with
quickfix-ID; zero means the id for the
current list or the list specified by "nr"
idx get information for the quickfix entry at this
index in the list specified by "id" or "nr".
If set to zero, then uses the current entry.
See quickfix-index
items quickfix list entries
lines parse a list of lines using 'efm' and return
the resulting entries. Only a List type is
accepted. The current quickfix list is not
modified. See quickfix-parse.
nr get information for this quickfix list; zero
means the current quickfix list and "$" means
the last quickfix list
qfbufnr number of the buffer displayed in the quickfix
window. Returns 0 if the quickfix buffer is
not present. See quickfix-buffer.
size number of entries in the quickfix list
title get the list title quickfix-title
winid get the quickfix window-ID
all all of the above quickfix properties
Non-string items in {what}
are ignored. To get the value of a
particular item, set it to zero.
If "nr" is not present then the current quickfix list is used.
If both "nr" and a non-zero "id" are specified, then the list
specified by "id" is used.
To get the number of lists in the quickfix stack, set "nr" to
"$" in {what}
. The "nr" value in the returned dictionary
contains the quickfix stack size.
When "lines" is specified, all the other items except "efm"
are ignored. The returned dictionary contains the entry
"items" with the list of entries.echo getqflist({'all': 1})
echo getqflist({'nr': 2, 'title': 1})
echo getqflist({'lines' : ["F1:10:L10"]})
{what}
(table?
)
any
){regname}
[, 1 [, {list}
]]]) getreg(){regname}
. Example:let cliptext = getreg('*')
{regname}
was not set the result is an empty
string.
The {regname}
argument must be a string.{list}
is present and TRUE, the result type is changed
to List. Each list item is one text line. Use it if you care
about zero bytes possibly present inside register: without
third argument both NLs and zero bytes are represented as NLs
(see NL-used-for-Nul).
When the register was not set an empty list is returned.{regname}
is not specified, v:register is used.{regname}
(string?
)
{list}
(nil|false?
)
string
){regname}
]) getreginfo(){regname}
as a
Dictionary with the following entries:
regcontents List of lines contained in register
{regname}
, like
getreg({regname}
, 1, 1).
regtype the type of register {regname}
, as in
getregtype().
isunnamed Boolean flag, v:true if this register
is currently pointed to by the unnamed
register.
points_to for the unnamed register, gives the
single letter name of the register
currently pointed to (see quotequote).
For example, after deleting a line
with dd
, this field will be "1",
which is the register that got the
deleted text.{regname}
argument is a string. If {regname}
is invalid
or not set, an empty Dictionary will be returned.
If {regname}
is not specified, v:register is used.
The returned Dictionary can be passed to setreg().{regname}
(string?
)
table
){pos1}
, {pos2}
[, {opts}
]) getregion(){pos1}
to {pos2}
from a
buffer.{pos1}
and {pos2}
must both be Lists with four numbers.
See getpos() for the format of the list. It's possible
to specify positions from a different buffer, but please
note the limitations at getregion-notes.{opts}
is a Dict and supports the
following items:{pos1}
and {pos2}
doesn't matter, it will always
return content from the upper left position to the lower
right position.
{pos1}
and {pos2}
are not in the same buffer, an empty
list is returned.
xnoremap <CR>
\ <Cmd>echom getregion(
\ getpos('v'), getpos('.'), #{ type: mode() })<CR>
{pos1}
(table
)
{pos2}
(table
)
{opts}
(table?
)
string[]
){pos1}
, {pos2}
[, {opts}
]) getregionpos(){pos1}
and
{pos2}
.
The segments are a pair of positions for every line:[[{start_pos}, {end_pos}], ...]
<Tab>
or after the last character.
If the "off" number of an ending position is non-zero, it is
the offset of the character's first cell not included in the
selection, otherwise all its cells are included.{opts}
also
supports the following:{pos1}
(table
)
{pos2}
(table
)
{opts}
(table?
)
integer[][][]
){regname}
]) getregtype(){regname}
.
The value will be one of:
"v" for charwise text
"V" for linewise text
"<CTRL-V>{width}" for blockwise-visual text
"" for an empty or unknown register
<CTRL-V>
is one character with value 0x16.
The {regname}
argument is a string. If {regname}
is not
specified, v:register is used.{regname}
(string?
)
string
){opts}
]) getscriptinfo():scriptnames
shows.{opts}
supports the following
optional items:
name Script name match pattern. If specified,
and "sid" is not specified, information about
scripts with a name that match the pattern
"name" are returned.
sid Script ID <SID>. If specified, only
information about the script with ID "sid" is
returned and "name" is ignored.{opts}
.
name Vim script file name.
sid Script ID <SID>.
variables A dictionary with the script-local variables.
Present only when a particular script is
specified using the "sid" item in {opts}
.
Note that this is a copy, the value of
script-local variables cannot be changed using
this dictionary.
version Vim script version, always 1echo getscriptinfo({'name': 'myscript'})
echo getscriptinfo({'sid': 15})[0].variables
{opts}
(table?
)
vim.fn.getscriptinfo.ret[]
)table[]
){tabnr}
]) gettabinfo(){tabnr}
is not specified, then information about all the
tab pages is returned as a List. Each List item is a
Dictionary. Otherwise, {tabnr}
specifies the tab page
number and information about that one is returned. If the tab
page does not exist an empty List is returned.{tabnr}
(integer?
)
any
){tabnr}
, {varname}
[, {def}
]) gettabvar(){varname}
in tab page
{tabnr}
. t:var
Tabs are numbered starting with one.
The {varname}
argument is a string. When {varname}
is empty a
dictionary with all tab-local variables is returned.
Note that the name without "t:" must be used.
When the tab or variable doesn't exist {def}
or an empty
string is returned, there is no error message.{tabnr}
(integer
)
{varname}
(string
)
{def}
(any?
)
any
){tabnr}
, {winnr}
, {varname}
[, {def}
]) gettabwinvar(){varname}
in window
{winnr}
in tab page {tabnr}
.
The {varname}
argument is a string. When {varname}
is empty a
dictionary with all window-local variables is returned.
When {varname}
is equal to "&" get the values of all
window-local options in a Dictionary.
Otherwise, when {varname}
starts with "&" get the value of a
window-local option.
Note that {varname}
must be the name without "w:".
Tabs are numbered starting with one. For the current tabpage
use getwinvar().
{winnr}
can be the window number or the window-ID.
When {winnr}
is zero the current window is used.
This also works for a global option, buffer-local option and
window-local option, but it doesn't work for a global variable
or buffer-local variable.
When the tab, window or variable doesn't exist {def}
or an
empty string is returned, there is no error message.
Examples:let list_is_on = gettabwinvar(1, 2, '&list')
echo "myvar = " .. gettabwinvar(3, 1, 'myvar')
gettabwinvar({tabnr}, {winnr}, '&')
{tabnr}
(integer
)
{winnr}
(integer
)
{varname}
(string
)
{def}
(any?
)
any
){winnr}
]) {winnr}
.
{winnr}
can be the window number or the window-ID.
When {winnr}
is not specified, the current window is used.
When window {winnr}
doesn't exist, an empty Dict is returned.{winnr}
(integer?
)
any
){text}
) gettext(){text}
if possible.
This is mainly for use in the distributed Vim scripts. When
generating message translations the {text}
is extracted by
xgettext, the translator can add the translated message in the
.po file and Vim will lookup the translation when gettext() is
called.
For {text}
double quoted strings are preferred, because
xgettext does not understand escaping in single quoted
strings.{text}
(string
)
string
){winid}
is given Information about the window with that ID
is returned, as a List with one item. If the window does not
exist the result is an empty list.{winid}
information about all the windows in all the
tab pages is returned.{winid}
(integer?
)
vim.fn.getwininfo.ret.item[]
){timeout}
]) getwinpos(){timeout}
can be used to specify how long to wait in msec for
a response from the terminal. When omitted 100 msec is used.while 1
let res = getwinpos(1)
if res[0] >= 0
break
endif
" Do some work here
endwhile
{timeout}
(integer?
)
any
):winpos
.integer
):winpos
.integer
){winnr}
, {varname}
[, {def}
]) getwinvar() let list_is_on = getwinvar(2, '&list')
echo "myvar = " .. getwinvar(1, 'myvar')
Parameters: ~
• {winnr} (`integer`)
• {varname} (`string`)
• {def} (`any?`)
Return: ~
(`any`)
glob({expr}
[, {nosuf}
[, {list}
[, {alllinks}
]]]) glob(){expr}
. See wildcards for the
use of special characters.{nosuf}
argument is given and is TRUE,
the 'suffixes' and 'wildignore' options apply: Names matching
one of the patterns in 'wildignore' will be skipped and
'suffixes' affect the ordering of matches.
'wildignorecase' always applies.{list}
is present and it is TRUE the result is a List
with all matching files. The advantage of using a List is,
you also get filenames containing newlines correctly.
Otherwise the result is a String and when there are several
matches, they are separated by <NL>
characters.{alllinks}
argument is present and it is
TRUE then all symbolic links are included.let tagfiles = glob("`find . -name tags -print`")
let &tags = substitute(tagfiles, "\n", ",", "g")
{expr}
(string
)
{nosuf}
(boolean?
)
{list}
(boolean?
)
{alllinks}
(boolean?
)
any
){string}
) glob2regpat()if filename =~ glob2regpat('Make*.mak')
" ...
endif
if filename =~ '^Make.*\.mak$'
" ...
endif
{string}
is an empty string the result is "^$", match an
empty string.
Note that the result depends on the system. On MS-Windows
a backslash usually means a path separator.{string}
(string
)
string
){path}
, {expr}
[, {nosuf}
[, {list}
[, {allinks}
]]]) globpath()
Perform glob() for String {expr}
on all directories in {path}
and concatenate the results. Example:echo globpath(&rtp, "syntax/c.vim")
{path}
is a comma-separated list of directory names. Each
directory name is prepended to {expr}
and expanded like with
glob(). A path separator is inserted when needed.
To add a comma inside a directory name escape it with a
backslash. Note that on MS-Windows a directory may have a
trailing backslash, remove it if you put a comma after it.
If the expansion fails for one of the directories, there is no
error message.{nosuf}
argument is given and is TRUE,
the 'suffixes' and 'wildignore' options apply: Names matching
one of the patterns in 'wildignore' will be skipped and
'suffixes' affect the ordering of matches.{list}
is present and it is TRUE the result is a List
with all matching files. The advantage of using a List is, you
also get filenames containing newlines correctly. Otherwise
the result is a String and when there are several matches,
they are separated by <NL>
characters. Example:echo globpath(&rtp, "syntax/c.vim", 0, 1)
{allinks}
is used as with glob().echo globpath(&rtp, "**/README.txt")
{path}
(string
)
{expr}
(string
)
{nosuf}
(boolean?
)
{list}
(boolean?
)
{allinks}
(boolean?
)
any
){feature}
) has(){feature}
is supported, 0 otherwise. The
{feature}
argument is a feature name like "nvim-0.2.1" or
"win32", see below. See also exists().print(vim.uv.os_uname().sysname)
if has('feature')
let x = this_breaks_without_the_feature()
endif
if has("nvim-0.2.1")
" ...
endif
if has("win32")
" ...
endif
if v:version > 602 || v:version == 602 && has("patch148")
" ...
endif
if has("patch-7.4.237")
" ...
endif
{feature}
(string
)
0|1
){dict}
, {key}
) has_key(){dict}
has an entry with key {key}
. FALSE otherwise. The {key}
argument is a string.{dict}
(table
)
{key}
(string
)
0|1
){winnr}
[, {tabnr}
]]) haslocaldir(){winnr}
is -1 and the tabpage
has set a local path via :tcd, otherwise 0.echo haslocaldir()
echo haslocaldir(0)
echo haslocaldir(0, 0)
{winnr}
use that window in the current tabpage.
With {winnr}
and {tabnr}
use the window in that tabpage.
{winnr}
can be the window number or the window-ID.
If {winnr}
is -1 it is ignored, only the tab is resolved.
Throw error if the arguments are invalid. E5000 E5001 E5002{winnr}
(integer?
)
{tabnr}
(integer?
)
0|1
){what}
[, {mode}
[, {abbr}
]]) hasmapto(){what}
in somewhere in the rhs (what it is
mapped to) and this mapping exists in one of the modes
indicated by {mode}
.
The arguments {what}
and {mode}
are strings.
When {abbr}
is there and it is TRUE use abbreviations
instead of mappings. Don't forget to specify Insert and/or
Command-line mode.
Both the global mappings and the mappings local to the current
buffer are checked for a match.
If no matching mapping is found FALSE is returned.
The following characters are recognized in {mode}
:
n Normal mode
v Visual and Select mode
x Visual mode
s Select mode
o Operator-pending mode
i Insert mode
l Language-Argument ("r", "f", "t", etc.)
c Command-line mode
When {mode}
is omitted, "nvo" is used.if !hasmapto('\ABCdoit')
map <Leader>d \ABCdoit
endif
{what}
(any
)
{mode}
(string?
)
{abbr}
(boolean?
)
0|1
){history}
, {item}
) histadd(){item}
to the history {history}
which can be
one of: hist-names {history}
string does not need to be the whole name, one
character is sufficient.
If {item}
does already exist in the history, it will be
shifted to become the newest entry.
The result is a Number: TRUE if the operation was successful,
otherwise FALSE is returned.call histadd("input", strftime("%Y %b %d"))
let date=input("Enter date: ")
{history}
(string
)
{item}
(any
)
0|1
){history}
[, {item}
]) histdel(){history}
, i.e. delete all its entries. See hist-names
for the possible values of {history}
.{item}
evaluates to a String, it is used as a
regular expression. All entries matching that expression will
be removed from the history (if there are any).
Upper/lowercase must match, unless "\c" is used /\c.
If {item}
evaluates to a Number, it will be interpreted as
an index, see :history-indexing. The respective entry will
be removed if it exists.call histdel("expr")
call histdel("/", '^\*')
call histdel("search", histnr("search"))
call histdel("search", -1)
call histdel("search", '^' .. histget("search", -1) .. '$')
call histdel("search", -1)
let @/ = histget("search", -1)
{history}
(string
)
{item}
(any?
)
0|1
){history}
[, {index}
]) histget(){index}
from
{history}
. See hist-names for the possible values of
{history}
, and :history-indexing for {index}
. If there is
no such entry, an empty String is returned. When {index}
is
omitted, the most recent item from the history is used.execute '/' .. histget("search", -2)
{num}
" that supports re-execution of
the {num}
th entry from the output of :history.command -nargs=1 H execute histget("cmd", 0+<args>)
{history}
(string
)
{index}
(integer|string?
)
string
){history}
) histnr(){history}
.
See hist-names for the possible values of {history}
.
If an error occurred, -1 is returned.let inp_index = histnr("expr")
{history}
(string
)
integer
){name}
) hlID(){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")
{name}
(string
)
integer
){name}
) hlexists(){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.{name}
(string
)
0|1
)string
){string}
, {from}
, {to}
) iconv(){string}
converted
from encoding {from}
to encoding {to}
.
When the conversion completely fails an empty string is
returned. When some characters could not be converted they
are replaced with "?".
The encoding names are whatever the iconv() library function
can accept, see ":!man 3 iconv".
Note that Vim uses UTF-8 for all Unicode encodings, conversion
from/to UCS-2 is automatically changed to use UTF-8. You
cannot use UCS-2 in a string anyway, because of the NUL bytes.{string}
(string
)
{from}
(string
)
{to}
(string
)
string
){expr}
) id()id(v1) ==# id(v2)
returns true iff type(v1) == type(v2) && v1 is v2
.
Note that v:_null_string
, v:_null_list
, v:_null_dict
and
v:_null_blob
have the same id()
with different types
because they are internally represented as NULL pointers.
id()
returns a hexadecimal representation of the pointers to
the containers (i.e. like 0x994a40
), same asprintf("%p",
{expr}
)`, but it is advised against counting on the exact
format of the return value.id(no_longer_existing_container)
will not be equal to some other id()
: new containers may
reuse identifiers of the garbage-collected ones.{expr}
(any
)
string
){lnum}
) indent(){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.{lnum}
(integer|string
)
integer
){object}
, {expr}
[, {start}
[, {ic}
]]) index(){expr}
in {object}
and return its index. See
indexof() for using a lambda to select the item.{object}
is a List return the lowest index where the item
has a value equal to {expr}
. There is no automatic
conversion, so the String "4" is different from the Number 4.
And the Number 4 is different from the Float 4.0. The value
of 'ignorecase' is not used here, case matters as indicated by
the {ic}
argument.{start}
is given then start looking at the item with index
{start}
(may be negative for an item relative to the end).{ic}
is given and it is TRUE, ignore case. Otherwise
case must match.{expr}
is not found in {object}
.
Example:let idx = index(words, "the")
if index(numbers, 123) >= 0
" ...
endif
{object}
(any
)
{expr}
(any
)
{start}
(integer?
)
{ic}
(boolean?
)
integer
){object}
, {expr}
[, {opts}
]) indexof(){object}
where {expr}
is
v:true. {object}
must be a List or a Blob.{object}
is a List, evaluate {expr}
for each item in the
List until the expression is v:true and return the index of
this item.{object}
is a Blob evaluate {expr}
for each byte in the
Blob until the expression is v:true and return the index of
this byte.{expr}
is a string: If {object}
is a List, inside
{expr}
v:key has the index of the current List item and
v:val has the value of the item. If {object}
is a Blob,
inside {expr}
v:key has the index of the current byte and
v:val has the byte value.{expr}
is a Funcref it must take two arguments:
1. the key or the index of the current item.
2. the value of the current item.
The function must return TRUE if the item is found and the
search should stop.{opts}
is a Dict and supports the
following items:
startidx start evaluating {expr}
at the item with this
index; may be negative for an item relative to
the end
Returns -1 when {expr}
evaluates to v:false for all the items.
Example:let l = [#{n: 10}, #{n: 20}, #{n: 30}]
echo indexof(l, "v:val.n == 20")
echo indexof(l, {i, v -> v.n == 30})
echo indexof(l, "v:val.n == 20", #{startidx: 1})
{object}
(any
)
{expr}
(any
)
{opts}
(table?
)
integer
){prompt}
(string
)
{text}
(string?
)
{completion}
(string?
)
string
){opts}
)
The result is a String, which is whatever the user typed on
the command-line. The {prompt}
argument is either a prompt
string, or a blank string (for no prompt). A '\n' can be used
in the prompt to start a new line.{prompt}
in the first form.
default "" Same as {text}
in the first form.
completion nothing Same as {completion}
in the first form.
cancelreturn "" The value returned when the dialog is
cancelled.
highlight nothing Highlight handler: Funcref.if input("Coffee or beer? ") == "beer"
echo "Cheers!"
endif
{text}
argument is present and not empty, this
is used for the default reply, as if the user typed this.
Example:let color = input("Color? ", "white")
{completion}
argument specifies the type of
completion supported for the input. Without it completion is
not performed. The supported completion types are the same as
that can be supplied to a user-defined command using the
"-complete=" argument. Refer to :command-completion for
more information. Example:let fname = input("File: ", "", "file")
highlight
key allows specifying function which
will be used for highlighting user input. This function
receives user input as its only argument and must return
a list of 3-tuples [hl_start_col, hl_end_col + 1, hl_group]
where
hl_start_col is the first highlighted column,
hl_end_col is the last highlighted column (+ 1!),
hl_group is :hi group used for highlighting.
E5403 E5404 E5405 E5406
Both hl_start_col and hl_end_col + 1 must point to the start
of the multibyte character (highlighting must not break
multibyte characters), hl_end_col + 1 may be equal to the
input length. Start column must be in range [0, len(input)),
end column must be in range (hl_start_col, len(input)],
sections must be ordered so that next hl_start_col is greater
then or equal to previous hl_end_col.highlight RBP1 guibg=Red ctermbg=red
highlight RBP2 guibg=Yellow ctermbg=yellow
highlight RBP3 guibg=Green ctermbg=green
highlight RBP4 guibg=Blue ctermbg=blue
let g:rainbow_levels = 4
function! RainbowParens(cmdline)
let ret = []
let i = 0
let lvl = 0
while i < len(a:cmdline)
if a:cmdline[i] is# '('
call add(ret, [i, i + 1, 'RBP' .. ((lvl % g:rainbow_levels) + 1)])
let lvl += 1
elseif a:cmdline[i] is# ')'
let lvl -= 1
call add(ret, [i, i + 1, 'RBP' .. ((lvl % g:rainbow_levels) + 1)])
endif
let i += 1
endwhile
return ret
endfunction
call input({'prompt':'>','highlight':'RainbowParens'})
nmap \x :call GetFoo()<CR>:exe "/" .. Foo<CR>
function GetFoo()
call inputsave()
let g:Foo = input("enter search pattern: ")
call inputrestore()
endfunction
{opts}
(table
)
string
){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, if the mouse is enabled in the command line ('mouse' is
"a" or includes "c"). 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'])
Parameters: ~
• {textlist} (`string[]`)
Return: ~
(`any`)
inputrestore() inputrestore()integer
)integer
){prompt}
[, {text}
]) inputsecret(){prompt}
(string
)
{text}
(string?
)
string
){object}
, {item}
[, {idx}
]) insert(){object}
is a List or a Blob insert {item}
at the start
of it.{idx}
is specified insert {item}
before the item with index
{idx}
. If {idx}
is zero it goes before the first item, just
like omitting {idx}
. A negative {idx}
is also possible, see
list-index. -1 inserts just before the last item.let mylist = insert([2, 3, 5], 1)
call insert(mylist, 4, -1)
call insert(mylist, 6, len(mylist))
{item}
is a List it is inserted as a single
item. Use extend() to concatenate Lists.{object}
(any
)
{item}
(any
)
{idx}
(integer?
)
any
)CTRL-C
, most commands won't execute and control
returns to the user. This is useful to abort execution
from lower down, e.g. in an autocommand. Example:function s:check_typoname(file)
if fnamemodify(a:file, ':t') == '['
echomsg 'Maybe typo'
call interrupt()
endif
endfunction
au BufWritePre * call s:check_typoname(expand('<amatch>'))
any
){expr}
) invert()let bits = invert(bits)
{expr}
(integer
)
integer
){path}
) isabsolutepath(){path}
is an
absolute path.
On Unix, a path is considered absolute when it starts with '/'.
On MS-Windows, it is considered absolute when it starts with an
optional drive prefix and is followed by a '\' or '/'. UNC paths
are always absolute.
Example:echo isabsolutepath('/usr/share/') " 1
echo isabsolutepath('./foobar') " 0
echo isabsolutepath('C:\Windows') " 1
echo isabsolutepath('foobar') " 0
echo isabsolutepath('\\remote\file') " 1
{path}
(string
)
0|1
){directory}
) isdirectory(){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.{directory}
(string
)
0|1
){expr}
) isinf(){expr}
is a positive infinity, or -1 a negative
infinity, otherwise 0.echo isinf(1.0 / 0.0)
echo isinf(-1.0 / 0.0)
{expr}
(number
)
1|0|-1
){expr}
) islocked() E786
The result is a Number, which is TRUE when {expr}
is the
name of a locked variable.
The string argument {expr}
must be the name of a variable,
List item or Dictionary entry, not the variable itself!
Example:let alist = [0, ['a', 'b'], 2, 3]
lockvar 1 alist
echo islocked('alist') " 1
echo islocked('alist[1]') " 0
{expr}
is a variable that does not exist you get an error
message. Use exists() to check for existence.{expr}
(any
)
0|1
){expr}
(number
)
0|1
){dict}
) items(){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. Also see keys() and values().
Example:for [key, value] in items(mydict)
echo key .. ': ' .. value
endfor
{dict}
(table
)
any
){job}
(integer
)
integer
){job}
, {width}
, {height}
) jobresize(){job}
to {width}
columns and {height}
rows.
Fails if the job was not started with "pty":v:true
.{job}
(integer
)
{width}
(integer
)
{height}
(integer
)
any
){cmd}
[, {opts}
]) jobstart()rpc
, pty
, or term
).{cmd}
as a job.
If {cmd}
is a List it runs directly (no 'shell').
If {cmd}
is a String it runs in the 'shell', like this:call jobstart(split(&shell) + split(&shellcmdflag) + ['{cmd}'])
call jobstart(['nvim', '-h'], {'on_stdout':{j,d,e->append(line('.'),d)}})
call jobstart(['nvim', '-h'], {'term':v:true})
{cmd}
[0] or 'shell' is not executable.
The returned job-id is a valid channel-id representing the
job's stdio streams. Use chansend() (or rpcnotify() and
rpcrequest() if "rpc" was enabled) to send data to stdin and
chanclose() to close the streams without stopping the job.{cmd}
is a List:
call jobstart(['ping', 'neovim.io'])
call jobstart(['System32\ping.exe', 'neovim.io'])
{cmd}
is collapsed to a string of quoted args as expected
by CommandLineToArgvW https://msdn.microsoft.com/bb776391
unless cmd[0] is some form of "cmd.exe".
env
option.{opts}
is a dictionary with these keys:
clear_env: (boolean) env
defines the job environment
exactly, instead of merging current environment.
cwd: (string, default=|current-directory|) Working
directory of the job.
detach: (boolean) Detach the job process: it will not be
killed when Nvim exits. If the process exits
before Nvim, on_exit
will be invoked.
env: (dict) Map of environment variable name:value
pairs extending (or replace with "clear_env")
the current environment. jobstart-env
height: (number) Height of the pty
terminal.
on_exit: (function) Callback invoked when the job exits.
on_stdout: (function) Callback invoked when the job emits
stdout data.
on_stderr: (function) Callback invoked when the job emits
stderr data.
overlapped: (boolean) Sets FILE_FLAG_OVERLAPPED for the
stdio passed to the child process. Only on
MS-Windows; ignored on other platforms.
pty: (boolean) Connect the job to a new pseudo
terminal, and its streams to the master file
descriptor. on_stdout
receives all output,
on_stderr
is ignored. terminal-start
rpc: (boolean) Use msgpack-rpc to communicate with
the job over stdio. Then on_stdout
is ignored,
but on_stderr
can still be used.
stderr_buffered: (boolean) Collect data until EOF (stream closed)
before invoking on_stderr
. channel-buffered
stdout_buffered: (boolean) Collect data until EOF (stream
closed) before invoking on_stdout
. channel-buffered
stdin: (string) Either "pipe" (default) to connect the
job's stdin to a channel or "null" to disconnect
stdin.
term: (boolean) Spawns {cmd}
in a new pseudo-terminal session
connected to the current (unmodified) buffer. Implies "pty".
Default "height" and "width" are set to the current window
dimensions. jobstart(). Defaults $TERM to "xterm-256color".
width: (number) Width of the pty
terminal.{opts}
is passed as self dictionary to the callback; the
caller may set other keys to pass application-specific data.{cmd}
(string|string[]
)
{opts}
(table?
)
integer
){id}
) jobstop(){id}
by sending SIGTERM to the job process. If
the process does not terminate after a timeout then SIGKILL
will be sent. When the job terminates its on_exit handler
(if any) will be invoked.
See job-control.{id}
(integer
)
integer
){jobs}
is a List of job-ids to wait for.
{timeout}
is the maximum waiting time in milliseconds. If
omitted or -1, wait forever.let running = jobwait([{job-id}], 0)[0] == -1
{jobs}
list may
be invoked. The screen will not redraw unless :redraw is
invoked by a callback.{jobs}
) integers, where each integer is
the status of the corresponding job:
Exit-code, if the job exited
-1 if the timeout was exceeded
-2 if the job was interrupted (by CTRL-C)
-3 if the job-id is invalid{jobs}
(integer[]
)
{timeout}
(integer?
)
integer[]
){list}
[, {sep}
]) join(){list}
together into one String.
When {sep}
is specified it is put in between the items. If
{sep}
is omitted a single space is used.
Note that {sep}
is not added at the end. You might want to
add it there too:let lines = join(mylist, "\n") .. "\n"
{list}
(any[]
)
{sep}
(string?
)
string
){expr}
) json_decode(){expr}
from JSON object. Accepts readfile()-style
list as the input, as well as regular string. May output any
Vim value. In the following cases it will output
msgpack-special-dict:
1. Dictionary contains duplicate key.
2. String contains NUL byte. Two special dictionaries: for
dictionary and for string will be emitted in case string
with NUL byte was a dictionary key.{expr}
(any
)
any
){expr}
) json_encode(){expr}
into a JSON string. Accepts
msgpack-special-dict as the input. Will not convert
Funcrefs, mappings with non-string keys (can be created as
msgpack-special-dict), values with self-referencing
containers, strings which contain non-UTF-8 characters,
pseudo-UTF-8 strings which contain codepoints reserved for
surrogate pairs (such strings are not valid UTF-8 strings).
Non-printable characters are converted into "\u1234" escapes
or special escapes like "\t", other are dumped as-is.
Blobs are converted to arrays of the individual bytes.{expr}
(any
)
string
){dict}
) keys(){dict}
. The List is in
arbitrary order. Also see items() and values().{dict}
(table
)
string[]
){string}
) keytrans()let xx = "\<C-Home>"
echo keytrans(xx)
<C-Home>
{string}
(string
)
string
){expr}
) len() E701
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 Blob the number of bytes is returned.
When {expr}
is a Dictionary the number of entries in the
Dictionary is returned.
Otherwise an error is given and returns zero.{expr}
(any[]
)
integer
){libname}
, {funcname}
, {argument}
) libcall() E364 E368
Call function {funcname}
in the run-time library {libname}
with single argument {argument}
.
This is useful to call functions in a library that you
especially made to be used with Vim. Since only one argument
is possible, calling standard library functions is rather
limited.
The result is the String returned by the function. If the
function returns NULL, this will appear as an empty string ""
to Vim.
If the function returns a number, use libcallnr()!
If {argument}
is a number, it is passed to the function as an
int; if {argument}
is a string, it is passed as a
null-terminated string.{libname}
should be the filename of the DLL
without the ".DLL" suffix. A full path is only required if
the DLL is not in the usual places.
For Unix: When compiling your own plugins, remember that the
object code must be compiled as position-independent ('PIC').
Examples: echo libcall("libc.so", "getenv", "HOME")
Parameters: ~
• {libname} (`string`)
• {funcname} (`string`)
• {argument} (`any`)
Return: ~
(`any`)
libcallnr({libname}
, {funcname}
, {argument}
) libcallnr()echo libcallnr("/usr/lib/libc.so", "getpid", "")
call libcallnr("libc.so", "printf", "Hello World!\n")
call libcallnr("libc.so", "sleep", 10)
{libname}
(string
)
{funcname}
(string
)
{argument}
(any
)
any
){winid}
argument the values are obtained for
that window instead of the current window.{expr}
and {winid}
.echo line(".") " line number of the cursor
echo line(".", winid) " idem, in window "winid"
echo line("'t") " line number of mark t
echo line("'" .. marker) " line number of mark marker
{expr}
(string|integer[]
)
{winid}
(integer?
)
integer
){lnum}
) line2byte(){lnum}
. This includes the end-of-line character, depending on
the 'fileformat' option for the current buffer. The first
line returns 1. UTF-8 encoding is used, 'fileencoding' is
ignored. This can also be used to get the byte count for the
line just below the last line:echo line2byte(line("$") + 1)
{lnum}
is used like with
getline(). When {lnum}
is invalid -1 is returned.
Also see byte2line(), go and :goto.{lnum}
(integer
)
integer
){lnum}
) lispindent(){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, -1 is returned.{lnum}
(integer
)
integer
){list}
) list2blob(){list}
.
Examples:echo list2blob([1, 2, 3, 4]) " returns 0z01020304
echo list2blob([]) " returns 0z
{list}
(any[]
)
string
){list}
[, {utf8}
]) list2str(){list}
to a character string can
concatenate them all. Examples:echo list2str([32]) " returns " "
echo list2str([65, 66, 67]) " returns "ABC"
echo join(map(list, {nr, val -> nr2char(val)}), '')
{utf8}
option has no effect,
and exists only for backwards-compatibility.
With UTF-8 composing characters work as expected:echo list2str([97, 769]) " returns "á"
{list}
(any[]
)
{utf8}
(boolean?
)
string
)integer
){expr}
) log(){expr}
as a Float.
{expr}
must evaluate to a Float or a Number in the range
(0, inf].
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo log(10)
echo log(exp(5))
{expr}
(number
)
number
){expr}
) log10(){expr}
to base 10 as a Float.
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo log10(1000)
echo log10(0.01)
{expr}
(number
)
number
){expr}
[, {expr}
]) luaeval(){expr}
and return its result converted
to Vim data structures. See lua-eval for more details.{expr}
(string
)
{expr1}
(any[]?
)
any
){expr1}
, {expr2}
) map(){expr1}
must be a List, String, Blob or Dictionary.
When {expr1}
is a List or Dictionary, replace each
item in {expr1}
with the result of evaluating {expr2}
.
For a Blob each byte is replaced.
For a String, each character, including composing
characters, is replaced.
If the item type changes you may want to use mapnew() to
create a new List or Dictionary.{expr2}
is a String, inside {expr2}
v:val has the value
of the current item. For a Dictionary v:key has the key
of the current item and for a List v:key has the index of
the current item. For a Blob v:key has the index of the
current byte. For a String v:key has the index of the
current character.
Example:call map(mylist, '"> " .. v:val .. " <"')
{expr2}
is the result of an expression and is then
used as an expression again. Often it is good to use a
literal-string to avoid having to double backslashes. You
still have to double ' quotes{expr2}
is a Funcref it is called with two arguments:
1. The key or the index of the current item.
2. the value of the current item.
The function must return the new value of the item. Example
that changes each value by "key-value":func KeyValue(key, val)
return a:key .. '-' .. a:val
endfunc
call map(myDict, function('KeyValue'))
call map(myDict, {key, val -> key .. '-' .. val})
call map(myDict, {key -> 'item: ' .. key})
call map(myDict, {_, val -> 'item: ' .. val})
let tlist = map(copy(mylist), ' v:val .. "\t"')
{expr1}
, the List or Dictionary that was filtered,
or a new Blob or String.
When an error is encountered while evaluating {expr2}
no
further items in {expr1}
are processed.
When {expr2}
is a Funcref errors inside a function are ignored,
unless it was defined with the "abort" flag.{expr1}
(string|table|any[]
)
{expr2}
(string|function
)
any
){name}
[, {mode}
[, {abbr}
[, {dict}
]]]) maparg(){dict}
is omitted or zero: Return the rhs of mapping
{name}
in mode {mode}
. The returned String has special
characters translated like in the output of the ":map" command
listing. When {dict}
is TRUE a dictionary is returned, see
below. To get a list of all mappings see maplist().{name}
, an empty String is
returned if {dict}
is FALSE, otherwise returns an empty Dict.
When the mapping for {name}
is empty, then "<Nop>" is
returned.{name}
can have special key names, like in the ":map"
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
"t" Terminal
"" Normal, Visual and Operator-pending
When {mode}
is omitted, the modes for "" are used.{abbr}
is there and it is TRUE use abbreviations
instead of mappings.{dict}
is there and it is TRUE return a dictionary
containing all the information of the mapping with the
following items: mapping-dict {lhs}
of the mapping as it would be typed
"lhsraw" The {lhs}
of the mapping as raw bytes
"lhsrawalt" The {lhs}
of the mapping as raw bytes, alternate
form, only present when it differs from "lhsraw"
"rhs" The {rhs}
of the mapping as typed.
"callback" Lua function, if RHS was defined as such.
"silent" 1 for a :map-silent mapping, else 0.
"noremap" 1 if the {rhs}
of the mapping is not remappable.
"script" 1 if mapping was defined with <script>
.
"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>). Negative for special contexts.
"scriptversion" The version of the script, always 1.
"lnum" The line number in "sid", zero if unknown.
"nowait" Do not wait for other, longer mappings.
(:map-<nowait>).
"abbr" True if this is an abbreviation.
"mode_bits" Nvim's internal binary representation of "mode".
mapset() ignores this; only "mode" is used.
See maplist() for usage examples. The values
are from src/nvim/state_defs.h and may change in
the future.exe 'nnoremap <Tab> ==' .. maparg('<Tab>', 'n')
{name}
(string
)
{mode}
(string?
)
{abbr}
(boolean?
)
{dict}
(false?
)
string
){name}
[, {mode}
[, {abbr}
]]) mapcheck(){name}
in mode
{mode}
. See maparg() for {mode}
and special names in
{name}
.
When {abbr}
is there and it is non-zero use abbreviations
instead of mappings.
A match happens with a mapping that starts with {name}
and
with a mapping which is equal to the start of {name}
.{name}
, while maparg() only finds a
mapping for {name}
exactly.
When there is no mapping that starts with {name}
, an empty
String is returned. If there is one, the RHS of that mapping
is returned. If there are several mappings that start with
{name}
, the RHS of one of them is returned. This will be
"<Nop>" if the RHS is empty.
The mappings local to the current buffer are checked first,
then the global mappings.
This function can be used to check if a mapping can be added
without being ambiguous. Example:if mapcheck("_vv") == ""
map _vv :set guifont=7x13<CR>
endif
{name}
(string
)
{mode}
(string?
)
{abbr}
(boolean?
)
any
){abbr}
]) maplist(){abbr}
is there and it is TRUE use
abbreviations instead of mappings.echo maplist()->filter({_, m ->
\ match(get(m, 'rhs', ''), 'MultiMatch') >= 0
\ })
let saved_maps = []
for m in maplist()
if and(m.mode_bits, 0x19) != 0
eval saved_maps->add(m)
endif
endfor
echo saved_maps->mapnew({_, m -> m.lhs})
omap xyzzy <Nop>
let op_bit = maplist()->filter(
\ {_, m -> m.lhs == 'xyzzy'})[0].mode_bits
ounmap xyzzy
echo printf("Operator-pending mode bit: 0x%x", op_bit)
{abbr}
(0|1?
)
table[]
){expr1}
, {expr2}
) mapnew(){expr1}
a new
List or Dictionary is created and returned. {expr1}
remains
unchanged. Items can still be changed by {expr2}
, if you
don't want that use deepcopy() first.{expr1}
(any
)
{expr2}
(any
)
any
){mode}
, {abbr}
, {dict}
) mapset(){dict}
)
Restore a mapping from a dictionary, possibly returned by
maparg() or maplist(). A buffer mapping, when dict.buffer
is true, is set on the current buffer; it is up to the caller
to ensure that the intended buffer is the current buffer. This
feature allows copying mappings from one buffer to another.
The dict.mode value may restore a single mapping that covers
more than one mode, like with mode values of '!', ' ', "nox",
or 'v'. E1276{mode}
and {abbr}
should be the same as
for the call to maparg(). E460
{mode}
is used to define the mode in which the mapping is set,
not the "mode" entry in {dict}
.
Example for saving and restoring a mapping:let save_map = maparg('K', 'n', 0, 1)
nnoremap K somethingelse
" ...
call mapset('n', 0, save_map)
:map!
, you need to save/restore the mapping for
all of them, when they might differ.{dict}
as the only argument, mode
and abbr are taken from the dict.
Example:let save_maps = maplist()->filter(
\ {_, m -> m.lhs == 'K'})
nnoremap K somethingelse
cnoremap K somethingelse2
" ...
unmap K
for d in save_maps
call mapset(d)
endfor
{dict}
(boolean
)
any
){expr}
, {pat}
[, {start}
[, {count}
]]) match(){expr}
is a List then this returns the index of the
first item where {pat}
matches. Each item is used as a
String, Lists and Dictionaries are used as echoed.{expr}
is used as a String. The result is a
Number, which gives the index (byte offset) in {expr}
where
{pat}
matches.echo match("testing", "ing") " results in 4
echo match([1, 'x'], '\a') " results in 1
{pat}
is used.
strpbrk() let sepidx = match(line, '[.,;: \t]')
let idx = match(haystack, '\cneedle')
{start}
is given, the search starts from byte index
{start}
in a String or item {start}
in a List.
The result, however, is still the index counted from the
first character/item. Example:echo match("testing", "ing", 2)
echo match("testing", "ing", 4)
echo match("testing", "t", 2)
{start}
> 0 then it is like the string starts
{start}
bytes later, thus "^" will match at {start}
. Except
when {count}
is given, then it's like matches before the
{start}
byte are ignored (this is a bit complicated to keep it
backwards compatible).
For a String, if {start}
< 0, it will be set to 0. For a list
the index is counted from the end.
If {start}
is out of range ({start}
> strlen({expr}
) for a
String or {start}
> len({expr}
) for a List) -1 is returned.{count}
is given use the {count}
th match. When a match
is found in a String the search for the next one starts one
character further. Thus this example results in 1:echo match("testing", "..", 0, 2)
{count}
is added the way {start}
works changes,
see above.{expr}
(string|any[]
)
{pat}
(string
)
{start}
(integer?
)
{count}
(integer?
)
any
){group}
, {pattern}
[, {priority}
[, {id}
[, {dict}
]]])
Defines a pattern to be highlighted in the current window (a
"match"). It will be highlighted with {group}
. Returns an
identification number (ID), which can be used to delete the
match using matchdelete(). The ID is bound to the window.
Matching is case sensitive and magic, unless case sensitivity
or magicness are explicitly overridden in {pattern}
. The
'magic', 'smartcase' and 'ignorecase' options are not used.
The "Conceal" value is special, it causes the match to be
concealed.{priority}
argument assigns a priority to the
match. A match with a high priority will have its
highlighting overrule that of a match with a lower priority.
A priority is specified as an integer (negative numbers are no
exception). If the {priority}
argument is not specified, the
default priority is 10. The priority of 'hlsearch' is zero,
hence all matches with a priority greater than zero will
overrule it. Syntax highlighting (see 'syntax') is a separate
mechanism, and regardless of the chosen priority a match will
always overrule syntax highlighting.{id}
argument allows the request for a specific
match ID. If a specified ID is already taken, an error
message will appear and the match will not be added. An ID
is specified as a positive integer (zero excluded). IDs 1, 2
and 3 are reserved for :match, :2match and :3match,
respectively. 3 is reserved for use by the matchparen
plugin.
If the {id}
argument is not specified or -1, matchadd()
automatically chooses a free ID, which is at least 1000.{dict}
argument allows for further custom
values. Currently this is used to specify a match specific
conceal character that will be shown for hl-Conceal
highlighted matches. The dict can have the following members:highlight MyGroup ctermbg=green guibg=green
let m = matchadd("MyGroup", "TODO")
call matchdelete(m)
{group}
(integer|string
)
{pattern}
(string
)
{priority}
(integer?
)
{id}
(integer?
)
{dict}
(string?
)
any
){group}
, {pos}
[, {priority}
[, {id}
[, {dict}
]]]) matchaddpos()
Same as matchadd(), but requires a list of positions {pos}
instead of a pattern. This command is faster than matchadd()
because it does not handle regular expressions and it sets
buffer line boundaries to redraw screen. It is supposed to be
used when fast match additions and deletions are required, for
example to highlight matching parentheses.
E5030 E5031
{pos}
is a list of positions. Each position can be one of
these:
highlight MyGroup ctermbg=green guibg=green
let m = matchaddpos("MyGroup", [[23, 24], 34])
call matchdelete(m)
{group}
(integer|string
)
{pos}
(any[]
)
{priority}
(integer?
)
{id}
(integer?
)
{dict}
(string?
)
any
){nr}
) matcharg(){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.{nr}
(integer
)
any
){buf}
, {pat}
, {lnum}
, {end}
, [, {dict}
]) matchbufline(){lnum}
to {end}
in
buffer {buf}
where {pat}
matches.{lnum}
and {end}
can either be a line number or the string "$"
to refer to the last line in {buf}
.{dict}
argument supports following items:
submatches include submatch information (/\(){buf}
is not a valid buffer, the buffer is not loaded or
{lnum}
or {end}
is not valid then an error is given and an
empty List is returned." Assuming line 3 in buffer 5 contains "a"
echo matchbufline(5, '\<\k\+\>', 3, 3)
[{'lnum': 3, 'byteidx': 0, 'text': 'a'}]
" Assuming line 4 in buffer 10 contains "tik tok"
echo matchbufline(10, '\<\k\+\>', 1, 4)
[{'lnum': 4, 'byteidx': 0, 'text': 'tik'}, {'lnum': 4, 'byteidx': 4, 'text': 'tok'}]
{submatch}
is present and is v:true, then submatches like
"\1", "\2", etc. are also returned. Example:" Assuming line 2 in buffer 2 contains "acd"
echo matchbufline(2, '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2, 2
\ {'submatches': v:true})
[{'lnum': 2, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}]
The "submatches" List always contains 9 items. If a submatch
is not found, then an empty string is returned for that
submatch.{buf}
(string|integer
)
{pat}
(string
)
{lnum}
(string|integer
)
{end}
(string|integer
)
{dict}
(table?
)
any
){id}
[, {win}
]) matchdelete() E802 E803
Deletes a match with ID {id}
previously defined by matchadd()
or one of the :match commands. Returns 0 if successful,
otherwise -1. See example for matchadd(). All matches can
be deleted in one operation by clearmatches().
If {win}
is specified, use the window with this number or
window ID instead of the current window.{id}
(integer
)
{win}
(integer?
)
any
){expr}
, {pat}
[, {start}
[, {count}
]]) matchend()echo matchend("testing", "ing")
let span = matchend(line, '[a-zA-Z]')
let span = matchend(line, '[^a-zA-Z]')
echo matchend("testing", "ing", 5)
{expr}
(any
)
{pat}
(string
)
{start}
(integer?
)
{count}
(integer?
)
any
){list}
, {str}
[, {dict}
]) matchfuzzy(){list}
is a list of strings, then returns a List with all
the strings in {list}
that fuzzy match {str}
. The strings in
the returned list are sorted based on the matching score.{dict}
argument always supports the following
items:
matchseq When this item is present return only matches
that contain the characters in {str}
in the
given sequence.
limit Maximum number of matches in {list}
to be
returned. Zero means no limit.{list}
is a list of dictionaries, then the optional {dict}
argument supports the following additional items:
key Key of the item which is fuzzy matched against
{str}
. The value of this item should be a
string.
text_cb Funcref that will be called for every item
in {list}
to get the text for fuzzy matching.
This should accept a dictionary item as the
argument and return the text for that item to
use for fuzzy matching.{str}
is treated as a literal string and regular expression
matching is NOT supported. The maximum supported {str}
length
is 256.{str}
has multiple words each separated by white space,
then the list of strings that have all the words is returned.{str}
is greater than
256, then returns an empty list.{limit}
is given, matchfuzzy() will find up to this
number of matches in {list}
and return them in sorted order.echo matchfuzzy(["clay", "crow"], "cay")
echo getbufinfo()->map({_, v -> v.name})->matchfuzzy("ndl")
echo getbufinfo()->matchfuzzy("ndl", {'key' : 'name'})
echo getbufinfo()->matchfuzzy("spl",
\ {'text_cb' : {v -> v.name}})
echo v:oldfiles->matchfuzzy("test")
let l = readfile("buffer.c")->matchfuzzy("str")
echo ['one two', 'two one']->matchfuzzy('two one')
['two one', 'one two']
.echo ['one two', 'two one']->matchfuzzy('two one',
\ {'matchseq': 1})
['two one']
.{list}
(any[]
)
{str}
(string
)
{dict}
(string?
)
any
){list}
, {str}
[, {dict}
]) matchfuzzypos(){str}
matches and a list of matching scores. You can
use byteidx() to convert a character position to a byte
position.{str}
matches multiple times in a string, then only the
positions for the best match is returned.echo matchfuzzypos(['testing'], 'tsg')
echo matchfuzzypos(['clay', 'lacy'], 'la')
echo [{'text': 'hello', 'id' : 10}]
\ ->matchfuzzypos('ll', {'key' : 'text'})
[[{"id": 10, "text": "hello"}], [[2, 3]], [127]]
{list}
(any[]
)
{str}
(string
)
{dict}
(string?
)
any
){expr}
, {pat}
[, {start}
[, {count}
]]) matchlist()echo matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)')
{expr}
(any
)
{pat}
(string
)
{start}
(integer?
)
{count}
(integer?
)
any
){expr}
, {pat}
[, {start}
[, {count}
]]) matchstr()echo matchstr("testing", "ing")
{start}
, if given, has the same meaning as for match().echo matchstr("testing", "ing", 2)
echo matchstr("testing", "ing", 5)
{expr}
is a List then the matching item is returned.
The type isn't changed, it's not necessarily a String.{expr}
(any
)
{pat}
(string
)
{start}
(integer?
)
{count}
(integer?
)
any
){list}
, {pat}
[, {dict}
]) matchstrlist(){list}
where {pat}
matches.
{list}
is a List of strings. {pat}
is matched against each
string in {list}
.{dict}
argument supports following items:
submatches include submatch information (/\(){list}
of the match.
text matched string
submatches a List of submatches. Present only if
"submatches" is set to v:true in {dict}
.echo matchstrlist(['tik tok'], '\<\k\+\>')
[{'idx': 0, 'byteidx': 0, 'text': 'tik'}, {'idx': 0, 'byteidx': 4, 'text': 'tok'}]
echo matchstrlist(['a', 'b'], '\<\k\+\>')
[{'idx': 0, 'byteidx': 0, 'text': 'a'}, {'idx': 1, 'byteidx': 0, 'text': 'b'}]
echo matchstrlist(['acd'], '\(a\)\?\(b\)\?\(c\)\?\(.*\)',
\ #{submatches: v:true})
[{'idx': 0, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}]
The "submatches" List always contains 9 items. If a submatch
is not found, then an empty string is returned for that
submatch.{list}
(string[]
)
{pat}
(string
)
{dict}
(table?
)
any
){expr}
, {pat}
[, {start}
[, {count}
]]) matchstrpos()echo matchstrpos("testing", "ing")
{start}
, if given, has the same meaning as for match().echo matchstrpos("testing", "ing", 2)
echo matchstrpos("testing", "ing", 5)
{expr}
is a List then the matching item, the index
of first item where {pat}
matches, the start position and the
end position of the match are returned.echo matchstrpos([1, '__x'], '\a')
{expr}
(any
)
{pat}
(string
)
{start}
(integer?
)
{count}
(integer?
)
any
){expr}
) max(){expr}
. Example:echo max([apples, pears, oranges])
{expr}
can be a List or a Dictionary. For a Dictionary,
it returns the maximum of all values in the Dictionary.
If {expr}
is neither a List nor a Dictionary, or one of the
items in {expr}
cannot be used as a Number this results in
an error. An empty List or Dictionary results in zero.{expr}
(any
)
number
){path}
[, {modes}
]) {path}
matches a menu by name, or all menus if {path}
is an
empty string. Example:echo menu_get('File','')
echo menu_get('')
{modes}
is a string of zero or more modes (see maparg() or
creating-menus for the list of modes). "a" means "all".nnoremenu &Test.Test inormal
inoremenu Test.Test insert
vnoremenu Test.Test x
echo menu_get("")
[ { "hidden": 0, "name": "Test", "priority": 500, "shortcut": 84, "submenus": [ { "hidden": 0, "mappings": { i": { "enabled": 1, "noremap": 1, "rhs": "insert", "sid": 1, "silent": 0 }, n": { ... }, s": { ... }, v": { ... } }, "name": "Test", "priority": 500, "shortcut": 0 } ] } ]
{path}
(string
)
{modes}
(string?
)
any
){name}
[, {mode}
]) {name}
in
mode {mode}
. The menu name should be specified without the
shortcut character ('&'). If {name}
is "", then the top-level
menu names are returned.{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
"t" Terminal-Job
"" Normal, Visual and Operator-pending
"!" Insert and Cmd-line
When {mode}
is omitted, the modes for "" are used.{rhs}
of the menu item is not
remappable else v:false.
priority menu order priority menu-priority
rhs right-hand-side of the menu item. The returned
string has special characters translated like
in the output of the ":menu" command listing.
When the {rhs}
of a menu item is empty, then
"<Nop>" is returned.
script v:true if script-local remapping of {rhs}
is
allowed else v:false. See :menu-script.
shortcut shortcut key (character after '&' in
the menu name) menu-shortcut
silent v:true if the menu item is created
with <silent>
argument :menu-silent
submenus List containing the names of
all the submenus. Present only if the menu
item has submenus.echo menu_info('Edit.Cut')
echo menu_info('File.Save', 'n')
" Display the entire menu hierarchy in a buffer
func ShowMenu(name, pfx)
let m = menu_info(a:name)
call append(line('$'), a:pfx .. m.display)
for child in m->get('submenus', [])
call ShowMenu(a:name .. '.' .. escape(child, '.'),
\ a:pfx .. ' ')
endfor
endfunc
new
for topmenu in menu_info('').submenus
call ShowMenu(topmenu, '')
endfor
{name}
(string
)
{mode}
(string?
)
any
){expr}
) min(){expr}
. Example:echo min([apples, pears, oranges])
{expr}
can be a List or a Dictionary. For a Dictionary,
it returns the minimum of all values in the Dictionary.
If {expr}
is neither a List nor a Dictionary, or one of the
items in {expr}
cannot be used as a Number this results in
an error. An empty List or Dictionary results in zero.{expr}
(any
)
number
){flags}
is present it must be a string. An empty string
has no effect.{flags}
can contain these character flags:
"p" intermediate directories will be created as necessary
"D" {name}
will be deleted at the end of the current
function, but not recursively :defer
"R" {name}
will be deleted recursively at the end of the
current function :defer{name}
has more than one part and "p" is used
some directories may already exist. Only the first one that
is created and what it contains is scheduled to be deleted.
E.g. when using:call mkdir('subdir/tmp/autoload', 'pR')
defer delete('subdir/tmp', 'rf')
{prot}
is given it is used to set the protection bits of
the new directory. The default is 0o755 (rwxr-xr-x: r/w for
the user, readable for others). Use 0o700 to make it
unreadable for others.{prot}
is applied for all parts of {name}
. Thus if you create
/tmp/foo/bar then /tmp/foo will be created with 0o700. Example:call mkdir($HOME .. "/tmp/foo/bar", "p", 0o700)
{flags}
set to
"p" mkdir() will silently exit.{name}
(string
)
{flags}
(string?
)
{prot}
(string?
)
integer
){expr}
]) mode(){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.
Also see state().CTRL-V
is one character
niI Normal using i_CTRL-O in Insert-mode
niR Normal using i_CTRL-O in Replace-mode
niV Normal using i_CTRL-O in Virtual-Replace-mode
nt Normal in terminal-emulator (insert goes to
Terminal mode)
ntT Normal using t_CTRL-\_CTRL-O in Terminal-mode
v Visual by character
vs Visual by character using v_CTRL-O in Select mode
V Visual by line
Vs Visual by line using v_CTRL-O in Select mode
CTRL-V
Visual blockwise
CTRL-V
s Visual blockwise using v_CTRL-O in Select mode
s Select by character
S Select by line
CTRL-S
Select blockwise
i Insert
ic Insert mode completion compl-generic
ix Insert mode i_CTRL-X completion
R Replace R
Rc Replace mode completion compl-generic
Rx Replace mode i_CTRL-X completion
Rv Virtual Replace gR
Rvc Virtual Replace mode completion compl-generic
Rvx Virtual Replace mode i_CTRL-X completion
c Command-line editing
cr Command-line editing overstrike mode c_<Insert>
cv Vim Ex mode gQ
cvr Vim Ex mode while in overstrike mode c_<Insert>
r Hit-enter prompt
rm The -- more -- prompt
r? A :confirm query of some sort
! Shell or external command is executing
t Terminal mode: keys go to the job{expr}
(any?
)
any
){list}
[, {type}
]) msgpackdump(){type}
contains "B", a Blob is
returned instead. Example:call writefile(msgpackdump([{}]), 'fname.mpack', 'b')
call writefile(msgpackdump([{}], 'B'), 'fname.mpack')
fname.mpack
file
(dictionary with zero items is represented by 0x80 byte in
messagepack).{list}
(any
)
{type}
(any?
)
any
){data}
) msgpackparse()let fname = expand('~/.config/nvim/shada/main.shada')
let mpack = readfile(fname, 'b')
let shada_objects = msgpackparse(mpack)
shada_objects
list._TYPE
and _VAL
.
2. _TYPE
key is one of the types found in v:msgpack_types
variable.
3. Value for _VAL
has the following format (Key column
contains name of the key from v:msgpack_types):_VAL[0] * ((_VAL[1] << 62) & (_VAL[2] << 31) & _VAL[3])
{data}
(any
)
any
){lnum}
) nextnonblank(){lnum}
that is not blank. Example:if getline(nextnonblank(1)) =~ "Java" | endif
{lnum}
is invalid or there is no non-blank line at or
below it, zero is returned.
{lnum}
is used like with getline().
See also prevnonblank().{lnum}
(integer
)
integer
){expr}
[, {utf8}
]) nr2char(){expr}
. Examples:echo nr2char(64) " returns '@'
echo nr2char(32) " returns ' '
echo nr2char(300) " returns I with bow character
{utf8}
option has no effect,
and exists only for backwards-compatibility.
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.{expr}
(integer
)
{utf8}
(boolean?
)
string
){...}
) nvim_...() E5555 eval-api
Call nvim api functions. The type checking of arguments will
be stricter than for most other builtins. For instance,
if Integer is expected, a Number must be passed in, a
String will not be autoconverted.
Buffer numbers, as returned by bufnr() could be used as
first argument to nvim_buf_... functions. All functions
expecting an object (buffer, window or tabpage) can
also take the numerical value 0 to indicate the current
(focused) object.{...}
(any
)
any
){expr}
, {expr}
) or()and()
and xor()
.
Example:let bits = or(bits, 0x80)
{expr}
(number
)
{expr1}
(number
)
any
){path}
[, {len}
]) pathshorten(){path}
and return the
result. The tail, the file name, is kept as-is. The other
components in the path are reduced to {len}
letters in length.
If {len}
is omitted or smaller than 1 then 1 is used (single
letters). Leading '~' and '.' characters are kept. Examples:echo pathshorten('~/.config/nvim/autoload/file1.vim')
echo pathshorten('~/.config/nvim/autoload/file2.vim', 2)
{path}
(string
)
{len}
(integer?
)
string
){expr}
) perleval(){expr}
and return its result
converted to Vim data structures.
Numbers and strings are returned as they are (strings are
copied though).
Lists are represented as Vim List type.
Dictionaries are represented as Vim Dictionary type,
non-string keys result in error.{expr}
must return a
reference to it.
Example:echo perleval('[1 .. 4]')
{expr}
(any
)
any
){x}
, {y}
) pow(){x}
to the exponent {y}
as a Float.
{x}
and {y}
must evaluate to a Float or a Number.
Returns 0.0 if {x}
or {y}
is not a Float or a Number.
Examples:echo pow(3, 3)
echo pow(2, 16)
echo pow(32, 0.20)
{x}
(number
)
{y}
(number
)
number
){lnum}
) prevnonblank(){lnum}
that is not blank. Example:let ind = indent(prevnonblank(v:lnum - 1))
{lnum}
is invalid or there is no non-blank line at or
above it, zero is returned.
{lnum}
is used like with getline().
Also see nextnonblank().{lnum}
(integer
)
integer
){fmt}
, {expr1}
...) printf(){fmt}
, where "%" items are replaced by
the formatted form of their respective arguments. Example:echo printf("%4d: E%d %.30s", lnum, errno, msg)
Compute()->printf("result: %d")
call()
to pass the items as a list.{n$}
, where n is >= 1.echo printf("%d: %.*s", nr, width, line)
{n$}
positional argument specifier. See printf-$.echo printf("%.2f", 12.115)
{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.#, c-format
msgid "%s returning %s"
msgstr "waarde %2$s komt terug van %1$s"
echo printf(
"In The Netherlands, vim's creator's name is: %1$s %2$s",
"Bram", "Moolenaar")
echo printf(
"In Belgium, vim's creator's name is: %2$s %1$s",
"Bram", "Moolenaar")
echo printf("%1$*2$.*3$d", 1, 2, 3)
echo printf("%2$*3$.*1$d", 1, 2, 3)
echo printf("%3$*1$.*2$d", 1, 2, 3)
echo printf("%1$*2$.*3$g", 1.4142, 2, 3)
echo printf("%1$4.*2$f", 1.4142135, 6)
echo printf("%1$*2$.4f", 1.4142135, 6)
echo printf("%1$*2$.*3$f", 1.4142135, 6, 2)
echo printf("%3$s%1$s", "One", "Two", "Three")
echo printf("%1$d at width %2$d is: %01$*2$d", 1, 2)
echo printf("%1$d at width %2$ld is: %01$*2$d", 1, 2)
echo printf("%1$d at width %2$d is: %01$*2$.*3$d", 1, 2)
echo printf("%01$*2$.*3$d %4$d", 1, 2)
echo printf("%1$s %2$s %1$d", "One", "Two")
echo printf("%1$d at width %2$d is: %01$*2$.3$d", 1, 2)
{fmt}
(string
)
{expr1}
(any?
)
string
){buf}
) prompt_getprompt(){buf}
. {buf}
can
be a buffer name or number. See prompt-buffer.{buf}
(integer|string
)
any
){buf}
, {expr}
) prompt_setcallback(){buf}
to {expr}
. When {expr}
is an empty string the callback is removed. This has only
effect if {buf}
has 'buftype' set to "prompt". func s:TextEntered(text)
if a:text == 'exit' || a:text == 'quit'
stopinsert
" Reset 'modified' to allow the buffer to be closed.
" We assume there is nothing useful to be saved.
set nomodified
close
else
" Do something useful with "a:text". In this example
" we just repeat it.
call append(line('$') - 1, 'Entered: "' .. a:text .. '"')
endif
endfunc
call prompt_setcallback(bufnr(), function('s:TextEntered'))
Parameters: ~
• {buf} (`integer|string`)
• {expr} (`string|function`)
Return: ~
(`any`)
prompt_setinterrupt({buf}
, {expr}
) prompt_setinterrupt(){buf}
to {expr}
. When {expr}
is an
empty string the callback is removed. This has only effect if
{buf}
has 'buftype' set to "prompt".CTRL-C
in Insert
mode. Without setting a callback Vim will exit Insert mode,
as in any buffer.{buf}
(integer|string
)
{expr}
(string|function
)
any
){buf}
, {text}
) prompt_setprompt(){buf}
to {text}
. You most likely want
{text}
to end in a space.
The result is only visible if {buf}
has 'buftype' set to
"prompt". Example:call prompt_setprompt(bufnr(''), 'command: ')
{buf}
(integer|string
)
{text}
(string
)
any
)any
)any
){expr}
) py3eval(){expr}
and return its result
converted to Vim data structures.
Numbers and strings are returned as they are (strings are
copied though, Unicode strings are additionally converted to
UTF-8).
Lists are represented as Vim List type.
Dictionaries are represented as Vim Dictionary type with
keys converted to strings.{expr}
(any
)
any
){expr}
) pyeval() E858 E859
Evaluate Python expression {expr}
and return its result
converted to Vim data structures.
Numbers and strings are returned as they are (strings are
copied though).
Lists are represented as Vim List type.
Dictionaries are represented as Vim Dictionary type,
non-string keys result in error.{expr}
(any
)
any
){expr}
) pyxeval(){expr}
and return its result
converted to Vim data structures.
Uses Python 2 or 3, see python_x and 'pyxversion'.
See also: pyeval(), py3eval(){expr}
(any
)
any
){expr}
]) rand(){expr}
. The returned number is 32 bits,
also on 64 bits systems, for consistency.
{expr}
can be initialized by srand() and will be updated by
rand(). If {expr}
is omitted, an internal seed value is used
and updated.
Returns -1 if {expr}
is invalid.echo rand()
let seed = srand()
echo rand(seed)
echo rand(seed) % 16 " random number 0 - 15
{expr}
(number?
)
any
){expr}
[, {max}
[, {stride}
]]) range() E726 E727
Returns a List with Numbers:
{expr}
is specified: [0, 1, ..., {expr}
- 1]
{max}
is specified: [{expr}
, {expr}
+ 1, ..., {max}
]
{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:echo range(4) " [0, 1, 2, 3]
echo range(2, 4) " [2, 3, 4]
echo range(2, 9, 3) " [2, 5, 8]
echo range(2, -2, -1) " [2, 1, 0, -1, -2]
echo range(0) " []
echo range(2, 0) " error!
{expr}
(any
)
{max}
(integer?
)
{stride}
(integer?
)
any
){fname}
[, {offset}
[, {size}
]]) readblob(){fname}
in binary mode and return a Blob.
If {offset}
is specified, read the file from the specified
offset. If it is a negative value, it is used as an offset
from the end of the file. E.g., to read the last 12 bytes:echo readblob('file.bin', -12)
{size}
is specified, only the specified size will be read.
E.g. to read the first 100 bytes of a file:echo readblob('file.bin', 0, 100)
{size}
is -1 or omitted, the whole data starting from
{offset}
will be read.
This can be also used to read the data from a character device
on Unix when {size}
is explicitly set. Only if the device
supports seeking {offset}
can be used. Otherwise it should be
zero. E.g. to read 10 bytes from a serial console:echo readblob('/dev/ttyS0', 0, 10)
{fname}
(string
)
{offset}
(integer?
)
{size}
(integer?
)
any
){directory}
[, {expr}
]) readdir(){directory}
.
You can also use glob() if you don't need to do complicated
things, such as limiting the number of matches.{expr}
is omitted all entries are included.
When {expr}
is given, it is evaluated to check what to do:
If {expr}
results in -1 then no further entries will
be handled.
If {expr}
results in 0 then this entry will not be
added to the list.
If {expr}
results in 1 then this entry will be added
to the list.
Each time {expr}
is evaluated v:val is set to the entry name.
When {expr}
is a function the name is passed as the argument.
For example, to get a list of files ending in ".txt":echo readdir(dirname, {n -> n =~ '.txt$'})
echo readdir(dirname, {n -> n !~ '^\.\|\~$'})
function! s:tree(dir)
return {a:dir : map(readdir(a:dir),
\ {_, x -> isdirectory(x) ?
\ {x : s:tree(a:dir .. '/' .. x)} : x})}
endfunction
echo s:tree(".")
{directory}
(string
)
{expr}
(integer?
)
any
){fname}
[, {type}
[, {max}
]]) readfile(){fname}
and return a List, each line of the file
as an item. Lines are 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 {type}
contains "b" binary mode is used:
{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
{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.
Deprecated (use readblob() instead): When {type}
contains
"B" a Blob is returned with the binary data of the file
unmodified.
When the file can't be opened an error message is given and
the result is an empty list.
Also see writefile().{fname}
(string
)
{type}
(string?
)
{max}
(integer?
)
any
){object}
, {func}
[, {initial}
]) reduce() E998
{func}
is called for every item in {object}
, which can be a
String, List or a Blob. {func}
is called with two
arguments: the result so far and current item. After
processing all items the result is returned.{initial}
is the initial result. When omitted, the first item
in {object}
is used and {func}
is first called for the second
item. If {initial}
is not given and {object}
is empty no
result can be computed, an E998 error is given.echo reduce([1, 3, 5], { acc, val -> acc + val })
echo reduce(['x', 'y'], { acc, val -> acc .. val }, 'a')
echo reduce(0z1122, { acc, val -> 2 * acc + val })
echo reduce('xyz', { acc, val -> acc .. ',' .. val })
{object}
(any
)
{func}
(fun(accumulator: T, current: any): any
)
{initial}
(any?
)
T
)any
)any
)any
){start}
)
reltime({start}
, {end}
)
Return an item that represents a time value. The item is a
list with items that depend on the system.
The item can be passed to reltimestr() to convert it to a
string or reltimefloat() to convert to a Float.{start}
and {end}
.{start}
and {end}
arguments must be values returned by
reltime(). Returns zero on error.{start}
(any?
)
{end}
(any?
)
any
){time}
) reltimefloat(){time}
.
Unit of time is seconds.
Example:
let start = reltime()
call MyFunction()
let seconds = reltimefloat(reltime(start))
See the note of reltimestr() about overhead.
Also see profiling.
If there is an error an empty string is returned{time}
(any
)
any
){time}
) reltimestr(){time}
.
This is the number of seconds, a dot and the number of
microseconds. Example:let start = reltime()
call MyFunction()
echo reltimestr(reltime(start))
echo split(reltimestr(reltime(start)))[0]
{time}
(any
)
any
){list}
, {idx}
) remove(){list}
, {idx}
, {end}
)
Without {end}
: Remove the item at {idx}
from List {list}
and
return the item.
With {end}
: Remove items from {idx}
to {end}
(inclusive) and
return a List with these items. When {idx}
points to the same
item as {end}
a list with one item is returned. When {end}
points to an item before {idx}
this is an error.
See list-index for possible values of {idx}
and {end}
.
Returns zero on error.
Example:echo "last item: " .. remove(mylist, -1)
call remove(mylist, 0, 9)
{list}
(any[]
)
{idx}
(integer
)
{end}
(integer?
)
any
){blob}
, {idx}
)
remove({blob}
, {idx}
, {end}
)
Without {end}
: Remove the byte at {idx}
from Blob {blob}
and
return the byte.
With {end}
: Remove bytes from {idx}
to {end}
(inclusive) and
return a Blob with these bytes. When {idx}
points to the same
byte as {end}
a Blob with one byte is returned. When {end}
points to a byte before {idx}
this is an error.
Returns zero on error.
Example:echo "last byte: " .. remove(myblob, -1)
call remove(mylist, 0, 9)
{blob}
(any
)
{idx}
(integer
)
{end}
(integer?
)
any
){dict}
, {key}
)
Remove the entry from {dict}
with key {key}
and return it.
Example:echo "removed " .. remove(dict, "one")
{key}
in {dict}
this is an error.
Returns zero on error.{dict}
(any
)
{key}
(string
)
any
){from}
, {to}
) rename(){from}
to the name {to}
. This
should also work to move files across file systems. The
result is a Number, which is 0 if the file was renamed
successfully, and non-zero when the renaming failed.
NOTE: If {to}
exists it is overwritten without warning.
This function is not available in the sandbox.{from}
(string
)
{to}
(string
)
integer
){expr}
, {count}
) repeat(){expr}
{count}
times and return the concatenated
result. Example:let separator = repeat('-', 80)
{count}
is zero or negative the result is empty.
When {expr}
is a List or a Blob the result is {expr}
concatenated {count}
times. Example:let longlist = repeat(['a', 'b'], 3)
{expr}
(any
)
{count}
(integer
)
any
){filename}
) resolve() E655
On MS-Windows, when {filename}
is a shortcut (a .lnk file),
returns the path the shortcut points to in a simplified form.
On Unix, repeat resolving symbolic links in all path
components of {filename}
and return the simplified result.
To cope with link cycles, resolving of symbolic links is
stopped after 100 iterations.
On other systems, return the simplified {filename}
.
The simplification step is done as by simplify().
resolve() keeps a leading path component specifying the
current directory (provided the result is still a relative
path name) and also keeps a trailing path separator.{filename}
(string
)
string
){object}
) reverse(){object}
. {object}
can be a
List, a Blob or a String. For a List and a Blob the
items are reversed in-place and {object}
is returned.
For a String a new String is returned.
Returns zero if {object}
is not a List, Blob or a String.
If you want a List or Blob to remain unmodified make a copy
first:let revlist = reverse(copy(mylist))
{object}
(T[]
)
T[]
){expr}
) round(){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.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo round(0.456)
echo round(4.5)
echo round(-4.5)
{expr}
(number
)
number
){channel}
, {event}
[, {args}
...]) rpcnotify(){event}
to {channel}
via RPC and returns immediately.
If {channel}
is 0, the event is broadcast to all channels.
Example:au VimLeave call rpcnotify(0, "leaving")
{channel}
(integer
)
{event}
(string
)
{...}
(any
)
integer
){channel}
, {method}
[, {args}
...]) rpcrequest(){channel}
to invoke {method}
via
RPC and blocks until a response is received.
Example:let result = rpcrequest(rpc_chan, "func", 1, 2, 3)
{channel}
(integer
)
{method}
(string
)
{...}
(any
)
any
){expr}
) rubyeval(){expr}
and return its result
converted to Vim data structures.
Numbers, floats and strings are returned as they are (strings
are copied though).
Arrays are represented as Vim List type.
Hashes are represented as Vim Dictionary type.
Other objects are represented as strings resulted from their
"Object#to_s" method.{expr}
(any
)
any
){row}
, {col}
) screenattr(){row}
(integer
)
{col}
(integer
)
integer
){row}
, {col}
) screenchar(){row}
(integer
)
{col}
(integer
)
integer
){row}
, {col}
) screenchars(){row}
(integer
)
{col}
(integer
)
integer[]
)nnoremap <expr> GG ":echom " .. screencol() .. "\n"
nnoremap <silent> GG :echom screencol()<CR>
noremap GG <Cmd>echom screencol()<CR>
integer[]
){winid}
, {lnum}
, {col}
) screenpos(){winid}
at buffer line {lnum}
and column
{col}
. {col}
is a one-based byte index.
The Dict has these members:
row screen row
col first screen column
endcol last screen column
curscol cursor screen column
If the specified position is not visible, all values are zero.
The "endcol" value differs from "col" when the character
occupies more than one screen cell. E.g. for a Tab "col" can
be 1 and "endcol" can be 8.
The "curscol" value is where the cursor would be placed. For
a Tab it would be the same as "endcol", while for a double
width character it would be the same as "col".
The conceal feature is ignored here, the column numbers are
as if 'conceallevel' is zero. You can set the cursor to the
right position and use screencol() to get the value with
conceal taken into account.
If the position is in a closed fold the screen position of the
first character is returned, {col}
is not used.
Returns an empty Dict if {winid}
is invalid.{winid}
(integer
)
{lnum}
(integer
)
{col}
(integer
)
any
)integer
){row}
, {col}
) screenstring(){row}
(integer
)
{col}
(integer
)
string
){pattern}
[, {flags}
[, {stopline}
[, {timeout}
[, {skip}
]]]]) search()
Search for regexp pattern {pattern}
. The search starts at the
cursor position (you can use cursor() to set it).{flags}
is a String, which can contain these character flags:
'b' search Backward instead of forward
'c' accept a match at the Cursor position
'e' move to the End of the match
'n' do Not move the cursor
'p' return number of matching sub-Pattern (see below)
's' Set the ' mark at the previous location of the cursor
'w' Wrap around the end of the file
'W' don't Wrap around the end of the file
'z' start searching at the cursor column instead of Zero
If neither 'w' or 'W' is given, the 'wrapscan' option applies.{stopline}
argument is given then the search stops
after searching this line. This is useful to restrict the
search to a range of lines. Examples:let match = search('(', 'b', line("w0"))
let end = search('END', '', line("w$"))
{stopline}
is used and it is not zero this also implies
that the search does not wrap around the end of the file.
A zero value is equal to not giving the argument.{timeout}
argument is given the search stops when
more than this many milliseconds have passed. Thus when
{timeout}
is 500 the search stops after half a second.
The value must not be negative. A zero value is like not
giving the argument.{skip}
expression.{skip}
expression is given it is evaluated with the
cursor positioned on the start of a match. If it evaluates to
non-zero this match is skipped. This can be used, for
example, to skip a match in a comment or a string.
{skip}
can be a string, which is evaluated as an expression, a
function reference or a lambda.
When {skip}
is omitted or empty, every match is accepted.
When evaluating {skip}
causes an error the search is aborted
and -1 returned.
search()-sub-match let n = 1
while n <= argc() " loop over all files in arglist
exe "argument " .. n
" start at the last char in the file and wrap for the
" first search to find match at start of file
normal G$
let flags = "w"
while search("foo", flags) > 0
s/foo/bar/g
let flags = "W"
endwhile
update " write the file if modified
let n = n + 1
endwhile
echo search('\<if\|\(else\)\|\(endif\)', 'ncpe')
{pattern}
(string
)
{flags}
(string?
)
{stopline}
(integer?
)
{timeout}
(integer?
)
{skip}
(string|function?
)
integer
){options}
]) searchcount(){options}
see further down.recompute: 0
. This sometimes returns
wrong information because n and N's maximum count is 99.
If it exceeded 99 the result must be max count + 1 (100). If
you want to get correct information, specify recompute: 1
:" result == maxcount + 1 (100) when many matches
let result = searchcount(#{recompute: 0})
" Below returns correct result (recompute defaults
" to 1)
let result = searchcount()
function! LastSearchCount() abort
let result = searchcount(#{recompute: 0})
if empty(result)
return ''
endif
if result.incomplete ==# 1 " timed out
return printf(' /%s [?/??]', @/)
elseif result.incomplete ==# 2 " max count exceeded
if result.total > result.maxcount &&
\ result.current > result.maxcount
return printf(' /%s [>%d/>%d]', @/,
\ result.current, result.total)
elseif result.total > result.maxcount
return printf(' /%s [%d/>%d]', @/,
\ result.current, result.total)
endif
endif
return printf(' /%s [%d/%d]', @/,
\ result.current, result.total)
endfunction
let &statusline ..= '%{LastSearchCount()}'
" Or if you want to show the count only when
" 'hlsearch' was on
" let &statusline ..=
" \ '%{v:hlsearch ? LastSearchCount() : ""}'
autocmd CursorMoved,CursorMovedI *
\ let s:searchcount_timer = timer_start(
\ 200, function('s:update_searchcount'))
function! s:update_searchcount(timer) abort
if a:timer ==# s:searchcount_timer
call searchcount(#{
\ recompute: 1, maxcount: 0, timeout: 100})
redrawstatus
endif
endfunction
" Count '\<foo\>' in this buffer
" (Note that it also updates search count)
let result = searchcount(#{pattern: '\<foo\>'})
" To restore old search count by old pattern,
" search again
call searchcount()
{options}
must be a Dictionary. It can contain:
let @/ = pattern
maxcount + 1
(default: 0)
pos List [lnum, col, off]
value
when recomputing the result.
this changes "current" result
value. see cursor(), getpos()
(default: cursor's position){options}
(table?
)
any
){global}
argument it works like gD, find
first match in the file. Otherwise it works like gd, find
first match in the function.{thisblock}
argument matches in a {} block
that ends before the cursor position are ignored. Avoids
finding variable declarations only valid in another scope.if searchdecl('myvar') == 0
echo getline('.')
endif
{name}
(string
)
{global}
(boolean?
)
{thisblock}
(boolean?
)
any
){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:echo searchpair('\<if\>', '\<else\>', '\<endif\>')
{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
outer pair. Implies the 'W' flag.
'm' Return number of matches instead of line number with
the match; will be > 1 when 'r' is used.
Note: it's nearly always a good idea to use the 'W' flag, to
avoid wrapping around the end of the file.{start}
, {middle}
or {end}
is found, the
{skip}
expression is evaluated with the cursor positioned on
the start of the match. It should return non-zero if this
match is to be skipped. E.g., because it is inside a comment
or a string.
When {skip}
is omitted or empty, every match is accepted.
When evaluating {skip}
causes an error the search is aborted
and -1 returned.
{skip}
can be a string, a lambda, a funcref or a partial.
Anything else makes the function fail.{start}
, {middle}
or {end}
at the next character, in the
direction of searching, is the first one found. Example:if 1
if 2
endif 2
endif 1
{end}
is more than one character,
it may be useful to put "\zs" at the end of the pattern, so
that when the cursor is inside a match with the end it finds
the matching start.echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',
\ 'getline(".") =~ "^\\s*\""')
echo searchpair('{', '', '}', 'bW')
echo searchpair('{', '', '}', 'bW',
\ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')
{start}
(string
)
{middle}
(string
)
{end}
(string
)
{flags}
(string?
)
{skip}
(string|function?
)
{stopline}
(integer?
)
{timeout}
(integer?
)
integer
){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')
{start}
(string
)
{middle}
(string
)
{end}
(string
)
{flags}
(string?
)
{skip}
(string|function?
)
{stopline}
(integer?
)
{timeout}
(integer?
)
[integer, integer]
){pattern}
[, {flags}
[, {stopline}
[, {timeout}
[, {skip}
]]]])
Same as search(), 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].
Example:let [lnum, col] = searchpos('mypattern', 'n')
let [lnum, col, submatch] = searchpos('\(\l\)\|\(\u\)', 'np')
{pattern}
(string
)
{flags}
(string?
)
{stopline}
(integer?
)
{timeout}
(integer?
)
{skip}
(string|function?
)
any
)echo serverlist()
string[]
){address}
]) serverstart(){address}
and listens for
RPC messages. Clients can send API commands to the
returned address to control Nvim.{address}
argument, see below).{address}
has a colon (":") it is a TCP/IPv4/IPv6 address
where the last ":" separates host and port (empty or zero
assigns a random port).
{address}
is the path to a named pipe (except on Windows).
{address}
has no slashes ("/") it is treated as the
"name" part of a generated path in this format:stdpath("run").."/{name}.{pid}.{counter}"
{address}
is omitted the name is "nvim".
echo serverstart()
=> /tmp/nvim.bram/oknANW/nvim.15430.5
ls ${XDG_RUNTIME_DIR:-${TMPDIR}nvim.${USER}}/*/nvim.*.0
if has('win32')
echo serverstart('\\.\pipe\nvim-pipe-1234')
else
echo serverstart('nvim.sock')
endif
echo serverstart('::1:12345')
{address}
(string?
)
string
){address}
) serverstop(){address}
.
Returns TRUE if {address}
is valid, else FALSE.
If v:servername is stopped it is set to the next available
address in serverlist().{address}
(string
)
integer
){buf}
, {lnum}
, {text}
) setbufline(){lnum}
to {text}
in buffer {buf}
. This works like
setline() for the specified buffer.{text}
can be a string to set one line, or a List of strings
to set multiple lines. If the List extends below the last
line then those lines are added. If the List is empty then
nothing is changed and zero is returned.{buf}
, see bufname() above.{lnum}
is used like with setline().
Use "$" to refer to the last line in buffer {buf}
.
When {lnum}
is just below the last line the {text}
will be
added below the last line.
On success 0 is returned, on failure 1 is returned.{buf}
is not a valid buffer or {lnum}
is not valid, an
error message is given.{buf}
(integer|string
)
{lnum}
(integer
)
{text}
(string|string[]
)
integer
){buf}
, {varname}
, {val}
) setbufvar(){varname}
in buffer {buf}
to
{val}
.
This also works for a global or local window option, but it
doesn't work for a global or local window variable.
For a local window option the global value is unchanged.
For the use of {buf}
, see bufname() above.
The {varname}
argument is a string.
Note that the variable name without "b:" must be used.
Examples:call setbufvar(1, "&mod", 1)
call setbufvar("todo", "myvar", "foobar")
{buf}
(integer|string
)
{varname}
(string
)
{val}
(any
)
any
){list}
) setcellwidths()call setcellwidths([
\ [0x111, 0x111, 1],
\ [0x2194, 0x2199, 2],
\ ])
{list}
argument is a List of Lists with each three
numbers: [{low}
, {high}
, {width}
]. E1109 E1110
{low}
and {high}
can be the same, in which case this refers to
one character. Otherwise it is the range of characters from
{low}
to {high}
(inclusive). E1111 E1114
Only characters with value 0x80 and higher can be used.{width}
must be either 1 or 2, indicating the character width
in screen cells. E1112 {list}
:call setcellwidths([])
{list}
argument.{list}
(any[]
)
any
){expr}
, {list}
) setcharpos()call setcharpos('.', [0, 8, 4, 0])
call setpos('.', [0, 8, 4, 0])
{expr}
(string
)
{list}
(integer[]
)
any
){dict}
) setcharsearch(){dict}
,
which contains one or more of the following entries:let prevsearch = getcharsearch()
" Perform a command which clobbers user's search
call setcharsearch(prevsearch)
{dict}
(string
)
any
){str}
[, {pos}
]) setcmdline(){str}
and set the cursor position to
{pos}
.
If {pos}
is omitted, the cursor is positioned after the text.
Returns 0 when successful, 1 when not editing the command
line.{str}
(string
)
{pos}
(integer?
)
integer
){pos}
) setcmdpos(){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.{pos}
(integer
)
any
){lnum}
, {col}
[, {off}
]) setcursorcharpos(){list}
)
Same as cursor() but uses the specified column number as the
character index instead of the byte index in the line.call setcursorcharpos(4, 3)
call cursor(4, 3)
{list}
(integer[]
)
any
){name}
, {val}
) setenv(){name}
to {val}
. Example:call setenv('HOME', '/home/myhome')
{name}
(string
)
{val}
(string
)
any
){fname}
, {mode}
) setfperm() chmod
Set the file permissions for {fname}
to {mode}
.
{mode}
must be a string with 9 characters. It 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. A '-' character means the
permission is off, any other character means on. Multi-byte
characters are not supported.{fname}
(string
)
{mode}
(string
)
any
){lnum}
, {text}
) setline(){lnum}
of the current buffer to {text}
. To insert
lines use append(). To set lines in another buffer use
setbufline().{lnum}
is used like with getline().
When {lnum}
is just below the last line the {text}
will be
added below the last line.
{text}
can be any type or a List of any type, each item is
converted to a String. When {text}
is an empty List then
nothing is changed and FALSE is returned.{lnum}
is invalid) TRUE is returned.call setline(5, strftime("%c"))
{text}
is a List then line {lnum}
and following lines
will be set to the items in the list. Example:call setline(5, ['aaa', 'bbb', 'ccc'])
for [n, l] in [[5, 'aaa'], [6, 'bbb'], [7, 'ccc']]
call setline(n, l)
endfor
{lnum}
(integer
)
{text}
(any
)
any
){nr}
, {list}
[, {action}
[, {what}
]]) setloclist(){nr}
.
{nr}
can be the window number or the window-ID.
When {nr}
is zero the current window is used.{nr}
, -1 is returned.
Otherwise, same as setqflist().
Also see location-list.{action}
see setqflist-action.{what}
dictionary argument is supplied, then
only the items listed in {what}
are set. Refer to setqflist()
for the list of supported keys in {what}
.{nr}
(integer
)
{list}
(any
)
{action}
(string?
)
{what}
(table?
)
any
){list}
[, {win}
]) setmatches(){win}
is specified, use the window with this number or
window ID instead of the current window.{list}
(any
)
{win}
(integer?
)
any
){expr}
, {list}
) setpos(){expr}
. Possible values:
. the cursor
'x mark x{list}
must be a List with four or five numbers:
[bufnum, lnum, col, off]
[bufnum, lnum, col, off, curswant]<Tab>
or after the last
character.{expr}
is invalid.{expr}
(string
)
{list}
(integer[]
)
any
){list}
[, {action}
[, {what}
]]) setqflist(){what}
dictionary argument is supplied, then
only the items listed in {what}
are set. The first {list}
argument is ignored. See below for the supported items in
{what}
.
setqflist-what {what}
is not present, the items in {list}
are used. Each
item must be a dictionary. Non-dictionary items in {list}
are
ignored. Each dictionary item can contain the following
entries:{list}
, the quickfix list will be
cleared.
Note that the list is not exactly the same as what
getqflist() returns.{action}
values: setqflist-action E927
'a' The items from {list}
are added to the existing
quickfix list. If there is no existing list, then a
new list is created.{list}
. This can also be used to
clear the list:call setqflist([], 'r')
{action}
is not present or is set to ' ', then a new list
is created. The new quickfix list is added after the current
quickfix list in the stack and all the following lists are
freed. To add a new quickfix list at the end of the stack,
set "nr" in {what}
to "$".{what}
:
context quickfix list context. See quickfix-context
efm errorformat to use when parsing text from
"lines". If this is not present, then the
'errorformat' option value is used.
See quickfix-parse
id quickfix list identifier quickfix-ID
idx index of the current entry in the quickfix
list specified by "id" or "nr". If set to '$',
then the last entry in the list is set as the
current entry. See quickfix-index
items list of quickfix entries. Same as the {list}
argument.
lines use 'errorformat' to parse a list of lines and
add the resulting entries to the quickfix list
{nr}
or {id}
. Only a List value is supported.
See quickfix-parse
nr list number in the quickfix stack; zero
means the current quickfix list and "$" means
the last quickfix list.
quickfixtextfunc
function to get the text to display in the
quickfix window. The value can be the name of
a function or a funcref or a lambda. Refer to
quickfix-window-function for an explanation
of how to write the function and an example.
title quickfix list title text. See quickfix-title
Unsupported keys in {what}
are ignored.
If the "nr" item is not present, then the current quickfix list
is modified. When creating a new quickfix list, "nr" can be
set to a value one greater than the quickfix stack size.
When modifying a quickfix list, to guarantee that the correct
list is modified, "id" should be used instead of "nr" to
specify the list.call setqflist([], 'r', {'title': 'My search'})
call setqflist([], 'r', {'nr': 2, 'title': 'Errors'})
call setqflist([], 'a', {'id':qfid, 'lines':["F1:10:L10"]})
:cc 1
to jump to the first position.{list}
(vim.quickfix.entry[]
)
{action}
(string?
)
{what}
(vim.fn.setqflist.what?
)
integer
){regname}
, {value}
[, {options}
]) setreg(){regname}
to {value}
.
If {regname}
is "" or "@", the unnamed register '"' is used.
The {regname}
argument is a string.{value}
may be any value returned by getreg() or
getreginfo(), including a List or Dict.
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" charwise 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 "u" or '"', then the unnamed register is
set to point to register {regname}
.{options}
contains no register settings, then the default
is to use character mode unless {value}
ends in a <NL>
for
string {value}
and linewise mode for list {value}
. Blockwise
mode is never selected automatically.
Returns zero for success, non-zero for failure.call setreg(v:register, @*)
call setreg('*', @%, 'ac')
call setreg('a', "1\n2\n3", 'b5')
call setreg('"', { 'points_to': 'a'})
let var_a = getreginfo()
call setreg('a', var_a)
let var_a = getreg('a', 1, 1)
let var_amode = getregtype('a')
" ....
call setreg('a', var_a, var_amode)
call setreg('a', '', 'al')
Parameters: ~
• {regname} (`string`)
• {value} (`any`)
• {options} (`string?`)
Return: ~
(`any`)
settabvar({tabnr}
, {varname}
, {val}
) settabvar(){varname}
to {val}
in tab page {tabnr}
.
t:var
The {varname}
argument is a string.
Note that the variable name without "t:" must be used.
Tabs are numbered starting with one.
This function is not available in the sandbox.{tabnr}
(integer
)
{varname}
(string
)
{val}
(any
)
any
){tabnr}
, {winnr}
, {varname}
, {val}
) settabwinvar(){varname}
in window {winnr}
to
{val}
.
Tabs are numbered starting with one. For the current tabpage
use setwinvar().
{winnr}
can be the window number or the window-ID.
When {winnr}
is zero the current window is used.
This also works for a global or local buffer option, but it
doesn't work for a global or local buffer variable.
For a local buffer option the global value is unchanged.
Note that the variable name without "w:" must be used.
Examples:call settabwinvar(1, 1, "&list", 0)
call settabwinvar(3, 2, "myvar", "foobar")
{tabnr}
(integer
)
{winnr}
(integer
)
{varname}
(string
)
{val}
(any
)
any
){nr}
, {dict}
[, {action}
]) {nr}
using {dict}
.
{nr}
can be the window number or the window-ID.{dict}
, refer to
gettagstack(). "curidx" takes effect before changing the tag
stack.
E962 {action}
argument:
{action}
is not present or is set to 'r', then the tag
stack is replaced.
{action}
is set to 'a', then new entries from {dict}
are
pushed (added) onto the tag stack.
{action}
is set to 't', then all the entries from the
current entry in the tag stack or "curidx" in {dict}
are
removed and then new entries are pushed to the stack.
call settagstack(3, {'items' : []})
let stack = gettagstack(1003)
" do something else
call settagstack(1003, stack)
unlet stack
{nr}
(integer
)
{dict}
(any
)
{action}
(string?
)
any
){nr}
, {varname}
, {val}
) setwinvar() call setwinvar(1, "&list", 0)
call setwinvar(2, "myvar", "foobar")
Parameters: ~
• {nr} (`integer`)
• {varname} (`string`)
• {val} (`any`)
Return: ~
(`any`)
sha256({string}
) sha256(){string}
.{string}
(string
)
string
){string}
[, {special}
]) shellescape(){string}
for use as a shell command argument.{string}
in
double-quotes and doubles all double-quotes within {string}
.
Otherwise encloses {string}
in single-quotes and replaces all
"'" with "'\''".{special}
argument adds additional escaping of keywords
used in Vim commands. If it is a non-zero-arg:
<NL>
character is escaped.
exe '!dir ' .. shellescape(expand('<cfile>'), 1)
call system("chmod +w -- " .. shellescape(expand("%")))
{string}
(string
)
{special}
(boolean?
)
string
){col}
]) shiftwidth()if exists('*shiftwidth')
func s:sw()
return shiftwidth()
endfunc
else
func s:sw()
return &sw
endfunc
endif
{col}
this is used as column number
for which to return the 'shiftwidth' value. This matters for the
'vartabstop' feature. If no {col}
argument is given, column 1
will be assumed.{col}
(integer?
)
integer
){name}
[, {dict}
]) sign_define(){list}
)
Define a new sign named {name}
or modify the attributes of an
existing sign. This is similar to the :sign-define command.{name}
with a unique text to avoid name collisions.
There is no {group}
like with placing signs.{name}
can be a String or a Number. The optional {dict}
argument specifies the sign attributes. The following values
are supported:
icon full path to the bitmap file for the sign.
linehl highlight group used for the whole line the
sign is placed in.
priority default priority value of the sign
numhl highlight group used for the line number where
the sign is placed.
text text that is displayed when there is no icon
or the GUI is not being used.
texthl highlight group used for the text item
culhl highlight group used for the text item when
the cursor is on the same line as the sign and
'cursorline' is enabled.{name}
already exists, then the attributes
of the sign are updated.{list}
can be used to define a list of signs.
Each list item is a dictionary with the above items in {dict}
and a "name" item for the sign name.{list}
is used, then returns a List of values one for each
defined sign.call sign_define("mySign", {
\ "text" : "=>",
\ "texthl" : "Error",
\ "linehl" : "Search"})
call sign_define([
\ {'name' : 'sign1',
\ 'text' : '=>'},
\ {'name' : 'sign2',
\ 'text' : '!!'}
\ ])
{list}
(vim.fn.sign_define.dict[]
)
(0|-1)[]
){name}
]) sign_getdefined(){name}
is not supplied, then a list of all the defined
signs is returned. Otherwise the attribute of the specified
sign is returned.{name}
is
not found." Get a list of all the defined signs
echo sign_getdefined()
" Get the attribute of the sign named mySign
echo sign_getdefined("mySign")
{name}
(string?
)
vim.fn.sign_getdefined.ret.item[]
){buf}
[, {dict}
]]) sign_getplaced(){buf}
is specified, then only the
list of signs placed in that buffer is returned. For the use
of {buf}
, see bufname(). The optional {dict}
can contain
the following entries:
group select only signs in this group
id select sign with this identifier
lnum select signs placed in this line. For the use
of {lnum}
, see line().
If {group}
is "*", then signs in all the groups including the
global group are returned. If {group}
is not supplied or is an
empty string, then only signs in the global group are
returned. If no arguments are supplied, then signs in the
global group placed in all the buffers are returned.
See sign-group.{bufnr}
. Each list
item is a dictionary with the below listed
entries" Get a List of signs placed in eval.c in the
" global group
echo sign_getplaced("eval.c")
" Get a List of signs in group 'g1' placed in eval.c
echo sign_getplaced("eval.c", {'group' : 'g1'})
" Get a List of signs placed at line 10 in eval.c
echo sign_getplaced("eval.c", {'lnum' : 10})
" Get sign with identifier 10 placed in a.py
echo sign_getplaced("a.py", {'id' : 10})
" Get sign with id 20 in group 'g1' placed in a.py
echo sign_getplaced("a.py", {'group' : 'g1',
\ 'id' : 20})
" Get a List of all the placed signs
echo sign_getplaced()
{buf}
(integer|string?
)
{dict}
(vim.fn.sign_getplaced.dict?
)
vim.fn.sign_getplaced.ret.item[]
){id}
, {group}
, {buf}
) sign_jump(){buf}
or jump to the window that contains
{buf}
and position the cursor at sign {id}
in group {group}
.
This is similar to the :sign-jump command." Jump to sign 10 in the current buffer
call sign_jump(10, '', '')
{id}
(integer
)
{group}
(string
)
{buf}
(integer|string
)
integer
){id}
, {group}
, {name}
, {buf}
[, {dict}
]) sign_place(){name}
at line {lnum}
in file or
buffer {buf}
and assign {id}
and {group}
to sign. This is
similar to the :sign-place command.{id}
is zero, then a new identifier is
allocated. Otherwise the specified number is used. {group}
is
the sign group name. To use the global sign group, use an
empty string. {group}
functions as a namespace for {id}
, thus
two groups can use the same IDs. Refer to sign-identifier
and sign-group for more information.{name}
refers to a defined sign.
{buf}
refers to a buffer name or number. For the accepted
values, see bufname().{dict}
argument supports the following entries:
lnum line number in the file or buffer
{buf}
where the sign is to be placed.
For the accepted values, see line().
priority priority of the sign. See
sign-priority for more information.{dict}
is not specified, then it modifies the
placed sign {id}
in group {group}
to use the defined sign
{name}
." Place a sign named sign1 with id 5 at line 20 in
" buffer json.c
call sign_place(5, '', 'sign1', 'json.c',
\ {'lnum' : 20})
" Updates sign 5 in buffer json.c to use sign2
call sign_place(5, '', 'sign2', 'json.c')
" Place a sign named sign3 at line 30 in
" buffer json.c with a new identifier
let id = sign_place(0, '', 'sign3', 'json.c',
\ {'lnum' : 30})
" Place a sign named sign4 with id 10 in group 'g3'
" at line 40 in buffer json.c with priority 90
call sign_place(10, 'g3', 'sign4', 'json.c',
\ {'lnum' : 40, 'priority' : 90})
{id}
(integer
)
{group}
(string
)
{name}
(string
)
{buf}
(integer|string
)
{dict}
(vim.fn.sign_place.dict?
)
integer
){list}
) sign_placelist(){list}
argument specifies the
List of signs to place. Each list item is a dict with the
following sign attributes:
buffer Buffer name or number. For the accepted
values, see bufname().
group Sign group. {group}
functions as a namespace
for {id}
, thus two groups can use the same
IDs. If not specified or set to an empty
string, then the global group is used. See
sign-group for more information.
id Sign identifier. If not specified or zero,
then a new unique identifier is allocated.
Otherwise the specified number is used. See
sign-identifier for more information.
lnum Line number in the buffer where the sign is to
be placed. For the accepted values, see
line().
name Name of the sign to place. See sign_define()
for more information.
priority Priority of the sign. When multiple signs are
placed on a line, the sign with the highest
priority is used. If not specified, the
default value of 10 is used, unless specified
otherwise by the sign definition. See
sign-priority for more information.{id}
refers to an existing sign, then the existing sign is
modified to use the specified {name}
and/or {priority}
." Place sign s1 with id 5 at line 20 and id 10 at line
" 30 in buffer a.c
let [n1, n2] = sign_placelist([
\ {'id' : 5,
\ 'name' : 's1',
\ 'buffer' : 'a.c',
\ 'lnum' : 20},
\ {'id' : 10,
\ 'name' : 's1',
\ 'buffer' : 'a.c',
\ 'lnum' : 30}
\ ])
" Place sign s1 in buffer a.c at line 40 and 50
" with auto-generated identifiers
let [n1, n2] = sign_placelist([
\ {'name' : 's1',
\ 'buffer' : 'a.c',
\ 'lnum' : 40},
\ {'name' : 's1',
\ 'buffer' : 'a.c',
\ 'lnum' : 50}
\ ])
{list}
(vim.fn.sign_placelist.list.item[]
)
integer[]
){name}
]) sign_undefine(){list}
)
Deletes a previously defined sign {name}
. This is similar to
the :sign-undefine command. If {name}
is not supplied, then
deletes all the defined signs.{list}
can be used to undefine a list of
signs. Each list item is the name of a sign.{list}
call, returns a list of values one for each undefined
sign." Delete a sign named mySign
call sign_undefine("mySign")
" Delete signs 'sign1' and 'sign2'
call sign_undefine(["sign1", "sign2"])
" Delete all the signs
call sign_undefine()
{list}
(string[]?
)
integer[]
){group}
[, {dict}
]) sign_unplace(){group}
is the sign group name. To use the global sign group,
use an empty string. If {group}
is set to "*", then all the
groups including the global group are used.
The signs in {group}
are selected based on the entries in
{dict}
. The following optional entries in {dict}
are
supported:
buffer buffer name or number. See bufname().
id sign identifier
If {dict}
is not supplied, then all the signs in {group}
are
removed. " Remove sign 10 from buffer a.vim
call sign_unplace('', {'buffer' : "a.vim", 'id' : 10})
" Remove sign 20 in group 'g1' from buffer 3
call sign_unplace('g1', {'buffer' : 3, 'id' : 20})
" Remove all the signs in group 'g2' from buffer 10
call sign_unplace('g2', {'buffer' : 10})
" Remove sign 30 in group 'g3' from all the buffers
call sign_unplace('g3', {'id' : 30})
" Remove all the signs placed in buffer 5
call sign_unplace('*', {'buffer' : 5})
" Remove the signs in group 'g4' from all the buffers
call sign_unplace('g4')
" Remove sign 40 from all the buffers
call sign_unplace('*', {'id' : 40})
" Remove all the placed signs from all the buffers
call sign_unplace('*')
Parameters: ~
• {group} (`string`)
• {dict} (`vim.fn.sign_unplace.dict?`)
Return: ~
(`0|-1`)
sign_unplacelist({list}
) sign_unplacelist(){list}
argument specifies the List of signs to remove.
Each list item is a dict with the following sign attributes:
buffer buffer name or number. For the accepted
values, see bufname(). If not specified,
then the specified sign is removed from all
the buffers.
group sign group name. If not specified or set to an
empty string, then the global sign group is
used. If set to "*", then all the groups
including the global group are used.
id sign identifier. If not specified, then all
the signs in the specified group are removed." Remove sign with id 10 from buffer a.vim and sign
" with id 20 from buffer b.vim
call sign_unplacelist([
\ {'id' : 10, 'buffer' : "a.vim"},
\ {'id' : 20, 'buffer' : 'b.vim'},
\ ])
{list}
(vim.fn.sign_unplacelist.list.item
)
(0|-1)[]
){filename}
) simplify(){filename}
designates the current directory, this will be
valid for the result as well. A trailing path separator is
not removed either. On Unix "//path" is unchanged, but
"///path" is simplified to "/path" (this follows the Posix
standard).
Example:simplify("./dir/.././/file/") == "./file/"
{filename}
(string
)
string
){expr}
) sin(){expr}
, measured in radians, as a Float.
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo sin(100)
echo sin(-4.01)
{expr}
(number
)
number
){expr}
) sinh(){expr}
as a Float in the range
[-inf, inf].
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo sinh(0.5)
echo sinh(-0.9)
{expr}
(number
)
any
){expr}
, {start}
[, {end}
]) slice(){end}
is omitted the slice continues to the last item.
When {end}
is -1 the last item is omitted.
Returns an empty value if {start}
or {end}
are invalid.{expr}
(any
)
{start}
(integer
)
{end}
(integer?
)
any
){mode}
, {address}
[, {opts}
]) sockconnect(){mode}
is "pipe" then
{address}
should be the path of a local domain socket (on
unix) or named pipe (on Windows). If {mode}
is "tcp" then
{address}
should be of the form "host:port" where the host
should be an ip address or host name, and port the port
number.{opts}
is an optional dictionary with these keys:
on_data : callback invoked when data was read from socket
data_buffered : read socket data in channel-buffered mode.
rpc : If set, msgpack-rpc will be used to communicate
over the socket.
Returns:
{mode}
(string
)
{address}
(string
)
{opts}
(table?
)
any
)let sortedlist = sort(copy(mylist))
{how}
is omitted or is a string, then sort() uses the
string representation of each item to sort on. Numbers sort
after Strings, Lists after Numbers. For sorting text in the
current buffer use :sort.{how}
is given and it is 'i' then case is ignored.
For backwards compatibility, the value one can be used to
ignore case. Zero means to not ignore case.{how}
is given and it is 'l' then the current collation
locale is used for ordering. Implementation details: strcoll()
is used to compare strings. See :language check or set the
collation locale. v:collate can also be used to check the
current locale. Sorting using the locale typically ignores
case. Example:" ö is sorted similarly to o with English locale.
language collate en_US.UTF8
echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l')
" ö is sorted after z with Swedish locale.
language collate sv_SE.UTF8
echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l')
{how}
is given and it is 'n' then all items will be
sorted numerical (Implementation detail: this uses the
strtod() function to parse numbers, Strings, Lists, Dicts and
Funcrefs will be considered as being 0).{how}
is given and it is 'N' then all items will be
sorted numerical. This is like 'n' but a string containing
digits will be used as the number they represent.{how}
is given and it is 'f' then all items will be
sorted numerical. All values must be a Number or a Float.{how}
is a Funcref or a function name, this function
is called to compare items. The function is invoked with two
items as argument and must return zero if they are equal, 1 or
bigger if the first one sorts after the second one, -1 or
smaller if the first one sorts before the second one.{dict}
is for functions with the "dict" attribute. It will be
used to set the local variable "self". Dictionary-functionfunc MyCompare(i1, i2)
return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1
endfunc
eval mylist->sort("MyCompare")
func MyCompare(i1, i2)
return a:i1 - a:i2
endfunc
eval mylist->sort({i1, i2 -> i1 - i2})
{list}
(T[]
)
{how}
(string|function?
)
{dict}
(any?
)
T[]
){word}
) soundfold(){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.{word}
(string
)
string
){sentence}
]) spellbadword(){sentence}
that
is badly spelled. If there are no spelling mistakes the
result is an empty string.echo spellbadword("the quik brown fox")
{sentence}
(string?
)
any
){word}
[, {max}
[, {capital}
]]) spellsuggest(){word}
.
When {max}
is given up to this number of suggestions are
returned. Otherwise up to 25 suggestions are returned.{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
returned. {word}
itself is not included in the suggestions,
although it may appear capitalized.{word}
(string
)
{max}
(integer?
)
{capital}
(boolean?
)
string[]
){string}
[, {pattern}
[, {keepempty}
]]) split(){string}
. When {pattern}
is omitted or
empty each white space separated sequence of characters
becomes an item.
Otherwise the string is split where {pattern}
matches,
removing the matched characters. 'ignorecase' is not used
here, add \c to ignore case. /\c
When the first or last item is empty it is omitted, unless the
{keepempty}
argument is given and it's non-zero.
Other empty items are kept when {pattern}
matches at least one
character or when {keepempty}
is non-zero.
Example:let words = split(getline('.'), '\W\+')
for c in split(mystring, '\zs') | endfor
echo split('abc:def:ghi', ':\zs')
['abc:', 'def:', 'ghi']
let items = split(line, ':', 1)
{string}
(string
)
{pattern}
(string?
)
{keepempty}
(boolean?
)
string[]
){expr}
) sqrt(){expr}
as a
Float.
{expr}
must evaluate to a Float or a Number. When {expr}
is negative the result is NaN (Not a Number). Returns 0.0 if
{expr}
is not a Float or a Number.
Examples:echo sqrt(100)
echo sqrt(-4.01)
{expr}
(number
)
any
){expr}
]) srand(){expr}
is not given, seed values are initialized by
reading from /dev/urandom, if possible, or using time(NULL)
a.k.a. epoch time otherwise; this only has second accuracy.
{expr}
is given it must be a Number. It is used to
initialize the seed values. This is useful for testing or
when a predictable sequence is intended.
let seed = srand()
let seed = srand(userinput)
echo rand(seed)
{expr}
(number?
)
any
){what}
]) state()state()
if the work can be done now, and if yes
remove it from the queue and execute.
Remove the autocommand if the queue is now empty.
Also see mode().
{what}
is given only characters in this string will be
added. E.g, this checks if the screen has scrolled:if state('s') == ''
" screen has not scrolled
{what}
(string?
)
any
){opts}
) stdioopen(){opts}
is a dictionary with these keys:
on_stdin : callback invoked when stdin is written to.
on_print : callback invoked when Nvim needs to print a
message, with the message (whose type is string)
as sole argument.
stdin_buffered : read stdin in channel-buffered mode.
rpc : If set, msgpack-rpc will be used to communicate
over stdio
Returns:
{opts}
(table
)
any
){what}
) stdpath() E6100
Returns standard-path locations of various default files and
directories.{what}
Type Descriptionecho stdpath("config")
{what}
('cache'|'config'|'config_dirs'|'data'|'data_dirs'|'log'|'run'|'state'
)
string|string[]
){string}
[, {quoted}
]) str2float(){string}
to a Float. This mostly works the
same as when using a floating point number in an expression,
see floating-point-format. But it's a bit more permissive.
E.g., "1e40" is accepted, while in an expression you need to
write "1.0e40". The hexadecimal form "0x123" is also
accepted, but not others, like binary or octal.
When {quoted}
is present and non-zero then embedded single
quotes before the dot are ignored, thus "1'000.0" is a
thousand.
Text after the number is silently ignored.
The decimal point is always '.', no matter what the locale is
set to. A comma ends the number: "12,345.67" is converted to
12.0. You can strip out thousands separators with
substitute():let f = str2float(substitute(text, ',', '', 'g'))
{string}
(string
)
{quoted}
(boolean?
)
any
){string}
[, {utf8}
]) str2list(){string}
. Examples:echo str2list(" ") " returns [32]
echo str2list("ABC") " returns [65, 66, 67]
{utf8}
option has no effect,
and exists only for backwards-compatibility.
With UTF-8 composing characters are handled properly:echo str2list("á") " returns [97, 769]
{string}
(string
)
{utf8}
(boolean?
)
any
){string}
[, {base}
]) str2nr(){string}
to a number.
{base}
is the conversion base, it can be 2, 8, 10 or 16.
When {quoted}
is present and non-zero then embedded single
quotes are ignored, thus "1'000'000" is a million.{base}
is omitted base 10 is used. This also means that
a leading zero doesn't cause octal conversion to be used, as
with the default String to Number conversion. Example:let nr = str2nr('0123')
{base}
is 16 a leading "0x" or "0X" is ignored. With a
different base the result will be zero. Similarly, when
{base}
is 8 a leading "0", "0o" or "0O" is ignored, and when
{base}
is 2 a leading "0b" or "0B" is ignored.
Text after the number is silently ignored.{string}
is empty or on error.{string}
(string
)
{base}
(integer?
)
any
){string}
) strcharlen(){string}
. Composing characters are ignored.
strchars() can count the number of characters, counting
composing characters separately.{string}
is empty or on error.{string}
(string
)
any
){src}
, {start}
[, {len}
[, {skipcc}
]]) strcharpart(){skipcc}
is omitted or zero, composing characters are
counted separately.
When {skipcc}
set to 1, composing characters are treated as a
part of the preceding base character, similar to slice().
When a character index is used where a character does not
exist it is omitted and counted as one character. For
example:echo strcharpart('abc', -1, 2)
{src}
(string
)
{start}
(integer
)
{len}
(integer?
)
{skipcc}
(boolean?
)
any
){string}
[, {skipcc}
]) strchars(){string}
.
When {skipcc}
is omitted or zero, composing characters are
counted separately.
When {skipcc}
set to 1, composing characters are ignored.
strcharlen() always does this.{skipcc}
is only available after 7.4.755. For backward
compatibility, you can define a wrapper function:if has("patch-7.4.755")
function s:strchars(str, skipcc)
return strchars(a:str, a:skipcc)
endfunction
else
function s:strchars(str, skipcc)
if a:skipcc
return strlen(substitute(a:str, ".", "x", "g"))
else
return strchars(a:str)
endif
endfunction
endif
{string}
(string
)
{skipcc}
(boolean?
)
integer
){string}
[, {col}
]) strdisplaywidth(){string}
occupies on the screen when it starts at {col}
(first column is zero). When {col}
is omitted zero is used.
Otherwise it is the screen column where to start. This
matters for Tab characters.
The option settings of the current window are used. This
matters for anything that's displayed differently, such as
'tabstop' and 'display'.
When {string}
contains characters with East Asian Width Class
Ambiguous, this function's return value depends on 'ambiwidth'.
Returns zero on error.
Also see strlen(), strwidth() and strchars().{string}
(string
)
{col}
(integer?
)
integer
){format}
[, {time}
]) strftime(){format}
string. The given {time}
is used,
or the current time if no time is given. The accepted
{format}
depends on your system, thus this is not portable!
See the manual page of the C function strftime() for the
format. The maximum length of the result is 80 characters.
See also localtime(), getftime() and strptime().
The language can be changed with the :language command.
Examples: echo strftime("%c") " Sun Apr 27 11:49:23 1997
echo strftime("%Y %b %d %X") " 1997 Apr 27 11:53:25
echo strftime("%y%m%d %T") " 970427 11:53:55
echo strftime("%H:%M") " 11:55
echo strftime("%c", getftime("file.c"))
" Show mod time of file.c.
Parameters: ~
• {format} (`string`)
• {time} (`number?`)
Return: ~
(`string`)
strgetchar({str}
, {index}
) strgetchar(){index}
in
{str}
. This uses a zero-based character index, not a byte
index. Composing characters are considered separate
characters here. Use nr2char() to convert the Number to a
String.
Returns -1 if {index}
is invalid.
Also see strcharpart() and strchars().{str}
(string
)
{index}
(integer
)
integer
){haystack}
, {needle}
[, {start}
]) stridx(){haystack}
of the first occurrence of the String {needle}
.
If {start}
is specified, the search starts at index {start}
.
This can be used to find a second match:let colon1 = stridx(line, ":")
let colon2 = stridx(line, ":", colon1 + 1)
{needle}
does not occur in {haystack}
.
See also strridx().
Examples:echo stridx("An Example", "Example") " 3
echo stridx("Starting point", "Start") " 0
echo stridx("Starting point", "start") " -1
{haystack}
(string
)
{needle}
(string
)
{start}
(integer?
)
integer
){expr}
) string(){expr}
converted to a String. If {expr}
is a Number,
Float, String, Blob or a composition of them, then the result
can be parsed back with eval().
{expr}
type resultstr2float('inf')
Funcref function('name')
Blob 0z00112233.44556677.8899
List [item, item]
Dictionary {key: value, key: value}
Note that in String values the ' character is doubled.
Also see strtrans().
Note 2: Output format is mostly compatible with YAML, except
for infinite and NaN floating-point values representations
which use str2float(). Strings are also dumped literally,
only single quote is escaped, which does not allow using YAML
for parsing back binary strings. eval() should always work
for strings and floats though, and this is the only official
method. Use msgpackdump() or json_encode() if you need to
share data with other applications.{expr}
(any
)
string
){string}
) strlen(){string}
in bytes.
If the argument is a Number it is first converted to a String.
For other types an error is given and zero is returned.
If you want to count the number of multibyte characters use
strchars().
Also see len(), strdisplaywidth() and strwidth().{string}
(string
)
integer
){src}
, {start}
[, {len}
[, {chars}
]]) strpart(){src}
, starting from
byte {start}
, with the byte length {len}
.
When {chars}
is present and TRUE then {len}
is the number of
characters positions (composing characters are not counted
separately, thus "1" means one base character and any
following composing characters).
To count {start}
as characters instead of bytes use
strcharpart().{len}
is missing, the copy continues from {start}
till the
end of the {src}
.echo strpart("abcdefg", 3, 2) " returns 'de'
echo strpart("abcdefg", -2, 4) " returns 'ab'
echo strpart("abcdefg", 5, 4) " returns 'fg'
echo strpart("abcdefg", 3) " returns 'defg'
{start}
must be 0. For
example, to get the character under the cursor:strpart(getline("."), col(".") - 1, 1, v:true)
{src}
(string
)
{start}
(integer
)
{len}
(integer?
)
{chars}
(0|1?
)
string
){format}
, {timestring}
) strptime(){timestring}
, which is expected to match
the format specified in {format}
.{format}
depends on your system, thus this is not
portable! See the manual page of the C function strptime()
for the format. Especially avoid "%c". The value of $TZ also
matters.{timestring}
cannot be parsed with {format}
zero is
returned. If you do not know the format of {timestring}
you
can try different {format}
values until you get a non-zero
result.echo strptime("%Y %b %d %X", "1997 Apr 27 11:49:23")
echo strftime("%c", strptime("%y%m%d %T", "970427 11:53:55"))
echo strftime("%c", strptime("%Y%m%d%H%M%S", "19970427115355") + 3600)
{format}
(string
)
{timestring}
(string
)
integer
){haystack}
, {needle}
[, {start}
]) strridx(){haystack}
of the last occurrence of the String {needle}
.
When {start}
is specified, matches beyond this index are
ignored. This can be used to find a match before a previous
match:let lastcomma = strridx(line, ",")
let comma2 = strridx(line, ",", lastcomma - 1)
{needle}
does not occur in {haystack}
.
If the {needle}
is empty the length of {haystack}
is returned.
See also stridx(). Examples:echo strridx("an angry armadillo", "an") 3
{haystack}
(string
)
{needle}
(string
)
{start}
(integer?
)
integer
){string}
) strtrans(){string}
with all unprintable
characters translated into printable characters 'isprint'.
Like they are shown in a window. Example:echo strtrans(@a)
{string}
(string
)
string
){string}
[, {countcc}
]) strutf16len(){string}
(after converting it to UTF-16).{countcc}
is TRUE, composing characters are counted
separately.
When {countcc}
is omitted or FALSE, composing characters are
ignored.echo strutf16len('a') " returns 1
echo strutf16len('©') " returns 1
echo strutf16len('😊') " returns 2
echo strutf16len('ą́') " returns 1
echo strutf16len('ą́', v:true) " returns 3
{string}
(string
)
{countcc}
(0|1?
)
integer
){string}
) strwidth(){string}
occupies. A Tab character is counted as one
cell, alternatively use strdisplaywidth().
When {string}
contains characters with East Asian Width Class
Ambiguous, this function's return value depends on 'ambiwidth'.
Returns zero on error.
Also see strlen(), strdisplaywidth() and strchars().{string}
(string
)
integer
){nr}
[, {list}
]) submatch() E935
Only for an expression in a :substitute command or
substitute() function.
Returns the {nr}
th submatch of the matched text. When {nr}
is 0 the whole matched text is returned.
Note that a NL in the string can stand for a line break of a
multi-line match or a NUL character in the text.
Also see sub-replace-expression.{list}
is present and non-zero then submatch() returns
a list of strings, similar to getline() with two arguments.
NL characters in the text represent NUL characters in the
text.
Only returns more than one item for :substitute, inside
substitute() this list will always contain one or zero
items, since there are no real line breaks.s/\d\+/\=submatch(0) + 1/
echo substitute(text, '\d\+', '\=submatch(0) + 1', '')
{nr}
(integer
)
{list}
(nil?
)
string
){string}
, {pat}
, {sub}
, {flags}
) substitute(){string}
, in which
the first match of {pat}
is replaced with {sub}
.
When {flags}
is "g", all matches of {pat}
in {string}
are
replaced. Otherwise {flags}
should be "".{pat}
is always done like the 'magic'
option is set and 'cpoptions' is empty (to make scripts
portable). 'ignorecase' is still relevant, use /\c or /\C
if you want to ignore or match case and ignore 'ignorecase'.
'smartcase' is not used. See string-match for how {pat}
is
used.{sub}
is not replaced with the previous {sub}
.
Note that some codes in {sub}
have a special meaning
sub-replace-special. For example, to replace something with
"\n" (two characters), use "\\\\n" or '\\n'.{pat}
does not match in {string}
, {string}
is returned
unmodified.let &path = substitute(&path, ",\\=[^,]*$", "", "")
echo substitute("testing", ".*", "\\U\\0", "")
{sub}
starts with "\=", the remainder is interpreted as
an expression. See sub-replace-expression. Example:echo substitute(s, '%\(\x\x\)',
\ '\=nr2char("0x" .. submatch(1))', 'g')
{sub}
is a Funcref that function is called, with one
optional argument. Example:echo substitute(s, '%\(\x\x\)', SubNr, 'g')
echo substitute(s, '%\(\x\x\)', {m -> '0x' .. m[1]}, 'g')
{string}
(string
)
{pat}
(string
)
{sub}
(string
)
{flags}
(string
)
string
) let save_dir = &directory
let &directory = '.'
let swapfiles = swapfilelist()
let &directory = save_dir
Return: ~
(`string[]`)
swapinfo({fname}
) swapinfo(){fname}
. The available fields are:
version Vim version
user user name
host host name
fname original file name
pid PID of the Nvim process that created the swap
file, or zero if not running.
mtime last modification time in seconds
inode Optional: INODE number of the file
dirty 1 if file was modified, 0 if not
In case of failure an "error" item is added with the reason:
Cannot open file: file not found or in accessible
Cannot read file: cannot read first block
Not a swap file: does not contain correct block ID
Magic number mismatch: Info in first block is invalid{fname}
(string
)
any
){buf}
) swapname(){buf}
.
For the use of {buf}
, see bufname() above.
If buffer {buf}
is the current buffer, the result is equal to
:swapname (unless there is no swap file).
If buffer {buf}
has no swap file, returns an empty string.{buf}
(integer|string
)
string
){lnum}
, {col}
, {trans}
) synID(){lnum}
and {col}
in the current window.
The syntax ID can be used with synIDattr() and
synIDtrans() to obtain syntax information about text.{col}
is 1 for the leftmost column, {lnum}
is 1 for the first
line. 'synmaxcol' applies, in a longer line zero is returned.
Note that when the position is after the last character,
that's where the cursor can be in Insert mode, synID() returns
zero. {lnum}
is used like with getline().{trans}
is TRUE, transparent items are reduced to the
item that they reveal. This is useful when wanting to know
the effective color. When {trans}
is FALSE, the transparent
item is returned. This is useful when wanting to know which
syntax item is effective (e.g. inside parens).
Warning: This function can be very slow. Best speed is
obtained by going through the file in forward direction.echo synIDattr(synID(line("."), col("."), 1), "name")
{lnum}
(integer
)
{col}
(integer
)
{trans}
(0|1
)
integer
){synID}
, {what}
[, {mode}
]) synIDattr(){what}
attribute of
syntax ID {synID}
. This can be used to obtain information
about a syntax item.
{mode}
can be "gui" or "cterm", to get the attributes
for that mode. When {mode}
is omitted, or an invalid value is
used, the attributes for the currently active highlighting are
used (GUI or cterm).
Use synIDtrans() to follow linked highlight groups.
{what}
result
"name" the name of the syntax item
"fg" foreground color (GUI: color name used to set
the color, cterm: color number as a string,
term: empty string)
"bg" background color (as with "fg")
"font" font name (only available in the GUI)
highlight-font
"sp" special color (as with "fg") guisp
"fg#" like "fg", but for the GUI and the GUI is
running the name in "#RRGGBB" form
"bg#" like "fg#" for "bg"
"sp#" like "fg#" for "sp"
"bold" "1" if bold
"italic" "1" if italic
"reverse" "1" if reverse
"inverse" "1" if inverse (= reverse)
"standout" "1" if standout
"underline" "1" if underlined
"undercurl" "1" if undercurled
"underdouble" "1" if double underlined
"underdotted" "1" if dotted underlined
"underdashed" "1" if dashed underlined
"strikethrough" "1" if struckthrough
"altfont" "1" if alternative font
"nocombine" "1" if nocombineecho synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
echo synID(line("."), col("."), 1)->synIDtrans()->synIDattr("fg")
{synID}
(integer
)
{what}
(string
)
{mode}
(string?
)
string
){synID}
) synIDtrans(){synID}
. This is the syntax group ID of what is being used to
highlight the character. Highlight links given with
":highlight link" are followed.{synID}
(integer
)
integer
){lnum}
, {col}
) synconcealed(){lnum}
and {col}
is not part of a concealable
region, 1 if it is. {lnum}
is used like with getline().
2. The second item in the list is a string. If the first item
is 1, the second item contains the text which will be
displayed in place of the concealed text, depending on the
current setting of 'conceallevel' and 'listchars'.
3. The third and final item in the list is a number
representing the specific syntax region matched in the
line. When the character is not concealed the value is
zero. This allows detection of the beginning of a new
concealable region if there are two consecutive regions
with the same replacement character. For an example, if
the text is "123456" and both "23" and "45" are concealed
and replaced by the character "X", then:
{lnum}
(integer
)
{col}
(integer
)
[integer, string, integer]
){lnum}
, {col}
) synstack(){lnum}
and {col}
in the current window. {lnum}
is
used like with getline(). Each item in the List is an ID
like what synID() returns.
The first item in the List is the outer region, following are
items contained in that one. The last one is what synID()
returns, unless not the whole item is highlighted or it is a
transparent item.
This function is useful for debugging a syntax file.
Example that shows the syntax stack under the cursor:for id in synstack(line("."), col("."))
echo synIDattr(id, "name")
endfor
{lnum}
and {col}
is invalid
an empty list is returned. The position just after the last
character in a line and the first column in an empty line are
valid positions.{lnum}
(integer
)
{col}
(integer
)
integer[]
){cmd}
as a string (systemlist() returns
a List) and sets v:shell_error to the error code.
{cmd}
is treated as in jobstart():
If {cmd}
is a List it runs directly (no 'shell').
If {cmd}
is a String it runs in the 'shell', like this:call jobstart(split(&shell) + split(&shellcmdflag) + ['{cmd}'])
<CR>
<NL>
is replaced with <NL>
echo system(['ls', expand('%:h')])
{input}
is a string it is written to a pipe and passed as
stdin to the command. The string is written as-is, line
separators are not changed.
If {input}
is a List it is written to the pipe as
writefile() does with {binary}
set to "b" (i.e. with
a newline between each list item, and newlines inside list
items converted to NULs).
When {input}
is given and is a valid buffer id, the content of
the buffer is written to the file line by line, each line
terminated by NL (and NUL where the text has NL).
E5677 echo system("cat - &", "foo")
$ echo foo | bash -c 'cat - &'
echo system('ls '..shellescape(expand('%:h')))
echo system('ls '..expand('%:h:S'))
{cmd}
(string|string[]
)
{input}
(string|string[]|integer?
)
string
){cmd}
[, {input}
[, {keepempty}
]]) systemlist(){binary}
argument
set to "b", except that a final newline is not preserved,
unless {keepempty}
is non-zero.
Note that on MS-Windows you may get trailing CR characters.echo split(system('echo hello'), '\n', 1)
{cmd}
(string|string[]
)
{input}
(string|string[]|integer?
)
{keepempty}
(integer?
)
string[]
){arg}
]) tabpagebuflist(){arg}
specifies the number of the 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:let buflist = []
for i in range(tabpagenr('$'))
call extend(buflist, tabpagebuflist(i + 1))
endfor
{arg}
(integer?
)
any
){arg}
]) tabpagenr(){arg}
supports the following values:
$ the number of the last tab page (the tab page
count).
# the number of the last accessed tab page
(where g<Tab> goes to). If there is no
previous tab page, 0 is returned.
The number can be used with the :tab command.{arg}
('$'|'#'?
)
integer
){tabarg}
[, {arg}
]) tabpagewinnr(){tabarg}
.
{tabarg}
specifies the number of tab page to be used.
{arg}
is used like with winnr():
tabpagewinnr(1) " current window of tab page 1
tabpagewinnr(4, '$') " number of windows in tab page 4
{tabarg}
is invalid zero is returned.{tabarg}
(integer
)
{arg}
('$'|'#'?
)
integer
)string[]
){expr}
[, {filename}
]) taglist(){expr}
.{filename}
is passed it is used to prioritize the results
in the same way that :tselect does. See tag-priority.
{filename}
should be the full path of the file.{expr}
. This also make the function work faster.
Refer to tag-regexp for more information about the tag
search regular expression pattern.{expr}
(any
)
{filename}
(string?
)
any
){expr}
) tan(){expr}
, measured in radians, as a Float
in the range [-inf, inf].
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo tan(10)
echo tan(-4.01)
{expr}
(number
)
number
){expr}
) tanh(){expr}
as a Float in the
range [-1, 1].
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo tanh(0.5)
echo tanh(-1)
{expr}
(number
)
number
)let tmpfile = tempname()
exe "redir > " .. tmpfile
string
)any
){id}
]) timer_info(){id}
is given only information about this timer is
returned. When timer {id}
does not exist an empty list is
returned.
When {id}
is omitted information about all timers is returned.{id}
(integer?
)
any
){timer}
, {paused}
) timer_pause(){paused}
evaluates to a non-zero Number or a non-empty
String, then the timer is paused, otherwise it is unpaused.
See non-zero-arg.{timer}
(integer
)
{paused}
(boolean
)
any
){time}
, {callback}
[, {options}
]) timer_start() timer
Create a timer and return the timer ID.{time}
is the waiting time in milliseconds. This is the
minimum time before invoking the callback. When the system is
busy or Vim is not waiting for input the time will be longer.
Zero can be used to execute the callback when Vim is back in
the main loop.{callback}
is the function to call. It can be the name of a
function or a Funcref. It is called with one argument, which
is the timer ID. The callback is only invoked when Vim is
waiting for input.{options}
is a dictionary. Supported entries:
"repeat" Number of times to repeat the callback.
-1 means forever. Default is 1.
If the timer causes an error three times in a
row the repeat is cancelled.func MyHandler(timer)
echo 'Handler called'
endfunc
let timer = timer_start(500, 'MyHandler',
\ {'repeat': 3})
{time}
(number
)
{callback}
(string|function
)
{options}
(table?
)
any
){timer}
) timer_stop(){timer}
is an ID returned by timer_start(), thus it must be a
Number. If {timer}
does not exist there is no error.{timer}
(integer
)
any
)any
){expr}
) tolower(){expr}
(string
)
string
){expr}
) toupper(){expr}
(string
)
string
){src}
, {fromstr}
, {tostr}
) tr(){src}
string with all characters
which appear in {fromstr}
replaced by the character in that
position in the {tostr}
string. Thus the first character in
{fromstr}
is translated into the first character in {tostr}
and so on. Exactly like the unix "tr" command.
This code also deals with multibyte characters properly.echo tr("hello there", "ht", "HT")
echo tr("<blob>", "<>", "{}")
{src}
(string
)
{fromstr}
(string
)
{tostr}
(string
)
string
){text}
[, {mask}
[, {dir}
]]) trim(){text}
as a String where any character in {mask}
is
removed from the beginning and/or end of {text}
.{mask}
is not given, or is an empty string, {mask}
is all
characters up to 0x20, which includes Tab, space, NL and CR,
plus the non-breaking space character 0xa0.{dir}
argument specifies where to remove the
characters:
0 remove from the beginning and end of {text}
1 remove only at the beginning of {text}
2 remove only at the end of {text}
When omitted both ends are trimmed.echo trim(" some text ")
echo trim(" \r\t\t\r RESERVE \t\n\x0B\xA0") .. "_TAIL"
echo trim("rm<Xrm<>X>rrm", "rm<>")
echo trim(" vim ", " ", 2)
{text}
(string
)
{mask}
(string?
)
{dir}
(0|1|2?
)
string
){expr}
) trunc(){expr}
as a Float (truncate towards zero).
{expr}
must evaluate to a Float or a Number.
Returns 0.0 if {expr}
is not a Float or a Number.
Examples:echo trunc(1.456)
echo trunc(-5.456)
echo trunc(4.0)
{expr}
(number
)
integer
){expr}
) type(){expr}
.
Instead of using the number directly, it is better to use the
v:t_ variable that has the value:
Number: 0 v:t_number
String: 1 v:t_string
Funcref: 2 v:t_func
List: 3 v:t_list
Dictionary: 4 v:t_dict
Float: 5 v:t_float
Boolean: 6 v:t_bool (v:false and v:true)
Null: 7 (v:null)
Blob: 10 v:t_blob
For backward compatibility, this method can be used:if type(myvar) == type(0) | endif
if type(myvar) == type("") | endif
if type(myvar) == type(function("tr")) | endif
if type(myvar) == type([]) | endif
if type(myvar) == type({}) | endif
if type(myvar) == type(0.0) | endif
if type(myvar) == type(v:true) | endif
if myvar is v:null | endif
if exists('v:t_number') | endif
{expr}
(any
)
integer
){name}
) undofile(){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.
If {name}
is empty undofile() returns an empty string, since a
buffer without a file name will not write an undo file.
Useful in combination with :wundo and :rundo.{name}
(string
)
string
){buf}
]) undotree(){buf}
is given. The
result is 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.{buf}
(integer|string?
)
vim.fn.undotree.ret
){list}
[, {func}
[, {dict}
]]) uniq() E882
Remove second and succeeding copies of repeated adjacent
{list}
items in-place. Returns {list}
. If you want a list
to remain unmodified make a copy first:let newlist = uniq(copy(mylist))
{func}
and {dict}
see sort().{list}
is not a List.{list}
(any
)
{func}
(any?
)
{dict}
(any?
)
any[]|0
){string}
, {idx}
[, {countcc}
[, {charidx}
]]) utf16idx(){idx}
in {string}
(after converting it to UTF-16).{charidx}
is present and TRUE, {idx}
is used as the
character index in the String {string}
instead of as the byte
index.
An {idx}
in the middle of a UTF-8 sequence is rounded
downwards to the beginning of that sequence.{idx}
bytes in {string}
. If there are exactly {idx}
bytes
the length of the string in UTF-16 code units is returned.echo utf16idx('a😊😊', 3) " returns 2
echo utf16idx('a😊😊', 7) " returns 4
echo utf16idx('a😊😊', 1, 0, 1) " returns 2
echo utf16idx('a😊😊', 2, 0, 1) " returns 4
echo utf16idx('aą́c', 6) " returns 2
echo utf16idx('aą́c', 6, 1) " returns 4
echo utf16idx('a😊😊', 9) " returns -1
{string}
(string
)
{idx}
(integer
)
{countcc}
(boolean?
)
{charidx}
(boolean?
)
integer
){dict}
) values(){dict}
. The List is
in arbitrary order. Also see items() and keys().
Returns zero if {dict}
is not a Dict.{dict}
(any
)
any
){expr}
[, {list}
[, {winid}
]]) virtcol(){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. conceal is ignored.
For the byte position use col().{expr}
see getpos() and col().
When {expr}
is "$", it means the end of the cursor line, so
the result is the number of cells in the cursor line plus one.{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 "off" is omitted zero is used. When
Virtual editing is active in the current mode, a position
beyond the end of the line can be returned. Also see
'virtualedit'{list}
is present and non-zero then virtcol() returns a
List with the first and last screen position occupied by the
character.{winid}
argument the values are obtained for
that window instead of the current window." With text "foo^Lbar" and cursor on the "^L":
echo virtcol(".") " returns 5
echo virtcol(".", 1) " returns [4, 5]
echo virtcol("$") " returns 9
" With text " there", with 't at 'h':
echo virtcol("'t") " returns 6
echo max(map(range(1, line('$')), "virtcol([v:val, '$'])"))
{expr}
(string|any[]
)
{list}
(boolean?
)
{winid}
(integer?
)
any
){winid}
, {lnum}
, {col}
) virtcol2col(){winid}
at buffer line {lnum}
and virtual
column {col}
.{lnum}
is an empty line, 0 is returned.{col}
is greater than the last virtual column in line
{lnum}
, then the byte index of the character at the last
virtual column is returned.{winid}
argument can be the window number or the
window-ID. If this is zero, then the current window is used.{winid}
doesn't exist or the buffer
line {lnum}
or virtual column {col}
is invalid.{winid}
(integer
)
{lnum}
(integer
)
{col}
(integer
)
integer
){expr}
]) visualmode()CTRL-V
character) for
character-wise, line-wise, or block-wise Visual mode
respectively.
Example:exe "normal " .. visualmode()
{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. See non-zero-arg.{expr}
(boolean?
)
string
){timeout}
, {condition}
[, {interval}
]) wait(){condition}
evaluates to TRUE, where {condition}
is a Funcref or string containing an expression.{timeout}
is the maximum waiting time in milliseconds, -1
means forever.{interval}
milliseconds (default: 200).{timeout}
(integer
)
{condition}
(any
)
{interval}
(number?
)
any
)<c-j>
work like <down>
in wildmode, use:cnoremap <expr> <C-j> wildmenumode() ? "\<Down>\<Tab>" : "\<c-j>"
any
){id}
, {command}
[, {silent}
]) win_execute()execute()
but in the context of window {id}
.
The window will temporarily be made the current window,
without triggering autocommands or changing directory. When
executing {command}
autocommands will be triggered, this may
have unexpected side effects. Use :noautocmd
if needed.
Example:call win_execute(winid, 'syntax enable')
setwinvar()
would not trigger
autocommands and not actually show syntax highlighting.{id}
does not exist then no error is given and
an empty string is returned.{id}
(integer
)
{command}
(string
)
{silent}
(boolean?
)
any
){bufnr}
) win_findbuf(){bufnr}
. When there is none the list is empty.{bufnr}
(integer
)
integer[]
){win}
[, {tab}
]]) win_getid(){win}
is missing use the current window.
With {win}
this is the window number. The top window has
number 1.
Without {tab}
use the current tab, otherwise the tab with
number {tab}
. The first tab has number one.
Return zero if the window cannot be found.{win}
(integer?
)
{tab}
(integer?
)
integer
){nr}
]) win_gettype(){nr}
not found{nr}
is omitted return the type of the current window.
When {nr}
is given return the type of this window by number or
window-ID.{nr}
(integer?
)
'autocmd'|'command'|''|'loclist'|'popup'|'preview'|'quickfix'|'unknown'
){expr}
) win_gotoid(){expr}
. This may also change the current
tabpage.
Return TRUE if successful, FALSE if the window cannot be found.{expr}
(integer
)
0|1
){expr}
) win_id2tabwin(){expr}
: [tabnr, winnr].
Return [0, 0] if the window cannot be found.{expr}
(integer
)
any
){expr}
) win_id2win(){expr}
.
Return 0 if the window cannot be found in the current tabpage.{expr}
(integer
)
integer
){nr}
, {offset}
) win_move_separator(){nr}
's vertical separator (i.e., the right border)
by {offset}
columns, as if being dragged by the mouse. {nr}
can be a window number or window-ID. A positive {offset}
moves right and a negative {offset}
moves left. Moving a
window's vertical separator will change the width of the
window and the width of other windows adjacent to the vertical
separator. The magnitude of movement may be smaller than
specified (e.g., as a consequence of maintaining
'winminwidth'). Returns TRUE if the window can be found and
FALSE otherwise.
This will fail for the rightmost window and a full-width
window, since it has no separator on the right.
Only works for the current tab page. E1308{nr}
(integer
)
{offset}
(integer
)
any
){nr}
, {offset}
) win_move_statusline(){nr}
's status line (i.e., the bottom border) by
{offset}
rows, as if being dragged by the mouse. {nr}
can be a
window number or window-ID. A positive {offset}
moves down
and a negative {offset}
moves up. Moving a window's status
line will change the height of the window and the height of
other windows adjacent to the status line. The magnitude of
movement may be smaller than specified (e.g., as a consequence
of maintaining 'winminheight'). Returns TRUE if the window can
be found and FALSE otherwise.
Only works for the current tab page.{nr}
(integer
)
{offset}
(integer
)
any
){nr}
) win_screenpos(){nr}
as a list with two
numbers: [row, col]. The first window always has position
[1, 1], unless there is a tabline, then it is [2, 1].
{nr}
can be the window number or the window-ID. Use zero
for the current window.
Returns [0, 0] if the window cannot be found.{nr}
(integer
)
any
){nr}
, {target}
[, {options}
]) win_splitmove(){target}
, then move window {nr}
to a new split adjacent to {target}
.
Unlike commands such as :split, no new windows are created
(the window-ID of window {nr}
is unchanged after the move).{options}
is a Dictionary with the following optional entries:
"vertical" When TRUE, the split is created vertically,
like with :vsplit.
"rightbelow" When TRUE, the split is made below or to the
right (if vertical). When FALSE, it is done
above or to the left (if vertical). When not
present, the values of 'splitbelow' and
'splitright' are used.{nr}
(integer
)
{target}
(integer
)
{options}
(table?
)
any
){nr}
) winbufnr(){nr}
. {nr}
can be the window number or
the window-ID.
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))
{nr}
(integer
)
integer
)integer
)string
){nr}
) winheight(){nr}
.
{nr}
can be the window number or the window-ID.
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.
This excludes any window toolbar line.
Examples:echo "The current window has " .. winheight(0) .. " lines."
{nr}
(integer
)
integer
){tabnr}
]) winlayout(){tabnr}
use the current tabpage, otherwise the tabpage
with number {tabnr}
. If the tabpage {tabnr}
is not found,
returns an empty list.["leaf", {winid}]
["col", [{nested list of windows}]]
["row", [{nested list of windows}]]
" Only one window in the tab page
echo winlayout()
['leaf', 1000]
" Two horizontally split windows
echo winlayout()
['col', [['leaf', 1000], ['leaf', 1001]]]
" The second tab page, with three horizontally split
" windows, with two vertically split windows in the
" middle window
echo winlayout(2)
['col', [['leaf', 1002], ['row', [['leaf', 1003], ['leaf', 1001]]], ['leaf', 1000]]]
{tabnr}
(integer?
)
any[]
)integer
){arg}
]) winnr(){arg}
supports the following values:
$ the number of the last window (the window
count).
# the number of the last accessed window (where
CTRL-W_p goes to). If there is no previous
window or it is in another tab page 0 is
returned. May refer to the current window in
some cases (e.g. when evaluating 'statusline'
expressions).
{N}
j the number of the Nth window below the
current window (where CTRL-W_j goes to).
{N}
k the number of the Nth window above the current
window (where CTRL-W_k goes to).
{N}
h the number of the Nth window left of the
current window (where CTRL-W_h goes to).
{N}
l the number of the Nth window right of the
current window (where CTRL-W_l goes to).
The number can be used with CTRL-W_w and ":wincmd w"
:wincmd.
When {arg}
is invalid an error is given and zero is returned.
Also see tabpagewinnr() and win_getid().
Examples:let window_count = winnr('$')
let prev_window = winnr('#')
let wnum = winnr('3k')
{arg}
(string|integer?
)
integer
)let cmd = winrestcmd()
call MessWithWindowSizes()
exe cmd
string
){dict}
) winrestview(){dict}
does not have to contain all values, that are
returned by winsaveview(). If values are missing, those
settings won't be restored. So you can use:call winrestview({'curswant': 4})
{dict}
(vim.fn.winrestview.dict
)
any
)vim.fn.winsaveview.ret
){nr}
) winwidth(){nr}
.
{nr}
can be the window number or the window-ID.
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
50 wincmd |
endif
{nr}
(integer
)
integer
)any
){object}
, {fname}
[, {flags}
]) writefile(){object}
is a List write it to file {fname}
. Each list
item is separated with a NL. Each list item must be a String
or Number.
All NL characters are replaced with a NUL character.
Inserting CR characters needs to be done before passing {list}
to writefile().{object}
is a Blob write the bytes to file {fname}
unmodified, also when binary mode is not specified.{flags}
must be a String. These characters are recognized:call writefile(["foo"], "event.log", "a")
call writefile(["bar"], "event.log", "a")
defer delete({fname})
{flags}
does not contain "S" or "s" then fsync() is
called if the 'fsync' option is set.let fl = readfile("foo", "b")
call writefile(fl, "foocopy", "b")
{object}
(any
)
{fname}
(string
)
{flags}
(string?
)
any
){expr}
, {expr}
) xor()and()
and or()
.
Example:let bits = xor(bits, 0x80)
{expr}
(integer
)
{expr1}
(integer
)
integer
)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".