Editing Text: Insert, Delete, Change, Undo

The everyday Vim edits on real config, CSV and Python files: entering Insert mode, deleting, changing, copying and pasting, undo and redo, the dot command, and saving.

By The Dark DebuggerUpdated 20 min read

This article covers the edits you make all day: the six ways into Insert mode, deleting and changing text, replacing characters, joining lines, yank and put, undo and redo, the dot command, indenting, and every way to save and quit. It builds on the motions from Modes and Moving Around. The next article, Operators, Motions, and Text Objects, turns these commands into a general grammar.

Why Vim edits feel different

Say you have to fix a config before a deploy: a typo in a port number, a worker count, a debug flag left on, the wrong database host. In most editors each fix is "click, select, type". In Vim each fix is a short command that says exactly what to do: r0 replaces one character with 0, C rewrites the rest of the line, dd deletes a line. These commands are small, so they are fast to type. And because each one is a single unit, Vim can repeat it with . and undo it with u.

Every example below shows a real file before and after the exact keys. I ran each one in Vim 9.1 with its stock defaults.

Six ways into Insert mode

KeyStarts insertingTypical use
iBefore the cursorInsert in the middle of a line
aAfter the cursorAdd after the character you are on
IBefore the first non-blank character of the linePrefix a line (comment it out)
AAt the end of the lineAdd a semicolon or a trailing comment
oOn a new line belowAdd a line after this one
OOn a new line aboveAdd a line before this one

The file before:

def connect(host, port):
    return Connection(host, port)

The keys, one edit at a time (Esc ends each insert):

  1. f) then i, timeout=5: insert before the ).
  2. j then A # caller handles retries: append to the end of line 2.
  3. k then O@retry(times=3): open a line above line 1.
  4. j then o"""Open a connection to the primary database.""": open a line below def.

The file after:

@retry(times=3)
def connect(host, port, timeout=5):
    """Open a connection to the primary database."""
    return Connection(host, port)  # caller handles retries

I did not type the four spaces before the docstring. Vim's Python indent rules supplied them when o opened the line under def.

a matters when the cursor is on the character you want to follow. In the original file, f( then aself, (and Esc) gives:

def connect(self, host, port):

And I is the quickest way to comment out a line, wherever the cursor is. 2GI# on the original file:

def connect(host, port):
    # return Connection(host, port)

I skipped the indentation and inserted before return, which is what you want for a comment.

Deleting characters: x, X and the xp swap

x deletes the character under the cursor and X the one before it (like Backspace). Both take counts: 3x deletes three characters.

The classic trick is xp, which swaps two characters. Here is a comment with a typo:

# Retry if we recieve a 503

2fi jumps to the second i on the line (the first is in if), x cuts it, and p puts it back after the next character:

# Retry if we receive a 503

Deleting lines and to the end: dd, D

dd deletes the current line; 3dd deletes three. Here is an orders export with a test row that must not ship:

order_id,customer,amount,status
4411,acme-corp,129.00,paid
4412,globex,75.50,refunded
4413,TEST-DO-NOT-SHIP,0.00,test
4414,initech,310.25,paid
4415,umbrella,42.00,paid

4Gdd:

order_id,customer,amount,status
4411,acme-corp,129.00,paid
4412,globex,75.50,refunded
4414,initech,310.25,paid
4415,umbrella,42.00,paid

On the original file, 2G3dd deleted three lines starting at line 2 and left only the header, 4414 and 4415.

D deletes from the cursor to the end of the line. This line has a comment that must go before release:

log_level = DEBUG ; temporary, revert before release

Where you start D matters. f;D deletes from the ; and leaves a trailing space behind. t;D starts one character earlier, on the space. Shown with cat -A, which marks the end of each line with $:

log_level = DEBUG $
log_level = DEBUG$

The first line is from f;D, the second from t;D. Trailing whitespace like that is what makes linters and git diff complain later.

d combines with any motion: dw, d$, dG, dt,. That grammar has its own article, Operators, Motions, and Text Objects.

Changing text: c, cw, C, s, S

Change means "delete, then start Insert mode in the gap". It saves you the extra i after a delete, and as you will see in the dot command section, it makes the whole edit a single repeatable unit.

KeysDeletesThen inserts
cwTo the end of the word (the same as ce, not dw)In its place
CTo the end of the line (same as c$)At the end
cc / SThe whole line, keeping indentation when autoindent is onOn that line
sThe character under the cursorIn its place

Here is the [server] and [database] config again, before:

[server]
host = 0.0.0.0
port = 8O80
workers = 4
log_level = DEBUG ; temporary, revert before release
 
[database]
url = postgres://app@db-01:5432/orders
pool_size = 5
expires = 2026-01-15

Three edits:

  1. 4G$s8: on line 4, go to the last character and substitute it with 8.
  2. 5GfDcwINFO: on line 5, jump to D and change the word to INFO.
  3. 8GWWCpostgres://app@db-02:5432/orders: on line 8, skip two WORDs to the URL and Change to the end of the line.

After (lines 4, 5 and 8 changed):

[server]
host = 0.0.0.0
port = 8O80
workers = 8
log_level = INFO ; temporary, revert before release
 
[database]
url = postgres://app@db-02:5432/orders
pool_size = 5
expires = 2026-01-15

S (or cc) rewrites a line but keeps its indentation. In the Python file, 2GSreturn Connection(host, port, timeout=5) produced:

def connect(host, port):
    return Connection(host, port, timeout=5)

Python's indent settings turn on autoindent, so S kept the four spaces. In a plain text file with Vim's defaults, autoindent is off and S starts at column 1.

Replacing: r and R

r followed by a character replaces the character under the cursor and stays in Normal mode. No Esc needed. The port above has a capital O where a zero belongs: 3GfOr0 gives port = 8080.

R enters Replace mode: everything you type overwrites what is there, one character for one character. It is ideal for fixed-width values such as dates. 10Gf2R2026-12-31 then Esc on expires = 2026-01-15:

expires = 2026-12-31

In Replace mode, Backspace restores the original characters instead of deleting them.

Joining lines: J and gJ

J joins the next line onto the current one. It removes the next line's leading whitespace and puts in a single space. gJ joins without touching whitespace. A SQL query split over three lines:

SELECT id, customer, amount
    FROM orders
    WHERE status = 'paid';

JJ (or 3J, which joins three lines in one go):

SELECT id, customer, amount FROM orders WHERE status = 'paid';

gJgJ, which kept the four-space indents:

SELECT id, customer, amount    FROM orders    WHERE status = 'paid';

Yank and put: y, yy, p, P

Vim's word for copy is yank. yy yanks the current line, y plus a motion yanks whatever the motion covers, and every delete also stores what it removed, so d works as cut. p puts (pastes) after the cursor and P before it. Whole lines go below the current line with p and above it with P.

An nginx upstream block:

upstream app {
    server 10.0.1.12:8080;
    server 10.0.1.15:8080;
}

3Gyyp duplicates the second server line, ready to edit into a third backend:

upstream app {
    server 10.0.1.12:8080;
    server 10.0.1.15:8080;
    server 10.0.1.15:8080;
}

2Gddp swaps two lines: dd cuts line 2, and the cursor lands on the line that moved up; p puts the cut line below it:

upstream app {
    server 10.0.1.15:8080;
    server 10.0.1.12:8080;
}

And 3GyyggP yanks line 3, jumps to the top, and puts it above line 1:

    server 10.0.1.15:8080;
upstream app {
    server 10.0.1.12:8080;
    server 10.0.1.15:8080;
}

Where your yanks and deletes are stored, and how to keep several at once, is covered in Macros and Registers. The one register gotcha you need today is in Common mistakes below.

Undo and redo: u, Ctrl-R, U

u undoes the last change and Ctrl-R redoes it. Vim keeps every change, and the message line tells you where you are in the history. A JavaScript file missing semicolons:

const port = process.env.PORT || 8080
const host = process.env.HOST || "0.0.0.0"
const workers = Number(process.env.WORKERS) || 4

I ran A; (then Esc) on line 1, jA; on line 2, then u. The second semicolon disappeared and Vim reported:

1 change; before #2  0 seconds ago                            2,42          All

Ctrl-R put it back:

1 change; after #2  1 second ago                              2,43          All

#2 is the change number. One "change" is one command: a dd, an x, or everything typed between entering Insert mode and pressing Esc. If you type three paragraphs in one Insert session, one u removes all three. When you want finer undo steps while writing, leave Insert mode now and then.

U (capital) is different: it undoes all recent changes on the current line at once. On line 2 I appended ; and then inserted export at the start (2GA; Esc Iexport Esc):

export const host = process.env.HOST || "0.0.0.0";

U restored the original line in one step, and pressing U again re-applied both edits, because U itself counts as a change. Most of the time plain u is what you want; U is for "put this line back how it was".

Vim's undo history is a tree, not a line, so it is hard to lose work. :earlier 10m and :later 10m move through it by time, and the undofile option keeps history after you close the file (Configuring Vim).

The dot command

. repeats the last change. The same change, at the cursor's current position. This is the most valuable key in Vim, and the reason for the advice "make each edit one command".

Adding semicolons to every line of the JavaScript file above takes A; (and Esc), then j. and j.:

const port = process.env.PORT || 8080;
const host = process.env.HOST || "0.0.0.0";
const workers = Number(process.env.WORKERS) || 4;

A; works with . because it does not depend on where the cursor is on the line: "append at the end" means the same thing on every line. Now look at an edit that does depend on the cursor. This logging config needs DEBUG changed to INFO on three lines:

loggers:
  app: DEBUG
  db: DEBUG
  http: DEBUG
  cache: WARN

I changed the first with 2GfDcwINFO (then Esc), then tried j. j.:

loggers:
  app: INFO
  db: DEBUINFO
  http: DEBUINFO
  cache: WARN

j keeps the column, and DEBUG starts in a different column on each line, so cw started in the wrong place. The fix is to let a search put the cursor at the start of the match. /DEBUG and Enter jumps to the first DEBUG, cwINFO and Esc changes it, and then n. (next match, repeat) twice:

loggers:
  app: INFO
  db: INFO
  http: INFO
  cache: WARN

n. lets you look at each match before changing it. Press n again to skip one. Search and Replace covers / in depth, and the pattern "search, change, n." comes up again there.

Dot also takes a count. In the orders CSV, 2Gdd deleted line 2, and then 2. repeated the delete with a count of 2, removing two more lines in one keystroke.

The rule to take away: put the cursor somewhere predictable (A, I, a search, f), then make the edit one command (c, d, A), so . can repeat it.

Indenting: >> and <<

>> shifts a line right by shiftwidth columns and << shifts it left. 3>> shifts three lines. The amount depends on settings, and this is where people get surprised. In a .conf file with no vimrc, :set shiftwidth? expandtab? tabstop? showed Vim's built-in defaults:

  shiftwidth=8
noexpandtab
  tabstop=8

So >> adds 8 columns as a tab character. On the nginx block, 2G>> and j>>, shown with cat -A (tabs appear as ^I):

upstream app {$
^I    server 10.0.1.12:8080;$
^I    server 10.0.1.15:8080;$
}$

A tab plus the original four spaces is not what anyone wants. Set the width and tell Vim to use spaces, then shift: :set shiftwidth=4 expandtab, then 2G2>>:

upstream app {$
        server 10.0.1.12:8080;$
        server 10.0.1.15:8080;$
}$

Python files behave because Vim's Python settings already use shiftwidth=4 and expandtab. Put the settings you want for everything else in your vimrc (the starter file in Installing Vim does this). > and < also work as operators with motions, such as >ip for a paragraph, covered in the next article.

Saving and quitting, properly

CommandDoes
:wWrite the file
:w newnameWrite a copy to newname; the buffer still belongs to the original file
:wqWrite (always) and quit
:x or ZZWrite only if there are changes, then quit
:q! or ZQQuit without writing
:w !cmdSend the buffer to a shell command's input; the file is not written

:wq vs :x. Both save and quit, but :wq writes even when nothing changed. That updates the file's modification time, which can trigger rebuilds, config reloads and "file changed" warnings for no reason. I set a file's time to 09:00, opened it, and quit without editing:

stat -c '%y' app.ini
2026-11-09 09:00:00.000000000 -0500

After :x the time was still 09:00:00. After :wq it became 21:51:52, the moment I quit. I use :x (or ZZ) by default.

:w newname keeps you on the original. After changing workers = 4 to 8 and running :w app.ini.new, Vim confirmed "app.ini.new" [New] 10L, 187B written. But :q still refused with E37, because the original file had not been saved. On disk:

app.ini:workers = 4
app.ini.new:workers = 8

Use :saveas newname if you want the buffer to switch to the new name.

:w !cmd pipes the buffer to a command. It is a quick way to ask questions about unsaved text:

:w !wc -l
6
:w !grep -c paid
3

Files you are not allowed to write. Open a root-owned file as a normal user and Vim marks it read-only in the message line: "/etc/hosts" [readonly] 12L, 427B. After an edit, :w says:

E45: 'readonly' option is set (add ! to override)

and :w! gets as far as the operating system, which says no:

"/etc/hosts" E212: Can't open file for writing

The well-known escape hatch is this:

:w !sudo tee % > /dev/null

Read it with the previous section in mind. :w !cmd sends the buffer to a command, % expands to the current file name, and sudo tee /etc/hosts writes its input to that file as root. > /dev/null throws away the copy tee would echo back. Vim then notices that the file changed on disk and asks whether to reload it. The mechanism works without sudo too. In the orders CSV, after deleting the test row, :w !tee orders.clean.csv > /dev/null wrote the edited buffer to a new file and left the original untouched:

order_id,customer,amount,status
4411,acme-corp,129.00,paid
4412,globex,75.50,refunded
4414,initech,310.25,paid
4415,umbrella,42.00,paid

My recommendation, though, is to start with sudoedit /etc/hosts (or sudo -e). It copies the file to a temporary location, runs your Vim with your settings as you, and writes the result back as root when you quit. No editor runs as root, and the sudo password prompt happens before Vim starts, not in the middle of a write.

Where you'll use this

Here is the full pre-deploy cleanup of the config from earlier, done the way you would do it on a server. The file before:

[server]
host = 0.0.0.0
port = 8O80
workers = 4
log_level = DEBUG ; temporary, revert before release
 
[database]
url = postgres://app@db-01:5432/orders
pool_size = 5
expires = 2026-01-15

The keys, one fix each:

KeysFix
3GfOr0Port typo: letter O to zero
4G$s8 EscWorkers 4 to 8
5GfDCINFO EscLog level to INFO and drop the "temporary" comment in one command
8Gf1r2Database host db-01 to db-02
9Gopool_timeout = 10 EscNew setting after pool_size
11Gf2R2027-01-15 EscOverwrite the expiry date (it moved to line 11 because of the new line)
:xSave and quit

diff -u against a copy of the original shows exactly those changes and nothing else:

--- app.ini.orig	2026-11-10 01:26:23.505434041 -0500
+++ app.ini	2026-11-10 01:26:27.258613834 -0500
@@ -1,10 +1,11 @@
 [server]
 host = 0.0.0.0
-port = 8O80
-workers = 4
-log_level = DEBUG ; temporary, revert before release
+port = 8080
+workers = 8
+log_level = INFO
 
 [database]
-url = postgres://app@db-01:5432/orders
+url = postgres://app@db-02:5432/orders
 pool_size = 5
-expires = 2026-01-15
+pool_timeout = 10
+expires = 2027-01-15

Six fixes, about 60 keystrokes, no mouse, and no "oops, I also deleted a bracket". The same edits come up when you rotate hostnames in an inventory file, bump versions in a manifest, or clean up a CSV export before importing it.

Common mistakes

p pastes what you deleted, not what you yanked. Deletes go into the same default register as yanks. I yanked the 4411 row (2Gyy), deleted the test row (4Gdd), went to the end and pressed p:

order_id,customer,amount,status
4411,acme-corp,129.00,paid
4412,globex,75.50,refunded
4414,initech,310.25,paid
4415,umbrella,42.00,paid
4413,TEST-DO-NOT-SHIP,0.00,test

The test row came back, which is exactly what you were trying to remove. :registers 0 1 " shows why:

:registers 0 1 "
Type Name Content
  l  ""   4413,TEST-DO-NOT-SHIP,0.00,test^J
  l  "0   4411,acme-corp,129.00,paid^J
  l  "1   4413,TEST-DO-NOT-SHIP,0.00,test^J
Press ENTER or type command to continue

"" (the default) holds the delete. Register 0 always holds the last yank, and deletes never overwrite it. "0p pasted the 4411 row as intended.

>> inserts tabs. With no vimrc, shiftwidth=8 and noexpandtab mean >> inserts a tab character, as shown above. Set shiftwidth and expandtab in your vimrc.

j. hits the wrong column. The dot command repeats the change at the cursor. If the cursor is not at the equivalent spot, you get DEBUINFO. Move with something that finds the target (/, f, A, I) before pressing ..

u undid more than expected. One Insert session is one undo step. If you typed for five minutes without pressing Esc, u removes all of it. Ctrl-R brings it back.

Summary

  • Insert with i/a (before/after the cursor), I/A (start/end of the line) and o/O (new line below/above). Esc ends the insert, and the whole insert counts as one change.
  • x deletes a character, xp swaps two, dd deletes a line, D deletes to the end of the line (t;D avoids leaving a trailing space).
  • c changes: cw, C, cc/S, s. r replaces one character without leaving Normal mode; R overtypes.
  • J joins lines with a space, gJ without changing whitespace.
  • yy/p/P copy and paste lines; ddp swaps two lines. Deletes overwrite the default register, but "0p always pastes the last yank.
  • u undoes, Ctrl-R redoes, U restores the whole line. One Insert session is one undo step.
  • . repeats the last change. Position the cursor predictably (search, f, A, I) and make each edit one command.
  • :x/ZZ write only when there are changes; :wq always writes. :w !cmd pipes the buffer; prefer sudoedit to :w !sudo tee %.

Exercises

The files are the ones used above: retry.py, orders.csv, app.ini and the nginx upstream.conf.

Exercise 1: Fix a transposed typoeasy

Fix recieve in # Retry if we recieve a 503 with two editing keys once the cursor is in place.

Show Solution

2fi puts the cursor on the misplaced i (the first i on the line is in if). Then xp:

# Retry if we receive a 503
Exercise 2: Remove a row and swap two rowseasy

In orders.csv, delete the TEST-DO-NOT-SHIP row, then put 4415 before 4414. Save with :wq.

Show Solution

4Gdd deletes the test row; the cursor is now on 4414. ddp swaps it with the line below:

order_id,customer,amount,status
4411,acme-corp,129.00,paid
4412,globex,75.50,refunded
4415,umbrella,42.00,paid
4414,initech,310.25,paid

I ran it as 4Gddddp. Read it as two commands: 4Gdd, then ddp.

Exercise 3: Comment out a block with the dot commandmedium

Comment out the three commands in this script (lines 2 to 4) using one insert and the dot command:

#!/usr/bin/env bash
systemctl stop legacy-sync.timer
systemctl disable legacy-sync.timer
rm -f /etc/cron.d/legacy-sync
echo "legacy sync disabled"
Show Solution

2GI# and Esc, then j. j.:

#!/usr/bin/env bash
# systemctl stop legacy-sync.timer
# systemctl disable legacy-sync.timer
# rm -f /etc/cron.d/legacy-sync
echo "legacy sync disabled"

I always inserts before the first non-blank character, so the repeat works on every line, whatever the column. Visual Mode shows a block-selection way to do the same.

Exercise 4: Walk the undo historymedium

In app.ini: change workers = 4 to 8, fix the port typo, then delete the last line. Now undo twice and redo once. Before you save, predict the state of the port, workers and expires lines.

Show Solution

Keys: 4G$s8 Esc, 3GfOr0, Gdd, then u u and Ctrl-R, then :wq.

port = 8080
workers = 8
expires = 2026-01-15

The first u restored the deleted expires line, the second undid the port fix, and Ctrl-R redid the port fix. The workers change was never undone. wc -l confirmed the file still has all 10 lines.

Exercise 5: Indent with spaces, not tabshard

In upstream.conf, shift both server lines one level further right so they use 8 spaces in total and no tab characters. Check your result with cat -A.

Hint

>> uses shiftwidth, and only expandtab turns the inserted whitespace into spaces.

Show Solution
:set shiftwidth=4 expandtab

Then 2G2>> and :wq:

cat -A upstream.conf
upstream app {$
        server 10.0.1.12:8080;$
        server 10.0.1.15:8080;$
}$

No ^I anywhere, so there are no tabs. Without the :set, the same keys produced ^I server ..., a tab in front of the existing spaces.


Tested with: Vim 9.1.0016 on Ubuntu 24.04 (WSL2), November 2026, with Vim's stock defaults.vim and no personal vimrc. Every before/after pair was produced by sending the exact keys shown to a real Vim session and printing the saved file. The /etc/hosts errors came from opening the root-owned file as a normal user. :w !sudo tee % and sudoedit were not run, because the lab account has no sudo; the tee mechanism was tested without sudo, as shown.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Vim tutorial here is tested end to end before publishing.