Modes and Moving Around

Vim's five modes and how to switch between them, then every motion you need: words, lines, characters, paragraphs, screens, marks and the jump list.

By The Dark DebuggerUpdated 22 min read

This article covers Vim's modes in detail and then the motions that move the cursor: by word, within a line, to a character, by paragraph and screen, to a line number or matching bracket, and back to where you were with marks and the jump list. It assumes you have finished Introduction to Vim and have a working Vim from Installing Vim. Every motion here is also an argument to the editing commands in Editing Text and Operators, Motions, and Text Objects, so time spent here pays off twice.

Why moving well matters

A Python traceback says the bug is on line 18 of a 300-line file. Holding j gets you there in about four seconds, and you overshoot. Typing 18G gets you there in under one. On line 18, the bad key is inside counts[record["code"]]. Tapping l twenty times is slow; f" (jump to the next ") takes two keystrokes.

That is the whole idea of this article. Vim gives you a motion for nearly every "go there" thought, and each one is a couple of keys. You do not need all of them on day one. Learn w, b, f, G and Ctrl-O first, and add the rest as you notice yourself tapping the same key over and over.

How I show cursor positions

A cursor does not show up in a text file, so most examples below use a caret diagram. I ran the keys in Vim 9.1, recorded the cursor column after each keypress (:echo col('.') gives the same number), and drew a ^ under each spot. The first caret is always where the cursor started. When a motion moves between lines, I give positions as line,column, which is the same format Vim shows in the bottom-right corner (the "ruler").

Most examples use this real 40-line script, health_check.py:

#!/usr/bin/env python3
"""Poll service health endpoints and report failures."""
 
import json
import sys
import time
from urllib.request import urlopen
 
SERVICES = {
    "api": "http://10.0.1.12:8080/healthz",
    "auth": "http://10.0.1.15:9000/status",
    "billing": "http://10.0.1.21:8080/healthz",
}
TIMEOUT_SECONDS = 3
 
 
def check(name, url):
    started = time.monotonic()
    try:
        with urlopen(url, timeout=TIMEOUT_SECONDS) as resp:
            ok = resp.status == 200
    except OSError as exc:
        print(f"{name}: unreachable ({exc})", file=sys.stderr)
        return False
    elapsed_ms = (time.monotonic() - started) * 1000
    print(f"{name}: {'ok' if ok else 'FAIL'} in {elapsed_ms:.0f} ms")
    return ok
 
 
def main():
    results = {name: check(name, url) for name, url in SERVICES.items()}
    failed = [name for name, ok in results.items() if not ok]
    if failed:
        print(json.dumps({"failed": failed}))
        return 1
    return 0
 
 
if __name__ == "__main__":
    sys.exit(main())

The five modes and how to switch

ModeWhat keys doEnter it withBottom line shows
NormalRun commands and motionsEsc from any other mode (it is also where Vim starts)nothing
InsertType texti, a, o, I, A, O (see Editing Text)-- INSERT --
VisualSelect text, then act on itv characters, V lines, Ctrl-V a block-- VISUAL --, -- VISUAL LINE --, -- VISUAL BLOCK --
Command-lineType an Ex command or a search:, / or ?the :, / or ? you typed
ReplaceOvertype existing textR-- REPLACE --

These are the exact bottom lines Vim 9.1 drew for each mode in my test session:

-- VISUAL --                                        1         1,1           Top
-- VISUAL LINE --                                   1         1,1           Top
-- VISUAL BLOCK --                                  1x1       1,1           Top
-- REPLACE --                                                 1,1           Top

The number in the middle is the selection size (1 character, 1 line, a 1x1 block). It comes from the showcmd option, which Vim's defaults turn on. The same spot shows a half-typed command: after pressing d and before giving it a motion, the bottom line looked like this:

                                                    d         1,1           Top

That in-between state is called Operator-pending mode. Vim is waiting for a motion to tell d what to delete. Press Esc to cancel it.

Two more things are worth knowing now:

  • Ctrl-O in Insert mode runs one Normal-mode command and drops you back into Insert mode. The bottom line shows -- (insert) -- while Vim waits for that command. Ctrl-O then $, for example, jumps to the end of the line without leaving Insert mode.
  • Leaving a mode. Esc returns to Normal mode from everywhere. Ctrl-[ sends the same key code as Esc and is easier to reach on some keyboards. Ctrl-C also gets you out of Insert mode, but it skips some things Esc does. When I typed 3i-ab and pressed Esc, the line got -ab-ab-ab; ending the same insert with Ctrl-C gave a single -ab. Make Esc the habit.

Visual Mode covers selections in depth, and the Command-line mode is the subject of Ex Commands, Ranges, and :global.

hjkl, and why not the arrow keys

h j k l move left, down, up and right. They come from the ADM-3A terminal that vi was written on, whose keyboard printed arrows on those four keys. The reason to use them today is practical: they sit under your right hand on the home row, so moving never means leaving the letters.

Arrow keys work fine in Vim and nobody will take them away. But a count makes the home-row keys much more useful: 5j moves down five lines, and 5j is also what you will type after an operator (d5j deletes six lines). Single-step movement is the slowest way to move, though. Most of this article is about not needing it.

Word motions: w, b, e and W, B, E

Vim has two definitions of a word:

  • A word (lowercase motions) is a run of letters, digits and underscores, or a run of other non-blank characters. urlopen is a word, and so is ( and =.
  • A WORD (uppercase motions) is any run of non-blank characters. urlopen(url, is one WORD.

The difference is clearest on punctuation-heavy code. Starting on with (line 20), I pressed w eleven times:

        with urlopen(url, timeout=TIMEOUT_SECONDS) as resp:
        ^    ^      ^^  ^ ^      ^^              ^ ^  ^   ^

w stopped on every bracket, comma and =. From the same start, W pressed five times:

        with urlopen(url, timeout=TIMEOUT_SECONDS) as resp:
        ^    ^            ^                        ^  ^

Four W presses reach resp; it takes ten w presses. The fifth W went on to the next line (position 21,13, the start of ok). Rule of thumb: use w to move within an expression, and W to skip over it.

e and E move to the end of the word or WORD instead of the start:

        with urlopen(url, timeout=TIMEOUT_SECONDS) as resp:
        ^  ^       ^^  ^^       ^
        with urlopen(url, timeout=TIMEOUT_SECONDS) as resp:
        ^  ^            ^                        ^  ^     ^

Going backwards: b and B move to the start of the previous word or WORD, and ge and gE to the end of the previous one. From the final : (column 59), b b b stopped at columns 55 (resp), 52 (as) and 50 ()). From the same spot, B B reached 55 and 52, then ge went to 50 and gE to 25 (the comma that ends the WORD urlopen(url,).

Moving within a line: 0, ^, $ and g_

This Markdown line starts with four spaces of indentation and ends with three trailing spaces:

    - Fixed: retry storm when the auth service times out.   
^   ^                                                   ^  ^
0   ^                                                   g_ $
KeyGoes toColumn on this line
0First column, even if it is whitespace1
^First non-blank character5
$Last character, including trailing whitespace60
g_Last non-blank character57

^ is the one you usually want in code, because indentation is rarely what you came for. g_ is the counterpart at the other end; its main use is yg_ and dg_, which act up to the last real character and leave trailing spaces alone.

Jumping to a character: f, t, ; and ,

f followed by a character jumps forward to the next occurrence of that character on the current line. t jumps to just before it. F and T do the same backwards. Then ; repeats the last jump and , repeats it in the opposite direction.

Here is a log line, with 0 first and then f: ; ; (the fourth press, ,, went back to column 17):

2026-11-09 14:02:17 ERROR [billing] payment 4417 failed: card_declined (attempt 2/3)
             ^  ^                                      ^

The first two colons are in the timestamp, and the third ends failed:. A count picks the nth match directly: 3f: from the start of the line went straight to column 56.

t( stops one column short of the (, which is exactly where you want to be before deleting up to it:

2026-11-09 14:02:17 ERROR [billing] payment 4417 failed: card_declined (attempt 2/3)
                                                                      ^

; after a t motion skips the character you are standing next to, so it does not get stuck. Starting with 0t: and then ;:

2026-11-09 14:02:17 ERROR [billing] payment 4417 failed: card_declined (attempt 2/3)
            ^  ^

Make f and t your default way to move sideways across a line. They take two keystrokes no matter how far the target is, and they combine with operators: dt( deletes up to the parenthesis, cf: changes through the colon.

Paragraphs: { and }

In Vim a paragraph ends at a blank line. } moves forward to the next blank line and { moves back to the previous one. In code, functions and blocks are usually separated by blank lines, so } hops from block to block. Starting at the top of health_check.py, } four times, then { twice:

KeypressLands onLine is
}3the blank line after the docstring
}8the blank line after the imports
}15the first of two blank lines before def check
}28the blank line after check() (a run of blank lines counts as one break)
{16the second blank line before def check
{8back to the blank line after the imports

Jumping to a line: gg, G, :N and N%

KeysGoes toMeasured
ggFirst line1,1
GLast line, first non-blank40,5
17G or 17ggLine 1717,1
:30 then EnterLine 3030,1
50%Halfway through the file20,9

You can also open a file directly at a line or at the first line matching a pattern:

vim +18 summarize.py
vim +/RELEASE_DIR deploy.sh

Line numbers on screen help with this. :set number turns them on for the current session; Installing Vim shows how to make it permanent.

Matching brackets: %

With the cursor on a (, [ or {, % jumps to its partner, and pressing it again jumps back. If the cursor is not on a bracket, % first searches forward on the current line for one. That makes 0% a quick way to say "go to the end of whatever this line opens".

StartKeysLands on
Line 9, SERVICES = { (column 1)%13,1: the closing } four lines down
(from there)%9,12: back on the {
Line 23, column 1%23,62: the ) that closes print(
(from there)%23,14: the ( itself

On line 23, % started from the first bracket on the line, the ( of print(, and matched it correctly across the nested {name} and (exc) to the final ). That is the check you want when you suspect a missing parenthesis.

Screen motions and scrolling

These motions depend on what is visible, so I measured them in a real 24-row terminal (23 lines of text plus the command line) on a 200-line access log. w0 and w$ below are the first and last lines visible on screen.

KeysDoesMeasured (cursor, visible lines)
Ctrl-DScroll down half a screenfrom line 1 (1-23) to line 17 (12-34)
Ctrl-D againline 28 (23-45)
Ctrl-UScroll up half a screenline 17 (12-34)
Ctrl-FForward a full screenline 38 (33-55)
Ctrl-BBack a full screenline 29 (12-34)
H / M / LCursor to the top / middle / bottom of the screen48 / 54 / 60 with lines 43-65 visible
zz / zt / zbScroll so the cursor line is in the middle / top / bottomline 100: 89-111 / 95-117 / 83-105

Two numbers look wrong at first, and both come from the scrolloff option, which Vim's defaults set to 5. Vim keeps at least 5 lines of context above and below the cursor, so H landed on line 48 and not 43, L on 60 and not 65, and zt put line 100 sixth from the top, not first. With :set scrolloff=0, H and L went to 43 and 65, the true top and bottom. Half a screen here was 11 lines, the value of the scroll option, which Vim sets from the window height.

My advice: use zz all the time. After any jump that lands near the bottom of the screen, zz puts the line you care about in the middle with context on both sides.

Counts

Almost every motion takes a count in front of it: 3w, 5j, 2}, 3f:. From with on line 20, 3w landed on column 22 (url, three words on). 5j from there went to 25,22. gg2} went straight to line 8, the second paragraph break.

Counts are worth using when the number is obvious at a glance: two words, three lines. When you would have to count to twelve, use a motion that names the target instead (f, t, /, %).

Marks

A mark remembers a position so you can come back to it. ma sets mark a at the cursor; there are 26 of them, a to z, per file. Then:

  • `a (backtick) jumps to the exact line and column of the mark.
  • 'a (apostrophe) jumps to the line, at its first non-blank character.

I moved to check on line 17 (17Gw), set ma, then wandered off with 30G and G. The jumps back measured:

KeysLands on
`a17,5 (the c of check, where the mark was set)
'a17,1 (start of the line)

:marks lists them all. Columns in this listing count from 0:

:marks
mark line  col file/text
 '     17    4 def check(name, url):
 a     17    4 def check(name, url):
 "      1    0 #!/usr/bin/env python3
 [      1    0 #!/usr/bin/env python3
 ]     40    0 sys.exit(main())
Press ENTER or type command to continue

Vim sets some marks itself. The most useful ones:

MarkPosition
`.Where the last change was made
`"Where the cursor was when you last left this file
`[ and `]Start and end of the last changed or yanked text
`` (two backticks) or ''Where you were before the latest jump

The last-change mark is the one I use most. After appending a comment on line 25 (25GA # wall-clock ms, then Esc) and jumping to the top with gg, `. returned to 25,69, the end of the new comment, and '. to 25,5.

Uppercase marks (mA to mZ) are global: they remember the file as well as the position, so 'A can reopen a different file. Buffers, Windows, and Tabs puts them to work.

The jump list: Ctrl-O and Ctrl-I

Vim records your position every time you make a jump: G, gg, NG, / and ? searches, n, %, (, ), {, }, H, M, L and mark jumps. Plain movement such as j, w or f is not a jump. Ctrl-O walks back through that list and Ctrl-I (or Tab) walks forward, like Back and Forward in a browser.

Here is a real walk through health_check.py, starting on line 1:

KeysCursor after
/def main then Enter30,1
G40,5
20G then j21,9
Ctrl-O40,5
Ctrl-O30,1
Ctrl-O1,1
Ctrl-I30,1

j was not recorded; the first Ctrl-O went back to where 20G jumped from. At that point, :jumps showed the list with > marking where I was in it:

:jumps
 jump line  col file/text
   1     1    0 #!/usr/bin/env python3
>  0    30    0 def main():
   1    40    4 sys.exit(main())
   2    21    8 ok = resp.status == 200
Press ENTER or type command to continue

This is the habit that makes exploring code comfortable. Jump to a definition with a search, read it, then Ctrl-O back to where you were working, without setting a mark first. The jump list works across files too.

Where you'll use this

Jumping to an error. Tools report locations as line numbers. Here is a deploy script with a bug:

bash deploy.sh 2.4.0
Deploying orders 2.4.0
deploy.sh: line 10: RELEASE_DIR: unbound variable

Open it on the right line:

vim +10 deploy.sh

The cursor starts at 10,1, on mkdir -p "$RELEASE_DIR/$VERSION". The variable defined on line 6 is RELEASES, not RELEASE_DIR. To see every place the wrong name is used, grep -n gives you a list of targets:

grep -n 'RELEASE' deploy.sh
6:RELEASES=/srv/$APP/releases
10:mkdir -p "$RELEASE_DIR/$VERSION"
11:cp -r "build/." "$RELEASE_DIR/$VERSION/"
12:ln -sfn "$RELEASE_DIR/$VERSION" "/srv/$APP/current"

vim +/RELEASE_DIR deploy.sh opens the file on the first matching line (10,1). Each n then goes to the next match: 10,12, then 11,19. That is three fixes in a handful of keystrokes. The same pattern works for compiler errors (app.c:42:), Python tracebacks and failing test reports.

Reading logs and configs safely. view file opens Vim read-only. All the motions work, and an accidental edit cannot be saved by mistake: when I pressed x and then :w in view deploy.sh, Vim refused with:

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

Code review in the terminal. In a long diff or a long file, } and { hop between blocks, % checks bracket balance, ma marks the spot you were reviewing, and Ctrl-O brings you back after a detour.

Common mistakes

Caps Lock is on. Uppercase letters are different commands. With Caps Lock on, every j you press is a J, which joins the next line onto the current one. I pressed J three times on line 9 of health_check.py and the dictionary collapsed into one long line (wrapped here by the 80-column screen):

SERVICES = { "api": "http://10.0.1.12:8080/healthz", "auth": "http://10.0.1.15:9
000/status", "billing": "http://10.0.1.21:8080/healthz",
}

K (looks up the word under the cursor in a manual) and L (jumps to the bottom of the screen) are the other usual suspects. If motions start doing strange things, check Caps Lock, then press u to undo the damage.

j skips a whole paragraph in prose. In a Markdown file where each paragraph is one long line, j moves by file lines, not screen lines. In a 60-column terminal, line 3 of this incident report wraps over four screen rows:

# Incident 2026-11-09: billing timeouts
 
Between 14:02 and 14:31 UTC the billing service returned 500
s for roughly a third of payment requests because the connec
tion pool to the primary database was exhausted after a depl
oy doubled the worker count without raising max_connections.
 
Action items are tracked in OPS-2291.

From 3,1, j jumped to 4,1, the blank line, skipping all four rows. gj moves one screen row instead: gj gj gj went to 3,61, 3,121 and 3,181, and gk went back up to 3,121. Use gj and gk for prose; some people map j and k to them in Markdown files.

Expecting H and L to reach the edge of the screen. With the default scrolloff=5, they stop five lines short (see the table in "Screen motions"). That is intended, so you always see context around the cursor. Set scrolloff=0 if you prefer the classic behavior.

Expecting Ctrl-O to undo a j. Only jumps go into the jump list. If you moved with 5j or w, Ctrl-O takes you to wherever the last jump started. Use '' to return to the position before the latest jump, and set a mark when you know you will want to come back.

Summary

  • Five modes: Normal, Insert, Visual (v, V, Ctrl-V), Command-line (:, /, ?) and Replace (R). The bottom line names the mode; Esc always returns to Normal.
  • w/b/e move by word, where punctuation counts as its own word; W/B/E move by space-separated WORD and are much faster across code.
  • Within a line: 0 column 1, ^ first non-blank, $ last character, g_ last non-blank. f/t/F/T jump to a character; ; and , repeat the jump.
  • {/} move by blank-line-separated paragraphs; gg, G, NG, :N and N% jump to lines; % jumps between matching brackets.
  • Ctrl-D/Ctrl-U scroll half a screen, Ctrl-F/Ctrl-B a full screen; zz, zt and zb reposition the view. scrolloff=5 keeps context lines visible and shifts H, L and zt.
  • ma sets a mark; `a returns to the exact spot and 'a to the line. `. is the last change.
  • Ctrl-O and Ctrl-I move back and forward through the jump list (searches, G, %, marks), and :jumps shows it.

Exercises

All exercises use health_check.py from the top of this article, or the log line from the f/t section saved as app.log.

Exercise 1: Jump and come backeasy

Open health_check.py. Jump to def main(): (line 30), then to the last line, then use the jump list to get back to line 30 and then to line 1. Which keys did you use, and where did the cursor land each time?

Show Solution
KeysCursor
30G30,1
G40,5
Ctrl-O30,1
Ctrl-O1,1

30G and G are both jumps, so Ctrl-O retraces them in reverse order. :30 instead of 30G works the same way.

Exercise 2: Reach the end of a busy lineeasy

On line 20 (with urlopen(url, timeout=TIMEOUT_SECONDS) as resp:), put the cursor on the r of resp in as few keystrokes as possible. Find two different ways.

Show Solution

From anywhere on line 20:

  • $b: $ lands on the final : and b goes back to the start of resp. Two keys.
  • ^4W: four WORDs from the first non-blank.

Both measured 20,55. $b is the one to remember: "end of line, back one word" works on any line whose last word you want.

Exercise 3: Find, till, and back againmedium

On the log line in app.log, starting at column 1, use one motion each to land on: the ( before attempt, then the character just before the closing ), then the [ before billing.

Hint

f lands on a character and t lands just before it. Use F to search backwards.

Show Solution

f( then t) then F[:

2026-11-09 14:02:17 ERROR [billing] payment 4417 failed: card_declined (attempt 2/3)
                          ^                                            ^          ^
                          F[                                           f(         t)

The cursor landed on columns 72, 83 and 27. t) stopped on the 3, the character before the ). That is what ct) or dt) would use as the end point.

Exercise 4: Mark, match, and returnmedium

Set mark a on line 17 (def check). Then go to line 9 and use % to jump to the closing brace of SERVICES. Return to the mark twice: once to the exact position and once to the line.

Show Solution

17Gma sets the mark (17G puts the cursor on column 1). 9G% jumps to the closing brace at 13,1. `a returns to 17,1, and so does 'a. In this case they agree because the mark was set on column 1; set it with 17Gwma instead and `a lands on 17,5 while 'a still lands on 17,1.

Exercise 5: Center a line in a long filehard

In a 200-line log in a 24-row terminal, jump to line 150 and make it the middle line of the screen. Which lines are visible afterwards? Then predict where zt will put line 150 with the default scrolloff=5.

Show Solution

150Gzz. In my test, the cursor was on line 150 and lines 139 to 161 were visible, 11 above and 11 below in the 23-line window.

zt asks for "cursor line at the top", but scrolloff=5 keeps five lines above it, so line 150 ends up sixth from the top. When I ran 150Gzt, lines 145 to 167 were visible. This is the same effect that put line 100 at 95-117 in the scrolling table above.


Tested with: Vim 9.1.0016 on Ubuntu 24.04 (WSL2), November 2026, with Vim's stock defaults.vim and no personal vimrc. Every position in this article was measured, not worked out by hand. I drove a real Vim through tmux with the exact keys shown and recorded line('.') and col('.') after each keypress; the caret diagrams are drawn from those numbers. Screen motions were measured in an 80x24 terminal (the wrapped-prose example in a 60x10 one).

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.