Unit 9: vi editor - Subjective Questions
CSE105 — Creative Engineering Workshop • Practice Questions with Detailed Answers
20 questions
Explain the different modes of operation in the vi editor. How does a user switch between them?
The vi editor operates in three distinct modes:
- Command Mode (Normal Mode): This is the default mode when vi starts. Keystrokes are interpreted as commands to navigate, delete, copy, or manipulate text rather than being inserted as content.
- Insert Mode: In this mode, whatever the user types is inserted into the file as text. It is entered from command mode using commands like
i,a,o, etc. - Ex Mode (Last Line Mode / Command Line Mode): Entered by pressing
:from command mode. It is used for file operations such as saving, quitting, searching, and substitution.
Switching between modes:
- From Command Mode to Insert Mode: press
i,a,o,I,A, orO. - From Insert Mode back to Command Mode: press the
Esckey. - From Command Mode to Ex Mode: press
:. - From Ex Mode back to Command Mode: press
Escor execute the command.
Understanding these modes is fundamental to using vi efficiently, as the same key can have completely different effects depending on the current mode.
Describe the various ways to start the vi editor from the command line, including options to open at a specific line.
The vi editor can be started in several ways from the shell prompt:
vi— Opens vi with an empty, unnamed buffer.vi filename— Opens the specified file for editing. If the file does not exist, vi creates a new empty buffer with that name.vi file1 file2 file3— Opens multiple files; you can move between them using:n(next) and:prev(previous).vi +n filename— Opens the file and places the cursor on line number n. For example,vi +10 notes.txtstarts on line 10.vi + filename— Opens the file with the cursor on the last line.vi +/pattern filename— Opens the file with the cursor positioned at the first occurrence of the given search pattern.vi -R filename— Opens the file in read-only mode to prevent accidental changes.view filename— Equivalent to opening in read-only mode.
These options make vi flexible for jumping directly to relevant sections of a file when it is opened.
Explain the basic cursor navigation commands (h, j, k, l) in vi. Why were these keys chosen for movement?
In the vi editor's command mode, the four home-row keys are used for single-character cursor movement:
h— Moves the cursor one character to the left.j— Moves the cursor one line down.k— Moves the cursor one line up.l— Moves the cursor one character to the right.
Why these keys were chosen:
- vi was originally developed on the ADM-3A terminal, which did not have dedicated arrow keys. The
h,j,k,lkeys were physically marked with arrow directions on that keyboard. - Keeping the movement keys on the home row allows touch typists to navigate without moving their hands, greatly increasing editing speed.
Repeat counts: These commands can be prefixed with a number for repeated movement. For example, 5j moves the cursor 5 lines down, and 10l moves 10 characters right.
Describe the word-based and line-based navigation commands available in vi with suitable examples.
vi provides several efficient navigation commands beyond single-character movement:
Word Navigation:
w— Moves the cursor forward to the beginning of the next word.b— Moves the cursor backward to the beginning of the previous word.e— Moves the cursor to the end of the current/next word.W,B,E— Same as above but treat punctuation as part of the word (whitespace-delimited).
Line Navigation:
0(zero) — Moves to the beginning of the current line.^— Moves to the first non-blank character of the line.$— Moves to the end of the current line.
File Navigation:
ggor1G— Moves to the first line of the file.G— Moves to the last line of the file.nG— Moves to line number n (e.g.,25Ggoes to line 25).
Example: With the cursor at the start of a paragraph, typing 3w jumps forward three words, and $ then jumps to the end of that line.
Explain the scrolling commands in vi and distinguish between full-screen and half-screen scrolling.
Scrolling commands allow the user to view different portions of a large file without moving line-by-line. They are used in command mode and typically involve the Ctrl key:
Full-Screen Scrolling:
Ctrl + f— Scrolls forward (down) by one full screen (page).Ctrl + b— Scrolls backward (up) by one full screen.
Half-Screen Scrolling:
Ctrl + d— Scrolls down by half a screen.Ctrl + u— Scrolls up by half a screen.
Line Scrolling:
Ctrl + e— Scrolls the screen down by one line (cursor stays if possible).Ctrl + y— Scrolls the screen up by one line.
Distinction:
| Aspect | Full-Screen (Ctrl+f/Ctrl+b) |
Half-Screen (Ctrl+d/Ctrl+u) |
|---|---|---|
| Amount moved | Entire visible page | Half of the visible page |
| Use case | Quickly skipping large sections | Smoother reading with context retained |
| Context overlap | Little to no overlap | Retains half-screen of context |
Half-screen scrolling is often preferred while reading because it keeps some previously visible lines on screen for continuity.
Compare the various insert commands (i, I, a, A, o, O) used to enter insert mode in vi.
vi provides several commands to switch from command mode to insert mode, each positioning the cursor differently:
i(insert) — Inserts text before the current cursor position.I(Insert) — Inserts text at the beginning of the current line (before the first non-blank character).a(append) — Inserts text after the current cursor position.A(Append) — Inserts text at the end of the current line.o(open) — Opens a new line below the current line and enters insert mode.O(Open) — Opens a new line above the current line and enters insert mode.
Comparison Table:
| Command | Position of insertion |
|---|---|
i |
Before cursor |
I |
Start of line |
a |
After cursor |
A |
End of line |
o |
New line below |
O |
New line above |
After typing, the user presses Esc to return to command mode. Choosing the right insert command saves navigation time.
Explain the different editing/change commands in vi such as r, R, cw, cc, and s.
vi offers several commands to change or replace existing text:
r(replace one) — Replaces the single character under the cursor with the next typed character. Does not enter insert mode.R(Replace mode) — Enters overtype mode; typed characters replace existing ones untilEscis pressed.cw(change word) — Deletes from the cursor to the end of the word and enters insert mode to type the replacement.cc(change line) — Clears the entire current line and enters insert mode.C— Changes text from the cursor to the end of the line.s(substitute character) — Deletes the character under the cursor and enters insert mode.S— Deletes the entire line and enters insert mode (same ascc).
Example: To correct a misspelled word, place the cursor at its start and type cw, then type the correct word and press Esc.
These change commands combine deletion and insertion in one step, making editing efficient.
Describe the delete commands in vi with examples, including single-character, word, and line deletion.
Deletion in vi is performed in command mode using the following commands:
Character Deletion:
x— Deletes the character under the cursor.X— Deletes the character before the cursor (like backspace).3x— Deletes 3 characters starting at the cursor.
Word Deletion:
dw— Deletes from the cursor to the beginning of the next word.db— Deletes backward to the beginning of the previous word.2dw— Deletes two words.
Line Deletion:
dd— Deletes the entire current line.3dd— Deletes 3 lines starting from the current line.d$orD— Deletes from the cursor to the end of the line.d0— Deletes from the cursor to the beginning of the line.
Important: Deleted text is stored in a temporary buffer and can be pasted back using p or P, so deletion also acts like a cut operation.
Example: With the cursor at line 5, typing 2dd removes lines 5 and 6.
Explain in detail the copy (yank) and paste operations in vi. Discuss how the buffer works during these operations.
Copying in vi is called yanking, and it works together with pasting through a temporary buffer.
Yank (Copy) Commands:
yyorY— Yanks (copies) the entire current line.3yy— Yanks 3 lines starting from the current line.yw— Yanks from the cursor to the end of the word.y$— Yanks from the cursor to the end of the line.y0— Yanks from the cursor to the beginning of the line.
Paste (Put) Commands:
p— Pastes the buffer contents after the cursor (or below the current line for line-yanks).P— Pastes the buffer contents before the cursor (or above the current line).
How the buffer works:
- When text is yanked or deleted, it is stored in an unnamed (default) buffer.
- A subsequent paste command retrieves text from this buffer.
- Because both delete and yank fill the same buffer, deletion effectively acts as a cut, and yank as a copy.
- Named buffers (
"ato"z) can store multiple pieces of text. For example,"ayyyanks a line into buffer a, and"appastes from it.
Example: To duplicate a line, position the cursor on it, type yy, then p to paste a copy on the line below.
Distinguish between the various save and exit operations in vi (:w, :q, :wq, :x, ZZ, :q!).
vi provides several ex-mode commands (entered by pressing : from command mode) to save and exit files:
:w— Writes (saves) the file to disk but keeps vi open.:w filename— Saves the buffer under a new file name (save as).:q— Quits vi. Fails if there are unsaved changes.:q!— Quits without saving, discarding all unsaved changes (force quit).:wq— Writes and quits — saves the file and then exits.:x— Saves and exits, but writes to disk only if changes were made (slightly more efficient than:wq).ZZ— A command-mode shortcut (no colon) that saves and quits, equivalent to:wq/:x.
Comparison Table:
| Command | Saves? | Exits? | Force? |
|---|---|---|---|
:w |
Yes | No | No |
:q |
No | Yes | No |
:q! |
No | Yes | Yes |
:wq |
Yes | Yes | No |
:x |
Only if modified | Yes | No |
ZZ |
Only if modified | Yes | No |
Use :q! cautiously, as it permanently discards unsaved work.
Define the vi editor and explain its significance as a standard Unix/Linux text editor.
Definition: The vi editor (short for visual editor) is a screen-oriented text editor originally created by Bill Joy in 1976 for the Unix operating system. It allows users to view and edit text files interactively on the terminal screen.
Significance:
- Universally available: vi (or its improved version vim) is included in virtually every Unix and Linux distribution, making it a reliable editor even on minimal or remote systems.
- Lightweight and fast: It runs entirely in the terminal, consumes few resources, and works well over slow network connections such as SSH.
- No mouse required: All operations are keyboard-driven, which improves editing speed for experienced users.
- Powerful editing features: Supports search-and-replace, macros, multiple buffers, and regular expressions.
- Modal design: Its separation into command, insert, and ex modes allows a compact set of keystrokes to perform many operations.
Because of its ubiquity, learning vi is considered an essential skill for system administrators and developers who work on Unix/Linux systems.
Explain the concept of repeat counts (numeric prefixes) in vi commands with examples across navigation, deletion, and yanking.
A repeat count is a numeric prefix typed before a vi command that tells the editor to repeat the command that many times. This makes vi extremely efficient for bulk operations.
General form: [count][command]
Navigation Examples:
5j— Move the cursor 5 lines down.3w— Move forward by 3 words.10l— Move 10 characters to the right.
Deletion Examples:
3dd— Delete 3 lines.4x— Delete 4 characters.2dw— Delete 2 words.
Yank Examples:
5yy— Yank (copy) 5 lines.3yw— Yank 3 words.
Insert Example:
3ihellofollowed byEsc— Inserts the text hello three times.
Advantage: Instead of pressing a command repeatedly, the user specifies the count once. This reduces keystrokes and speeds up editing large files.
Describe how search operations work in vi and how they aid navigation within a file.
vi provides fast search commands to locate and navigate to text patterns, which is far quicker than scrolling for large files.
Search Commands (Command Mode):
/pattern— Searches forward for the given pattern from the cursor position. PressEnterto execute.?pattern— Searches backward for the pattern.n— Repeats the last search in the same direction.N— Repeats the last search in the opposite direction.
Character Search on a Line:
f<char>— Moves the cursor to the next occurrence of a character on the current line.F<char>— Moves backward to the previous occurrence on the line.t<char>/T<char>— Moves just before the character (forward/backward).
Regular Expressions: Search patterns can use regex metacharacters, e.g. /^main finds lines beginning with main, and /end$ finds lines ending with end.
How it aids navigation: By jumping directly to matching text, search commands let the user move to any location instantly. Combined with n/N, one can cycle through all occurrences of a term, which is essential for editing code or long documents.
Explain the substitute (search and replace) command in vi using the :s syntax with examples.
The substitute command in ex mode performs powerful search-and-replace operations. Its general syntax is:
:[range]s/old/new/[flags]
Common Forms:
:s/old/new/— Replaces the first occurrence of old with new on the current line.:s/old/new/g— Replaces all occurrences on the current line (g= global within line).:1,5s/old/new/g— Replaces all occurrences in lines 1 to 5.:%s/old/new/g— Replaces all occurrences in the entire file (%= all lines).:%s/old/new/gc— Replaces globally but asks for confirmation on each change (cflag).
Flags:
g— Global (all matches in the line, not just the first).c— Confirm each substitution.i— Case-insensitive matching (in vim).
Example: :%s/color/colour/g changes every occurrence of color to colour throughout the file.
This command supports regular expressions, making it a very flexible tool for bulk text editing.
Distinguish between the command mode and insert mode in vi. Why is understanding this distinction important for beginners?
The distinction between command mode and insert mode is the most fundamental concept in vi.
Command Mode:
- Default mode when vi starts.
- Keystrokes are interpreted as commands (navigate, delete, copy, paste, save).
- No typed text is added to the file.
Insert Mode:
- Entered using commands like
i,a,o, etc. - Keystrokes are interpreted as literal text and inserted into the file.
- Exited by pressing
Esc.
Comparison Table:
| Feature | Command Mode | Insert Mode |
|---|---|---|
| Default at start | Yes | No |
| Keys act as | Commands | Text input |
| Entered by | Esc |
i, a, o, etc. |
| Purpose | Editing, navigation | Typing content |
Why it matters for beginners:
- Beginners often try to type text while in command mode, causing unexpected deletions or cursor jumps.
- Forgetting to press
Escbefore issuing a command results in commands being typed as text. - Recognizing the current mode (and using
Escto reset) prevents confusion and data corruption, which is why this distinction is emphasized first.
Explain the undo and redo commands in vi and their importance in the editing workflow.
vi provides undo and redo facilities to reverse or reapply editing changes, which is crucial for correcting mistakes.
Undo Commands (Command Mode):
u— Undoes the last change (in vim, repeateduundoes multiple changes; in classic vi it toggles the last change).U— Undoes all changes made on the current line, restoring it to its original state.
Redo Command:
Ctrl + r— Redoes a change that was undone withu(available in vim).
Repeat Last Change:
.(dot) — Repeats the last editing command. For example, if you deleted a word withdw, pressing.deletes another word.
Importance in the workflow:
- Allows quick recovery from accidental deletions or wrong edits.
- Encourages experimentation, since changes can be reversed safely.
- The
.command combined with undo makes repetitive editing fast and error-tolerant.
Example: After deleting a line with dd, pressing u restores it; pressing Ctrl + r deletes it again.
Describe how to join lines, transpose characters, and change case in vi using command-mode operations.
vi includes several handy command-mode operations for small text manipulations:
Joining Lines:
J— Joins the next line to the end of the current line, inserting a space between them.3J— Joins the current line with the next two lines.gJ— Joins lines without adding a space (in vim).
Transposing / Swapping Characters:
xp— A common idiom:xdeletes the character under the cursor andppastes it after the next character, effectively swapping two adjacent characters. Useful for fixing typos like teh → the.
Changing Case:
~(tilde) — Toggles the case of the character under the cursor (upper ↔ lower) and moves right.3~— Toggles the case of the next 3 characters.- In vim:
gU<motion>converts to uppercase andgu<motion>converts to lowercase (e.g.,gUwuppercases a word).
Example: To correct hte to the, place the cursor on h, type x to delete it, move to after t, and type p.
These operations let users make precise corrections without entering insert mode.
Explain the concept of named and numbered buffers (registers) in vi and how they enhance copy-paste operations.
vi maintains several buffers (also called registers) that store text from delete and yank operations, allowing more advanced copy-paste workflows.
Types of Buffers:
-
Unnamed (default) buffer: Holds the text from the most recent yank or delete. Pasting with
p/Puses this buffer by default. -
Numbered buffers (
"0to"9):"0— Stores the text from the last yank operation."1to"9— Store the last nine deletions, with"1being the most recent. Each new delete shifts the older ones down.
-
Named buffers (
"ato"z):- Explicitly chosen by the user to store text.
- Prefix a yank/delete with
"<letter>. Example:"ayyyanks a line into buffer a. - Using an uppercase letter (
"A) appends to that buffer instead of overwriting it.
Using a buffer to paste: Prefix the paste command with the buffer name. Example: "ap pastes the contents of buffer a.
How they enhance copy-paste:
- Allow the user to store multiple independent pieces of text simultaneously.
- Numbered buffers act as a delete history, so recently deleted text can be recovered.
- Appending to named buffers lets the user collect text from different locations before pasting it together.
Example: "ayy on line 1, then "Ayy on line 5 appends line 5 to buffer a; "ap then pastes both lines.
A student accidentally makes several unwanted changes to a file in vi and wants to exit without saving any of them. Explain the steps and the command used, and contrast it with saving.
When a user wants to discard all edits made during a vi session, they must quit without writing the buffer to disk.
Steps to exit without saving:
- Ensure vi is in command mode by pressing
Esc(this cancels any partial insert or command). - Type the colon
:to enter ex mode. - Type
q!and pressEnter.
The full command is:
:q!
The ! is a force flag that tells vi to quit even though the buffer has been modified. Without it, plain :q would fail with the message No write since last change.
Contrast with saving:
| Goal | Command | Effect |
|---|---|---|
| Discard changes and exit | :q! |
Buffer modifications are lost; file on disk is unchanged |
| Save changes and exit | :wq or :x or ZZ |
Buffer is written to disk, then vi exits |
| Save without exiting | :w |
Buffer written, vi stays open |
Why this matters: Because vi edits a copy of the file in a buffer, nothing is permanently written until a :w-type command is issued. Therefore :q! safely abandons the buffer, leaving the original file exactly as it was before the session.
Explain how marks work in vi and how they can be combined with navigation and editing commands.
Marks in vi are named bookmarks that let a user record a cursor position and quickly return to it, which is very useful in large files.
Setting a Mark:
m<letter>— Sets a mark at the current cursor position using a lettera–z. Example:mamarks the current position as a.
Jumping to a Mark:
`<letter>(backtick) — Moves the cursor to the exact position (line and column) of the mark. Example:`a.'<letter>(apostrophe) — Moves the cursor to the beginning of the line containing the mark. Example:'a.
Special Marks:
``(two backticks) — Jumps back to the position before the last jump.
Combining Marks with Editing Commands:
Marks can be used as motion targets for operators, enabling operations over a range:
d'a— Deletes all lines from the current line to the line of mark a.y'a— Yanks all lines from the current line to mark a.d`a— Deletes text from the cursor to the exact position of mark a.
Example workflow: Place a mark at the start of a block with ma, move to the end of the block, and type d'a to delete the entire block in one command.
Marks thus combine navigation and editing, allowing precise operations across arbitrary regions of a file.
Explain the different modes of operation in the vi editor. How does a user switch between them?
The vi editor operates in three distinct modes:
- Command Mode (Normal Mode): This is the default mode when vi starts. Keystrokes are interpreted as commands to navigate, delete, copy, or manipulate text rather than being inserted as content.
- Insert Mode: In this mode, whatever the user types is inserted into the file as text. It is entered from command mode using commands like
i,a,o, etc. - Ex Mode (Last Line Mode / Command Line Mode): Entered by pressing
:from command mode. It is used for file operations such as saving, quitting, searching, and substitution.
Switching between modes:
- From Command Mode to Insert Mode: press
i,a,o,I,A, orO. - From Insert Mode back to Command Mode: press the
Esckey. - From Command Mode to Ex Mode: press
:. - From Ex Mode back to Command Mode: press
Escor execute the command.
Understanding these modes is fundamental to using vi efficiently, as the same key can have completely different effects depending on the current mode.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →