Vim

From Colettapedia
Revision as of 20:45, 23 September 2018 by Colettace (talk | contribs) (→‎Links)
Jump to navigation Jump to search

Links

Normal Mode

Basic Commands

  • h, j, k, l = left, down, up, right
  • H, L - move cursor to {first, last} line in window
  • :q<Enter> = close window
  • :qa! = Get out of vim, all changes lost!
  • Ctrl-] = jump to the definition of the function that the cursor is on, if you ran ctags. Also, jump to a subject in help window
  • Ctrl-T = jump back
  • <Esc>/Ctrl-C = put you in NORMAL MODE/ Start command over
  • x = delete
  • i = go into insert mode at the current cursor position.
  • I = go into insert mode at the first column on this line
  • a = go into insert mode one position to the right of this cursor position.
  • A = Capital A = go into insert mode at the end of the line.
  • o = (lowercase o) go into insert mode on the line right below cursor pos.
  • O = (Capital O) go into insert mode on the line right above.
  • gi = go to insert mode right where I left it last time.
  • ^ = Shift-6 = move cursor to the first non-whitespace character on this line
  • :wq = write the current buffer to a file
  • dw = "delete word" delete all text from current cursor position to to next space character to the right, inclusive.
  • d$ = "delete line" delete all text from curr cursor pos to the right, inclusive of current cursor pos
  • de = just like dw, only leave the last space
  • w = move forward one word
  • W = move forward to the next word that has a space before it.
  • 2w = move forward 2 words
  • b = move back one word
  • e = move to the end of the next word
  • 3e = move the the end of the third next word
  • 0 = goto start of line
  • $ = goto end of line
  • d3w = delete the next 3 words
  • dd = delete (kill) the whole line
  • u = undo last action
  • 2u = undo last two actions
  • Ctrl-r = redo last action
  • U = "capital U" undo all changes on current line
  • y = copy the selected region
  • y$ = copy from cursor pos to end of line.
  • yy = yank the whole line
  • yw = yank all the characters between the cursor pos, and where you end up after using 'w' to move the cursor
  • yiw = "yank inner word" = yank the whole word under the cursor
  • viwp = paste the last word you yanked on top of this word
  •  :%y+ = yank the whole document
  • p = paste the last thing that was deleted to this cursor location
  • P = paste before
  • ]p/]P = paste before/after but adjust the indent
  • . = repeat the last command you just executed (super useful!)
  • rx = replace the character at the cursor with 'x' - for spot corrections, one char only.
  • R = (Capital R) = Replace more than one character. Like insert mode, but every typed character deletes an existing character.
  • ce = delete the word form this character to the end, cursor position inclusive, and automatically go into insert mode.
  • cw = like dw, then i
  • c5e = delete the next 5 words and go into insert mode
  • c$e = delete all the characters form here to the end of the line and go into insert mode.
  • <backspace> = correct mistakes while typing
  • :set ruler, and :set noruler
  • 30| = "30 pipe" = goto 30th column in line
  • Ctrl-g = show file status and cursor position
  • Ctrl-o
  • Ctrl-l - refresh screen (useful when running inside a terminal)
  • G = goto end of file
  • gg = goto beginning of file
  • 500G = "500 capital G" = goto line 500
  • :600<Enter> = goto line 600
  • Command line completion - press Ctrl-D while typing the command.
  • Ctrl-t/Ctrl-d = tab/de-tab.
  • :set number = turn line numbering on
  • ~ = toggle upper/lowercase
  • make <BAckspace> act as <Delete> in visual mode:
    • :vmap <BS> x
  • :[range]g/<pattern>/cmd - do cmd for all lines that match <pattern>
    • :g!/<pattern>/cmd - do cmd for all lines that DO NOT MATCH <pattern>
    • cmd is usually s (perform substitution on that line) or d (delete that line), or m (move the line to some other line)
  • :g/^/m0 - reverse a file
  • :g/<pattern>/m$ - move all lines matching pattern to end of the file
    • Where I guess $ is the end of the file as opposed to end of the line in this context

Visual Mode

  • v = Visual-mode character-wise. Select text starting with current cursor pos.
  • V = visual mode, line-wise.
  • ctrl-v = visual mode, column wise
  • = = fix indent (super useful!)
  • < = reduce indent
  • > = increase indent

Registers

  • :reg = show me what's in my registers
  • "<char> before a yank/delete/paste specifies a register named <char>
  • copying to uppercase registers append to their contents
  • "wyy = yank the current line into register w
  • "WD = cut the rest of teh line and append it to the contents of register w
  • "wp - paste the contents of register w
  • ctrl-rw = inserts the contents of register w (in insert mode)
  • Registers 0-10 are the "recently killed ring"
    • If you ended up pasting something you didn't mean to, do a :reg to figure out which register has the real text you want.
    • then do a "3P or whatever number register has it.

Bookmarking

  • m<letter> = sets mark named <letter> at current location
  • `<letter> = jump precisely to that mark
  • '<letter> = jump to the line with the mark
  • lowercase letter = mark is local to buffer
  • uppercase letter = mark is global; your buffer will be switched to the file with the mark
  • :marks = show me my current marks
  • :delm! = delete all marks
  • d`a = delete text from current cursor pos to mark a
  • gi = go into insert mode in the last place you edited.

Reversing the order of specified lines

  1. go to line above and mark with mt
  2. go to last line in list and type :'t+1,.g/^/m 't
  • see also :help 12.4

Navigating buffers within a window

  • Vim Buffer FAQ
  • :ls = :buffers = show all the buffers
  • :bu5 = :buffer 5 = go the the buffer labelled 5
  • 5 C-^ = go the the buffer labelled 5
  • :badd
  • :bdelete
  • :sbuffer 5 = split open a new window (horizontally) and open the specified buffer in that window.
  • :bp[revious] = go back to the last buffer
  • :bn[ext] = go to the next buffer

Scrolling/Windowing in Normal Mode

  • Ctrl-e/Ctrl-y = Scroll down/up one line.
  • Ctrl-d/Ctrl-u = Scroll down/up half a screen.
  • Ctrl-f/Ctrl-b = Scroll down/up a full screen.
  • :vsp<Enter> = Split window vertically
  • Ctrl-w Ctrl-w = Move between windows
  • Ctrl-W s = split window horizontally
  • :q<Enter> = kill window
  • Ctrl-W j = go to window below
  • Ctrl-W k = go to window above
  • Ctrl-w o = make the current window the only one on the screen. All other windows are closed
  • Ctrl-w = = make the windows equally high and wide
  • Ctrl-w | = make the windows as wide as possible
  • :vertical res 80 = resize the current window to 80 columns
  • zz - scroll such that line that cursor is on goes to the MIDDLE of the window
  • zt - scroll such that line that cursor is on goes to the TOP of the window
  • zb - scroll such that line that cursor is on goes to the BOTTOM of the window

Code Folding

  • zM - fold all
  • zR - unfold all
  • za - toggle fold/unfold function
  • python-specific: :set foldmethod=indent and :set foldnestmax=2
  • zfa} - put cursor inside block of code punctuated by curly braces, then type zfa} to create code fold for that block
  • zf10{j, k} - create a code fold from cursor to 10 lines {down, up}
  • zo - open a fold you created
  • zc - close a fold you created

Open documents in tabs (Vim 7 only)

  • :tabe <file> = open <file> in a new tab
  • :tabc = close current tab
  • gt, gT = cycle through tabs (also :tabn and :tabp)

Searching

    • /foobar = search for the next instance of the word 'foobar'
    • ?foobar = find the last instance of the word 'foobar'
    • n = repeat last search
    • N = repeat last search in opposite direction
  •  % = find the other parentheses that matches the one at the current cursor position.
  • */# = find next/previous instance of word at cursor
  • :noh[lsearch] = Removes the highlighting for the current search. The highlighting returns for the next search.

Substitute

  • :s/foo/bar <Enter> = substitute the first "foo" for "bar" in this line
  • :s/foo/bar/g <Enter> = substitute all the "foo"s for "bar"s in this line
  • :100,200s/foo/bar/g <Enter> = substitute all the "foo"s for "bar"s in lines 100 through 200
  •  :%s/foo/bar/g <Enter> = the whole file
  •  :%s/foo/bar/gc <Enter> = the whole file, prompt every time
  •  :%s/^\s*\r\?\n//g <Enter> = remove all blank lines from the entire document
    • even better way: :%g/^$/d
      • g means do the following command on every line that matches the following regex
      • d is delete

differences with perl

  • capture parentheses and the "at least once" operator '+' need to be escaped:
    • s/^class^I\(\S\+\)/class^I\1^I\1^I110/g
  • need to escape ~:
    •  :%s/\~/\/home\/colettace/g
  • need to escape the "at least one" '?' operator:
    •  :%s/t\(\d\d\.\?\d\?$\)/^I\1/g
  • in the replace section of the regexp, the ampersand character needs to be escaped
  • non-greedy operator is \{-}
  • In the replace part of the regexp \0 means the entire part of the string that matched the string. \1, \2 etc. are teh individual matches captured by parentheses in the find part of the regexp

I/O and interacting with shell

  •  :!ls = Suspend vim and run ls, and prompt to reenter vim
  • :w filename = Write the buffer to 'filename'
  • :wa = write all buffers
  •  :!rm filename = delete file 'filename'
  • :r filename = insert the file 'filename' at cursor location
  • :r !ls = read the output of the command 'ls' and dump it below cursor position
  • :e filename = edit file
  • :e! = revert buffer, reload file from disk, dump current changes
  • :args file1 file2 file3 = load multiple files into their own buffers
  • :ene = edit a new unnamed buffer
  • gf - open the file under the cursor
  • :fin filename = find filename in path and edit it.
  • Typing ":set xxx" sets the option "xxx". Some options are:
    • 'ic' 'ignorecase' ignore upper/lower case when searching
    • 'is' 'incsearch' show partial matches for a search phrase
    • 'hls' 'hlsearch' highlight all matching phrases
    • You can either use the long or the short option name.
    • Prepend "no" to switch an option off: :set noic
    • If you want to ignore case for just one search command, use \c in the phrase: /ignore\c <ENTER>

Insert mode

  • ctrl-[ = exit mode and finish abbrieviations
  • Ctrl-T, Ctrl-D = tab and de-tab
  • ctrl-h - backspace
  • ctrl-w = delete word before cursor
  • ctrl-u = delete all entered characters in the current line
  • ctrl-<left>, ctrl-<right>, <home>, <end>

diff mode

  • do = diff obtain = pull changes from other file into this one
  • dp = diff put
  • [c = put cursor on earlier difference
  • ]c = put cursor on next difference

cscope - tried it didn't work for me

  • cscope vim tutorial
  • requires sudo apt-get install cscope
  • put cscope_maps.vim in your ~/.vim/plugins directory
  • find /my/project/dir -name '*.c' -o -name '*.cpp' -o -name '*.cxx' -o -name '*.h' -o -name '*.hpp' -o -name '*.hxx'> cscope.files
  • run cscope -b -R in the top level directory of the source
  • now either start vim in the same dir as the generated cscope.out file, or export CSCOPE_DB=/home/colettace/src/wnd-charm/cscope.out

usage

  • vim -t <symbol - Start vim with a C symbol (ex: 'vim -t main')
  • "CTRL-\ s" (Control-backslash, then just 's') -
  • "CTRL-t" to jump back to your original location before the search
        USAGE   :cs find {querytype} {name}

            {querytype} corresponds to the actual cscope line
            interface numbers as well as default nvi commands:

                0 or s: Find this C symbol
                1 or g: Find this definition
                2 or d: Find functions called by this function
                3 or c: Find functions calling this function
                4 or t: Find this text string
                6 or e: Find this egrep pattern
                7 or f: Find this file
                8 or i: Find files #including this file

        For all types, except 4 and 6, leading white space for {name} is
        removed.  For 4 and 6 there is exactly one space between {querytype}
        and {name}.  Further white space is included in {name}.


Debugger

  • <F1> : resizing windows
  • <F2> : step into
  • <F3> : step over
  • <F4> : step out
  • <F6> : stop debugging
  • <F11> : shows all variables
  • <F12> : shows variable on current cursor
  • ,e : evalute expression and display result. cursor is automatically move to watch window. type line and just press enter.

Command line command

  • :Bp : toggle breakpoint on current line
  • :Up : goto upper level of stack
  • :Dn : goto lower level of stack
  • press <F6> to stop debugging. then, debugger windows will be closed and windows will be restored. (holy :mksession feature )

.vimrc

" ----- General Settings  -----------------------------------------------------

" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.

set nocompatible
let mapleader='\'
set notimeout
"set updatetime=4000

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

" plugins will go here (see next step) 
" (be sure to replace 'Plugin' with 'Plug')
"
Plug 'altercation/vim-colors-solarized'
"Plug 'tomasr/molokai'
Plug 'bling/vim-airline'

Plug 'scrooloose/nerdtree'
Plug 'jistr/vim-nerdtree-tabs'
Plug 'scrooloose/syntastic'


Plug 'xolox/vim-misc'
Plug 'xolox/vim-easytags'
Plug 'majutsushi/tagbar'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }

Plug 'qpkorr/vim-bufkill'

Plug 'airblade/vim-gitgutter'
Plug 'tpope/vim-fugitive'


call plug#end()

filetype plugin indent on
syntax on

" allow backspacing over everything in insert mode
set backspace=indent,eol,start

set history=1000       " keep 1000 lines of command line history
set number             " line numbers
set ruler              " show the cursor position all the time
set showcmd            " display incomplete commands
set incsearch          " do incremental searching
set linebreak          " wrap lines on 'word' boundaries
set scrolloff=3        " don't let the cursor touch the edge of the viewport
set splitright         " Vertical splits use right half of screen
set timeoutlen=100     " Lower ^[ timeout
set fillchars=fold:\ , " get rid of obnoxious '-' characters in folds
set tildeop            " use ~ to toggle case as an operator, not a motion
if exists('&breakindent')
  set breakindent      " Indent wrapped lines up to the same level
endif

" Tab settings
set expandtab          " Expand tabs into spaces
set tabstop=4          " default to 2 spaces for a hard tab
set softtabstop=4      " default to 2 spaces for the soft tab
set shiftwidth=4       " for when <TAB> is pressed at the beginning of a line



" ----- Convenience commands and cabbrev's ------------------------------------

" Make these commonly mistyped commands still work
command! WQ wq
command! Wq wq
command! Wqa wqa
command! W w
command! Q q

" vim reloads my vimrc if it detects that I edited it
augroup myvimrc
    au!
    au BufWritePost .vimrc,_vimrc,vimrc,.gvimrc,_gvimrc,gvimrc so $MYVIMRC | if has('gui_running') | so $MYVIMRC | endif
augroup END

" pull up my .vimrc
:nnoremap <leader>ev :e $MYVIMRC<cr>

" ----- Terminal-as-GUI settings ----------------------------------------------

" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
  set mouse=a
endif



" ----- Plugin-Specific Settings --------------------------------------

" ----- altercation/vim-colors-solarized settings -----
" Toggle this to "light" for light colorscheme
set background=dark

" Uncomment the next line if your terminal is not configured for solarized
"let g:solarized_termcolors=256

" Set the colorscheme
colorscheme solarized

" make background color behave in tmux
set t_ut=

" ----- bling/vim-airline settings -----
" Always show statusbar
set laststatus=2

" Fancy arrow symbols, requires a patched font
" To install a patched font, run over to
"     https://github.com/abertsch/Menlo-for-Powerline
" download all the .ttf files, double-click on them and click "Install"
" Finally, uncomment the next line
"let g:airline_powerline_fonts = 1

" Show PASTE if in paste mode
let g:airline_detect_paste=1

" Show airline for tabs too
let g:airline#extensions#tabline#enabled = 1


" ----- jistr/vim-nerdtree-tabs -----
" Open/close NERDTree Tabs with \t
nmap <silent> <leader>t :NERDTreeToggle<CR>
"map <C-n> :NERDTreeToggle<CR>
" To have NERDTree always open on startup
let g:nerdtree_tabs_open_on_console_startup = 0
let g:nerdtree_tabs_open_on_gui_startup=0

" ----- scrooloose/syntastic settings -----
let g:syntastic_error_symbol = '✘'
let g:syntastic_warning_symbol = "▲"
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*

let g:syntastic_always_populate_loc_list = 0
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_open = 0
let g:syntastic_check_on_wq = 0
"let g:syntastic_python_checkers = ['python']
let g:syntastic_python_pylint_args = "--extension-pkg-whitelist=numpy,scipy --disable=trailing-whitespace,bad-whitespace,missing-docstring,bad-continuation,invalid-name,line-too-long,too-many-statements"
augroup mySyntastic
  au!
  au FileType tex let b:syntastic_mode = "passive"
augroup END

nmap <silent> <leader>s :SyntasticCheck<CR>
nmap <silent> <leader>e :Errors<CR>
nmap <silent> <leader>c :lclose<CR>

" ----- xolox/vim-easytags settings -----
" Where to look for tags files
set tags=./tags;,~/.vimtags
" Sensible defaults
let g:easytags_events = ['BufReadPost', 'BufWritePost']
let g:easytags_async = 1
let g:easytags_dynamic_files = 2
let g:easytags_resolve_links = 1
let g:easytags_suppress_ctags_warning = 1

" ----- majutsushi/tagbar settings -----
" Open/close tagbar with \b
nmap <silent> <leader>b :TagbarToggle<CR>
" Uncomment to open tagbar automatically whenever possible
"autocmd BufEnter * nested :call tagbar#autoopen(0)


" ----- airblade/vim-gitgutter settings -----
" Required after having changed the colorscheme
hi clear SignColumn
" In vim-airline, only display "hunks" if the diff is non-zero
let g:airline#extensions#hunks#non_zero_only = 1

Sessions (projects)

  • session keeps the views for all windows, plus the global settings
  • you can save a session and when you restore it, the window layout looks the same
  • :mksession <file> to write out a session to a file
  • :source <file> to load a session from a file
  • vim -S <file> to start editing a session

~/.vim/plugins/stab.vim

" put all this in your .vimrc or a plugin file
command! -nargs=* Stab call Stab()
function! Stab()
  let l:tabstop = 1 * input('set shiftwidth=')

  if l:tabstop > 0
    " do we want expandtab as well?
    let l:expandtab = confirm('set expandtab?', "&Yes\n&No\n&Cancel")
    if l:expandtab == 3
      " abort?
      return
    endif

    let &l:sts = l:tabstop
    let &l:ts = l:tabstop
    let &l:sw = l:tabstop

    if l:expandtab == 1
      setlocal expandtab
    else
      setlocal noexpandtab
    endif
  endif

  " show the selected options
  try
    echohl ModeMsg
    echon 'set tabstop='
    echohl Question
    echon &l:ts
    echohl ModeMsg
    echon ' shiftwidth='
    echohl Question
    echon &l:sw
    echohl ModeMsg
    echon ' sts='
    echohl Question
    echon &l:sts . ' ' . (&l:et ? '  ' : 'no')
    echohl ModeMsg
    echon 'expandtab'
  finally
    echohl None
  endtry
endfunction