Day 11: Neovim basics for terminal people
Goal: Change files faster with vim motions, text objects and macros than with the mouse. · Duration: approx. 90 min · Prerequisite: Day 10
Briefing
- vim is a language: operator + motion/text object,
for example
d+worc+i". - A number in front repeats:
d3w. The dot.repeats the last change. - The configuration is a single
init.luaof about 60 lines. You don’t need a distribution like LazyVim for that. - The lab Neovim starts via the
nvscript. It only redirects the XDG paths; your real~/.config/nvimstays untouched.
d 3 w c i "
│ │ └ motion │ │ └ object: "…"
│ └ count │ └ inner (without edge) / a = around (with edge)
└ operator └ operator
Drill 1: Setting up the lab Neovim
Copy init.lua and the wrapper script nv
into the practice home. ~/term-lab/bin is already on the
PATH in the lab zsh (Day 0):
mkdir -p ~/term-lab/config/nvim
cp $BUCH/nvim/init.lua ~/term-lab/config/nvim/init.lua
cp $BUCH/nvim/nv ~/term-lab/bin/nv && chmod +x ~/term-lab/bin/nv
cat ~/term-lab/bin/nvExpected:
#!/bin/sh
# nv – Neovim mit Lab-Konfiguration (Tag 11).
# Echte ~/.config/nvim, ~/.local/share/nvim und ~/.local/state/nvim bleiben unberührt.
LAB="${LAB:-$HOME/term-lab}"
export XDG_CONFIG_HOME="$LAB/config" \
XDG_DATA_HOME="$LAB/share" \
XDG_STATE_HOME="$LAB/state" \
XDG_CACHE_HOME="$LAB/cache"
exec nvim "$@"
Now check the configuration without a UI:
nvim --headless -u ~/term-lab/config/nvim/init.lua +q && echo "init.lua ok"
nv --headless +'lua print(vim.fn.stdpath("config"), vim.o.clipboard)' +q; echoExpected:
init.lua ok
/Users/<du>/term-lab/config/nvim unnamedplus
An error in init.lua shows up here as a Lua stack trace
with a line number. That’s the fastest test after every change.
Tip: Alternatively,
NVIM_APPNAME=lab nvimseparates configurations. But that creates~/.config/lab. The wrapper, on the other hand, keeps everything under~/term-lab.
Today’s practice files:
mkdir -p ~/term-lab/tag11 && cd ~/term-lab/tag11
cat > server.py <<'EOF'
# TODO: Konfig aus Umgebung lesen
import os
def connect(host, port):
url = "http://localhost:8080/api"
print("connecting to", host, port)
return {"host": host, "port": port, "timeout": 30}
def disconnect(conn):
print("closing", conn["host"])
EOF
printf 'web-01\nweb-02\ndb-01\ncache-01\n' > hosts.txt
git init -q && git add . && git commit -qm "start"The mini repo (with the lab gitconfig from Day 10) is your undo
across file boundaries: git restore server.py resets an
exercise, git diff shows what you changed.
Save your progress? Sign up for free
Drill 2: Motions
nv server.py opens the file. The relative line numbers
show you which number goes before j or k. Type
one after another and watch the cursor:
gg G 5G } { start/end of file, line 5, paragraph forward/back
w b e W B word forward/back/word end, WORD = up to whitespace
0 ^ $ start of line, first character, end of line
f( t, ; , jump to "(" / until before ",", repeat forward/back
% to the matching bracket
/connect<CR> n N search, next/previous match
* # search word under the cursor forward/backward
Now with an operator. Each line is a separate task, u
undoes it:
/print<CR>f(ldt, deletes up to before the comma
/def connect<CR>wd2w deletes "connect("
/return<CR>f{%x jumps to the closing } and deletes it
Expected (line after the respective task):
print(, host, port)
def host, port):
return {"host": host, "port": port, "timeout": 30
Tip:
ciwalmost always beatsdw+i. Remember: prefer text objects to counting.
Save your progress? Sign up for free
Drill 3: Text objects
Text objects work no matter where in the object the cursor is.
i means inner, a means around.
/localhost<CR>ciwexample<Esc> replace word
/connecting<CR>ci"verbinde mit<Esc> replace contents of the quotes
/30<CR>cw60<Esc> replace number
/return<CR>f{di{ empty the contents of the curly braces
Gdap delete last paragraph (function)
Expected (changed lines, each time back to the original with
u):
url = "http://example:8080/api"
print("verbinde mit", host, port)
return {"host": host, "port": port, "timeout": 60}
return {}
(def disconnect … is gone)
| Object | Meaning | Example |
|---|---|---|
iw / aw |
word / with whitespace | ciw, daw |
i" / a" |
inside/around quotes | ci", da" |
i( / i{ / i[ |
inside brackets | di(, yi{ |
it / at |
inside/around HTML tag | cit |
ip / ap |
paragraph | yap, dap |
y yanks, and thanks to
clipboard=unnamedplus it lands directly on the macOS
clipboard. Try yi{, then pbpaste in the
terminal (Day 12).
Save your progress? Sign up for free
Drill 4: Dot command and cgn
. repeats the last change. Together with
cgn (“change next match”) it becomes a search and replace
with judgment. You rename the parameter host; the
dictionary key "host" should stay.
/(host<CR>l cursor on the parameter host
*N set word as search pattern, back to the first match
cgnhostname<Esc> change the first match
. next match (print line)
nn skip the "host" key
. change the value host in the dictionary
:w<CR>
grep -n host server.pyExpected:
5:def connect(hostname, port):
6: url = "http://localhost:8080/api"
7: print("connecting to", hostname, port)
8: return {"host": hostname, "port": port, "timeout": 30}
12: print("closing", conn["host"])
Why nn? After . the cursor is before the
next match. The first n jumps onto the key, the second one
past it. . always changes the match from the cursor on.
Save your progress? Sign up for free
Drill 5: Macros
The host list should become a YAML list. Open
nv hosts.txt and type:
qa record into register a
I - name: <Esc> insert prefix
j one line down
q stop recording
3@a play back three times
:w<CR>
cat hosts.txtExpected:
- name: web-01
- name: web-02
- name: db-01
- name: cache-01
The rule for robust macros: start at the beginning of the line
(0 or I), end on the next line. Then the macro
can be played back as often as you like, also via
:%normal @a.
Tip:
@@repeats the last played macro.:reg ashows what was recorded.
Save your progress? Sign up for free
Drill 6: Search, replace and quickfix
Reset server.py and replace port only where
it’s a variable:
git restore server.py
nv server.py:%s/\<port\>\ze[,)]/port_nr/gc
:w<CR>
\< and \> are word boundaries,
\ze ends the match before , or ).
With y/n you confirm each match; the preview
(inccommand=split) shows them all in advance.
Expected (after y, y, n,
changed lines):
def connect(host, port_nr):
print("connecting to", host, port_nr)
return {"host": host, "port": port, "timeout": 30}
Across several files you use :grep (thanks to
grepprg that’s ripgrep) and the quickfix list:
mkdir -p pkg
printf 'package main\n\n// TODO: Fehler behandeln\nfunc main() {}\n' > pkg/main.go
nv:silent grep! TODO matches into the quickfix list
:copen show the list, Enter jumps there
:cdo s/TODO/FIXME/ | update replace in every match and save
:qa
rg -n FIXMEExpected:
pkg/main.go:3:// FIXME: Fehler behandeln
server.py:1:# FIXME: Konfig aus Umgebung lesen
:g/print/d deletes all lines with print,
:g!/def/d all without def. That’s
grep -v directly in the buffer.
Save your progress? Sign up for free
Drill 7: Windows, buffers and finding files
Start nv in the tag11 folder and work
without a mouse (mouse="" is intentional):
<Space>ff main<Tab><CR> :find with ** finds pkg/main.go
:vs server.py<CR> vertical split
<C-h> <C-l> switch between windows (own mappings)
:ls<CR> open buffers
:b#<CR> to the previous buffer, like git co -
<Space>e netrw in the current folder, - goes up one level
<C-o> <C-i> jump list back/forward
Ask the configuration itself for the leader mappings:
nv --headless +'lua for _, m in ipairs(vim.api.nvim_get_keymap("n")) do
if m.lhs:find("^ ") then print(m.lhs, m.desc) end end' +qa; echoExpected:
fg Grep ins Quickfix
ff Datei finden (eingebaut)
e Dateibrowser (netrw)
q Fenster schließen
w Speichern
For large repos a fuzzy finder pays off. The init.lua
optionally brings fzf-lua, installed via
vim.pack, the package manager built into Neovim 0.12:
LAB_PLUGINS=1 nv --headless +'lua print(vim.pack.get()[1].spec.name)' +qa; echoExpected (the first time with download messages):
vim.pack: 100% Installing plugins (1/1) - fzf-lua
fzf-lua
After that, <Space>ff,
<Space>fg and <Space>fb replace
the built-in variants with fzf pickers. The plugin lives under
~/term-lab/share/nvim/site/pack/core/opt/.
Tip: Telescope is the best-known alternative to fzf-lua. Ready-made distributions like LazyVim only pay off once you’ve mastered the basics here – otherwise you won’t know which key comes from where.
Save your progress? Sign up for free
Drill 8: Neovim as $EDITOR
Git, zsh and many CLIs open $EDITOR. In the lab that’s
nv:
export EDITOR=nv VISUAL=nv
git config --global core.editor nv
git config --global core.editorExpected:
nv
Thanks to GIT_CONFIG_GLOBAL,
git config --global writes to
~/term-lab/gitconfig here. To make it permanent, replace
the line export EDITOR=nvim VISUAL=nvim in
~/term-lab/zsh/.zshenv with
export EDITOR=nv VISUAL=nv. Useful invocations from now
on:
nv +3 server.py # straight to line 3
nv -q <(rg --vimgrep FIXME) # rg matches as a quickfix list
nv -d server.py pkg/main.go # diff mode, ]c/[c jump
git log --oneline | nv - # stdin as a bufferExpected for nv -q … (status line at the bottom):
(1 of 2): // FIXME: Fehler behandeln
In zsh, ⌃X⌃E opens the current command line in
$EDITOR (Day 3). After :wq, the edited command
is back at the prompt.
Save your progress? Sign up for free
Shortcut table
| Key | Effect | Mnemonic |
|---|---|---|
ciw / ci" / di( |
change word / string / bracket contents | change inner |
dap / yap |
delete / yank paragraph | delete a paragraph |
f t ; , |
jump within the line, repeat | find, till |
* + cgn + . |
replace match by match | gn = go next |
qa … q, @a,
@@ |
record, play back, repeat a macro | q = queue |
g⌃A (visual) |
increment numbers progressively | g = graduated |
⌃O / ⌃I |
jump list back / forward | Out / In |
:cdo + command + update |
command on all quickfix matches | c = quickfix |
Space ff / fg |
find file / grep | find file / grep |
Checkpoint
cd ~/term-lab/tag11
ok() { if eval "$1" >/dev/null 2>&1; then echo "✔ $2"; else echo "✘ $2"; fi; }
ok 'nvim --headless -u ~/term-lab/config/nvim/init.lua +q' "init.lua lädt fehlerfrei"
ok '[ "$(nv --headless +"lua io.write(tostring(vim.o.relativenumber))" +q)" = true ]' \
"relativenumber aktiv"
ok '[ -d ~/term-lab/state/nvim ]' "Lab-State statt ~/.local/state"
ok '[ "$(grep -c "^ - name: " hosts.txt)" -eq 4 ]' "Makro: 4 YAML-Einträge"
ok '[ "$(rg -c FIXME . | wc -l)" -eq 2 ]' "cdo: 2 Dateien mit FIXME"
ok '[ "$EDITOR" = nv ]' "EDITOR=nv"Expected:
✔ init.lua lädt fehlerfrei
✔ relativenumber aktiv
✔ Lab-State statt ~/.local/state
✔ Makro: 4 YAML-Einträge
✔ cdo: 2 Dateien mit FIXME
✔ EDITOR=nv
Challenge
Number the lines of the original host list as 1. web-01
to 4. cache-01 – without typing the numbers one by one.
Hint: First prepend 0. everywhere, then
increment progressively in visual mode.
Solution
git show HEAD:hosts.txt > nummern.txt
nv nummern.txt:%s/^/0. /<CR>
ggVG
g<C-a>
:w<CR>
cat nummern.txtExpected:
1. web-01
2. web-02
3. db-01
4. cache-01
Alternative without visual mode:
:%s/^/\=line('.') . '. '/ – \= evaluates an
expression.
Save your progress? Sign up for free
Enterprise Note
- On servers there’s often only
vi/vimwithout your config. The motions from this day still work there. sudoedit dateiinstead ofsudo nvim datei: the editor runs as you, only the writing happens with root privileges.- Pin plugins:
vim.packwrites a lock file (nvim-pack-lock.json) – put it in your dotfiles too (Day 13). - No secrets in swap/undo files: for sensitive files use
nvim -n(no swap) and:setlocal noundofile. - Teams tend to standardize on
.editorconfigrather than editor configs. Neovim reads it by itself since 0.9.