The vi Editor — Modes, Navigation, Yank-Put, Recovery and Search
7.1 Why vi Still Matters in Systems Work
7.1.1 The Console Advantage
Hook — Why learn an editor from the 1970s? Imagine you log into a remote server at 2 a.m. to fix a broken web service. No desktop, no mouse, no app store — just a black terminal over Secure Shell. The service config is wrong by one line. You need to open it, fix it, save, and restart in under a minute. What tool is guaranteed to be there and ready in that black window?
Intuition — The console workbench. Think of the Linux terminal as a single workbench where every tool hangs within arm's reach. The compiler hangs on one hook, the linker on the next, make and git on the next, and vi sits in the centre holding the file you are shaping. A vi editor — a modal, keyboard-driven text editor that runs inside a terminal without a windowing system — lets you stay at that bench. You open a file, edit, write with :w, compile with :!cc %, run, and inspect output without leaving the shell session. A graphical editor forces you to step away from the bench to another room. In systems work, staying at the bench keeps you close to the build chain and keeps feedback loops short.
Where the analogy breaks: a real workbench is physical — you can see every tool. The console hides its power behind memorized keystrokes, so the first days feel like working blindfolded. Muscle memory replaces vision.
Formalize — What "modal, keyboard-driven, terminal-resident" means.
- Modal means the same key does different jobs in different modes (see 7.2). In insert mode
jinserts the letter j; in command modejmoves the cursor down. Mode decides meaning. - Keyboard-driven means every action has a key or key-pair. No menus, no mouse dependency.
yycopies a line,ppastes it,uundoes. - Terminal-resident means vi draws its user interface with terminal character cells, not a graphical toolkit. It works over any Secure Shell connection, inside a
docker execsession, on a headless Raspberry Pi, or on a serial console where no window system exists. The editor needs only stdin/stdout and a terminal capability database.
Why this matters for systems programming: systems code is often built and debugged where it runs — on the target machine. You edit a Makefile, a kernel module source, an /etc/nginx/nginx.conf, or a shell script on the machine that will execute it. Having an editor that is always present on Unix-like systems removes a deployment dependency.
Visual intuition — Picture a two-column diagram. Left column lists the console session: prompt line user@server:~/project\\$ at the bottom, file buffer in the middle showing sample.c text, and a status line :w at the very bottom. Right column shows a graphical desktop with separate windows for editor, terminal, and file manager, connected by arrows that cross window borders. The left picture has one border, one focus, and all arrows stay inside. The right picture has three focuses and context switches. The takeaway: vi collapses the edit-compile-run loop into one visual context.
Scope — When the advantage applies and when it does not.
- Applies: remote administration over Secure Shell, emergency recovery, editing on build servers, inside containers (
docker exec -it app sh), on embedded devices, when you need to edit quickly without installing software. Vi is part of the POSIX base and is installed by default. - Does not replace: long-form writing with live collaboration, heavy graphical debugging with breakpoints and variable watches, or projects where deep language-server features (refactoring across 10,000 files) outweigh console speed. There vi is complementary, not primary.
- Assumption that must hold: you have keyboard fluency. Without memorized commands vi is slower than a menu. The advantage appears only after practice.
Pitfalls — Early traps.
- Mistaking "terminal editor" for "outdated editor." The lack of a mouse is a feature for remote work, not evidence of inferiority.
- Assuming you must choose one editor forever. Many engineers use Visual Studio Code locally and vi remotely. Use the right tool per context.
- Trying to install a graphical editor on a headless server to avoid learning vi. That install may not be allowed, may require X forwarding that adds latency, and still may not help when the network is degraded.
Recap + Bridge. vi earns its place not by having more buttons than a graphical IDE, but by being present, fast, and integrated with the console toolchain — compiler, linker, make, pipes, and version control are one command away. Next we make that power usable: we learn the three modes that make every key do double duty.
Real-world & domain connection — System administrators routinely fix a production outage by Secure Shell into a machine that has only vi installed. Site-reliability engineers edit a Kubernetes manifest with kubectl edit (which opens vi by default) and save to apply. Embedded Linux developers cross-compile on a laptop but edit startup scripts directly on the device over a serial link where no graphical session exists. In all these cases the ability to edit without a windowing system is not convenience but requirement.
7.1.2 How vi Compares with Other Editors
vi is not claimed to be technically superior to every modern editor. Editors such as Emacs share the same console-first philosophy, and Visual Studio Code dominates desktop work for good reason. The lecture's stance is practical: pick the editor whose strengths match the context, and know that vi is the guaranteed fallback on Unix-like systems.
| Dimension | vi / Vim | Emacs | Visual Studio Code |
|---|---|---|---|
| Runs without window system | Yes — pure terminal | Yes — terminal mode with emacs -nw |
No — needs graphical session or remote extension |
| Availability on bare server | Always present | Often present, not guaranteed | Not installed by default |
| Input model | Modal (command vs insert vs command-line) | Modifier-heavy (Ctrl/Meta chords), modeless | Menu + shortcuts + mouse, modeless |
| Startup time | Instant (<100 ms) | Fast but heavier | Seconds, plus window draw |
| Extensibility | Vim script / Lua | Emacs Lisp (a full Lisp machine) | TypeScript extensions, huge marketplace |
| Learning curve — first week | Steep — commands silent until learned | Steep — chord memorization | Gentle — menus guide discovery |
When to pick which: use vi when you are on a remote shell, in a container, or need a zero-install edit. Use Emacs if you live inside its ecosystem and prefer chorded commands. Use Visual Studio Code on a local desktop where graphical debugging, live share, and rich language completions save time. Many developers mix them — Code on the laptop, vi on the server — and that is normal practice.
Professor intuition — Hardcore practitioners and time. The lecture notes that hardcore practitioners swear by vi or Emacs despite Visual Studio Code's dominance, and that the professor's own observation is: the first days with vi feel tedious, you must remember which key works in which mode, and a simple copy-paste takes two specific keystrokes instead of a menu. After repeated use those two keystrokes become faster than reaching for a mouse, and many developers report that after the learning period there is nothing quicker than working in the command line. This was listed as warm, practical advice, not as a claim that beginners should feel instant speed.
Pitfalls — Comparison traps.
- Treating "always present" as "always best." Presence is an availability guarantee, not a feature ranking.
- Counting graphical features as the only measure of productivity. In systems work, latency to edit and proximity to the shell are features too.
- Forcing team members to use one editor. Teams standardize on tools where it helps (build, version control), but editor choice can stay personal as long as file formats agree.
7.1.3 What to Practice and What to Expect in Assessment
Purpose of the drill. The exercise asks you to create a file with a supplied paragraph and then press distinct characters while in command mode, in insert mode, and in command-line mode to see what each key does. The point is to make mode-dependence physical. The same key w inserts the letter w in insert mode, jumps a word forward in command mode, and types the character w as part of a :w command after a colon. Until you feel this shift by trying it, the description stays abstract.
Worked mini-trace — Predict the effect before you press.
- Open
content.txtwithvi content.txt. You start in command mode. - Press
i— nothing inserts, but you are now in insert mode. Typehello— the word hello appears. You are still inserting. - Press
Esc— you return to command mode. Now pressw— the cursor jumps to the next word start; no letter w is inserted. Presswagain — another word jump. - Press
:— a colon appears at the bottom. You are in command-line mode. Now typew— the letter w appears after the colon as part of:w. PressEnter— the buffer writes to disk with message"content.txt" 3 lines, 132 characters. - Press
Esctheniagain — back to insert, andwinserts again.
Count the roles of one key w across three modes: text in insert mode, motion in command mode, file-command letter in command-line mode. Assessment will ask you to follow a chain like this and state the final cursor position or file content.
Exam guidance — Must-know for this section. Practice until you can predict the effect without trial. Questions will give a short key sequence such as i hello Esc w : w Enter and ask what appears on screen or which mode you end in. Know that the colon prompt : at the bottom is the reliable test for command-line mode, and the absence of a colon plus non-inserting keys is the test for command mode. Build a personal reference sheet with one line per key and per mode as you discover them.
Recap + Bridge. vi's value comes from terminal residency and zero-install availability; the cost is a modal interface that must be practiced. The comparison is not about winning but about choosing the right editor per context. With motivation clear, we now open the core mechanic: the three modes that explain every later command.
7.2 The Three Modes and Basic File Handling
7.2.1 Edit, Command and Command-Line Modes
Hook — One key, three jobs. Press w on your keyboard. Did you insert the letter w, jump to the next word, or start to write a file? In vi all three are possible, and the answer depends only on which mode you are in. How can one keyboard do three jobs without adding new keys?
Intuition — The keyboard with a switch. Picture a railway switch that routes the same train onto different tracks. In insert mode the switch points to the "type text" track — every key adds characters to the file. In command mode the switch points to the "do command" track — keys are read as movements or edits. In command-line mode the switch points to the "operate on file" track — the colon prompt : at the bottom collects a line-oriented instruction for the whole file. The keys do not change; the switch position does.
Mapping: switch position = current mode; track = interpretation; train = your keystroke; destination = effect on buffer, cursor, or file. The analogy breaks when you forget which track you set — vi gives only subtle feedback (the colon, or the absence of it), so you must track the switch yourself.
Formalize — Three modes defined.
- Insert mode (also called edit mode) — typed characters are inserted into the buffer as text at the cursor. Backspace deletes within the insert that started the session; you cannot backspace past where that insert began. Prompt feedback is minimal — the text simply appears.
- Command mode — keys are interpreted as navigation or edit commands, not text.
h j k lmove,w bjump by word,yyyanks a line,pputs,uundoes,:enters command-line mode. You normally start here when you open a file withvi filename. - Command-line mode — entered by typing
:while in command mode. A colon appears at the bottom and you type a line-oriented command there.:pluswwrites the buffer to disk,:wqwrites and quits,:qattempts to quit (warns if unsaved changes remain),:q!abandons changes,N1,N2yyanks a range,:set nushows line numbers,:!cmdruns a shell command without leaving vi.
Symbol note: we use Esc for the Escape key, Enter for Return, and : to mean the colon prompt itself. When we write :w we mean colon then w then Enter.
Visual intuition — Draw a triangle with three nodes: Command at the top, Insert at lower left, Command-line at lower right. Arrows: i a o from Command to Insert; Esc back to Command; : from Command to Command-line; Enter or Esc back to Command. No direct arrow connects Insert to Command-line — you must pass through Command. The takeaway: Command mode is the hub; every path returns there.
Scope — When each mode applies.
- Insert mode applies only when you are adding or correcting text character by character. Stay there briefly; return to Command mode to navigate.
- Command mode applies to all cursor motion and structural edits (yank, delete, put, change). Never try to type text there — it will be read as commands and may delete material.
- Command-line mode applies to file-level and ex-editor actions: save, quit, range yank, option setting, shell escape. Think of the colon as a tiny shell that operates on the current file.
If any assumption fails — you are in the wrong mode — the symptom is diagnostic: text appears when you expected motion means you are still in Insert; a colon does not appear means you are not in Command mode.
Pitfalls — Beginners trip here.
- Forgetting to press
Escbefore a command. You pressyyhoping to copy a line, but because you are still in Insert the literal letters yy are inserted instead. - Pressing
:while still in Insert. The colon is inserted as text, not as a prompt. AlwaysEscfirst. - Confusing
:the prompt with:inside text. Real command-line mode shows the colon at the bottom status line, not inside the buffer area. - Typing
:qand being surprised by the warningNo write since last change. That warning is safety, not an error — vi protects you from losing edits. Use:q!only when you mean to abandon them.
Recap + Bridge. A mode decides how a keystroke is read: insert writes text, command moves and edits, colon operates on the file. With definitions crisp, we now walk the paths that move you between them and show how file handling (:w, :wq, :q) lives on the colon track.
7.2.2 How the Modes Interact
State transitions — The hub model.
- Start state: opening with
vi filenamelands you in command mode. - Command → Insert:
iinserts before cursor,aappends after cursor,Iinserts at line start,Aappends at line end,oopens a new line below,Oopens above,ssubstitutes a character,cchanges through a motion,Renters overstrike. All begin an insert that ends withEsc. - Insert → Command:
Esc(one press, sometimes two if you are unsure) moves cursor back one character and returns to command mode. The beep when you pressEscalready in command mode is confirmation. - Command → Command-line:
:moves you to the colon prompt. You remain there until you finish the command. - Command-line → Command:
Enterexecutes the command and returns to command mode;Escabandons the command and returns as well. - No direct Insert → Command-line path: you must
Escto Command first.
Think of Command mode as the hallway: every room connects to the hallway, but rooms do not connect directly to each other.
Worked trace — The same characters in three modes. File content.txt is open. Perform the key sequence i hello Esc : w Enter w and predict state after each key.
iin command mode — switch to insert, no visible insert yet.h e l l o— text hello appears in buffer.Esc— back to command mode, cursor ono.:— colon appears at bottom, now in command-line mode.w— letter w appears after colon as:w, not in buffer.Enter— buffer writes to disk, message"content.txt" 3 lines, X characters, return to command mode.w— now in command mode, cursor jumps to start of next word; no letter is inserted.
Final state: file contains hello plus original content, cursor is one word forward from where it was, and you are in command mode. If at step 7 you had expected a letter w to appear, you were still mentally in insert mode.
Pitfalls — Interaction traps.
- Pressing arbitrary characters to test modes as the exercise requests: in insert they insert, in command they may delete a line or move wildly, after
:they become part of a file command. The drill is meant to feel startling — that surprise teaches mode awareness. - Pressing
Escmultiple times is harmless; pressingEnterat the colon prompt with no command is also harmless (no-op). Use these to reset when lost.
7.2.3 Creating and Opening the Practice Files
What to open and why it matters. The session uses concrete files. One demo opens sample.c with vi sample.c, notes that an empty or unsuitable file is not ideal for the navigation drill, exits, and then opens content.txt with vi content.txt containing a short literary passage. The passage used was:
Woods are lovely, dark and deep, but I have promises to keep. And miles to go before I sleep and miles to go before I sleep.
The wording is pinned because later drills search for specific words and yanking relies on repeated words. You may use any paragraph of two to three lines, but keeping this exact passage reproduces the class results for search (three) and word jumps.
Setup — Recreate the practice file in full.
- At the shell:
cat > content.txtthen type the Woods passage over 2–3 lines, add two blank lines at the bottom for empty-line tests, pressCtrl-Dto save. Or in vi:vi content.txt, pressi, paste/type the passage, pressEsc, type:wEnter. - Verify:
cat content.txtshould show the passage plus blank lines.wc -l content.txtshould report at least 4–5 lines so that ranges like:7,9y(see 7.6) can be tried after adding lines — add extra linesline 4throughline 10if needed. - Open for drills:
vi content.txt— you land in command mode. Keep this terminal open for the entire sequence 7.3 through 7.8 so yank buffers and search history persist.
Sense-check: if vi sample.c opens empty, that is expected — you created no such file yet. Quit with :q and return to content.txt.
Scope — Files and modes for saving.
- Editing happens on a copy in memory (the buffer). Disk changes happen only when you write (
:w,:wq,:x, orZZ). Closing the terminal without writing loses the buffer, except for the recovery copy discussed in 7.7. - Command-line mode also runs shell escapes (
:!ls,:!cc %) without leaving vi — the colon prompt is the gateway to the rest of the toolchain.
Recap + Bridge + Exam note. The three modes explain every key's behaviour: insert writes, command moves and edits, colon operates on the file and transitions all pass through command mode as the hub. For assessment, know the transition keys (i a o Esc : Enter) and the file handlers (:w :wq :q :q!) cold, and be able to predict the result of chaining them. With the bench set up and the modes clear, we move to the first command-mode skill: fast horizontal motion with w and b.
Real-world & domain connection — Opening files this way mirrors daily systems work: you Secure Shell to a host, vi /etc/hosts or vi app.py in the project checkout, and keep one terminal window per task. The fact that vi filename always starts in command mode means scripts can safely invoke vi without risk of unintended inserts before the operator takes control.
7.4 Copy and Paste in Command Mode — Yank and Put
7.4.1 The Core Vocabulary: Yank, Put, Undo
Hook — Why "yank" instead of "copy"? When vi says yank, put, and undo, it is not being quaint. Those words appear on the screen in status messages such as 5 lines yanked and in help text. Knowing the vocabulary means you understand what the editor is telling you after each command.
Intuition — Copy is photographing, put is printing. Think of yanking as photographing text with a single-frame camera called the buffer. The original scene does not move or disappear; the camera's memory card now holds an image of it. Putting (p or P) prints that image at the cursor position. You can print the same image many times without re-photographing, and the next photograph overwrites the previous one. Undo (u) peels off the last print you made.
Where the analogy breaks: a real camera keeps every photo unless you delete it; vi's buffer keeps only the most recent yank or cut, so a second yank before you put discards the first.
Formalize — Commands in the (count)(command)(motion) family. In vi a yank means copy without removal and a put means paste, and synchronization is via an internal buffer (also called the yank buffer or unnamed buffer). Every command below must be in command mode; Esc first if you are in insert or at the colon prompt. After : presses, use Esc or Enter to return.
yy— yank current line. AlsoY. Yanks the whole line including its newline, regardless of cursor column.n yyornYY— yank n lines starting at current line.5yyyanks five lines; message5 lines yankedconfirms.yw— yank word: pressythenw. Yanks from cursor to start of next word (equivalently, to end of current word plus trailing space). Varianty\\$yanks to end of line,y0to line start.p— lowercase put: paste buffered content after current line (for line yank) or after cursor (for word/character yank). Cursor ends on the first character of pasted text for line puts.P— uppercase put: paste before current line (for line yank) or before cursor (for word yank).u— undo last change. Repeateduin classic vi toggles; in Vim it steps back through changes.Ctrl-Rredoes in Vim.
General pattern: vi commands follow (count)(command)(motion). d2w and 2dw both delete two words; similarly 3yy and y3y overlap, but 5yy is the idiomatic count-first form.
Visual intuition — Picture the buffer as a sticky note attached to the editor frame, not to the file. Arrow yy copies the current line up to the sticky note; dotted box buffer: "Woods are lovely..." appears. Arrow p copies from the sticky note down to after the cursor line. Arrow P copies above. Repeated p draws multiple arrows from the same sticky note, showing persistence.
Scope — Buffer rules that govern correctness.
- Any yank or any cut (delete/change) overwrites the same unnamed buffer, so the buffer always holds the most recent material, whether you intended to copy or to delete.
- Put does not empty the buffer; you can press
pmany times and get the same text until a new yank replaces it. - Line yanks versus word yanks create different paste geometry: a line yank always inserts whole lines above/below; a word yank inserts inline at the cursor. Mixing them without noting which you did is a classic source of surprise pastes.
Pitfalls — Yank-put traps to memorize.
- Yanking in insert mode inserts literal
yyorywinstead of copying. AlwaysEscfirst. - Yanking and then yanking again before putting — the first yank is gone. Yank then put before the next yank unless you mean to overwrite.
- Expecting a status message for single-line
yy. Many vi builds are silent for one line; absence of1 line yankeddoes not mean failure — the paste will prove the buffer. - Confusing
pversusP. Lowercasepmeans "put after," uppercasePmeans "put before." The session intentionally demoed both to lock the mnemonic.
7.4.2 Worked Example 1 — Yank a Single Line with yy and p
Setup. content.txt open, command mode, cursor on a line of the Woods passage, e.g. line 1 Woods are lovely, dark and deep, but I have promises to keep.
Steps.
- Press
Esc. Verify you are in command mode — typing should not insert. - Press
ythenyquickly (yy). No visible change. The line including its newline is now in the unnamed buffer. - Keep cursor on same line or move one line down with
j. - Press lowercase
p. The yanked line appears immediately after the current line. File now has a duplicated line: line 1 original, line 2 copy. - Press
pagain. A second duplicate appears after the new current line, so you now have two pasted copies in succession (total three occurrences counting original). - Press
u. The last paste is undone; file returns to having one duplicate.
Resulting file sketch (cursor on line 2 before second p):
1: Woods are lovely, dark and deep, but I have promises to keep. <- original
2: Woods are lovely, dark and deep, but I have promises to keep. <- first p
3: Woods are lovely, dark and deep, but I have promises to keep. <- second p, then u removes this line
Sense-check: Both copy and paste happened without insert mode or colon prompt; buffer persistence explains why p twice gave two copies and u removed one. Status area may not announce single-line yank — paste is the proof.
Exam cue: yy then p is the minimal line-duplicate pattern. Know that p pastes after for line yanks.
7.4.3 Worked Example 2 — Yank Multiple Lines with 5yy
Setup. content.txt with at least 6 lines (add lines line 2 through line 6 if needed). Cursor on line 1, command mode.
Steps.
- Type
5yy— keys5thenytheny. Bottom message shows5 lines yanked. This count message is the confirmation — always check it before you navigate away. - Move cursor toward end, e.g.
Gto last line orja few times. - Press
p. All five lines are inserted after the current line, preserving original order and line breaks. The block appears as lines 1-5 copied in sequence.
Variation — Count verification:
3yyyanks three lines,10yyyanks ten. Message always reports the count so you can verify before pasting.- If you type
5yywhen only 2 lines remain below cursor, vi yanks whatever exists — message will say2 lines yanked. The count is a request bounded by file length.
Sense-check: Pasted block order must match source order. If lines appear reversed, you used a different command.
Exam cue: n yy count is inclusive starting at cursor; 5yy starting at line 1 copies lines 1-5.
7.4.4 Worked Example 3 — Yank a Single Word with yw
Setup. Same file, line Woods are lovely, dark and deep, with cursor on l of lovely in command mode.
Steps.
- Press
ythenw(yw). Fromlthe yank goes to end of the word (throughyand the following space depending on build). Buffer holds only that word fragment, not a full line. - Move cursor to another position:
\\$to end of line, orGto end of file, or to a blank line. - Press
p. The word fragment appears immediately after the cursor. For a word yank, paste is inline, not on a new line. Presspagain — same word pastes a second time, proving buffer persistence at word scale.
Geometry contrast:
- Line yank +
p→ new lines appear. - Word yank +
p→ text appears inside the current line at cursor.
Sense-check: If after yw the paste inserts a whole line, you accidentally typed yy or Y instead of yw. The granularity of the yank decides the geometry of the put.
Exam cue: yw is "yank word" from cursor to next word start; p after a word yank is character-wise, not line-wise.
7.4.5 Placement with p versus P
After versus before — The placement rule.
- Lowercase
p— put after current line (for line yank) or after cursor (for word yank). Demo showed yanking a line and usingpto create lines below the cursor. - Uppercase
P— put before current line (for line yank) or before cursor (for word yank). If cursor is on line 3 and you pressPafter a line yank, the new line becomes the new line 3 and the old line 3 shifts to line 4.
Memory aid: lowercase p = "put after (push down)"; uppercase P = "put before (push up)". Same buffer, no re-yank needed to switch.
Quick table:
| Yank type | p result |
P result |
|---|---|---|
Line (yy, 5yy) |
New lines inserted after current line | New lines inserted before current line |
Word (yw) |
Word inserted after cursor | Word inserted before cursor |
Placement trace — See the difference. File lines: line 1 alpha, line 2 bravo, line 3 charlie. Cursor on line 2 bravo, buffer holds line X (single line yank).
- Press
p— file becomesalpha, bravo, X, charlie(X after bravo). - Undo
uback to original, then pressP— file becomesalpha, X, bravo, charlie(X before bravo).
For word yank yw on lovely with cursor after dark: p gives darklovely, P gives lovelydark adjacent at cursor halves. Same letters, different side.
Sense-check: If p and P give the same visual result, check whether you yanked a line or a word — for empty lines around cursor the distinction can look similar.
Pitfalls — Placement confusions.
- Expecting
Pto paste above the file when cursor is on line 1 — it does, creating a new line 1. Valid and testable. - Mixing
pwith:put— both use the same buffer (see 7.6), but placement defaults differ::putwithout address puts after current line likep;:7putputs after line 7.
Recap + Bridge. In command mode yy copies the current line, n yy copies n lines, yw copies a word, p puts after, P puts before, and u undoes — all without insert or colon; the buffer holds the last yank and survives repeated puts until overwritten. With line-level copy solid, we now ask what that buffer actually is and why its overwrite rule explains most paste surprises.
Real-world & domain connection — Editing configuration or source on a server, you duplicate a block, tweak one copy, and keep the original as fallback: yy p then edit the second copy. For a five-line function header you 5yy p to clone it elsewhere and adjust. The speed comes from doing this entirely with keystrokes while staying over a Secure Shell link without a graphical clipboard.
7.5 The Yank Buffer — What Happens in Memory
7.5.1 Buffer as Temporary Memory
Hook — Where does the copied text wait? You pressed yy and nothing visibly happened. You pressed p a minute later in a different part of the file and the line reappeared. What held the text during that minute, and why was it not written to a file on disk?
Intuition — The single sticky note on the editor's desk. Picture vi's workspace as a desk. The file buffer is the open document on the desk. Beside it sits a single sticky note — the yank buffer (also called the unnamed buffer or temporary memory). Every yank or cut copies text onto that sticky note, covering whatever was there before. Put (p/P) copies from the sticky note onto the document. The sticky note never leaves the desk (it is not a file on disk), it is not visible unless you paste, and it survives across cursor moves and screen scrolls until the next yank or cut replaces it.
Where the analogy breaks: a real desk could hold many sticky notes; vi's unnamed buffer holds exactly one item at a time. (Vim adds numbered and named registers, but the core unnamed buffer — the one yy/p use by default — is still single-slot.)
Formalize — Buffer mechanics.
- Definition: a buffer here is a dedicated memory area inside the editor session that holds the most recent yanked or cut text. It lives in RAM associated with the vi process, not as a visible file.
- What writes the buffer: any yank (
yy,n yy,yw,y\\$, colon:...y) and any delete or change that removes text (dd,dw,x,c, etc.) overwrites the same unnamed buffer path. The buffer always reflects the last operation that moved text into it. - What reads the buffer:
p,P, and:putread the current contents and insert at the cursor using placement rules from 7.4.5. The read does not empty the buffer — you canprepeatedly and get the same text each time. - Visibility: the buffer has no on-disk file. Its content is confirmed two ways: the message
n lines yankedafter a count yank, and the result of a paste. Absence of a message foryyalone does not indicate empty buffer.
Visual intuition — Draw a three-box data flow: source range in file → arrow labeled yank → sticky note labeled buffer "3 lines yanked" → arrow labeled put → insertion point at cursor. Show a second yank arrow from a different source overwriting the sticky note with new content. The takeaway: every yank mutates the buffer; puts are pure reads.
Scope — What the buffer is and is not.
- Applies for the lifetime of the vi process. Closing vi discards the buffer. Opening a new vi instance starts with an empty buffer.
- Applies as a single slot by default. If you need multiple snippets preserved, you must yank and paste each in turn; yanking several items in sequence before pasting keeps only the last.
- Does not interact with the system clipboard. A Windows
Ctrl-Ccopy goes to the operating system's clipboard, not to vi's buffer — sopafter a Windows copy does not paste that text (see 7.8.7). - In Vim, numbered registers
"1–"9and named registers"a–"zextend this model, but the unnamed default used in this lecture behaves as a single overwriting slot.
Pitfalls — Why pastes surprise.
- Yanking a line with
yythen yanking a word withyw— the word replaces the line in the buffer. Pastes now give a word, not the line you thought you saved. - Yanking
5yythen immediatelyyyon another line — the five-line block is gone; buffer now holds one line. The lecture stresses the5 lines yankedmessage exactly to make you verify buffer content before you move away. - Deleting a line with
ddand then expecting the earlier yank to remain.ddis a cut and overwrites the buffer just like a yank — a classic overwrite surprise.
7.5.2 Overwrite Behavior
Overwrite rule in full detail. The buffer follows a last-write-wins policy with no history in the default slot. Sequence matters:
yyon line A — buffer = line A.ywon word B — buffer = word B; line A is no longer available viapin that slot.5yyon lines C — buffer = five-line block C; word B is gone.p p p— three copies of block C appear; buffer still = block C after each put.ddon line D — buffer = line D (cut, not yank, but same path).
Practical rule: yank then put before the next yank, unless you intend to replace. If you need two distinct snippets at two destinations, interleave: yank snippet 1 → go to dest 1 → put → go back → yank snippet 2 → go to dest 2 → put. Do not batch all yanks then all puts.
Message as confirmation: after 5yy vi shows 5 lines yanked; after :7,9y it shows 3 lines yanked. Treat these as readouts of buffer size. For single-line yy absence of a message does not mean empty — verify by pasting into an undoable buffer.
Trace — Overwrite matters. Start with buffer empty, file lines L1 L2 L3 L4 L5 plus blank, cursor on L1.
5yy— buffer =L1-L5, message5 lines yanked.- Move to
L10withG,p— blockL1-L5appears afterL10. File now has 15 lines. - Without moving,
yyon current line (L1copy) — buffer now = single lineL1, five-line block gone. p— inserts only that single line, not the five-line block.
If you needed both, you lost data. Undo u only undoes the put, not the buffer overwrite — the five-line block is still gone. You would need to re-yank it.
Second trace — Delete overwrites:
yyonL2— buffer =L2.ddonL3— buffer =L3(cut),L2gone. PresspexpectingL2and you getL3.
Sense-check: Every yank and every delete is a write to the same sticky note.
Recap + Bridge. The yank buffer is a single invisible memory slot that holds the most recent yanked or cut text, overwritten on every new yank or cut, readable many times via p/P without emptying. Knowing this overwrite rule turns confused pastes into predictable behaviour. Next we use the same buffer from a different entry point: the colon prompt, where line numbers replace cursor proximity.
Real-world & domain connection — When editing a large config file over a slow Secure Shell link, you yank a 20-line server { } block with :10,30y while your cursor stays at the insertion point near line 100. The buffer's ability to hold an off-screen range without moving the cursor is why the colon-range yank exists. But the overwrite rule also explains outages: an operator yanks the good block, then accidentally dd deletes a stray line — the good block is gone from the buffer and the paste gives the wrong text. Verify the n lines yanked message and paste immediately to build good habit.
7.6 Copy and Paste in Command-Line Mode with Line Ranges
7.6.1 The Colon Syntax with Line Numbers
Hook — Copy what you can name, not just what you can see. In command mode you copy by moving the cursor to the text and pressing yy. What if the block you need is on line 7 but your cursor is on line 100, and you know the line numbers but do not want to scroll there?
Intuition — Addressing by street number, not by walk. Picture a street where each house has a number on its door. Command-mode yanks are like walking to a house and photographing it. Colon-range yanks are like calling the address desk: "photograph houses 7 through 9" — no walking required. The colon prompt : is the desk, N1,N2 are the house numbers, y is "photograph", and the same sticky-note buffer from 7.5 receives the copy.
The analogy holds because the buffer is shared: a photograph taken by walking (5yy) and a photograph taken by address (:7,9y) land on the same sticky note, and either can be printed with p or :put.
Formalize — Colon yank and put syntax.
- General form:
:N1,N2ywhere:enters command-line mode,N1is start line number,N2is end line number, comma separates, andymeans yank the inclusive rangeN1throughN2. - Examples:
:2,4yyanks lines 2, 3, and 4 — three lines.:7,9yyanks lines 7, 8, and 9 — three lines.:1,5yyanks first five lines. - Special addresses:
:1,10ylines 1-10,:.,+3yfrom current line (.) three ahead,:\\$ylast line,:%ywhole file (%=1,\\$). - Yank destination: the inclusive range goes to the same unnamed buffer that
yy/ywuse. - Paste options after any yank: return to command mode and press
p/P, or stay at colon and type:put(or:put!to put before).:putwithout address puts after current line, exactly likep;:7putputs after line 7. - Interchangeable: a range yanked with
:N1,N2ycan be pasted with plainp; a line yanked withyycan be pasted with:put. Both draw from the same buffer.
Visual intuition — Draw the file as a vertical gutter with line numbers 1 to 10 at left, cursor star at line 2. Highlight lines 7-9 in a bracket labeled :7,9y. Draw a horizontal arrow from that bracket to a sticky note labeled buffer 3 lines yanked. Then draw a second arrow from the sticky note down to after line 2, labeled p insert. Axes: vertical is line number, horizontal is buffer flow. The takeaway: address selects the source, cursor selects the destination — source and destination are decoupled.
Scope — When to use which path.
- Use command-mode
yy/n yy/ywwithp/Pwhen the cursor is already near the source. Fastest when visible. - Use colon ranges
:N1,N2ywithpor:putwhen you know the numbers or the source is off-screen and scrolling would disturb your destination position. Also useful in scripts and macros that address by line number. - Assumes you can see line numbers. If not, enable
:set nuto display them while you work;:set nonuhides them.
Pitfalls — Range yank traps.
- Off-by-one on inclusivity:
:2,4yis lines 2, 3, 4 — three lines total, not two. The range is inclusive on both ends. - Forgetting
Enterafter:7,9y. The yank executes only onEnter; typingpwithoutEnterjust addspto the prompt. - Typing line numbers without the colon — on the buffer as text if you are still in insert mode. Always
Escto command, then:. - Confusing
:mode with command mode due to similar names. The reliable test from the lecture: if you see:at the bottom you are in command-line mode; if not, you are in command mode. The hesitation between the two names was acknowledged as natural.
7.6.2 Worked Example 4 — Yank Lines 7 to 9 and Put Them
Setup. content.txt open, command mode, file padded to at least 10 lines so the range is clear. If your file from 7.2 is short, add filler lines line 4 through line 10 (some blank) before starting. Line 9 will be empty in the demo — keep it empty to see empty-line handling.
Steps — Yank by address:
- Press
:— colon appears at bottom, now in command-line mode. - Type
7,9yso the full command reads:7,9y. Numbers are literal line numbers in current file. - Press
Enter. Message shows3 lines yanked, confirming the range size (lines 7, 8, 9 inclusive). Count = 9−7+1 = 3. - Notice no visible copy in the file yet — the range is in the buffer.
Steps — Paste by cursor:
- Move cursor to desired paste location, e.g.
Gto end or2Gto after line 2. Demo moves to end to make the result easy to see. - Press lowercase
pin command mode. The three lines appear after the current line in original order: line 7 text, line 8 text, then an empty line from line 9. The empty line is real content — vi correctly yanks and reproduces it, showing buffer fidelity.
Alternative paste — Via colon:
- Press
:then typeputso prompt reads:put, pressEnter. The same three lines insert again after current line. This confirms:putandpread the same buffer; second paste proves buffer persistence.
Appearance after one p (cursor was on line 10 end):
7: some text for line 7
8: some text for line 8
9: (empty)
10: original end line
11: some text for line 7 <- pasted
12: some text for line 8 <- pasted
13: (empty) <- pasted, then ~ lines below show end-of-file
Sense-check: Pasted block must be exactly 3 lines and preserve the empty line 9. If you see only two, you excluded line 9 or had no empty line there. Tilde ~ handling is discussed next.
Exam cue: Know that :2,4y means lines 2, 3, 4 and that 3 lines yanked is the confirmation to note in answers.
7.6.3 Reading the Screen — The Tilde and Empty Lines
Tilde ~ means "no file content on this screen row," not "empty line in file." Vi fills screen rows beyond the end of the file with a tilde in blue at column 1 so you can distinguish a real blank line (a line that contains only a newline) from a screen row that has no file backing. A real empty line occupies a line number and is yankable; a tilde row has no number and cannot be yanked because it is not data.
When the demo pastes a block that includes an empty line (line 9 empty), the pasted block shows a blank pasted line (genuine empty content) and then, on the next screen row below the file end, a blue ~. That juxtaposition proves the empty line was genuinely copied. If you count pasted lines, include empty lines in the count. The 3 lines yanked message already includes them.
Screen sketch after pasting an empty line:
12: pasted empty line content <- blank but real line, no ~
~ <- blue ~ on next screen row, not a file line
~ <- more ~ rows to bottom of window
Test: with cursor on a blank line press 0 — cursor moves to column 1 on a real blank. Move to a ~ row — cursor refuses, because there is no line to occupy. This physical test distinguishes file data from window decoration.
Sense-check: Every ~ row disappears after you append real lines past that point; a blank line remains as a numbered entry.
Pitfalls — Tilde confusions.
- Counting
~rows as pasted empty lines and overcounting. Only blank lines that show as empty numbered positions count. - Expecting yank of a
~row to change buffer. It cannot — there is no file content there. - On some terminals the tilde is rendered faint; look at the column 1 position carefully.
7.6.4 Command Mode versus Command-Line Mode for Yank-Put
Both paths use the same buffer and reach the same result; the choice is about convenience and stability.
| Situation | Fastest method | Why |
|---|---|---|
| Cursor already on source | yy / 5yy then p / P |
No line numbers needed, one-step |
| Source is far off-screen, numbers known | :N1,N2y then p at destination |
No scrolling away from destination |
| Scripting or repeating exact range | :7,9y then :put or :100put |
Addressable and reproducible |
| Need to copy without moving cursor at all | :7,9y then p |
Cursor never leaves insertion point |
| Yanking inside a line | yw / y\\$ (only command mode) |
No colon equivalent for intra-line |
The session intentionally shows both so you can choose per context. A moment of confusion in the live naming — hesitation between "command mode" and "command-line mode" — was normalized. The screen test is definitive: : at bottom = command-line mode, no : = command mode.
Combined workflow — Using both modes on one task. Goal: duplicate lines 2-4 into two places (after line 10 and after line 1) without re-yanking.
- Type
:2,4yEnter— buffer = lines 2,3,4, message3 lines yanked. - Move to line 10, press
p— block appears after line 10. - Move to line 1, press
P— same block appears before line 1+offset, after shift.
Buffer still holds lines 2-4, so step 3 needed no re-yank. This interleaves the two modes in one sequence and proves the shared buffer.
Recap + Bridge. Colon ranges :N1,N2y yank an inclusive line range into the shared buffer by address, and either p/P or :put pastes it; empty lines count and ~ marks non-content rows, not data. With copying from both near and far under control, we now cover what happens when the editor session ends without a save — how vi protects that work.
Real-world & domain connection — In production configs many blocks are addressable by number: lines 7-9 might be a virtual host entry. An operator who knows grep -n reported the duplicate entry lives on lines 7-9 can immediately :7,9y then navigate to the insertion point and p without opening a second window or scrolling through 500 lines over a laggy link. The same pattern is used in code to duplicate a test fixture block by address while keeping the cursor on the call site being edited.
7.7 Recovering Files After a Disruption
7.7.1 Why vi Keeps a Temporary Copy
Hook — The night the network dies. You have typed for twenty minutes on a remote server. You have not yet pressed :w. The Secure Shell connection drops. When you log back in, is your work gone, or did vi keep a shadow copy while you typed?
Intuition — The shadow notebook. Picture vi working with two documents: the original file on disk (the bound book on the shelf) and a working copy on the desk (the buffer). As you type, vi continuously updates a second copy — a temporary recovery file — hidden on disk elsewhere. While you edit you write only to the desk copy; the bound book changes only when you explicitly :w. The hidden shadow notebook, however, gets updated as you edit. Normal exit with write and quit discards the shadow because it is no longer needed. Abnormal exit — network drop, terminal closed, power cut, kill — leaves the shadow behind, and that is what recovery loads.
Where the analogy breaks: the shadow is not a full version history; it reflects the last flushed state, not every keystroke, so the very last unwritten characters might still be lost if the flush did not happen before the disruption.
Formalize — Temporary copy as recovery mechanism.
- Definition: a temporary copy (also called swap or recovery file in Vim) is an extra file vi maintains and updates as you edit, separate from the file you opened. Location is typically near the original or in a configured swap directory; Vim names it
.filename.swp. - Lifecycle: on
vi filenameopen, vi creates or reuses the temporary file and tracks the original. Edits accumulate in the buffer and are flushed to the temporary file periodically and on certain actions. On normal save-and-quit (:wq,:x,ZZ) the temporary copy is cleaned up. On abnormal termination, the temporary copy remains. - Why it matters for remote edits: the class stressed editing over Secure Shell where the connection can drop at any time. Without a shadow copy, unsaved changes would be lost completely. Because vi kept a temporary copy that tracked edits, work up to the last flush is still available for recovery.
- What the shadow contains: the buffer state at the time of last update, not the last disk write. Recovery shows you that state so you can save it back to the original.
Visual intuition — Draw two parallel timelines. Top: original file on disk, flat line until :w lifts it. Middle: buffer/keystrokes spiking as you type. Bottom: temporary copy, a stepped line that follows the buffer with slight delay and persists after a vertical red line labeled "connection drop" where the top line stops short. Arrow from bottom stepped line back up labeled vi -r shows recovery path. The takeaway: disk original diverges from buffer, temporary copy shadows the buffer and survives the drop.
Scope — What the temporary copy guarantees and does not.
- Guarantees availability of a restorable snapshot after abnormal exit, within the limits of the last flush. Recent edits that had not yet been flushed may be absent — save frequently with
:wduring long edits to minimize window of risk. - Does not replace explicit saves. Until you save the recovered buffer back with
:wor:wq, the restore exists only in memory. - Does not handle cases where the disk itself fails or the swap directory is on lost storage. Headless environments that discard
/tmpon reboot may lose the swap — configure swap location to persistent storage for recovery to matter. - On Linux Vim, a stale
.swpfile blocks normal open until you handle the prompt; you must delete it manually if you choose to abandon recovery.
Pitfalls — Misreading the shadow.
- Assuming every keystroke is in the temporary copy. Some last characters may be missing — inspect the recovered buffer before saving.
- Opening the original with another editor while vi still holds the swap, thinking both edits will merge. Concurrent edits can diverge; resolve by choosing one.
- Ignoring the swap warning on reopen and picking a choice at random. The prompt holds the decision between keeping disk file and keeping buffered work — read it.
7.7.2 Worked Example 5 — Recover with vi -r
Setup. You were editing content.txt over Secure Shell, had typed a new paragraph but had not pressed :w, and the connection dropped.
Steps — Manual recovery path taught in class:
- Log back in once the connection is stable. Return to the same directory:
cd ~/projector wherevercontent.txtlives. - At the shell prompt type
vi -rfollowed by the same filename, e.g.vi -r content.txt, and pressEnter. The flag-ris the recovery flag. The automated caption rendered this as "iPhone R" due to transcription noise, but the intended flag is hyphenr. - Vi locates the temporary copy associated with that filename and shows recovery information. Choose the recovery option to load the temporary content into the editor — the buffer now shows the state from the shadow file.
- Inspect the recovered content: scroll with
j/korgg/G, search for recent words with/threeto confirm presence. If the last few characters are missing, retype them now. - Save explicitly with
:wor:wq. This writes the recovered buffer back to the original filename so the file you continue working with contains the restored work. Until this save, the recovered content exists only in the editor's memory. - If Vim left a
.content.txt.swpfile, it may prompt on next open; after a successful save you can remove the swap withrm .content.txt.swpor let vi clean it on next successful write depending on configuration.
Expected shell trace:
\\$ vi -r content.txt
"content.txt" [Recovery] 8 lines, 310 characters
: w
"content.txt" 8 lines, 310 characters written
Sense-check: After :w the original file timestamp updates (ls -l content.txt shows now), and reopening without -r should not show the stale recovery prompt.
Exam cue: Know the command is vi -r filename, why the shadow exists, and that explicit save is the durable step. Be able to explain the "iPhone R" caption noise as hyphen r.
7.7.3 The Modern Prompt on Reopen
Convenience path — Auto-detection on plain open. Current implementations (notably Vim) add a prompt so manual -r is not always needed. If a temporary recovery file exists and you simply run vi filename again without -r, vi detects the mismatch between the original file and the shadow and prompts at open time.
Typical prompt choices:
Recover/Open Read-Only + Recover— loads the shadow content into the buffer (same asvi -r).Delete swap / Abandon— discards the shadow and keeps the disk file as is.Quit / Abort— exits without deciding, leaving the choice for later.Diff/Show differences— in some builds shows swap vs disk.
Choose according to whether you want unsaved edits back. After choosing to recover, the same final step applies: inspect and then save with :w or :wq. After choosing to keep the disk file, you may need to manually delete the .swp file if it persists.
Relationship between the two paths: manual vi -r filename and the auto-prompt are the same mechanism surfaced at different times. Manual -r explicitly asks for recovery; auto-prompt surfaces the decision when you happen to reopen. Both feed the same shadow into the buffer and both require an explicit save.
Platform note from references: Linux users who see E325: ATTENTION Found a swap file and cannot edit should note the .swp file path shown in the message and handle it — do not leave the swap forever or every open will warn. The lecture adds that on Linux you may need to delete the .swp manually otherwise the file will not be editable.
Trace — Reopen prompt flow.
- After disruption, shell shows prompt
\\$. - Type
vi content.txtEnter(without-r). Screen shows:
E325: ATTENTION
Found a swap file by the name ".content.txt.swp"
dated: Thu May 7 10:59:00
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit
- Press
Rfor Recover — buffer fills with shadow state. - Verify, then
:wEnter— swap cleared on write.
If you had pressed Q then later decided to recover, you would then use vi -r content.txt — the two entries converge.
Sense-check: After recover + write, reopening vi content.txt without -r should not show the E325 warning. If it still does, the swap was not cleaned — ls -la .*.swp will show it.
Exam cue: Be able to name both recovery entry points (vi -r filename and plain vi filename auto-prompt), and to state that the swap persists until saved and cleaned.
Recap + Bridge. vi protects unsaved work via an automatically maintained temporary copy that survives abnormal exit; vi -r filename is the manual recovery entry and the newer auto-prompt on plain reopen is the same shadow surfaced at open, both requiring an explicit :w to make the restore durable. With recovery understood, the last major command-mode skill is fast search — finding any string without leaving vi.
Real-world & domain connection — Site-reliability playbooks include the step: after a dropped Secure Shell session during a production config edit, immediately re-ssh and vi -r /etc/app.conf before restarting the service, to avoid restarting with a truncated file. In team workflows, the swap warning on git pull after a crash reminds engineers to resolve recovered versus committed versions rather than silently overwriting. The habit of periodic :w during long edits is the human complement to the shadow — it narrows the window of potential loss to seconds.
7.8 Searching Inside vi
7.8.1 Forward Search with Forward Slash and Backward Search with Question Mark
Hook — Find a name in a 2,000-line log without scrolling. You Searched the web with Ctrl-F to find a word. In vi there is no Ctrl-F menu, yet you can jump to any occurrence with one character. Which character jumps forward and which jumps backward, and why does direction matter?
Intuition — Two flashlights on a dark hallway. Picture the file as a long hallway with doors (lines) and the cursor as your position holding a flashlight. Typing /text points the beam forward toward the end of the hallway and walks you to the next door whose name contains text. Typing ?text points the beam backward toward the entrance and walks you to the previous door containing text. Both are issued in command mode: the slash or question mark appears at the bottom after you Esc to command mode, and Enter starts the walk.
Where the analogy breaks: a flashlight shows what is ahead visually; vi's search jumps instantly without revealing intermediate matches unless you repeat with n/N.
Formalize — Search commands defined.
/text— search forward fortextstarting from cursor toward end of file. The forward slash/indicates forward direction. As you type, many builds highlight the match near the cursor — a live preview before you pressEnter.?text— search backward fortextstarting from cursor toward beginning. The question mark?indicates backward direction.- Both are command-mode commands. In insert mode
/inserts the character; after:it is part of a file command. PressEscfirst. - Pattern
/textor?textis a character string that can be a whole word, part of a word, or phrase. Spaces included before or after the pattern are part of the pattern. Classic vi also supports full regular expressions for variable patterns (e.g. words starting with capital, line-start anchors), covered more in later chapters; for now treat the pattern as a literal string. - On
Enterthe cursor jumps to the matched occurrence. If no match exists, vi reports pattern not found and does not move. If wrapping is enabled (default), a search that reaches the end continues from the opposite end and showsSearch hit BOTTOM, continuing at TOP(orTOPfor backward).
Visual intuition — Draw a vertical file gutter numbered 1 to 20, cursor star at line 15. Forward arrow /three points down labeled "to next match below cursor" and stops at line 18 where three appears, with note "no match between 16-18 would wrap to 1." Backward arrow ?three points up from line 15 and stops at line 4. Horizontal axis is file position, vertical is match highlight intensity. The takeaway: starting point is cursor, direction decides which half of the file is searched first.
Scope — When each search applies.
- Use
/when the target lies below the cursor or you are at the top and want the next occurrence down. - Use
?when the target lies above the cursor or you are at the bottom and want the previous occurrence up. - The choice matters because a forward search from the last character toward the end finds nothing ahead even if the word occurs many times earlier — you need backward there. The lecture demo at the last character showed exactly this.
- Up to this point many vi features mirror other editors' find, but explicit direction control is the vi difference and is testable.
Pitfalls — Direction traps.
- Searching forward from the end of the file and concluding the word is missing. It may be above; try backward
?. - Forgetting
Enterafter/textor?text. Until you pressEnterthe pattern is not accepted andn/Nwill not step through matches. - Typing the slash while still in insert mode and wondering why text
/threewas inserted. AlwaysEscfirst.
7.8.2 Reference Point — The Cursor Position
The reference point is the cursor, not the file top. Search starts where the cursor sits, not from line 1. This explains the lecture's live question: with cursor at the very last character, searching for a word that occurs earlier such as three, a forward /three finds no match ahead and would need to wrap, while a backward ?three finds the occurrence behind without wrapping. The conclusion drawn was that backward with ? was the correct choice because the target lay behind the cursor.
Consequences:
- Placing cursor at top and searching forward with
/walks the file top-to-bottom in natural order. - Placing cursor at bottom and searching backward with
?walks bottom-to-top. - Repeated
nwalks forward through occurrences in the order?or/defined;Nwalks the reverse. Cursor moves after each jump, so the reference point for the nextnis the match you just landed on.
Trace — Same word, different reference. File content.txt with three on line 5 and line 12.
- Cursor on line 20 (last char), type
?threeEnter— lands on line 12, the nearest occurrence behind. - From there
n(same direction = backward) would go to line 5;Nwould return forward to line 12. - Reset cursor to line 1, type
/threeEnter— lands on line 5, the nearest occurrence ahead.ngoes to line 12.
Same file, same word, different landing because reference point differed.
7.8.3 Worked Example 6 — Search for the Word three
Setup. content.txt containing the word three at least once. To reproduce the class drill, place the cursor at the end of the file (G then \\$ in command mode).
Steps — Backward search path (as demoed from file end):
- Ensure command mode: press
Esc. - Press
?— a?prompt appears at the bottom status line. - Type
threeso the prompt reads?three. Live preview may highlight the first match near the cursor as you type. - Press
Enterto confirm. Cursor jumps to the matched occurrence ofthreebehind the start point. - If the term is absent, vi reports no match rather than moving.
Steps — Forward search path (from top):
- Move to top with
gg. Ensure command mode. - Press
/— a/prompt appears. - Type
threeso prompt reads/three, pressEnter. Cursor jumps to the next forward occurrence. - Observe status may indicate direction and highlight the match.
Variation — Wrapping note: if you search forward from below the last occurrence, the message Search hit BOTTOM, continuing at TOP appears and the cursor wraps to the first occurrence. The analogous TOP message appears for backward wrap.
Sense-check: Cursor must move to a three. If it did not, check you were in command mode and pressed Enter.
7.8.4 Repeating a Search with n and N
Repeat without retyping — n and N. After a search, the last pattern stays available for the session so you can walk through all matches:
- Lowercase
nrepeats the last search in the same direction originally issued — next forward for a/search, next backward for a?search. - Uppercase
Nrepeats in the opposite direction — stepping backward through matches for a/search and forward for a?search. - Also
/Enterrepeats forward and?Enterrepeats backward without retyping.
Operational detail shown in class and emphasized: after typing /three or ?three you must press Enter before n or N will step. If you type the pattern and press n without Enter, the editor has not yet accepted the search — n does nothing or inserts unexpectedly. The required sequence is: ?three Enter then n then n then N to step back.
Wrapping interaction: when repeated n reaches the last occurrence and continues, vi shows Search hit BOTTOM, continuing at TOP (or the TOP variant for backward) and continues from the opposite end. That message is informational — the search wrapped and landed on the first/last match again.
Trace — Walking two occurrences and wrap. File has three on line 8 and line 15, cursor at top, wrapscan default on.
- Type
/threeEnter— lands on line 8, highlight onthree. - Press
n— lands on line 15, second occurrence forward. - Press
nagain — no more ahead, so vi wraps: messageSearch hit BOTTOM, continuing at TOPand lands back on line 8. - Press
N— moves backward to line 15, confirmingNreverses direction.
Similarly from line 15, ?three Enter lands on line 8 (backward), n would wrap to line 15 if there are only two.
Option control: :set nowrapscan disables wrapping. With it set, a failing forward search shows Address search hit BOTTOM without matching pattern (or TOP for backward) and does not wrap. :set wrapscan restores wrapping.
Sense-check: After Enter the prompt disappears and the next n must move. If it does not, you missed Enter.
Pitfalls — Repeat traps.
- Pressing
nbeforeEnter— most frequent error; lecture flagged it explicitly. - Forgetting which direction
nfollows. It follows the original/or?, not the lastn. After?threeEnter,nalways goes backward; after/threeEnter,nalways goes forward. - Disabling wrapscan and expecting wrap. Check
:set wrapscan?if searches seem to stop early.
7.8.5 Worked Example 7 — Stepping Through Multiple Occurrences
Setup. Same file with two occurrences of three. Start at top with gg.
Steps.
- With cursor at top, issue
/threeand pressEnter. First occurrence highlighted, cursor on it. - Press
n. Cursor moves to second occurrence below the first. - Press
nagain. With only two occurrences, vi shows wrap messageSearch hit BOTTOM, continuing at TOPand the cursor wraps to the first occurrence. - Press
N. Cursor moves back to the previous match, confirmingNreverses.
What to observe for assessment: the order is deterministic from the start direction, wrap is announced, and N is exactly opposite of n. Write the sequence and the landing line number each time — presentation matters for scoring on output-prediction questions.
Sense-check: A complete cycle returns to the start after k+1 presses where k is the number of occurrences minus one, plus one wrap.
Exam cue: Expect questions that give a file sketch with line numbers and a sequence like /three Enter n n N and ask which line the cursor ends on. Track direction and wraps.
7.8.6 Character Search Within the Current Line with f and F
Single-line character finder — f and F. Beyond file-wide / and ?, vi offers a single-line finder issued in command mode:
ffollowed by a character finds the next occurrence of that character forward within the current line only. Example: cursor at line start, typef?(keysfthen?) — cursor jumps to the?character on that same line if it exists ahead. It does not print anything; it only moves the cursor.Ffollowed by a character finds backward within the current line. CapitalFsearches toward column 1.- Limits:
fandFoperate only within the current line. They do not cross line boundaries, unlike/and?. For multi-line search use/and?; for quick intra-line edits usefandF. - Companion commands
;repeats the lastf/Fin same direction,,repeats in opposite direction.t/Tare variants that land just before/after the character (until), useful for change commands likect,to change up to a comma.
Trace — Demo moves from lecture. Line in file: What? Are you sure, really? Cursor on W start, command mode.
- Press
f?— cursor jumps to the?afterWhat. Only that line was searched; no other line moved. - Press
F,— looks backward within the same line for a comma. There is none before the?, so cursor stays. Move cursor to aftersure, then pressF,— lands on the,aftersure. - Press
f,again forward — stays if no,ahead on that line. Tryf,from start — lands on the,aftersureforward.
Second demo pairing: f? to land on ?, then F, to search backward for , on same line. The uppercase variant searches backward, lowercase forward — same mirror as N/n but at intra-line scale.
When to use: quick edits such as df, delete from cursor to next comma on that line, or cf, change up to comma, without leaving the line. The search is character-wise and local, so it is safe for structured lines like comma-separated values.
Sense-check: If f finds nothing on this line, cursor does not move and some terminals beep. It never jumps to the next line.
Pitfalls — Character finder traps.
- Pressing
fin insert mode inserts the letter f. - Expecting
fto search the whole file — it is line-limited by design. - Confusing
f(find forward) with/(search forward).fneeds a single character and stays on one line;/needs a string and crosses lines.
7.8.7 Student Questions and Answers
Q: How do we copy from another file and paste it into the file opened in vi? Does p work for content copied outside vi? Many students asked this same confusion point — expecting the system clipboard and vi's buffer to be the same.
A: A vi put command p only pastes what vi itself yanked into its internal unnamed buffer, so it does not paste a system-wide copy made with Control C in Windows. Copying with Ctrl-C places text on the operating system clipboard, which vi's p does not read. The working method shown in the answer is: select and copy the external text with the normal Windows copy (Ctrl-C), switch to the vi window, enter insert mode (i or a), and then do a mouse right-click to paste. The right-click paste in insert mode inserts the Windows clipboard contents at the cursor like typed text. Staying in command mode and pressing p after a Windows copy does not insert the external text because p reads the vi buffer, not the system clipboard. For terminal-native clipboard integration in Vim, options include "*p or "+p (clipboard registers) if the build supports clipboard, and :set clipboard=unnamed to sync, but the lecture's reliable cross-platform method is insert-mode right-click paste.
Why the confusion seemed plausible: other applications share a clipboard so Ctrl-C then Ctrl-V works across them; vi's p looks like Ctrl-V and the buffer looks like a clipboard, so learners map them. The correction is the mental model: two clipboards exist — system and vi buffer — and p reads only the latter unless you explicitly configure sync.
Recap + Bridge — Search family in one view. /text and ?text are file-wide string searches whose starting point is the cursor and whose direction is explicit; n repeats same direction and N opposite after an Enter-accepted pattern, with wrap messages and wrapscan control; f/F (and ;/, and t/T) are line-local character finders. The external-paste question reminds you that vi's buffer and the system clipboard are separate unless explicitly bridged.
Exam note — Must-memorize for this section: know when to use / versus ? based on cursor, that Enter must precede n/N, that n is same direction and N opposite, that wrap messages signal continuation at the opposite end, and that f/F plus repeats work only within the current line. Character-find with f? and F, will be asked as motion, not as file search.
Overall capsone bridge: the three modes, word motions (w/b/gg), yank-put in both command and colon forms sharing one overwriting buffer, swap-based recovery, and directional search together give you a complete console editing loop — fast enough for production work over Secure Shell and inspectable enough for assessment chains that ask you to simulate the buffer after a series of commands.
Real-world & domain connection — Walking a 10,000-line syslog with /ERROR n n N is daily work for systems programmers chasing a failure signature, and intra-line f, is how you land on the field past a comma without leaving the line while editing a CSV or a C argument list. Knowing that / and ? are directional from the cursor prevents scanning the wrong half of a log when time matters.
Exam Guidance Summary
- Practice the mode task: create a file with given content and press the same keys in command mode, insert mode, and command-line mode to see the difference. Assessment may present a sequence of mode-dependent keystrokes such as
i hello Esc w : w Enterand ask for the resulting buffer, cursor position, or mode. Know the transition keys (i,a,o,Esc,:,Enter) and the colon tests (:at bottom means command-line mode) and be able to predict without trial.
- Navigation and yank-put are fertile ground for short-answer and output-prediction questions. Expect direct questions on what
yy,5yy,yw,p,P,u,:2,4y,:7,9y,:put,/text,?text,n,N,f?, andF,do, and multi-step simulation questions that ask you to predict the file after a series such as5yy p uor:7,9y pstarting from a given cursor. Forn yyand:N1,N2ystate the inclusive count (5yy= 5 lines,:2,4y= lines 2-4 = 3 lines).
- Remember line-range inclusivity (
:2,4ymeans lines 2, 3, and 4) and that status reports5 lines yankedor3 lines yankedconfirm what is now in the shared buffer before pasting. Empty lines count and are reproduced on paste; tilde~rows beyond the end of the file are not file content and are not yanked. Always note the message in your answer where a count applies.
- Recovery via
vi -r filenameand the newer auto-prompt on reopening the same filename are both testable. Know that a temporary copy (swap) is maintained and updated while you edit, that abnormal termination leaves it behind, thatvi -rloads it or the auto-promptE325offersRecoverversusKeepchoices, and that you must save explicitly with:wor:wqafter recovery to make the restore durable. The caption noise "iPhone R" means hyphenr.
- Search direction is tied to cursor position. Know when to use
/(forward toward end) versus?(backward toward start) based on where the cursor sits relative to the target, that you must pressEnterafter typing/threeor?threebeforen/Nwill step, that lowercasenmoves same direction and uppercaseNopposite, and that wrap messagesSearch hit BOTTOM, continuing at TOP(orTOPanalogue) signal wrapping at the file boundary and continuation at the opposite end. Thewrapscan/nowrapscanoption controls this.
- Character find with
fandFworks only within the current line.f?finds the next?forward on that line,F,finds a comma backward on that line, and they never cross line boundaries. Do not confuse this intra-line motion with file-wide/and?string search; companion repeat keys;and,follow the same same/opposite pattern at intra-line scale.
- Presentation matters: when asked to show work that involves pasting or repeated search, write the order of operations in order, note each buffer message and each search landing line, and label
pversusPplacement. Keep the shared-buffer and overwrite rules visible in your explanation and show steps legibly — clarity helps scoring.
- The break notice — roughly eight to ten minutes around 11 o'clock with the recording paused — has no effect on content but signals that the second half of the session continues immediately after. No assessment content was taught during the break.
Key Industry Applications
- Remote server editing over Secure Shell as the guaranteed fallback. Production hosts, build servers, and network appliances often expose only a terminal.
viis part of the base install and works over any Secure Shell link without X forwarding. Engineers openvi /etc/nginx/nginx.conforvi app.pyon the target, fix,:w, and restart the service in one session. Recovery via the temporary swap file protects against the common failure of a dropped connection — work up to the last flush remains restorable withvi -ror theE325prompt.
- Console workflows that keep the toolchain in one window. Systems programming cycles edit → compile → link → run → inspect in a tight loop. With vi you keep the compiler (
: !cc %),make(: !make), pipes, andgitone:escape orCtrl-Z/fgaway instead of switching between a graphical editor and a separate terminal. That proximity shortens feedback loops when iterating on a driver, a shell utility, or a Makefile.
- Editor choice as a context trade-off, not a loyalty test. Visual Studio Code dominates Windows desktop work for rich completion, integrated debugging, and graphical file views and is preferred there. Vi and Emacs persist among practitioners who value instant startup, ubiquity on headless machines, and keyboard-only speed after muscle memory forms. Many teams use Code locally and vi remotely — the lecture's balanced comparison reflects real practice where convenience and availability are weighted per situation.
- Yank buffer versus system clipboard — a frequent integration error. Understanding that
p/P/:putread vi's internal unnamed buffer while WindowsCtrl-C/ right-click paste uses the operating system clipboard explains whypafter a Windows copy does not paste that text. The correct cross-application path is copy withCtrl-C, enter insert mode in vi, and right-click paste, or use Vim's clipboard registers ("*p,"+p) when the build supports them. Naming the two clipboards separately prevents data-loss surprises when moving snippets between an external spec and a file being edited in vi.
- Directional search for large logs and code bases. Forward
/ERRORand backward?WARNwith repeatn(same direction) andN(opposite) plus wrap messages mirror find-next in other editors but give explicit direction control from the cursor reference point. Operators walk a 10,000-linesyslogto chase a failure signature and use intra-linef/F(e.g.f,to land on a comma in a CSV) for field-level navigation without leaving the line. The explicit cursor-reference model is why vi search stays predictable on large files over a high-latency link.
SP Lecture 7 notes · The vi Editor — Modes, Navigation, Yank-Put, Recovery and Search
Sections Breakdown
Motivation for vi: terminal-resident modal editor over SSH, trade-offs vs VS Code and Emacs.
Insert writes, command moves, colon operates files; command is hub.
w next word start, b previous, counts multiply, gg top.
yy line, 5yy n lines, yw word, p after, P before, u undo.
Single buffer slot overwritten each yank, readable repeatedly.
Colon ranges :N1,N2y to same buffer, :put pastes, ~ not content.
Temporary copy shadows buffer; vi -r or E325 recovers then :w.
/ forward ? backward from cursor, n same N opposite after Enter, f/F line-local, p not clipboard.
Consolidated exam guidance.
Industry apps.
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
Why vi Still Matters in Systems Work
Must-know: vi is terminal-resident and always present, guaranteed over SSH.
âš ï¸ Top pitfall: Assuming graphical editor everywhere.
Self-check: Why vi over SSH?
Connects to: 7.2
The Three Modes and Basic File Handling
Must-know: Insert writes, command moves, colon file ops; Esc to command, : to colon; :w writes.
âš ï¸ Top pitfall: Trying :w in insert.
Self-check: yy inserts text - which mode?
Connects to: 7.1
Word-Level Navigation with W and B
Must-know: w next word start, b previous, gg top.
âš ï¸ Top pitfall: Home vs gg.
Self-check: How to reach line 1?
Connects to: 7.4
Copy and Paste in Command Mode - Yank and Put
Must-know: yy line, 5yy 5 lines, yw word, p after P before.
âš ï¸ Top pitfall: Yank before put overwrites.
Self-check: yw then p twice?
Connects to: 7.5
The Yank Buffer - What Happens in Memory
Must-know: Buffer RAM single slot overwrites.
âš ï¸ Top pitfall: dd overwrites.
Self-check: yy then yw what pastes?
Connects to: 7.4
Copy and Paste in Command-Line Mode with Line Ranges
Must-know: :2,4y 3 lines, empty counts, ~ no content.
âš ï¸ Top pitfall: Counting ~.
Self-check: :7,9y lines?
Connects to: 7.5
Recovering Files After a Disruption
Must-know: Shadow copy vi -r then :w.
âš ï¸ Top pitfall: No :w after recover.
Self-check: Flag for recover?
Connects to: 7.2
Searching Inside vi
Must-know: / forward ? backward, Enter before n/N, f line-local, clipboard separate.
âš ï¸ Top pitfall: n before Enter.
Self-check: Cursor at end target above which search?
Connects to: 7.3
Exam Guidance Summary
Must-know: Mode chains, counts, recovery.
âš ï¸ Top pitfall: Presentation.
Self-check: What does :2,4y show?
Connects to: None — standalone
Key Industry Applications
Must-know: Remote SSH, console loops, clipboard.
âš ï¸ Top pitfall: ~ counting.
Self-check: Production recover example?
Connects to: None — standalone
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.