Vi and Vim


vi is the first full-screen text editor written for Unix.

  • vim, or vi improved, is an updated version
    • is upward compatible with vi
    • all the following vi info also applies to vim
  • excels at editing program files

Modes

  • 3 modes
    • Command Mode
      • accepts commands, usually entered as single letters
      • aka normal mode
      • e.g.,
        • i enters insert mode
        • o opens a new line below current one
    • Ex Mode
      • used to manipulate files, save files, and run outside programs
      • aka colon commands
      • enter ex mode by typing a colon :
        • then type ex mode command
        • after command, returns automatically to command mode
    • Insert Mode
      • used to insert text
      • aka edit mode or entry mode
      • enter insert mode by typing i
      • Esc exits insert mode back to command mode

Check vi/vim Editor Package

A Linux distro may not have the full vi package installed. To check:

  1. type vi to get package location
  2. readlink -f {location} to determine if the package is linked to another package
  • may get: /usr/bin/vim.tiny or /usr/bin/vim if its vim
  1. check the package that provided the program: sudo dpkg -S /usr/bin/vim

Basic Text Editing

  • vi filename to create and open a file
  • i to enter insert mode
    • --INSERT-- appears at the bottom of the window
  • Esc to exit insert mode
  • : to enter ex mode
  • wq writes the buffer contents to the file and quits
  • some systems display a line of ~ down the left side to indicate the end of the file
  • loading an existing file shows a status line at the bottom with the name, number of lines, and number of characters
  • use arrow keys to move
  • O opens a new line above current line and enters insert mode
  • o opens a new line below current line and enters insert mode
  • Copy and paste
    • yy to copy (aka yank) a line
      • precede with a number for multiple lines (e.g., 3yy)
      • move to line before where you want to paste
      • p pastes the buffer to the following line
  • dd to delete a line
  • ZZ saves and quits
    • same as :wq
  • ~ changes case of highlighted character
  • u to undo
  • / to forward search for text
  • ? to backward search for text
  • cc to change text of entire line
  • cw to change text of current word
  • G + number moves to a specified line number
  • H brings cursor to home (top of file)
  • L brings cursor to bottom of file
  • replace all occurrences of a string with another
    • :%s/original/replacement/g
    • change % to a starting line number, comma, ending line number
  • :w to save changes
  • :e filepath edits a new file
    • first file must be saved first or forced with :e!
  • :r appends contents of an old file in an existing one
  • :! executes a specified external command
    • e.g., :!ls runs ls
  • :q quits
    • only works if changes have been saved or if forced :q!