Nvim Session 09: Command-line Mode

The : command line is where Vim’s power multiplies. Line ranges, global operations, substitution, and shell integration.

Pre-Session State

  • Use :w and :q

  • Know basic :s substitute

  • Understand line ranges

  • Use :g global command

  • Filter through external commands

Lesson 1: Command Line Basics

Exercise 1.1: Entering command mode

:        " Enter command-line mode
<Esc>    " Cancel
<CR>     " Execute

Exercise 1.2: Command history

:        " Start
<Up>     " Previous command
<Down>   " Next command
q:       " Open command history window

Exercise 1.3: Command completion

:wri<Tab>     " Completes to :write
:e ~/at<Tab>  " Completes path
Ctrl-d        " Show all completions

Lesson 2: Line Ranges

Exercise 2.1: Range syntax

:10          " Go to line 10
:10,20       " Lines 10-20
:.           " Current line
:$           " Last line
:%           " Entire file (same as 1,$)
:'<,'>       " Visual selection

Exercise 2.2: Relative ranges

:.,.+5       " Current line and next 5
:.-3,.       " Previous 3 lines to current
:10,+5       " Line 10 to 5 lines below it

Exercise 2.3: Pattern ranges

:/start/,/end/      " From "start" to "end"
:?function?,/end/   " From previous "function" to next "end"

Exercise 2.4: Range with commands

:10,20d           " Delete lines 10-20
:10,20y           " Yank lines 10-20
:10,20m 0         " Move lines 10-20 to beginning
:10,20t $         " Copy lines 10-20 to end
:.,$d             " Delete from current to end
:1,.-1d           " Delete from start to previous line

Lesson 3: Substitution

Exercise 3.1: Basic substitute

:s/old/new/       " First occurrence on current line
:s/old/new/g      " All occurrences on current line
:%s/old/new/g     " All occurrences in file

Exercise 3.2: Substitute flags

g     " Global (all matches on line)
c     " Confirm each
i     " Case insensitive
I     " Case sensitive
n     " Count matches (don't replace)
e     " No error if no match
:%s/old/new/gc    " All occurrences, confirm each
:%s/old/new/gi    " Case insensitive
:%s/old/new/gn    " Count matches

Exercise 3.3: Special replacements

:%s/old/new/g     " Literal replacement
:%s/old/\U&/g     " Uppercase match (\U = uppercase, & = match)
:%s/old/\L&/g     " Lowercase match
:%s/\(foo\)/[\1]/g  " Capture group
:%s/old/&_new/g   " Append to match

Exercise 3.4: Practical substitutions

" Delete trailing whitespace
:%s/\s\+$//g

" Delete blank lines
:g/^$/d

" Convert tabs to spaces
:%s/\t/    /g

" Wrap lines in quotes
:%s/.*/"&"/

" Remove duplicate lines
:sort u

" Add prefix to lines
:%s/^/prefix_/

" Add suffix to lines
:%s/$/_suffix/

Lesson 4: Global Command

Concept: :g/pattern/command - Execute command on all matching lines.

Exercise 4.1: Basic global

:g/pattern/d      " Delete lines matching pattern
:g/ERROR/d        " Delete all ERROR lines
:g/^#/d           " Delete comment lines
:g/^$/d           " Delete blank lines

Exercise 4.2: Inverse global

:g!/pattern/d     " Delete lines NOT matching
:v/pattern/d      " Same (v = inverse)
:v/keep/d         " Keep only lines with "keep"

Exercise 4.3: Global with other commands

:g/TODO/t $       " Copy TODO lines to end
:g/FIXME/m 0      " Move FIXME lines to beginning
:g/DEBUG/s//INFO/ " Replace DEBUG with INFO on matching lines
:g/^/m 0          " Reverse file order!

Exercise 4.4: Global with ex commands

:g/function/p     " Print lines with "function"
:g/error/y A      " Yank (append) error lines to register A
:g/^import/normal A;  " Append semicolon to import lines

Exercise 4.5: Complex global patterns

" Delete lines between patterns (inclusive)
:g/START/,/END/d

" Operate on lines after match
:g/SECTION/.+1,/SECTION/-1 d

" Indent matching lines
:g/function/normal >>

Lesson 5: External Commands

Exercise 5.1: Run shell command

:!ls             " Run ls, show output
:!date           " Show date
:r !date         " Insert command output
:r !hostname     " Insert hostname

Exercise 5.2: Filter through command

:%!sort          " Sort entire file
:10,20!sort      " Sort lines 10-20
:'<,'>!sort      " Sort visual selection
:%!uniq          " Remove duplicate adjacent lines
:%!tac           " Reverse lines (GNU coreutils)

Exercise 5.3: Filter with awk/sed

:%!awk '{print $1}'           " First column only
:%!sed 's/foo/bar/g'          " sed substitute
:10,20!awk '{print NR": "$0}' " Add line numbers
:'<,'>!jq .                   " Format JSON

Exercise 5.4: Write to command

:w !wc           " Pipe buffer to wc (word count)
:w !cat -n       " Show with line numbers
:'<,'>w !pbcopy  " macOS: copy to clipboard
:'<,'>w !xclip  " Linux: copy to clipboard

Lesson 6: Useful Ex Commands

Exercise 6.1: File operations

:w               " Write file
:w filename      " Write to filename
:w >> filename   " Append to filename
:10,20w filename " Write lines 10-20 to file
:r filename      " Read file into buffer
:e filename      " Edit file
:e!              " Reload, discard changes

Exercise 6.2: Buffer operations

:ls              " List buffers
:b N             " Go to buffer N
:bn              " Next buffer
:bp              " Previous buffer
:bd              " Delete buffer
:bufdo %s/old/new/g | w   " Run on all buffers

Exercise 6.3: Window operations

:sp              " Horizontal split
:vsp             " Vertical split
:sp filename     " Split with file
:only            " Close other windows
:close           " Close current window

Exercise 6.4: Marks and registers

:marks           " Show marks
:reg             " Show registers
:delmarks a-z    " Delete marks

Lesson 7: Advanced Patterns

Exercise 7.1: Chain commands

:g/TODO/d | w              " Delete TODOs, save
:%s/old/new/g | %s/foo/bar/g   " Multiple substitutes

Exercise 7.2: Apply normal mode

:%normal A;          " Append ; to every line
:g/function/normal >>   " Indent function lines
:'<,'>normal @a      " Run macro 'a' on selection

Exercise 7.3: Record and execute

" In :commands, you can use expressions
:let @a = 'iHello<Esc>'    " Set register/macro
:@a                        " Execute register

Exercise 7.4: Practical workflows

Config file transformation:

" Convert = to :
:%s/ = /: /g

" Wrap values in quotes
:%s/: \(.*\)/: "\1"/g

" Remove empty values
:g/: ""$/d

Log analysis:

" Keep only errors
:v/ERROR/d

" Extract timestamps
:%s/^\([^ ]*\) .*/\1/

" Sort by timestamp
:%!sort

Summary: Command Reference

Command Effect

:s/p/r/

Substitute first match

:s/p/r/g

Substitute all on line

:%s/p/r/g

Substitute in file

:g/p/cmd

Run cmd on matching lines

:v/p/cmd

Run cmd on non-matching

:!cmd

Run shell command

:r !cmd

Insert command output

:%!cmd

Filter through command

:w !cmd

Pipe to command

Range Reference

Range Meaning

.

Current line

$

Last line

%

All lines (1,$)

'<,'>

Visual selection

10,20

Lines 10 to 20

.,.+5

Current to 5 below

/p/,/q/

Pattern range

Exercises to Complete

  1. [ ] Delete all blank lines with :g/^$/d

  2. [ ] Substitute in a range (visual or line numbers)

  3. [ ] Use :r !date to insert current date

  4. [ ] Filter selection through sort or uniq

  5. [ ] Use :g/pattern/normal >> to indent matches

Next Session

Session 10: Macros & Repeat - Automate everything.

Session Log

Timestamp Notes

Start

<Record when you started>

End

<Record when you finished>

Discoveries

<What surprised you?>