Viml builtin functions

From wikinotes


:h builtin


get line info

line('.')        " current line number

getline('.')     " current line
getline(10, 20)  " get list of lines 10-through-20
getline(1)[0]    " get char at line-1, col-0

change line info

setline('.', 'new text')                    " set current line
setline(10, 15, ['1', '2', '3', '4', '5'])  " set lines within buffer
deletebufline(bufnr(), 10, 15)               " delete lines 10-15 in current buffer
appendbufline(bufnr(), 3, 'abc')             " append 'abc' after line 3 in current buffer


call cursor(5, 10)               " move cursor to line-5, col-10

let s:saved_view = winsaveview() " save cursor pos
call winrestview(s:saved_view)   " restore cursor pos


b     mybuffer                          " open buffer in current window
badd  mybuffer                          " create buffer
bd    mybuffer                          " delete buffer
bufnr('buffername')                     " get buffer number from name

buffers!                                " list all buffers
files!                                  " list all buffers representing files

current buffer

map <buffer> q :echom helloworld<CR>    " buffer-specific mapping
setlocal nonmodifiable                  " makes buffer read-only
setlocal nobuflisted                    " changes buffer type to 'unlisted'
setlocal textwidth=70                   " Restrict a buffer's allowed characters

line('$')                              " number of lines in current buffer

:0 | exec printf('delete %d', line('$'))  " delete all lines in buffer

temporary buffer (no warn to save on exit)

badd mybuffer
b mybuffer
setlocal buftype=nofile
setlocal bufhidden=delete   " or hide, if preferred
setlocal noswapfile

bufwinnr('myfile.txt') > 0    " check if buffer exists, and is being viewed in a window
bufname('myfile.txt') != ''   " check if buffer exists (may be hidden)

list buffers in vimscript

let all_buffers = filter(map(filter(range(1, bufnr('$')), 'bufexists(v:val)'), 'bufname(v:val)'), '!empty(v:val)')


sp +/searchstring file.txt                        " open window at line matching searchstring
wincmd c                                          " equivalent to <C-w><C-w>
exec printf('%d wincmd c', bufwinnr('mybuffer'))  " open window with buffer 'mybuffer'


split('/abc/def/ghi', '/')
join(["a", "b", "c"], ".")
substitute(var, '[^a-zA-Z_\\\-]', '', 'g')


execute 'echom "hi"'     " execute vim command in string
system('ls -la')         " execute system command in string
pyeval('print("hi")')    " execute python command in string


filter(['a', '', 'b'], '!empty(v:val)')                            " ['a', 'b']
map(['a', 'b'], 'v:val + "---")                                    " ['a---', 'b---']
map(['abc', '123'], "substitute(v:val, '\\w\\(bc\\)\\+', '\\1')")  " ['bc', '123']  (regex backslashes must be escaped)


messages   " print all messages printed within vim


executable("tmux")  " true if 'tmux' executable available