📝

Vi/Vim Basic Usage and Commands

Jul 17, 2025

Overview

This lecture covers the basic usage, commands, and shortcuts of the Vi/Vim text editor, focusing on essential navigation, editing, search, and file operations.

Vi Modes

  • Vi has four main modes: Command (normal), Insert, Escape, and Visual mode.
  • Command mode is default; used for navigation and entering commands; press ESC to switch here.
  • Insert mode is for adding/editing text; press 'i' to enter.
  • Escape mode (accessed with ':') is used for actions like save, quit, or themes.
  • Visual mode allows text selection; press 'v' for character-wise, 'Shift+v' for line-wise selection.

Opening and Saving Files

  • Open or create a file by typing vi filename in the terminal.
  • Press 'i' to enter Insert mode and start editing the file.
  • Save and quit by pressing ESC, typing :wq, then pressing Enter.
  • To quit without saving, press ESC, type :q!, and hit Enter.
  • To force save and quit even on read-only files, use :wq!.

Useful Vi Shortcuts

Navigation

  • Move cursor to start of line: '0'; to end: '$'; to first non-blank: '^'.
  • To first line: 'gg'; to last line: 'G'; to specific line: '20G' (replace 20 as needed).
  • Screen navigation: first line of screen 'H', middle 'M', bottom 'L'.
  • Full screen forward: 'Ctrl+F'; backward: 'Ctrl+B'.
  • Word navigation: end of word 'e', start of current word 'b', start of next word 'w'.

Editing, Copying, Cutting, and Pasting

  • Delete character: 'x'; delete whole line: 'dd'; delete multiple lines: '4dd'.
  • Select and cut: 'v', select, then 'd'.
  • Select and copy: 'v', select, then 'y'.
  • Paste after cursor: 'p'; before cursor: 'P'.
  • Undo last change: 'u'.

Searching and Replacing

  • Search forward: '/pattern', press Enter; next match: 'n'; previous: '#'.
  • Search backward: '?pattern', press Enter; previous match: 'n'.
  • Replace in current line: :s/old/new/; all in line: :s/old/new/g.
  • Replace in entire file: :%s/old/new/g; confirm each: :%s/old/new/gc.

Miscellaneous Commands

  • Show line numbers: :set number; hide: :set nonumber.
  • Change color scheme: :colorscheme darkblue.
  • Show current line number: :.=.

Key Terms & Definitions

  • Vi (Vim) — A standard Linux/Unix text editor, Vim is Vi Improved.
  • Command Mode — Default vi mode for navigation and running commands.
  • Insert Mode — Mode for entering and editing text.
  • Visual Mode — Mode used for selecting blocks of text.
  • Escape Mode — Mode for executing file actions and commands.
  • :wq — Command to write (save) changes and quit.
  • :q! — Command to quit without saving changes.

Action Items / Next Steps

  • Practice opening, editing, saving, and quitting files in Vi.
  • Memorize and use core navigation and editing shortcuts.
  • Try search and replace commands in a sample text file.