Visual Mode

Select text with v, V and Ctrl-V and then act on it: block inserts and appends, column edits, ranges, and when an operator is the better tool.

By The Dark DebuggerUpdated 21 min read

Visual mode is Vim's "select first, then act" mode. This article covers the three kinds of selection (v, V and Ctrl-V), the operators that work on them, block inserts and appends for editing many lines at once, and the cases where a selection is the wrong tool. It assumes you know Normal-mode operators and text objects from Operators, Motions, and Text Objects and the :s command from Search and Replace.

Why a selection helps

In Normal mode you name the action first and the text second: d2j deletes this line and the two below it. That is fast when you can count, and annoying when you can't. Picture a Kubernetes manifest where you need to comment out a resources: block, or a hosts file where every name needs staging changed to prod in the middle of the line. You want to see exactly what will change before you change it.

Visual mode flips the order. You start a selection, move the cursor with any motion you already know, watch the highlighted region grow, and only then press the operator. It also gives you one thing Normal mode can't do at all: rectangular (block) selections, which let you edit a column of text on many lines in one go.

Throughout this article, keystrokes are written in Vim's own notation: <C-v> is Ctrl-V, <Esc> is Escape, <CR> is Enter and <Space> is a literal space you type.

The three Visual modes

KeyModeSelectsStatus line shows
vcharacterwisefrom the start position to the cursor, like a mouse drag-- VISUAL --
Vlinewisewhole lines-- VISUAL LINE --
<C-v>blockwisea rectangle: the same columns on every line-- VISUAL BLOCK --

Press the key, move with any motion (w, e, j, }, G, /pattern<CR>, f, …), then press an operator. <Esc> cancels the selection without doing anything. Pressing one of the other two keys while selecting switches the selection type in place: start with v, realise you want whole lines, press V.

When I opened the hosts file below in a 60-column terminal, searched for staging, and selected a block with <C-v>3je, the bottom line of the screen read:

-- VISUAL BLOCK --              4x7       4,26          All

4x7 is the size of the selection (4 lines by 7 columns). It appears because showcmd is on, which Vim's defaults.vim enables when you don't have a vimrc of your own. With v it shows a character count, with V a line count. Glance at it before you press d.

Operating on a selection

Almost every operator you use in Normal mode works on a selection. The ones you'll reach for most:

KeyAction on the selection
d or xdelete
c or sdelete and start Insert mode
yyank (copy)
p / Preplace the selection with a register (P leaves the register alone)
> / <shift lines right / left by shiftwidth
=re-indent using the file type's indent rules
J / gJjoin the lines (with / without adding spaces)
u / U / ~lowercase / uppercase / toggle case
r{char}replace every selected character with {char}
gqre-wrap to textwidth
g<C-a>increment numbers, adding 1 more on each line
:run an Ex command on the selected lines
!filter the selected lines through a shell command

Here is a linewise example. This nginx server block has no indentation:

server {
listen 443 ssl;
server_name shop.example.com;
ssl_certificate /etc/ssl/shop.crt;
}
2G      go to "listen"
V       start a linewise selection
jj      extend it over the next two lines
>       shift them right
server {
	listen 443 ssl;
	server_name shop.example.com;
	ssl_certificate /etc/ssl/shop.crt;
}

The indent is a tab because Vim's defaults are shiftwidth=8 and noexpandtab. Setting :set shiftwidth=4 expandtab (or a per-filetype setting, covered in Configuring Vim) gives you four spaces instead.

Moving the other end with o

A selection has two ends: where you started and where the cursor is. Only the cursor end moves. If you started one word too late, you don't need to start over. Press o to jump to the other end, then keep moving.

ERROR checkout-api: payment declined for order 88412
/declined<CR>     put the cursor on "declined"
ve                select "declined"
o                 jump to the start of the selection
b                 extend it backwards over "payment"
c                 change the selection...
card declined     ...type the replacement
<Esc>
ERROR checkout-api: card declined for order 88412

In block mode, o jumps to the diagonally opposite corner and O jumps to the other corner on the same line, so you can grow a rectangle in any direction.

Reselecting with gv, and the '< and '> marks

Every operator ends Visual mode. To get the same selection back, press gv. The usual use is applying a second operator to the same lines. Starting again from the unindented nginx block:

2GVjj>      select three lines and indent them once
gv>         reselect the same lines and indent again
server {
		listen 443 ssl;
		server_name shop.example.com;
		ssl_certificate /etc/ssl/shop.crt;
}

. would have done the same here (2GVjj>.), because repeating a visual operation applies it to the same number of lines from the cursor. That "same size" rule matters later.

Vim remembers the selection in two marks: '< is its first line and '> its last. You can jump to them like any mark ('< moves to the first selected line), and they are what Ex commands use, as we'll see shortly.

Visual mode and text objects

Text objects work inside Visual mode, and they are often the fastest way to make a precise selection: viw selects a word, vi" the inside of a string, vip a paragraph, vi{ the inside of a brace block, vit the inside of an HTML tag. The selection stays open, so you can extend it further before acting.

Changing an image tag in a Kubernetes deployment, without caring where the cursor is on the line:

          image: "registry.example.com/shop/checkout-api:1.4.2"
11G                                              go to the image line
vi"                                              select everything inside the quotes
c                                                change it
registry.example.com/shop/checkout-api:1.5.0     type the new value
<Esc>
          image: "registry.example.com/shop/checkout-api:1.5.0"

vip is the one I use most: it selects the block of lines around the cursor up to the blank lines on either side. Sorting just the first group in a requirements.txt:

requests==2.32.3
flask==3.0.3
gunicorn==22.0.0
boto3==1.35.10
 
pytest==8.3.2
black==24.8.0
gg          first line
vip         select the paragraph (the first four lines)
:sort<CR>   Vim fills in :'<,'> for you, so this runs :'<,'>sort
boto3==1.35.10
flask==3.0.3
gunicorn==22.0.0
requests==2.32.3
 
pytest==8.3.2
black==24.8.0

The test dependencies below the blank line are untouched.

Block mode: editing columns

<C-v> selects a rectangle. Deleting, changing and replacing then act on the same columns of every selected line. Two extra commands make block mode special: I inserts text before the block on every line, and A appends text after it.

Block insert: commenting out lines

This log-rotation script has three commands we want to disable for a test run:

#!/usr/bin/env bash
set -euo pipefail
echo "rotating logs in /var/log/checkout"
find /var/log/checkout -name '*.log' -mtime +7 -delete
gzip -9 /var/log/checkout/*.log.1
systemctl reload checkout-api
echo "done"
4G          go to the find line
<C-v>       start a block selection
2j          extend down to the systemctl line
I           insert before the block
#<Space>    type "# "
<Esc>       leave Insert mode: Vim now repeats the text on every line
#!/usr/bin/env bash
set -euo pipefail
echo "rotating logs in /var/log/checkout"
# find /var/log/checkout -name '*.log' -mtime +7 -delete
# gzip -9 /var/log/checkout/*.log.1
# systemctl reload checkout-api
echo "done"

While you type, the text appears only on the first line. That is normal; the other lines are filled in when you press <Esc>. To undo the commenting, select the two comment characters as a block and delete them:

4G<C-v>2jld     line 4, block down two lines, one column wider, delete

When I ran diff against the original file afterwards, there was no difference.

I and A only repeat across lines in block mode. When I tried VjjI>><Space><Esc> on a three-line file in linewise mode, Vim inserted >> on the first line only.

Block append on ragged lines: $A

Lines of different lengths are the normal case. A Dockerfile RUN instruction split over several lines needs a backslash at the end of each line but the last:

FROM debian:12-slim
RUN apt-get update && apt-get install -y --no-install-recommends
    ca-certificates
    curl
    postgresql-client
    && rm -rf /var/lib/apt/lists/*
COPY app /srv/app
2G          the RUN line
<C-v>3j     block over four lines
$           extend the block to the end of EVERY line, however long
A           append after the block
<Space>\    type " \"
<Esc>
FROM debian:12-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    curl \
    postgresql-client \
    && rm -rf /var/lib/apt/lists/*
COPY app /srv/app

Without $, the block has a fixed right edge, and A pads shorter lines with spaces up to that edge. That is also useful: it gives you aligned backslashes. Starting from the same file, I made the block, moved its right edge to column 66 with 66|, and appended (lines 2 to 5 shown):

2G$<C-v>3j66|A<Space>\<Esc>
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates                                              \
    curl                                                         \
    postgresql-client                                            \

The opposite rule applies to I: a line that is too short to reach the block's left edge gets nothing inserted. Blank lines inside a commented-out block stay blank, which is usually what you want.

Adding a column to a CSV

$A doesn't care that CSV rows have different lengths, so it is a quick way to add a column at the end:

id,email,plan
101,ana@example.com,pro
102,raj.patel@example.org,free
103,mei@example.net,team
2G<C-v>G$A,active<Esc>     append ",active" to every data row
gg$a,status<Esc>           add the header by hand
id,email,plan,status
101,ana@example.com,pro,active
102,raj.patel@example.org,free,active
103,mei@example.net,team,active

A first column is the same idea with I at column 1: gg<C-v>GIeu-west-1,<Esc>, then fix the header with gg0ct,region<Esc>.

Block change, delete and replace

c on a block replaces the same columns on every line. In this hosts file the names line up, so staging sits in the same columns on all four lines:

10.20.1.11   web01.staging.internal   web01
10.20.1.12   web02.staging.internal   web02
10.20.1.21   api01.staging.internal   api01
10.20.1.22   api02.staging.internal   api02
/staging<CR>    jump to the first "staging"
<C-v>3je        a 4x7 block covering the word on every line
c               change it
prod<Esc>       type the replacement once
10.20.1.11   web01.prod.internal   web01
10.20.1.12   web02.prod.internal   web02
10.20.1.21   api01.prod.internal   api01
10.20.1.22   api02.prod.internal   api02

r{char} fills the whole block with one character. Before pasting log lines into a ticket, you can mask the middle of API keys:

gg/sk_live_<CR>     first key
8l                  skip past "sk_live_"
<C-v>jj7l           an 8-column block on three lines
r*                  replace every character in it with *
2026-11-09 10:42:17 auth ok key=sk_live_********7b1d user=ana
2026-11-09 10:42:19 auth ok key=sk_live_********6c5d user=raj
2026-11-09 10:43:02 auth ok key=sk_live_********a1f8 user=mei

Numbering lines with g<C-a>

<C-a> adds one to the number under or after the cursor. In Visual mode, g<C-a> adds 1 to the first selected line, 2 to the second, and so on, which turns copies of one line into a sequence. Building an Ansible inventory from a single line:

[web]
web-00.prod.internal
:set nrformats+=unsigned<CR>    treat "-00" as a number, not minus zero
2Gyy5p                          five copies of line 2
2GVG                            select all six host lines
g<C-a>                          increment progressively
[web]
web-01.prod.internal
web-02.prod.internal
web-03.prod.internal
web-04.prod.internal
web-05.prod.internal
web-06.prod.internal

The nrformats line matters with hyphenated names; the Common mistakes section shows what happens without it.

Ex commands on a selection

Press : while a selection is active and Vim puts :'<,'> on the command line: the range "from the first selected line to the last". Anything you type after it runs on those lines:

:'<,'>sort
:'<,'>s/http:/https:/g
:'<,'>normal A;
:'<,'>!column -t

The last one sends the lines to a shell command and replaces them with its output. It is the quickest way to align a messy table:

web01 10.20.1.11 running 14d
api01 10.20.1.21 running 3d
db-primary 10.20.2.5 running 41d
cache01 10.20.3.7 stopped 0d
ggVG            select every line
!column -t<CR>  Vim shows :'<,'>!column -t and runs it
web01       10.20.1.11  running  14d
api01       10.20.1.21  running  3d
db-primary  10.20.2.5   running  41d
cache01     10.20.3.7   stopped  0d

Ranges, :normal and filters get a full treatment in Ex Commands, Ranges, and :global.

Limiting :s to the selected columns with \%V

'<,'> is always a range of whole lines, even when you selected a block or a few characters. To restrict a substitution to the selected text, add \%V to the pattern: it matches only inside the last Visual area.

host     cpu_pct  mem_pct
web01    85       40
web02    40       85
db01     85       90

To change 85 to 95 in the mem_pct column only, select that column as a block and use \%V:

/mem_pct<CR>j               the first value under mem_pct
<C-v>2jl                    a 3x2 block over the column
:s/\%V85/95/g<CR>           Vim shows :'<,'>s/\%V85/95/g
host     cpu_pct  mem_pct
web01    85       40
web02    40       95
db01     85       90

When Visual mode is the wrong tool

Visual operations repeat by size, not by meaning. . after a visual change repeats it on the same number of characters (or lines) starting at the cursor. Watch what happens when you uppercase log levels of different lengths:

level=debug
level=warning
level=critical
gg0f=l      cursor on "debug"
viwU        select the word, uppercase it
j.          next line, repeat
j.          and again
level=DEBUG
level=WARNIng
level=CRITIcal

The selection was 5 characters, so . uppercased 5 characters each time. The operator plus text object version repeats the meaning, "this word":

gg0f=lgUiwj.j.
level=DEBUG
level=WARNING
level=CRITICAL

The same applies to macros (see Macros and Registers): a recorded selection replays its size, which breaks on lines of different lengths. My rule of thumb:

  • Use an operator and a text object (ciw, dap, gUiw, >ip) when the edit might be repeated with . or recorded in a macro.
  • Use Visual mode when you need to see the extent before acting, when there is no convenient motion or text object for the region, and for anything column-shaped, where block mode has no Normal-mode equivalent.

Where you'll use this

Visual mode earns its keep in config files, data files and code reviews, where edits are shaped like blocks and columns:

  • Temporarily disabling config or script lines: block-insert # (or // , -- ) in front of a few lines, and delete the two-column block to restore them.
  • Column edits in fixed-width files: hosts files, /etc/fstab, aligned tables in logs and reports. Block c, r and \%V substitutions change one column without touching the others.
  • Generating repetitive config: copy one line, select the copies, g<C-a> to number them.
  • Tidying data before you paste it somewhere: :'<,'>!column -t, :'<,'>sort u, masking secrets with block r*.

A complete example: disabling a service's resource limits in the Kubernetes manifest from earlier (lines 12 to 15) for a load test.

          resources:
            limits:
              cpu: "500m"
              memory: "512Mi"

YAML's indent rules interfere with typing # (the first mistake below explains why), so switch that rule off for this buffer first, then block-insert as usual:

:setlocal indentkeys-=0#<CR>    stop "#" from re-indenting the line
12G<C-v>3j                      block over the four lines, at the "r" of resources
I#<Space><Esc>                  insert "# " on every line
          # resources:
          #   limits:
          #     cpu: "500m"
          #     memory: "512Mi"

The comment markers line up in one column and the nesting stays readable, so removing them later is a single <C-v>3jld. If you'd rather not touch options, a substitute on the selected lines never triggers indenting. 12GV3j followed by :s/^\(\s*\)/\1# /<CR> puts # after each line's own indentation:

          # resources:
            # limits:
              # cpu: "500m"
              # memory: "512Mi"

Both are valid YAML; I prefer the aligned column because it is easier to undo with a block.

Common mistakes

Block-commenting YAML or Python moves the comment

The first time I block-commented the resources: lines above with 12G<C-v>3jI#<Space><Esc>, the result was not what I typed:

            # resources:
            #   limits:
            #     cpu: "500m"
            #     memory: "512Mi"

The comments landed two columns to the right of resources:, and every line shifted. The cause is indentkeys. With file-type indenting on (which defaults.vim turns on), YAML's indent settings contain 0#, meaning "re-indent the line when # is typed as the first character". Typing # re-indented the first line, and the block insert then copied the extra spaces to every line:

:set indentkeys?
  indentkeys=!^F,o,O,0#,0},0],<:>,0-

Python has 0# too. Shell scripts and plain config files don't, which is why the rotate.sh example worked. Two fixes: run :setlocal indentkeys-=0# before the block insert (I did, and the comments lined up at the original column), or use the substitute shown in the previous section, which never triggers indenting.

:'<,'>s changes text you didn't select

You select one column as a block and run :s/85/95/g, expecting only that column to change:

host     cpu_pct  mem_pct
web01    95       40
web02    40       95
db01     95       90

Every 85 on the selected lines changed, including the CPU values. '<,'> is a line range; the column information is lost. Put \%V in the pattern: :'<,'>s/\%V85/95/g.

Pasting over a selection twice pastes the wrong thing

You yank pgbouncer and paste it over localhost on two lines with viwp:

# route everything through pgbouncer
db_host = localhost
replica_host = localhost
gg$yiw          yank "pgbouncer"
j$viwp          replace the first localhost
j$viwp          replace the second one
# route everything through pgbouncer
db_host = pgbouncer
replica_host = localhost

The second line didn't change. p in Visual mode puts the text it replaced into the unnamed register, so the second paste put back localhost. Use P instead (viwP), which leaves the register alone; with j$viwPj$viwP both lines ended up as pgbouncer. Pasting from the yank register with viw"0p works too, as explained in Macros and Registers.

g<C-a> eats the hyphen in host names

Without nrformats+=unsigned, the inventory example produced this:

[web]
web01.prod.internal
web02.prod.internal
web03.prod.internal
web04.prod.internal
web05.prod.internal
web06.prod.internal

Vim read -00 as the number minus zero, added to it, and the result no longer needed a sign. :set nrformats? shows nrformats=bin,hex by default; adding unsigned makes Vim ignore minus signs. Put set nrformats+=unsigned in your vimrc if you work with names like these often.

<C-v> pastes instead of starting a block

In Windows Terminal and some other terminal programs, Ctrl+V is bound to paste, so Vim never sees it. Vim accepts <C-q> as an alternative for starting a block selection (see :help CTRL-V-alternative), or you can remove the paste binding from the terminal's settings. I tested everything in this article in a Linux terminal, so I did not verify this one myself.

Summary

  • v selects characters, V whole lines, <C-v> a rectangle; press any of them to switch type mid-selection and <Esc> to cancel. showcmd displays the selection size.
  • Select, move with any motion or text object (vip, vi"), then apply an operator. o moves the other end of the selection; gv brings the last selection back.
  • In block mode, I and A insert and append on every line when you press <Esc>; $A appends at the end of ragged lines, a fixed right edge pads short lines.
  • : on a selection gives :'<,'>, a range of whole lines. Use \%V in the pattern to restrict a substitution to the selected columns.
  • !cmd filters the selection through a shell command: !column -t, !sort, !jq ..
  • Visual operations repeat by size, so prefer operator + text object (gUiw, ci") for edits you will repeat with . or record in a macro.
  • viwP replaces a selection without overwriting the register; g<C-a> numbers lines, with nrformats+=unsigned for names like web-01.

Exercises

Exercise 1: Disable two cron jobseasy

Create jobs.cron with this content, then comment out the three jobs from */5 to the weekly report with a block insert of # at column 1. Afterwards, restore them.

# m h dom mon dow command
15 2 * * * /opt/backup/run.sh --full
*/5 * * * * /opt/monitor/check-disk.sh
0 * * * * /opt/reports/hourly.sh
30 6 * * 1 /opt/reports/weekly.sh
Show Solution
3G0         line 3, column 1
<C-v>2j     a one-column block over three lines
I#<Esc>     insert "#" on all of them
# m h dom mon dow command
15 2 * * * /opt/backup/run.sh --full
#*/5 * * * * /opt/monitor/check-disk.sh
#0 * * * * /opt/reports/hourly.sh
#30 6 * * 1 /opt/reports/weekly.sh

To restore, select the same one-column block and delete it: 3G0<C-v>2jd. The file is back to the original. 3G moves to the first non-blank character of the line; the 0 makes sure the block starts in column 1 even if a line is indented.

Exercise 2: Fix a SQL column listeasy

The column list in this query is missing commas. Add a comma to the end of every column line except the last one (o.total_cents) with one block append.

SELECT
    o.id
    o.created_at
    c.email
    o.total_cents
FROM orders o JOIN customers c ON c.id = o.customer_id;
Show Solution
2G<C-v>2j$A,<Esc>
SELECT
    o.id,
    o.created_at,
    c.email,
    o.total_cents
FROM orders o JOIN customers c ON c.id = o.customer_id;

The block covers lines 2 to 4 only, and $ makes it end at each line's own end, so the commas land right after each name instead of being padded to one column.

Exercise 3: Generate database host namesmedium

Start from a file with [db] on line 1 and db-01.prod.internal on line 2. Using copies and g<C-a>, turn it into db-01 to db-04, keeping the hyphen.

Hint

Copy line 2 three times, then select only the copies, so the first host stays 01.

Show Solution
:set nrformats+=unsigned<CR>
2Gyy3p          three copies below line 2
3GVG            select the copies (lines 3 to 5)
g<C-a>          add 1, 2 and 3
[db]
db-01.prod.internal
db-02.prod.internal
db-03.prod.internal
db-04.prod.internal

Selecting from line 2 instead would have produced db-02 to db-05.

Exercise 4: Change one column onlymedium

Using the usage.txt table from the \%V section, change every 85 in the cpu_pct column to 95 without touching the memory column.

Show Solution
/cpu<CR>j                   first value under cpu_pct
<C-v>2jl                    a 3x2 block over the CPU column
:s/\%V85/95/g<CR>
host     cpu_pct  mem_pct
web01    95       40
web02    40       85
db01     95       90

web02's memory value is still 85. If you extend the block with $ instead of l, it covers both columns and both values change.

Exercise 5: Sort and align a status reporthard

This file has a title, a blank line, and an unaligned list of servers. Without touching the title, sort the server lines by status (third field), then by name, and align them into columns, all in one command.

Fleet status, 9 Nov
 
web01 10.20.1.11 running 14d
api01 10.20.1.21 running 3d
db-primary 10.20.2.5 running 41d
cache01 10.20.3.7 stopped 0d
api02 10.20.1.22 stopped 0d
Show Solution
3G                                  any line in the server list
vip                                 select the paragraph
!sort -k3,3 -k1,1 | column -t<CR>   filter it through a pipeline
Fleet status, 9 Nov
 
api01       10.20.1.21  running  3d
db-primary  10.20.2.5   running  41d
web01       10.20.1.11  running  14d
api02       10.20.1.22  stopped  0d
cache01     10.20.3.7   stopped  0d

Vim hands everything after ! to the shell, so pipes work. vip stops at the blank line, which keeps the title out of the filter.


Tested with: Vim 9.1 (Ubuntu 24.04 package 9.1.0016) on Ubuntu 24.04 (WSL2), November 2026. Every keystroke sequence was replayed exactly as written with vim -u DEFAULTS -s keys, and the before/after files are the real results; the status-line capture came from Vim running inside tmux. The YAML indent surprise was a genuine first result. The Windows Terminal <C-q> note was not tested.

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.