Module 1 · Lesson 13 of 103

Vim modes and editing

Use Vim's modes, motions, operators and search-and-replace to navigate, edit and substitute text without the mouse.

  • Beginner to advanced
  • 7 min read
  • 11 min lab
What you will need

Ubuntu 24.04 (WSL2, VM or container); a Raspberry Pi or any SSH host for the log-following lab

Your place in the module
By the end you can 3 objectives
  • Switch among Vim's normal, insert, command-line and visual modes, and save or quit with :w, :q, :wq and :q!.
  • Move with motions (h/j/k/l, w/b, 0/$/^, gg/G) and edit with operators, counts and the dot command.
  • Run :s and :%s to search for and substitute text across a file, and confirm each replacement with /c.
Video coming soonVim modes and editing
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Paging and counting text
  • Match the viewer to the question: cat for a whole short file, less to page and search, head and tail for a slice, wc to count.
  • less scrolls with space and b, searches with /, jumps with g and G, numbers lines with -N, and zless reads compressed files.
  • tail -f follows a file, tail -F reopens it after log rotation, and less +F combines following with a pager.
01

Vim modes: the mental model

4 min read

You can now view and count text with less, head, tail, nl and wc. This lesson answers how Vim's modes let you navigate, edit and replace text without the mouse.

The single most important fact about Vim is that it is . It opens in normal mode, where every key is a command: typing letters moves the cursor or triggers actions, it does not insert text. That is why a first Vim session feels broken: you type and letters jump around instead of appearing.

There are four modes. Normal mode is the default and the base you always return to. Insert mode is where typing inserts text; enter it with i (insert before the cursor), a (append after the cursor), or o (open a new line below). Command-line mode is where you run colon commands; enter it by pressing : in normal mode. Visual mode, entered with v, V or Ctrl+v, selects text to act on, and it gets its own section later. Press Esc from any of them to return to normal mode.

Try the mode switches below:

Vim opens in Normal mode. i, a or o enter Insert; : enters Command-line; v, V or Ctrl+v enter Visual; and Esc returns to Normal from any of the other three modes.

  • states: [{"id": "normal", "label": "Normal"}, {"id": "insert", "label": "Insert"}, {"id": "command", "label": "Command-line"}, {"id": "visual", "label": "Visual"}]
  • transitions: [{"from": "normal", "to": "insert", "event": "i"}, {"from": "normal", "to": "insert", "event": "a"}, {"from": "normal", "to": "insert", "event": "o"}, {"from": "normal", "to": "command", "event": ":"}, {"from": "normal", "to": "visual", "event": "v"}, {"from": "normal", "to": "visual", "event": "V"}, {"from": "normal", "to": "visual", "event": "Ctrl+v"}, {"from": "insert", "to": "normal", "event": "Esc"}, {"from": "command", "to": "normal", "event": "Esc"}, {"from": "visual", "to": "normal", "event": "Esc"}]

Saving and quitting happen from command-line mode. :w writes the buffer to the file, :q quits, :wq writes and quits, and :q! quits and discards any unsaved changes. The ! in :q! means force it, and it is the escape hatch when you have made a mess and want out without saving.

bash
vim notes.txt
# i to insert, type some text, Esc to normal mode, :wq to save and quit

If Vim is not available, or you just want a gentle editor, nano is the fallback. It is not modal: you type directly, and the commands are shown at the bottom as Ctrl combinations, Ctrl+o to write, Ctrl+x to exit, Ctrl+w to search. Minimal and embedded images often ship only a small vi (BusyBox's vi applet) or nano rather than full Vim, so knowing nano and basic vi keys covers every board you will meet. To build muscle memory for Vim itself, run the built-in interactive tutorial:

bash
vimtutor
Going deeperWhy Vim sees each key the moment you press it

The terminal normally operates in canonical mode: the terminal driver buffers your input line by line and does not hand it to a program until you press Enter. That is why the shell echoes what you type and lets you backspace before you commit. Vim turns canonical mode off and switches the terminal into raw, non-canonical mode via the termios settings, so every keystroke is delivered to Vim immediately, with no Enter and no line buffering. Vim then paints the whole screen itself, moving the cursor and redrawing text in response to each key. It restores the terminal's original settings when it exits, which is why a crashed editor can leave the terminal in a strange state and why reset exists. This single design choice, seeing each key as it is pressed, is what makes modal editing fast.

Stuck in Vim

If keys do strange things, you are in normal mode. Press i to type, Esc to go back, and :q! to quit without saving. If you are stuck in less or a man page instead, press q.

Vim modesNormalInsertCommand-lineVisualTransitionsi, a, oNormalInsertEscInsertNormal:NormalCommand-lineEscCommand-lineNormalv, V, Ctrl+vNormalVisualEscVisualNormalNormalInsertCommand-lineVisualTransitionsi, a, oNormalInsertEscInsertNormal:NormalCommand-lineEscCommand-lineNormalv, V, Ctrl+vNormalVisualEscVisualNormal
Vim's mode state machine: normal as the hub, with i, a and o entering insert, colon entering command-line, v entering visual, and Esc returning to normal from each.
02

Vim navigation and editing

3 min read

Movement uses the home-row keys so your hands never leave the keyboard: h left, j down, k up, l right. Word-wise, w moves to the start of the next word and b back to the previous. On the current line, 0 goes to the first character, ^ to the first non-blank character, and $ to the end. Whole-buffer, gg goes to the first line, G to the last, Ctrl+u scrolls up half a screen, and Ctrl+d down half a screen. These are the s.

Editing commands are s. The core set: x deletes the character under the cursor, dd deletes a line, yy yanks (copies) a line, p puts (pastes) after the cursor, u undoes, Ctrl+r redoes, r replaces one character, cw changes the rest of the current word, and . repeats the last change. The dot command is the highest-value key in the editor: make one edit, move somewhere, press . to do it again.

The power is composition. An operator takes a motion and acts on everything it covers: dw deletes a word, d$ deletes to the end of the line, d2w deletes two words, 3dd deletes three lines. Doubling the operator acts on the whole line (dd, yy, cc). Counts combine the same way: 5j moves down five lines, 2dw deletes two words, 3yy yanks three lines.

bash
# in normal mode, on the line "the quick brown fox"
dw        # delete the word under the cursor
yyp       # yank the line and paste a copy below it
c$        # delete to end of line and enter insert mode
3dd       # delete three lines
.         # repeat the last change
Going deeperText objects: acting on things, not distances

Beyond motions, Vim has text objects, which describe a thing to act on rather than a distance to travel. diw deletes inside a word, ci" changes inside a pair of double quotes, da( deletes a parenthesised group including the parentheses, and cit changes inside an HTML tag. The pattern is operator plus i (inside) or a (around) plus an object. Because the object is defined by the surrounding text, not by where the cursor happens to be, these work identically from anywhere inside the region, which is why they are so reliable for editing code and config values.

Vim motionsh / j / k /lleft / down / up/ rightw / bnext / previousword0 / $ / ^start / end /non-blankgg / Gfirst / lastlineCtrl+u /Ctrl+dup / down halfscreenmotions combine with operators andcounts
The home-row motions h/j/k/l, the word motions w/b, the line motions 0/$/^, the buffer motions gg/G and the half-screen scrolls Ctrl+u/Ctrl+d.
03

Search and replace in Vim

3 min read

Search from normal mode with /pattern then Enter; Vim jumps to the first match, and n moves to the next while N moves to the previous. ?pattern searches backward. Search wraps around the end of the file, and the pattern is a regular expression, so . matches any character, * means zero or more of the previous thing, and special characters such as .*[]^$ must be escaped with a backslash to match literally. This is the same regex engine you will meet again in the grep and sed session.

Try the pattern below:

The dot matches any single character, so c.t matches cat, cot, cut and even c.t (the dot matches the literal dot), but not ct, which has no character between c and t. In Vim, * means zero or more of the previous character, and a special character such as . must be escaped with a backslash to match literally.

Substitution runs from command-line mode and has the shape :s/old/new/. By itself it replaces the first old on the current line. Add g to replace every occurrence on the line, prefix % to run it on every line of the file, and add c to confirm each change one at a time. The range can be narrowed to specific lines with :n,ms/old/new/g, which substitutes only between lines n and m.

bash
:s/old/new/          # first match, current line
:s/old/new/g         # every match, current line
:%s/old/new/g        # every match, every line
:%s/old/new/gc       # every match, confirm each
:10,20s/old/new/g    # only lines 10 through 20

Because / is the separator, a pattern or replacement containing a slash needs it escaped, or you can use any other character as the separator: :%s#/usr/bin#/usr/local/bin#g reads better than escaping. The g flag is the one beginners most often forget; leaving it off changes only the first match on each line, which is a classic source of a half-done edit.

Anatomy of :%s/old/new/g:command-line%every linessubstituteoldmatchnewreplacementgevery match:command-line%every linessubstituteoldmatchnewreplacementgevery match
The anatomy of :%s/old/new/g: colon enters command-line mode, % selects every line, s means substitute, old is the match, new the replacement, and g means every match per line.
Vim's :%s replaces text across the file
learner@embeddex:~/lab$ # the line has cat twice
learner@embeddex:~/lab$ cat pets.txt
the cat sat on the cat mat
learner@embeddex:~/lab$ # Vim's :%s without g changes only the first match on the line
learner@embeddex:~/lab$ ex -s -c '%s/cat/dog/' -c 'wq' pets.txt
learner@embeddex:~/lab$ # one cat survived: the classic half-done edit
learner@embeddex:~/lab$ cat pets.txt
the dog sat on the cat mat
learner@embeddex:~/lab$ # add g to replace every match
learner@embeddex:~/lab$ ex -s -c '%s/cat/dog/g' -c 'wq' pets.txt
learner@embeddex:~/lab$ # now both cats are dogs
learner@embeddex:~/lab$ cat pets.txt
the dog sat on the dog mat

Key takeaways

  • Vim is modal: it opens in normal mode, i/a/o enter insert mode, : enters command-line mode, and Esc returns to normal.
  • Vim's power is grammar: an operator like d or y combines with a count and a motion, and . repeats the last change.
  • :%s/old/new/g replaces every match on every line; add /c to confirm each one.
Reflect
  1. Explain to a colleague, in two sentences: switch among Vim's normal, insert, command-line and visual modes, and save or quit with :w, :q, :wq and :q!.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close