vim - RicoJia/notes GitHub Wiki

Intro

  • Learn a bit of vim every week! It does take a long time to command. Practice lots.

    • Vi is for "visual", vim = Vi + improved. Tailored for Unix systems, and actually vim starts when we start vi.
    • Even more ubiquitous than emacs or nano
  • Vim introduces mode, cuz a key can only function in a certain way: normal, insert, visual (highlight).

  • vimtutor

  • Think in vim

    • Use hjkl first
    • Motion and operator: in dw, d is operator, w is motion.
    • There's also count: Count+operator+motion, or operator + count+ motion, like 3D means delete from current cursor 3 times
    • READ THE COMMANDS OUT LOUD WILL HELP typing!
    • use . for repeated action
    • You will see a lot of e vs E, b vs B, the key difference is caps think a word is surrounded by whitespace, while small letters can be surrounded by chars
    • Text objects: {operator}a{object} or {operator}i{object}, a means a, i means inside. - E.g,daw(delete word including extra spacing), - diw (delete a word, but keeps spacing) - ciw easiest way to change word - dap deletes a whole paragraph, dip keeps the paragraph boundary, which is a line - das deletes a sentence, diskeeps the sentence boundary, which is a . - da[ or da] deletes everything in a [], while di[, di] keeps the boundary - within a tag cit, cat for angle brackets like <p><\p> - same thing can be used on y: yaw, yiw; yap, yip, yas, yis, ya], yi]
  • Terminology

    • ^f means C-f
    • # is to find the last single words, similar to viw, 8

Basic Concepts

  • Registers: storage locations for yanking
    • use :reg, you can see what's in the register
      • :reg z is to see the z register
    • "vy is to yank a line into register v
    • There are numbered registers 1,2,3.. and registers with chars.
      • "add means to store the line into reg a
      • "Add means to append to a register
      • black hole register: _
      • "" stores the most recently deleted regs
      • "0p means to put from the 0 register, which is the most recent.
    • eol stands for end of line

Visual Mode

  • . means current line
  • Save a block in visual mode:
     - select using v
     - enter :w FiLENAME #u will see <,>yank, that just means "block"
  • v, then do 3j to select 3 lines down
  • Execute normal mode command :
     : <,>,norm i# #Best way to insert comment #, Better than insert block, since it's faster
  • you can do these operations on the visual mode!
    • U is for uppercase, u is for lower case, ~ switch cases
    • c for change, like select and delete!
    • J for join: join all selected text into one
    • gv is to reselect the last selection!!
  • Tricks
    • o to go to the other end of the selection, so you can add stuff to the selection
      • In visual block mode, O is to go to the same end of the line
      • so you can use this to add lines to selection!!
    • a is to select the whole paragraph.
  • Stuff you can do with block visual mode
    • I + <Esc> inserts at the beginning of line
    • A+<Esc> inserts at the end of selection
    • $ + A + <Esc> inserts at the end of every line (not working for line mode, so substitute is developed)
    • c change selection to.

Basic Operations

Good cheatsheet: try to practice!!

  • x for cutting char

  • Insert

    • A is for append at the end of the line, a appends at the end of a char
    • I is to insert at the beginning of line
  • Delete d, gets stored in the "bin register":

    • dw: delete word, at the beginning, including the space
    • d$: delete everything from the cursor till the end, $ is regex
    • de: delete will the end of word, not including space
    • db: delete until the beginning of the word
    • 3dx: delete 3 chars, 3 dw, delete 3 words
      • 3dd is to delete 3 lines. 3D is to delete 3 lines from the current cursor. it means do dd 3 times
      • ** Hold down x will delete like backspace!!**
    • di" delete inside quotes.
    • D delete from the cursor to the end of the line
    • df<space> is to delete the whole word
    • dt char delete everything up to char
  • undo

    • u is to undo a single thing
    • U is to undo everything on that line
  • put & yank

    • y (copy) is yank
      • "word." is actually two words, . is a separate word.
      • you can do y2w to yank two lines
      • cut is saved onto a "register", like a clipboard.
    • P is put
    • -e means edit, that's the edit mode.
    • ge, previous word
    • Note that . cannot repeat previous navigation motions
  • replace (mode)

    • r: replace a single character, R is to replace multiple char, (also the replace mode)
    • s: delete the current char and insert
  • change, delete and get into the insertion mode, c

    • ce: change everthing from this char, to the end of the word
    • c$, c3w ...
    - **"in", super cool**
    	```
    	yis # yank in sentence, here sentence from one . or new line, to the next
    	vip	# visual select in paragraph
    	vis
    	```
    
    
  • Cool tricks

    • cw: In insert mode, delete the current word and insert

      • cc, deletes a whole line of text
      • C, deletes the second half of the line
    • ~ switches cases!

      • gw, g$ ... g means group, so you can switch cases here.
      • GUW ... IS TO USE UPPER CASE
      • GUU is to make the entire line uppercase
      • guu is to make everything lowercase
    • J means join lines.

    • execute external bash commands in vim**

      • :!COMMANDS : means type in a command, ! means an external command. - :r! is to redirect the output of a bash command
    • exchange chars: xc

    • Insert 80 * in a row: 80I *

      • 80* in a column: 80O *
    • save as

      • :w FILENAME
    • "Read/Retrieve": -r

      •   1. -r FILE_NAME #paste everything in FILE_NAME to the cursor position
          2. -r !ls       # pase everything from the external command over here, GREAT FOR REPORT!!
    1. In File Navigation
    ]] (like >>, next), [[ (like going back)goes to the beginning of the next {} (with the outmost indentation)
    [], like go back to the previous, then come the end. 
    ][, like go down to the next {}, then come back to the current's end
    
    1. gf: go to file under cursor
  • Indent and unindent:

    shift . # do this twice
    shift , # do this twice  
    get into visual mode, select lines, #indent a block of code
    shift . 
    
    gg
    =G  # proper indentation. BUT THERE MIGHT BE THINGS IT LEAVES OUT!!
    • indent
      • i + delim + > pushes everything within the delim >
      • Alignment -left [WIDTH] this align your selected lines to the left, and indent [Width] chars. Default is 80 chars -center [Width] -right[WIDTH]
  • Appearance

    • set ruler/noruler: you can see the line numbers.
    • z after search is to change pos

Low Level

  • <C-W>x = <C_W><C-x>
  • <C-W><C-V> = :vs; <C_W><C-S> = :s
  • file ending with rc means "run command"

Advanced

  • Cursor navigation:

    • use ctrl-g can see the current line number if you don't see it
      edit /etc/vimrc
      Changed set nocompatible ---> set compatible
    • jumps ctrl-o, ctrl-I
    • going down the end of a line: $, j
    • parenthese matching, once u r on a parenthese, hit %, you find the other matching parenthese.
    • gg is ceiling, G is ground (bottom of file)
    • File Scroll down: C-F, C_B for full pages, C-D, C-U for half page up and down
    • H is head, M is the middle part, L is the lower part of the page.
    • ^ means jumping to the first char of the line.
      • marks:
        • ma, mb is to set marks. Then you can go to the line with marker: v'a
      • { and } is to jump to the last paragraph, {d} will cut the line above the paragraph and the bottom.
      • '[ and '] will go to the first & last line of pasted text.
      • gJ is to join without space
  • Substitute:

    • :s/old/new/g replace in the same line, globally, else, only the first occurence will be subed
    • :a,bs/foo/bar/g from line a to line b:
    • :%s/old/new/g sub in the whole file
      • :%s/old/new/gc sub in the whole file and prompts the user.
  • Search:

    • / for forward search, / for backward search
    • Vanilla version :START_LINE, END_LINE s///gci...
      • % means all lines
      • . means the current line, $ last line
      • You can also do pattern searching, from line the START_WORD, to line with END_WORD :/START_WORD/./END_WORD/s///gcl
    • when you search for special chars like *, you need \
    • case insensive:
      • /\c something
      • set ic #ic means ignore case
    • set
      • :set hls is #high light search, incremental search
      • :set nohls nois #cancel high light search, incremental search
    • f,t, (search for a char in the same line); F,T (searchf for previous char)
      • ; go to the next char
      • t is to stop at the char before
    • (shift 8) is to find all occurences of the word the current cursor points to. Then you can hit h.
      • :nohl means no highlight, will turn back on next time.
    • exact_match /\<exact_match\>
  • File navigation

    1. go back to previous file: ctrl ^

    2. with local .vimrc: move cursor to a file name, then type gf.

    3. if you want to switch window, C-W W; quit the window is just :q

      • :vs #vertical split. :vsplit
      • C-W-P previous window
      • C-W-C Close the window
      • C-W-Direction hjkl, arrows, switch windows
      • C-W-O is to close all other windows?
      • vertical window -> horizontal window: ctrl-w shift-h
      • horizontal window -> vertical window: ctrl-w shitf-k
      • neutral sub window size: ctrl-w-=
      • C-W | is to maximize window size
    4. Adjust window size:

      • C-W-= All windows with same size
      • C-W-o To maximize a window
  • Macros: keystrokes you record: good for a specific repeating task!

    • q + REG_CHAR, do stuff, , q to stop recording.
      • Make sure your cursor starts at the same place.
      • first go to the beginning of the line, then do your stuff, finally, go to the end of the line
    • use macro:
      • @ REG_CHAR to play back
      • @@ means the most current macro, but first, you need to use one
      • :START_LINE, END_LINE normal @REG
    • save macros:
      • .viminfo, stores history and non-empty regs
      • in .vimrc:
        • record your Macros in register a
        • let @a = ' ' inside '', just copy your reg content by "ap
          • If you have ' in your macro, use let @char = "... "
      • how to save a macro: qq, then go to vimrc, do "qp

Special CHar

  • find the corresponding character: insert mode, then hit ctrl-v, and type in the char
  • You can't type ^[ as , these are two different chars. You have to use ctrl-v to do that

Buffer

  • Basic flow for buffer and windows
       vim * 
       :ls   # see files in the current buffer
       :b ANOTHER_FILE 
       :wa   #save all files, short for :wall
       :qa!	" quit everthing
       :b# # you are go to the last open file
       :b1 # the 1st item on the buffer. 
       :ls! #you can see hidden files as well
       :bufdo set nu "bufdo is to execute a command on every buffer
  • By default, files created in buffer is not saved onto the disk yet. You have to save it.
    • 3 states: active, and loaded into memory; loaded into memory, not loaded into memory nor being active
      • hidden buffer is fully loaded into the memory, marked withh, it's just not in view.
      • # means previously accessed buffer
      • with set hidden, When you switch away from a buffer and leave, you will be asked to save.
      • :ls! will list ones marked with u, those are unlisted
      • + means modified, but not saved.
    • Basic switching
      • :bn " next buffer
      • :- Windows
      • :bf " b first
      • :bl "b last
      • :b tab will cycle thru the buffers
      • :bp "previous Buffer
    • Basic Deletions
      • :1,3bd " delete 1,3 buffers
      • :%bd " delete all buffers
      • :bd 1 3delete buffer 1, 3
    • Explore
      • :E is to Explore, like nerdtree
      • :bd is to delete the explore buffer and go back

Windows

  • Basic movements
	```:vs.```  #see all files in the split 
	```:sp```  see fills in horizontal split
	C-W-V #in normal command, create a vertically split window
	C_W-C - close the open window 
  • clipboard
    • make sure you have vim-gtk and vim-gnome

Auto-complete

- rn we have installed [clang auto-complete](https://github.com/xavierd/clang_complete)
	ctrl-p / ctrl-n	
- Problems
    - You need C++17, [see here](https://stackoverflow.com/questions/65284572/your-c-compiler-does-not-fully-support-c17)
    - if ymcd server is down, [try this](https://vi.stackexchange.com/questions/26435/the-ycmd-server-shut-down-with-vim-8-1)
    - But you may need vim 8.1+, [see here](https://ubuntuhandbook.org/index.php/2019/12/install-vim-8-2-ubuntu-18-04-16-04-19-10/) 
- file path completion
    you should do ctrl+x + ctrl+f, however we have configured in ~/.vimrc, so you can ctrl-p
- you complete me.
    a. you need to copy .vimrc to every root directory of a project
    b. I downloaded youcompleteme at ~/.vim/bundle
    c. I modified ~/.vimrc for you complete me.
    d. I added .ycm_extra_conf.py in  ~/.vim/bundle/YouCompleteMe  

========================================================================

Plugins

========================================================================

  1. update plugins
    • :source%
    • PluginClean and PlugClean
⚠️ **GitHub.com Fallback** ⚠️