Vim

From Colettapedia
(Redirected from Vim Stuff I learned)
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!
  • <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 resize 80 = resize the current window to 80 columns
    • :vertical res -30 = make the current pane 30 less wide so as to expand the sidebar
  • 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
  • :on - remove any windows, make the current buffer the "ONLY" window, but keep all buffers open

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 )

Tags

  • Use vim with ctags
  • Rlang ctags
  • ctags -R --languages=R - run manually in top-level directory, ctags doesn't seem to do R files by default
  • 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

Built-in Autocomplete

.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
set clipboard=unnamed

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

" fugitive = git command line interface inside vim
Plug 'tpope/vim-fugitive'

" nerdtree = File system explorer for vim, basically a pseudo file explorer GUI, with some file operations
Plug 'preservim/nerdtree'

" Simply show high-level global variables and functions within the current buffer - not used to jump!
Plug 'preservim/tagbar'

Plug 'airblade/vim-gitgutter'

" I can't get 'youcompleteme' to work anymore
"Plug 'valloric/youcompleteme'

" Jedi is specific to Python
" Jedi is a static analysis tool for Python that is typically used in IDEs/editors plugins.
" Jedi has a focus on autocompletion and goto functionality.
" Other features include refactoring, code search and finding references.
" https://jedi.readthedocs.io/en/latest/
" https://github.com/davidhalter/jedi-vim
Plug 'davidhalter/jedi-vim'

Plug 'nanotech/jellybeans.vim'
"Plug 'altercation/vim-colors-solarized'
"Plug 'tomasr/molokai'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'

Plug 'dense-analysis/ale'
"Plug 'sheerun/vim-polyglot'
Plug 'pangloss/vim-javascript'
Plug 'xolox/vim-misc'
Plug 'xolox/vim-easytags'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'qpkorr/vim-bufkill'
"Plug 'chrisbra/csv.vim'
Plug 'ntpeters/vim-better-whitespace'
"Plug 'posva/vim-vue'
Plug 'leafOfTree/vim-svelte-plugin'
"Plug 'Jorengarenar/COBOl.vim'
"
Plug 'jalvesaq/Nvim-R'

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=2          " default to 2 spaces for a hard tab
set softtabstop=2      " default to 2 spaces for the soft tab
set shiftwidth=2       " 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


" ----- 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
colorscheme jellybeans

" make the solarized background work inside a tmux pane
set t_ut=

" set vim to monitor changes I make to my .vimrc
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>

" ----- 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


" ----- preservim/nerdtree -----
"nnoremap <leader>n :NERDTreeFocus<CR>
"nnoremap <C-n> :NERDTree<CR>
nnoremap <C-t> :NERDTreeToggle<CR>
"nnoremap <C-f> :NERDTreeFind<CR>

" ----- tagbar -----
nmap <F8> :TagbarToggle<CR>
" To have NERDTree always open on startup

" ----- 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 = 1
"let g:syntastic_auto_loc_list = 1
"let g:syntastic_check_on_open = 1
"let g:syntastic_check_on_wq = 0
"let g:syntastic_python_checkers = ['ruff', 'pylint', 'python3']
"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,too-many-arguments,too-many-locals,too-many-branches,protected-access,fixme,too-many-lines,too-many-instance-attributes,too-many-public-methods"

"let g:syntastic_cobol_compiler_options = "--free -std=cobol2014"
"let g:syntastic_cobol_compiler_options = "--free"
"let cobol_format_free = 1

"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


" ----- 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

autocmd BufNewFile,BufRead *.ipynb set filetype=javascript


" ----- dense-analysis/ale settings -----
" No idea how to get this woring
" let g:ale_linters = {'ruff', 'pylint'}
let g:ale_r_lintr_options = 'with_defaults()'



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

Plugins

Ways to customize

  • <leader> - type :echo mapleader to see what it is currently; Defaults to backslash
  • remap is an *option* that makes mappings work recursively.
  • :map and :noremap are recursive and non-recursive versions of the various mapping commands.
    • Recursive refers to the chaning commands to other commands
    • Remaps specific to normal mode of vim editor are preceeded by letter n, e.g., :nmap and :nnoremap
    • Run :map to see a list of all mappings

tpope/vim-fugitive

  • git command line interface inside vim
  • :Git or :G calls any arbitrary git command

preservim/nerdtree

  • File system explorer for vim, basically a pseudo file explorer GUI, with some file operations
  • nnoremap <C-t> :NERDTreeToggle<CR>
  • NERDTreeCWD - change root of nerdtree to current working directory
  • :NERDtree then ? for full list

Tagbar

  • Simply show high-level global variables and functions within the current buffer - not used to jump!
  • Requires Universal ctags
    • brew install --HEAD universal-ctags/universal-ctags/universal-ctags
  • I have F8 mapped to :TagbarToggle
  • preservim/tagbar on github.com

Jedi-vim

  • Code completion FOR PYTHON ONLY
  • Used in place of syntastic, since I can't get that to work consistently
  • Ctrl+Space for code completion
  • \g - goto assignment/function
  • \d - goto definition (follow identifier as far as possible, includes imports and statements)
  • \r - rename every instance of this variable
  • \s - Goto (typing) stub
  • K - Show Documentation/Pydoc K (shows a popup with assignments)
  • \n - Show all usages of this symbol in the open buffer within a small pop-up window
  • :Pyimport modulename - open module
  • :help jedi-vim

EasyTags

jalvesaq/NVim-R