Merikanto

一簫一劍平生意,負盡狂名十五年

Introduction to Vim

In today’s post, we will review some basic operations in Vim.



Basics

Moving Around: h, j, k, l

  • To start: gg
  • To end: G
  • To start of line: 0
  • To end of line: $
  • To previous location: Ctrl + o

Number + Char:

  • 5j: Down 5 lines
  • 6dd: Delete 6 lines
  • 7G: Jump to line 7

Other:

  • Quit: Shift + zz

  • Repeat Same Command: .

  • Change cases (upper / lower): -

  • Quick switch with the line below: ddp

  • Tab: >>, and back: <<



Common Options


Delete

  • x: Del the char

  • dw & de: Del words

  • dgg: Del till start of file

  • D: Del till end of line


Undo

  • u: Undo

  • Ctrl + r: Undo undo


Cut, Copy & Paste

Cut:

  • dd: Cut

Copy:

  • y: Copy
  • yy: Whole line
  • Other usage are the same with Delete.

Paste:

  • p: After the cursor

  • P: Before the cursor


  • /<STRING> & ?<STRING>

  • n: Next result

  • N: Previous one


Find & Replace

Format: : {range} s/ {target} / {replace} / {sign}


:%s/hello/world/g

  • %: Range is entire file (Without %: Only current line)
  • hello: Found string
  • world: Replace to this word
  • g: Only replace first match of each line
  • Other choices of {sign}: Ignore the cases (i), Confirm at each replacement (gc)

:5,12s/hello/world: Between line 5 - 12


:.,+2s/hello/world:

  • .: Current line
  • +2: 2 lines after

:'<,'>s/hello/world: In Visual mode, :'<,'> is auto-complete in the selected area



Additional Options


Edit Multiple Files

Two Files: vim file1 file2

  • :n: Switch to file 2 (changes unsaved)

  • :N: Switch to file 1 (changes unsaved)


Multiple Files:

  • Open a 3rd file: :e file3

  • :e! file4: Abandon file3 (unsaved), open a new file

  • Back to previous: :e#

  • List the files: :ls

  • Go to file 1: b file1

  • Change filename: :f <NEW NAME>


Open Multiple Windows

  • Open a new window: :new or Ctrl + w

  • New horizontal window: :sp file1

  • New vertical window: :vsp file2

  • Move among windows: Ctrl + w h / j / k / l

  • Move windows around: Ctrl + w H / J / K / L

  • Reduce / Increase window’s height: Ctrl + w - / +


Command-Line Mode

Check vim’s settings (:scriptname). Create .vimrc under home directory.


  • :set nu: Line numbers

  • :set tabstop=4: Set to 4 (Default is 8)

  • :set autoindent: Indent automatically

  • :ce: Center the line

  • :set readonly: Read-only

  • :set encoding=utf-8: UFT-8 coding

  • :set backup: Backup file

  • :ver: Show version


Other

  • Visual mode: v, highlighting texts

  • Select mode: gvim

    • Start: :set selectmode+=mouse
  • Replace mode: R

  • Encrypt file: vim -x <FILE>

  • Help: F1