Linux :: Vim

Vim

modeline

# with set, ends at the first :
# must have a space before vim
/* vim: set ai tw=75: */
/* vim: set ft=json: */

# without set, ends at the line
// vim: ai:sw=3 ts=6

Command

# search and replace
# use % for the complete file
# otherwise only subject line
# g for all occurrence
# c for prompt
:%s/original/new/g
:%s/old/new/gc

# use ! to execute external command
:!ls

# start terminal
:terminal {command}

# start neovim with a command
nvim -c ":terminal"

# add in vimrc
# need -bar to enable <bar> for custom ex command
command -bar W :execute ':silent w !sudo tee % > /dev/null' <bar> :edit!
command WQ :W <bar> :q

Operators

c:  change
d:  delete
y:  yank
r:  replace
R:  stay replace
gu: lowercase
gU: uppercase
>:  shift right
<:  shift left
=:  format?

Motion

    k
h       l
    j

## horizontal
w: start of next word
e: end of current word
b: backwards

$: move to end of line
0: start of the line
g0: when lines wrap, to the first char
g^: when lines wrap, to the first non-blank char of the line
gm: half of screenwidth to the right
g$: when lines wrap, to the end of line
gj: move screen line (when there is wrap)
gk: move screen line
%:  brackets

f{char}:    to the Nth occurrence of {char}
F{char}:    backwards
t{char}:    till before Nth occurrence
T{char}:    till after Nth occurrence

# vertical
4j: four lines down
gg: first line of the file
G: last line of the file
C-g: display location and file status
N G:    move to the line number
C-f: next page
C-b: previous page

# visual blocks
# use C-v or C-q to start visual mode, and use motion

Text objects

# selection
aw  word including spaces
iw  inner word

as  sentence
is

ap   paragraph
ip

# blocks, [], (), {}
a[ a]
i[ i]

# tags
a<
a>
i<
i>
at
it

# quotes
a"
i"
a'
i'

Editing

x: delete, alias for dl
X: backspace, alias for dh
i: insert
u: undo
U: undo whole line
A: append text to end of sentence
dw: delete a word
d$: delete to end of line
dd: current line, dj is delete next line
dgn: delete next match pattern
o: opening a line below the current; O: above
V: select the whole line; d cut
y: yank, copy
p: paste, P for paste at cursor
J: join lines
f: search within the line and move to next instance
/: search and move with n and N (backwards)
?: search backwards


## unicode
## C-v or C-q in insert mode
u2560	# four-digit HEX
U7fffffff	# eight-digit
# also works for ASCII, and o

## autocomplete
## popup, or preview, or none
set completeopt=menu,menuone,popup,noselect,noinsert
## change colors
hi Pmenu ctermfg=NONE ctermbg=236 cterm=NONE guifg=NONE guibg=#64666d gui=NONE
hi PmenuSel ctermfg=NONE ctermbg=24 cterm=NONE guifg=NONE guibg=#204a87 gui=NONE

Key Mapping

imap jk <esc> # insert mode
nmap # normal mode
vmap # visual mode
omap # when an operator(d, c, y etc) is pending

## find out existing map
:verbose imap <C-v>

## list built in map
:help index

Managing files

:bn move to next file
:bp move to previous file
:buffers no.
:e path/to/file # open another file to buffer

v motion :w FILENAME    save selection to file
:e FILENAME Edit a file
:r FILENAME Insert the content of the file
:r !ls  insert the content from `ls`

Windows

Ctrl+w v    # vertically split window
:vsplit     # vertically split window
:vs newfile # open a new file in v split window

Ctrl+w h/j/k/l  # navigate between windows
<C-w><C-w>  # jump between windows
Ctrl+w c    # close current window, or :q
Ctrl+w o	# closes other windows

:ls         # list buffers
:on         # only the current window
:bd%        # delete buffer No. %

set splitbelow	# show preview window below

Colors

if !has('gui_running')
    set t_Co=256
endif
if (match($TERM, "-256color") != -1) && (match($TERM, "screen-256color") == -1)
    " screen does not (yet) support truecolor
    set termguicolors
endif
set background=dark
if filereadable(expand("~/.vimrc_background"))
"  let base16colorspace=256
  source ~/.vimrc_background
endif
if has('mac')
   colorscheme base16-phd
endif
highlight Normal ctermbg=none

Plugins

# install vim-plug
# nvim folder
# ${XDG_DATA_HOME:-$HOME/.local/share}"/nvim/site/autoload/plug.vim
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim


# edit .vimrc file
call plug#begin('~/.vim/plugged')

Plug 'tpope/vim-sensible'

call plug#end()

# Install
:PlugInstall

# update
:PlugUpdate

# upgrade vim-plug
:PlugUpgrade

# check status
:PlugStatus

# Uninstall
# comment out unused plugin then run
:PlugClean

Lua

-- this is a comment
num = 22 -- this global variable represents a number
local num2 = 33 -- local variable
str1 = 'this is a string'
str2 = "and so is this"
str3 = [[ and this is a string too ]]
str4 = "string " .. "concatenation"
val = true and not false -- booleans and logical operators

if str1 == 'something' then
  print("YES")
elseif str2 ~= 'is not equal' then
  print('Maybe')
else
  print('no')
end

function printText(text)
  print(text)
  return true
end

-- table is also array
tab1 = { "this", "is", "a", "table" }
-- tables are both arrays and dictionaries
tab2 = { also = 'this is a table' }
-- dictionary
-- use either ["key"] or key
dict = { ["window"] = { width = 0.9, height = 0.6 }}

tab2["new_key"] = "new value"

print(tab2["also"])

require('plugins') -- will find and execute plugins.lua file

Vim to Lua

-- use vim.cmd to run VIM script
-- currently cant create or call ex-cmd, autocmd
vim.cmd([[
set notimeout
set encoding=utf-8
]])

## check config and data folder
:echo stdpath('config')
:echo stdpath('data')
vim.cmd 'source ~/.config/nvim/theme.vim'

-- let g:mapleader = ','
vim.g.mapleader = ","

-- set encoding=utf-8
-- vim.wo for window options
-- vim.bo for buffer options
vim.opt.encoding="utf-8"
vim.opt.wrap = true
vim.opt.wildignore = '*/cache/*,*/tmp/*'
vim.opt.wildignore = {'*/cache/*', '*/tmp/*'}

-- set errorformat+=%f|%l\ col\ %c|%m
vim.opt.errorformat:append('%f|%l col %c|%m')
-- ^=
vim.opt.errorformat:prepend('%f|%l col %c|%m')
-- -=
vim.opt.errorformat:remove('%f|%l col %c|%m')


-- functions
vim.fn.thisIsMyFun
vim.fn["thisIsMyFun"]
vim.fn.thisIsMyFun()
vim.fn["thisIsMyFun"]()

if vim.fn.has('nvim') == 1 then
 -- some thing here
end

-- same
vim.fn['fzf#vim#files']('~/projects', false)
vim.call('fzf#vim#files', '~/projects', false)


-- set HOME var
HOME = os.getenv("HOME")
-- use .. to concatenate strings
vim.opt.backupdir = HOME .. "/.vim/backup"

-- vim.api is a collection of API fn
-- vim.api.nvim_set_keymap(mode, keys, mapping, options)
-- nnoremap <leader>a :Git blame<CR>
vim.api.nvim_set_keymap(
  "n",
  "<leader>a",
  ":Git blame<cr>",
  { noremap = true }
 )

-- use a function for keymapping
function map(mode, shortcut, command)
  vim.api.nvim_set_keymap(mode, shortcut, command, { noremap = true, silent = true })
end

function nmap(shortcut, command)
  map('n', shortcut, command)
end

function imap(shortcut, command)
  map('i', shortcut, command)
end

-- e.g.
nmap("<leader>a", "<cmd>Git blame<CR>")


-- vim-plug
local Plug = vim.fn['plug#']

vim.call('plug#begin', '~/.config/nvim/plugged')

Plug 'wellle/targets.vim'
Plug('scrooloose/nerdtree', {on = 'NERDTreeToggle'})
Plug('junegunn/goyo.vim', {['for'] = 'markdown'})
Plug('junegunn/fzf', {['do'] = vim.fn['fzf#install']})
Plug('VonHeikemen/rubber-themes.vim', {
  ['do'] = function()
    vim.opt.termguicolors = true
    vim.cmd('colorscheme rubber')
  end
})
Plug 'tpope/vim-surround'
Plug 'tpope/vim-repeat'

vim.call('plug#end')