Skip to content
Search

Vim:Script

lastmod 2024-07-10created 2015-02-1679 edits

A summary of scripts that can be used in Vim.

Basic Layout

~/.vim/colors/
Handles color schemes. For example, if you run :color mycolors (in Command Mode while Vim is running), Vim will look for the file ~/.vim/colors/mycolors.vim and run it. This file should contain all the Vimscript commands needed to create the color scheme.
~/.vim/plugin/
Each file is run every time Vim starts. This means these files contain code you want loaded every time Vim starts.
~/.vim/ftdetect/
Run every time Vim starts. ftdetect stands for "filetype detection". Files in this directory set up autocommands that detect files and set their filetype, or do nothing.
~/.vim/ftplugin/
The naming of these files matters! When Vim sets a buffer's filetype value, it looks for a matching file in ~/.vim/ftplugin/. For example, if you run set filetype=derp, Vim will look for ~/.vim/ftplugin/derp.vim, and if the file exists, it will run it.
Vim also supports directories inside ~/.vim/ftplugin/. In the example, set filetype=derp runs all *.vim files inside ~/.vim/ftplugin/derp/. This lets you split a plugin's ftplugin files into logical groups.
Because these files run every time a buffer's filetype is set, they must set only buffer-local options. If they set options globally, they will overwrite them for all open buffers.
~/.vim/indent/
Very similar to ftplugin files. They are loaded based on their names.
indent files set indentation-related options for their filetype, and these options should be buffer-local.
Of course, you could simply put this code in ftplugin files, but it is better to keep it separate so Vim users can understand what you are doing. It is just a convention, but it is good to follow it out of consideration for plugin authors.
~/.vim/compiler/
Works like indent files. It sets compiler-related options in the current buffer based on the name.
~/.vim/after/
Files in this directory are loaded every time Vim starts, but only after the files in ~/.vim/plugin/.
This lets you override Vim's internal files.
~/.vim/autoload/
autoload is a way to delay loading plugin code until it is actually needed.
~/.vim/doc/
Directory for plugin documentation.

Simple debugging

Using echom keeps the message in the history. You can check it with :message.

:echom 'Message'
:message

Script help

Within a Vim session, you can view Vim's own documentation on Vimscript through the built-in help system by typing the following.

:help vim-script-intro

Keyward

Additional keywords supported by Vim:

  • autocmd: Automatically runs specific commands depending on the type of file being edited. See the download for a sample.vimrc file that includes autocmd examples.
  • filetype: Loads and enables various plugins that provide extra features when editing a particular file type.
  • function: Defines a user-defined function that can be mapped to a key command.
  • syntax: Enables or disables syntax highlighting.

Configuration and custom commands:

  • ab: Defines an abbreviation that expands from a specific sequence of characters encountered while typing text in Insert mode.
  • map: Assigns an existing vi or Vim command to a custom key, or defines your own custom command.
  • set: Sets a vi or Vim variable.

Key code

Enter the command below to see the full list of available key codes.

:help keycodes

Execute

You can run a Vim script with :source [PATH].

Script file path

How to find the path of the running script file:

" Relative path of script file:
let s:path = expand('<sfile>')

" Absolute path of script file:
let s:path = expand('<sfile>:p')

" Absolute path of script file with symbolic links resolved:
let s:path = resolve(expand('<sfile>:p'))

" Folder in which script resides: (not safe for symlinks)
let s:path = expand('<sfile>:p:h')

" If you're using a symlink to your script, but your resources are in
" the same directory as the actual script, you'll need to do this:
"   1: Get the absolute path of the script
"   2: Resolve all symbolic links
"   3: Get the folder of the resolved absolute file
let s:path = fnamemodify(resolve(expand('<sfile>:p')), ':h')

WARNING

Note that if you use expand('<sfile>') inside a function, it returns the function name.

File Read

" Read the created file and echo it
let s:lines = readfile('readfile.txt')
for s:line in s:lines
  echo s:line
endfor

Current file

echo @%

" full path
call expand('%:p')

" full path copy to buffer 'a'
redir @a | echo expand('%:p') | redir END

" full path copy to default buffer
redir @" | echo expand('%:p') | redir END

Variable

To assign a variable in Vimscript, you must use the special keyword let. There are the following kinds of variables.

" 스칼라: 문자열이나 숫자와 같은 단일 값이다.
let name = "Damian"
let height = 165

" 목록: 대괄호로 구분되고 0부터 시작하는 묵시적 정수 인덱스를 사용하는 정렬된 값 시퀀스이다.
let interests = [ 'Cinema', 'Literature', 'World Domination', 101 ]

" 사전: 중괄호로 구분되고 명시적 문자열 키를 사용하는 정렬되지 않은 값 세트이다.
let phone = { 'cell':5551017346, 'home':5558038728, 'work':'?' }

Unlike values, variables have no inherent type. Instead, they take the type of the value first assigned to them. So the name and height variables above are scalar types (that is, they can only store strings or numbers), interests is a list variable (it can only store lists), and phone is a dictionary variable (it can only store dictionaries). Once assigned, a variable's type stays strictly fixed for the rest of runtime.

By default, a variable's scope is limited to the function in which it is first assigned. Otherwise, a variable whose first assignment happens outside a function is a global variable. However, you can also explicitly declare a variable as belonging to another scope by using various prefixes, as below.

  • g: varname: The variable is global.
  • s: varname: The variable is local to the current script file.
  • w: varname: The variable is local to the current editor window.
  • t: varname: The variable is local to the current editor tab.
  • b: varname: The variable is local to the current editor buffer.
  • l: varname: The variable is local to the current function.
  • a: varname: The variable is a parameter of the current function.
  • v: varname: The variable is predefined by Vim.

Vim also provides pseudo-variables that scripts can use to access other kinds of value containers. Below is a summary of those variables.

  • & varname: Vim option (local if defined, otherwise global)
  • &l: varname: Local Vim option
  • &g: varname: Global Vim option
  • @ varname: Vim register
  • $ varname: Environment variable

Pseudo-variables can be very useful. For example, you can set up two key maps as follows to increase or decrease the current tab spacing.

nmap <silent> ]] :let &tabstop += 1<CR>
nmap <silent> [[ :let &tabstop -= &tabstop > 1 ? 1 : 0<CR>

Check variables

Variables added by plugins and the like can be checked as follows.

if exists("g:pymode")
" TODO ...
endif

Innser variables

The set command lets users set internal vi and Vim variables. Variables are set in different ways depending on their type, as follows.

  • Variables that are set on or off are set with the set variable command and unset with the set novariable command.
  • Variables that take a value are set with the set variable=value command.

To check the current values of all options that can be set in vi or Vim, use the :set all command within vi or Vim. To display the current value of a specific option, use the f:set option? command. To display all options changed from their defaults, use the :set command.

Fixed window size

set wfh  
set wfw 

(set WinFixHeight, set WinFixWidth)

Read-only buffer

function UpdateModifiable()
  if !exists("b:setmodifiable")
    let b:setmodifiable = 0
  endif
  if &readonly
    if &modifiable
      setlocal nomodifiable
      let b:setmodifiable = 1
    endif
  else
    if b:setmodifiable
      setlocal modifiable
    endif
  endif
endfunction
autocmd BufReadPost * call UpdateModifiable()

Resize window

:resize 60
:res +5
:res -5
:vertical resize 80
:vertical resize +5
:vertical resize -5

String

Testing for an empty string

let result_string = GetResult();
if empty(result_string)
   echo "No result"
endif

String concatenation

let newstr1 = str1 . str2
let newstr2 .= str1

Note that you must not use +=.

Specifying case sensitivity for string comparison operators (==?, ==#)

String comparisons usually follow the local setting of the Vim ignorecase option, but you can explicitly mark a string comparison operator as

  • case-sensitive (add #) or
  • case-insensitive (add ?)

as follows:

if name ==? 'Batman'         |"Equality always case insensitive
   echo "I'm Batman"
elseif name <# 'ee cummings' |"Less-than always case sensitive
   echo "the sky was can dy lu minous"
endif

Operators with "explicitly specified case sensitivity" let scripts run reliably regardless of users' modified option settings, so it is a good idea to use them for all string comparisons.

Regex

There are two more for strings:

  • str =~ pattern: When the pattern matches.
  • str !~ pattern: The pattern does not match.

If you need a function, use matchstr().

let url = matchstr(test, '\ca href=\([''"]\)\zs.\{-}\ze\1')
if empty(url) 
   throw "no url recognized into ``".test."''"
endif

Function

Enter the following command for detailed information about functions.

:help functions

User defined function

Functions can be added as below. Note that the first letter of a function name must be uppercase.

function TestFunction()
    echom "Test Function!"
endfunction

Vimscript functions always return a value, so if no return is specified, 0 is returned automatically.

A function is called as follows.

:call TestFunction()

In addition, a function definition with arguments and a return value looks like this.

function f (int k, int l) returns float
begin
  f = k * l;
  for (int i=0; i<10; i++)
  begin
      f += sqrt(k) * sqrt(l);
  end
  return f + 2;
endfunction

You can also use scope prefixes, as with variables.

function s:TestFunction()
    " ...
endfunction

You can separate namespaces with the hash (#) character.

function! myplugin#hello()
    " ...
endfunction

Redeclarable functions

Function declarations in Vimscript are runtime statements, so if a script is loaded twice, every function declaration in it runs twice and the functions are rewritten.

Redeclaring a function is treated as a fatal error. (This prevents conflicts that can occur when two different scripts accidentally declare functions with the same name.) This makes it hard to write functions in scripts that need to be loaded repeatedly, such as custom syntax highlighting scripts.

So Vimscript lets you use a keyword modifier (function!) to mark a function declaration that can safely be reloaded as needed.

function! s:save_backup ()
    let b:backup_count = exists('b:backup_count') ? b:backup_count+1 : 1
    return writefile(getline(1,'$'), bufname('%') . '_' . b:backup_count)
endfunction

No redeclaration check is performed for functions defined with this keyword modifier, so it is well suited for use with explicitly scoped functions. (Because they are scoped, functions do not conflict across scripts.)

Abortable function

Aborts when an error occurs.

function! myfunction() abort
    " ...
endfunction

Return values

Using a function's return value:

let success = setline('.', ExpurgateText(getline('.')) )

Note that in Vimscript, unlike C or Perl, you cannot simply discard a function's return value by not using it. So to use a function as a procedure or subroutine and ignore its return value, you must put the call command before the call.

call SaveBackup()

Accessing argument values inside a function

function PrintDetails(name, title, email)
    echo 'Name:   '  a:title  a:name
    echo 'Contact:'  a:email
endfunction

Variadic parameters

If you don't know the number of arguments given to a function, you can specify a variadic parameter list with an ellipsis (...) instead of named parameters. This lets the function be called with any number of arguments, and their values are collected in a single variable, an array named a:000. Individual arguments are also given positional parameter names such as a:1, a:2, a:3, and a:0 holds the number of arguments.

function Average(...)
    let sum = 0.0

    for nextval in a:000        "a:000 is the list of arguments
        let sum += nextval
    endfor

    return sum / a:0            "a:0 is the number of arguments
endfunction

You can also combine regular arguments and variadic arguments, as below.

function CommentBlock(comment, ...)
    " ...
endfunction

The total number of arguments can be checked with len(a:000).

Default arguments

You need to use the get function.

function! FunctionName(arg1,...)
    let arg2 = get(a:, 1, 0)
    let arg3 = get(a:, 2, 0)

    if arg2
        "Do stuff with arguments"
    else
        "Do stuff without arguments"
    endif
endfunction

Loop

for s in list
  echo s
  continue  " jump to start of loop
  break     " breaks out of a loop
endfor
while x < 5
endwhile

Custom commands

Commands with arguments:

command! -nargs=? Save call script#foo(<args>)
" -nargs=0  0개의 인수. 기본값.
" -nargs=1  1개의 인수. 공백을 포함한다.
" -nargs=?  0개 또는 1개의 인수.
" -nargs=*  공백으로 구분된 0개 이상의 인수.
" -nargs=+  공백으로 구분된 1개 이상의 인수.

Example

command! -nargs=0 -bang               OpvimPreview  call opvim#Preview(<bang>0)
command! -nargs=? -complete=shellcmd  OpvimExec     call opvim#Exec(<f-args>)
command! -nargs=?                     OpvimMode     call opvim#Mode(<f-args>)
command! -nargs=0                     OpvimModeMenu call quickmenu#bottom(g:opm_quickmenu_mode_id)
command! -nargs=0                     OpvimCMake    call opvim#CMake()
command! -nargs=?                     OpvimBuild    call opvim#Build(<f-args>)
command! -nargs=?                     OpvimDebug    call opvim#Debug(<f-args>)
command! -nargs=?                     OpvimScript   call opvim#Script(<f-args>)
command! -nargs=0                     OpvimReload   call OpmReloadQuickMenu()
command! -nargs=0                     OpvimCreate   call opvim#CreateProject()
command! -nargs=0 OpvimDebugDone call opvim#ExitDebug()

Internalizing a function's line range

Calling the function repeatedly for each line (call-the-function-repeatedly-for-each-line) is a convenient default behavior. But sometimes you want to specify a range, call the function only once, and then handle the range semantics within the function itself. This is also easy in Vimscript. Just add a special modifier (range) to the function declaration, as follows.

function DeAmperfyAll() range
    "Step through each line in the range...
    for linenum in range(a:firstline, a:lastline)
        "Replace loose ampersands (as in DeAmperfy())...
        let curr_line   = getline(linenum)
        let replacement = substitute(curr_line,'&\(\w\+;\)\@!','&amp;','g')
        call setline(linenum, replacement)
    endfor

    "Report what was done...
    if a:lastline > a:firstline
        echo "DeAmperfied" (a:lastline - a:firstline + 1) "lines"
    endif
endfunction

If the range modifier is specified after the parameter list, the function can be called with a range as follows.

:1,$call DeAmperfyAll()

Executing expressions

To run a colon command (a command-mode command starting with :), use execute.

:execute "tag " . tag_name

For other normal mode commands, use normal. Here the argument is not an expression but the literal characters representing the command.

:normal gg=G

To use the normal command with an expression, combine it with execute.

:execute "normal " . normal_commands

Getting the word under the cursor

let wordUnderCursor = expand("<cword>")
let currentLine = getline(".")

Folder scan (listing files)

That is due to how the glob() function works: A single-star pattern does not match hidden files by design. In most shells, the default globbing style can be changed to do so (e.g., via </code>shopt -s dotglob</code> in Bash), but it is not possible in Vim, unfortunately.

However, one has several possibilities to solve the problem still. First and most obvious is to glob hidden and not hidden files separately and then concatenate the results:

:let backupfiles = glob(&backupdir..'/*').."\n"..glob(&backupdir..'/.[^.]*')

(Be careful not to fetch the . and .. entries along with hidden files.)

Another, perhaps more convenient but less portable way is to use the backtick expansion within the glob() call:

:let backupfiles = glob('`find '..&backupdir..' -maxdepth 1 -type f`')

This forces Vim to execute the command inside backticks to obtain the list of files. The find shell command lists all files (-type f) including the hidden ones, in the specified directory (-maxdepth 1 forbids recursion).

Listing only files

let find_path = fnameescape('/home/user')
let normal_files = globpath(find_path, '*', 0, 1)
let hidden_files = globpath(find_path, '.[^.]*', 0, 1)
let files = normal_files + hidden_files

for file in files
    if isdirectory(file)
        continue
    endif

    let filename = fnamemodify(file, ':t')
    if filename == '.' || filename == '..'
        continue
    endif

    echom filename
endfor

Lowercase command

" Save file with sudo
command! -nargs=0  :WriteWithSudo :w !sudo tee % >/dev/null

" Use :ww instead of :WriteWithSudo
cnoreabbrev ww WriteWithSudo

Listing loaded scripts

:scriptnames

Variables and Env

:set            - shows vars different from defaults
:set all        - shows all values
:set foo?       - shows the value of foo
:set foo+=opt   - add opt to the value w/o changing others
:set foo-=opt   - remove opt from value
:set foo&       - reset foo to default value
:setlocal foo   - only the current buffer

Line continuation

When continuing a line with a backslash, unlike other scripting languages (e.g. Bash), you put it at the start of the next line rather than at the end of the line.

call SetName(
\             first_name,
\             middle_initial,
\             family_name
\           )

Command chaining

You can also put two or more statements on one line by separating them with a vertical bar.

echo "Starting..." | call Phase(1) | call Phase(2) | echo "Done"

In other words, the vertical bar in Vimscript plays the same role as the semicolon in most other programming languages. In Vim, the semicolon cannot be used to separate statements because it already has another meaning at the start of a command (specifically, "from the current line to ..." as part of the command's line range).

Copy ex command output

To copy the output of an Ex command into a buffer:

:redir @a
:set all
:redir END

You can paste the contents of register a with "ap.

List of built-in functions

Alternatively, you can run the following command to access a handy list grouped by category.

:help function-list

String manipulation (string-functions)

  • nr2char(): Get a character from its ASCII value
  • char2nr(): Get the ASCII value of a character
  • str2nr(): Convert a string to a number
  • str2float(): Convert a string to a Float
  • printf(): Format a string with % notation
  • escape(): Escape characters in a string with '\'
  • shellescape(): Escape a string for use in a shell command
  • fnameescape(): Escape a file name for use in a Vim command
  • tr(): Replace a set of characters with corresponding characters
  • strtrans(): Make every character in a string printable on screen
  • tolower(): Convert all letters to lowercase
  • toupper(): Convert all letters to uppercase
  • match(): Find where a pattern matches in a string
  • matchend(): Find where a pattern match ends in a string
  • matchstr(): Text of a pattern match in a string
  • matchlist(): Same as matchstr(), but also returns the text of submatches
  • stridx(): First occurrence of a short string in a long string
  • strridx(): Last occurrence of a short string in a long string
  • strlen(): String length
  • substitute(): Replace a pattern match with another string
  • submatch(): Get the text of a submatch within ":s" and substitute()
  • strpart(): Get part of a string
  • expand(): Expand reserved keywords into their actual content
    • expand('%'): Get the name of the current file.
  • iconv(): Convert text from one encoding to another
  • byteidx(): Byte position of a character in a string
  • repeat(): Repeat a string multiple times
  • eval(): Evaluate a string expression

List manipulation (list-functions)

  • get(): Get an item, without an error for an invalid index
  • len(): Number of items
  • empty(): Check whether it is empty
  • insert(): Insert at a specific position
  • add(): Append an item to the list
  • extend(): Append another list to the list
  • remove(): Delete one or more items
  • copy(): Make a shallow copy of a list
  • deepcopy(): Make a full copy of a list, including items within items
  • filter(): Delete selected items
  • map(): Change each item
  • sort(): Sort
  • reverse(): Reverse the order
  • split(): Split a string into a list
  • join(): Join list items into a string
  • range(): Return a list of consecutive numbers
  • string(): String representation of a list
  • call(): Call a function with a list as arguments
  • index(): Index of an item in a list
  • max(): Maximum value among items
  • min(): Minimum value among items
  • count(): Number of times a value appears in a list
  • repeat(): Repeat a list multiple times

Dictionary manipulation (dict-functions)

  • get(): Get an item, without an error for an invalid key
  • len(): Number of items
  • has_key(): Check whether a key exists
  • empty(): Check whether it is empty
  • remove(): Delete an item
  • extend(): Add the contents of another dictionary
  • filter(): Delete selected items
  • map(): Change each item
  • keys(): Get a list of keys
  • values(): Get a list of values
  • items(): Get a list of key-value pairs
  • copy(): Make a shallow copy of a dictionary
  • deepcopy(): Make a full copy of a dictionary, including items within items
  • string(): String representation of a dictionary
  • max(): Maximum value among values
  • min(): Minimum value among values
  • count(): Number of times a value appears in a dictionary

Floating-point computation (float-functions)

  • float2nr(): Convert a Float to an integer (Number)
  • abs(): Absolute value (also works on Number)
  • round(): Round
  • ceil(): Round up
  • floor(): Round down
  • trunc(): Drop everything after the decimal point
  • log10(): Base-10 logarithm
  • pow(): x to the power of y
  • sqrt(): Square root
  • sin(): Sine
  • cos(): Cosine
  • tan(): Tangent
  • asin(): Arcsine
  • acos(): Arccosine
  • atan(): Arctangent
  • atan2(): Arctangent
  • sinh(): Hyperbolic sine
  • cosh(): Hyperbolic cosine
  • tanh(): Hyperbolic tangent

Other computation (bitwise-function)

  • and(): Bitwise AND
  • invert(): Bitwise invert
  • or(): Bitwise OR
  • xor(): Bitwise XOR

Variables (var-functions)

  • type(): Type of a variable
  • islocked(): Check whether a variable is locked
  • function(): Get a function reference (Funcref) from a function name
  • getbufvar(): Get a variable value from a specific buffer
  • setbufvar(): Set a variable value in a specific buffer
  • getwinvar(): Get a variable value from a specific window
  • gettabvar(): Get a variable value from a specific tab
  • gettabwinvar(): Get a variable value from a specific window in a specific tab
  • setwinvar(): Set a variable value in a specific window
  • settabvar(): Set a variable value in a specific tab
  • settabwinvar(): Set a variable value in a specific window in a specific tab
  • garbagecollect(): Free as much memory as possible

Cursor and mark positions (cursor-functions, mark-functions)

  • col(): Column number of the cursor or a mark
  • virtcol(): Screen column number of the cursor or a mark
  • line(): Line number of the cursor or a mark
  • wincol(): Column number of the cursor within the window
  • winline(): Line number of the cursor within the window
  • cursor(): Move the cursor to the given column/line
  • getpos(): Get the position of the cursor, a mark, etc.
  • setpos(): Set the position of the cursor, a mark, etc.
  • byte2line(): Get the line number at a specific byte offset
  • line2byte(): Get the byte position of a specific line
  • diff_filler(): Count the filler lines above a line

Working with the current buffer's text (text-functions)

  • getline(): Get one line or a list of lines from the buffer
  • setline(): Replace the contents of a line in the buffer
  • append(): Append one line or a list of lines
  • indent(): Indentation of a specific line
  • cindent(): Indentation according to C indenting
  • lispindent(): Indentation according to Lisp indenting
  • nextnonblank(): Find the next non-blank line
  • prevnonblank(): Find the previous non-blank line
  • search(): Search for a pattern
  • searchpos(): Search for a pattern
  • searchpair(): Find the other end of a start/middle/end
  • searchpairpos(): Find the other end of a start/middle/end
  • searchdecl(): Find the declaration of a name

System functions and file handling (system-functions, file-functions)

  • glob(): Expand wildcards
  • globpath(): Expand wildcards across multiple directories
  • findfile(): Find a file in the given directories
  • finddir(): Find a directory in the given directories
  • resolve(): Find where a shortcut points to
  • fnamemodify(): Modify a file name according to rules
  • pathshorten(): Shorten the directory names in a path
  • simplify(): Simplify a path without changing what it points to
  • executable(): Check whether an executable exists
  • filereadable(): Check whether a file can be read
  • filewritable(): Check whether a file can be written
  • getfperm(): Get a file's permissions
  • getftype(): Get a file's type
  • isdirectory(): Check whether a directory exists
  • getfsize(): Get a file's size
  • getcwd(): Get the current working directory
  • haslocaldir(): Check whether the current window uses :lcd
  • tempname(): Get a temporary file name
  • mkdir(): Create a directory
  • delete(): Delete a file
  • rename(): Rename a file
  • system(): Run a shell command and get the result
  • hostname(): Host name
  • readfile(): Return a file's contents as a list of lines
  • writefile(): Write a list of lines to a file

Date and time (date-functions, time-functions)

  • getftime(): Get a file's last modification time
  • localtime(): Get the current time in seconds
  • strftime(): Format a time as a string
  • reltime(): Get the current or elapsed time precisely
  • reltimestr(): Convert a reltime() result to a string

Buffers, windows, and the argument list (buffer-functions, window-functions, arg-functions)

  • argc(): Number of arguments in the argument list
  • argidx(): Current position in the argument list
  • argv(): Get one argument from the argument list
  • bufexists(): Check whether a buffer exists
  • buflisted(): Check whether a buffer exists and is listed
  • bufloaded(): Check whether a buffer exists and is loaded
  • bufname(): Get the name of a specific buffer
  • bufnr(): Get the number of a specific buffer
  • tabpagebuflist(): Get the list of buffers in a tab
  • tabpagenr(): Get the tab number
  • tabpagewinnr(): winnr() for a specific tab
  • winnr(): Get the window number of the current window
  • bufwinnr(): Get the window number of a specific buffer
  • winbufnr(): Get the buffer number of a specific window
  • getbufline(): Get the contents of a specific buffer as a list of lines

Command line (command-line-functions)

  • getcmdline(): Get the current command line
  • getcmdpos(): Get the cursor position in the command line
  • setcmdpos(): Set the cursor position in the command line
  • getcmdtype(): Get the type of the current command line

Quickfix and location lists (quickfix-functions)

  • getqflist(): Quickfix error list
  • setqflist(): Modify the quickfix list
  • getloclist(): Location list
  • setloclist(): Modify the location list

Insert mode completion (completion-functions)

  • complete(): Set completion candidates
  • complete_add(): Add a completion candidate
  • complete_check(): Check whether completion should be aborted
  • pumvisible(): Check whether the popup menu is displayed

Folds (folding-functions)

  • foldclosed(): Check whether there is a closed fold at a specific line
  • foldclosedend(): Like foldclosed(), but returns the last line
  • foldlevel(): Get the fold level of a specific line
  • foldtext(): Generate the text displayed for a closed fold
  • foldtextresult(): Get the text displayed for a closed fold

Syntax and highlighting (syntax-functions, highlighting-functions)

  • clearmatches(): Delete all matches defined by matchadd() and the :match command
  • getmatches(): Get all matches defined by matchadd() and the :match command
  • hlexists(): Check whether a highlight group exists
  • hlID(): Get the ID of a highlight group
  • synID(): Get the syntax ID at a specific position
  • synIDattr(): Get a specific attribute of a syntax ID
  • synIDtrans(): Get the translated syntax ID
  • synstack(): Get the list of syntax IDs at a specific position
  • synconcealed(): Get conceal information
  • diff_hlID(): Get the highlight ID at a specific position in diff mode
  • matchadd(): Define a pattern to highlight (called a match)
  • matcharg(): Get :match argument information
  • matchdelete(): Delete a match defined by matchadd() and the :match command
  • setmatches(): Restore a list of matches saved with getmatches()

Spelling (spell-functions)

  • spellbadword(): Find a spelling error after the cursor
  • spellsuggest(): Return correction suggestions
  • soundfold(): Return words that sound similar to a word

History (history-functions)

  • histadd(): Add an item to the history
  • histdel(): Delete an item from the history
  • histget(): Get an item from the history
  • histnr(): Number of the highest-numbered item in the history list

Interaction (interactive-functions)

  • browse(): Open a file dialog
  • browsedir(): Open a directory dialog
  • confirm(): Get the user's choice
  • getchar(): Get a character input from the user
  • getcharmod(): Get the modifier key information of the last input
  • feedkeys(): Put characters into the typeahead queue
  • input(): Get a line of input from the user
  • inputlist(): Let the user pick one item from a list
  • inputsecret(): Get a line of input from the user without displaying it on screen
  • inputdialog(): Get a line of input in a dialog
  • inputsave(): Save and clear the typeahead
  • inputrestore(): Restore the saved typeahead

Graphical user interface (gui-functions)

  • getfontname(): Get the name of the font in use
  • getwinposx(): X position of the GUI Vim window
  • getwinposy(): Y position of the GUI Vim window

Vim server (server-functions)

  • serverlist(): Return the list of server names
  • remote_send(): Send command characters to a Vim server
  • remote_expr(): Evaluate an expression in a Vim server
  • server2client(): Send a reply to a client of the Vim server
  • remote_peek(): Check whether there is a reply from a Vim server
  • remote_read(): Read a reply from a Vim server
  • foreground(): Move the Vim window to the foreground
  • remote_foreground(): Move the Vim server window to the foreground

Window size and position (window-size-functions)

  • winheight(): Get the height of a specific window
  • winwidth(): Get the width of a specific window
  • winrestcmd(): Return a command that restores window sizes
  • winsaveview(): Get the view of the current window
  • winrestview(): Restore the saved view of the current window

Mappings (mapping-functions)

  • hasmapto(): Check whether a mapping exists
  • mapcheck(): Check whether a matching mapping exists
  • maparg(): Get the expansion of a mapping
  • wildmenumode(): Check whether wildmode is active

Other (various-functions)

  • mode(): Get the current editing mode
  • visualmode(): Get the last used visual mode
  • exists(): Check whether a variable, function, etc. exists
  • has(): Check whether a feature is supported in Vim
  • changenr(): Return the number of the most recent change
  • cscope_connection(): Check whether there is a cscope connection
  • did_filetype(): Check whether a FileType autocommand has been used
  • eventhandler(): Check whether invoked by an event handler
  • getpid(): Get Vim's process ID
  • libcall(): Call a function in an external library
  • libcallnr(): Same as above, but returns a number
  • getreg(): Get the contents of a register
  • getregtype(): Get the type stored in a register
  • setreg(): Set the contents and type of a register
  • taglist(): Get the list of matching tags
  • tagfiles(): Get the list of tag files
  • mzeval(): Evaluate an MzScheme expression

Redirect

Simple usage is as follows.

:redir @a
:set all
:redir END

When used in a function, a sample that puts the output into the output variable looks like this.

function Exec(command)
    redir => output
    silent exec a:command
    redir END
    return output
endfunction

See also

Favorite site

Tutorials

Guide

Cheatsheets

References


  1. Vim-ko-master-_4ef19e0.zip ↩

  2. Part 1 ~ Part 5: IBM_developer_works_-_Scripting_the_Vim_editor.tar.gz ↩

  3. Noon.tistory.com_-Vim_Script-_Part_1.pdf ↩

  4. Noon.tistory.com_-Vim_Script-_Part_2.pdf ↩

author Zer0 sitemap