Text Editors: Vim & Modern Alternatives#

Why Learn Vim?#

Real-world analogy: Learning Vim is like learning to touch-type. Initially slower, but once mastered, youโ€™ll edit text at the speed of thought.

Why Vim matters in 2024:

  • Available on EVERY Unix system (servers, Docker containers, embedded systems)

  • Keyboard-only editing = blazing fast

  • Vim motions work in: VS Code, IntelliJ, Chrome, Jupyter, and more

  • SSH into servers? Vim is there. Nano? Sometimes. VS Code? Never.

What youโ€™ll learn:

  • Vim basics (modes, movements, commands)

  • Practical editing workflows

  • Configuration and plugins

  • Modern alternatives (Neovim, Helix)

  • When to use Vim vs GUI editors

Time investment: 90-120 minutes
Difficulty: Intermediate


1. Vim Philosophy#

The Modal Paradigm#

Unlike most editors, Vim has different modes:

Mode

Purpose

Enter

Key Feature

Normal

Navigate & manipulate

Esc

Default mode, keyboard = commands

Insert

Type text

i, a, o

Like normal editors

Visual

Select text

v, V, Ctrl-v

Visual selection

Command

Run commands

:

Save, quit, search & replace

Key insight: Most editing is NOT typing new textโ€”itโ€™s navigating, changing, deleting, and copying existing text. Vim optimizes for this!

Learning Curve Reality#

Productivity
    |
    |                    โ•ฑ
    |                  โ•ฑ
    |                โ•ฑ
    |              โ•ฑ
    |            โ•ฑ  (After 2 weeks)
    |          โ•ฑ
    |  Normal editors
    | โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    |        โ•ฒ
    |         โ•ฒ  (First week - you'll be slower!)
    |          โ•ฒ
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Time

First week: Youโ€™ll be slower. This is NORMAL.
Second week: Back to normal speed.
Third week+: Faster than before, and improving.


2. Getting Started: Basic Survival#

Opening and Closing Files#

# Open Vim
vim                    # Empty buffer
vim filename.txt       # Open specific file
vim +10 file.py       # Open at line 10
vim +/pattern file    # Open at first match of pattern
# Let's create a file to practice with
practice_text = """Hello Vim!
This is line 2.
This is line 3 with some text to edit.
Line 4 contains: Python, Java, JavaScript
The quick brown fox jumps over the lazy dog.
"""

with open('vim_practice.txt', 'w') as f:
    f.write(practice_text)

print("โœ… Created vim_practice.txt")
print("\nTry: vim vim_practice.txt")

The Sacred Trinity: How to Quit Vim#

Most important commands to memorize:

:q          " Quit (fails if unsaved changes)
:q!         " Quit without saving (force quit)
:wq         " Write and quit (save & exit)
:x          " Write (if changes) and quit
ZZ          " Same as :x (in normal mode)
ZQ          " Same as :q! (in normal mode)

Pro tip: ZZ is the fastest way to save and quit!


3. Normal Mode: Navigation#

Basic Movement (Donโ€™t use arrow keys!)#

h   " Left
j   " Down
k   " Up
l   " Right

Why not arrow keys? Your fingers never leave the home row = faster!

     โ†‘
   k
 โ† h   l โ†’
   j
     โ†“

Word Movement#

w       " Next word (start)
e       " Next word (end)
b       " Previous word
W, E, B " Same but ignore punctuation

Example:

const greeting = "Hello, World!";
^     ^        ^ ^
b     b        w w

Line Movement#

0       " Start of line (column 0)
^       " First non-whitespace character
$       " End of line
g_      " Last non-whitespace character

File Navigation#

gg      " Go to first line
G       " Go to last line
10G     " Go to line 10
:42     " Go to line 42

Ctrl-d  " Scroll down half page
Ctrl-u  " Scroll up half page
Ctrl-f  " Scroll down full page (forward)
Ctrl-b  " Scroll up full page (backward)

H       " High (top of screen)
M       " Middle of screen
L       " Low (bottom of screen)

Search Movement#

/pattern    " Search forward
?pattern    " Search backward
n           " Next match
N           " Previous match
*           " Search for word under cursor (forward)
#           " Search for word under cursor (backward)

f{char}     " Find next {char} on line
F{char}     " Find previous {char} on line
t{char}     " Till next {char} (stop before)
T{char}     " Till previous {char}
;           " Repeat last f/F/t/T
,           " Repeat last f/F/t/T (opposite direction)

4. Insert Mode: Adding Text#

Entering Insert Mode#

i       " Insert before cursor
a       " Append after cursor
I       " Insert at start of line
A       " Append at end of line

o       " Open new line below
O       " Open new line above

s       " Substitute character (delete & insert)
S       " Substitute line
C       " Change to end of line

Remember: Esc returns to Normal mode!


5. Editing: The Real Power#

Delete Commands#

x       " Delete character under cursor
X       " Delete character before cursor

dw      " Delete word
dd      " Delete line
D       " Delete to end of line

d$      " Delete to end of line
d0      " Delete to start of line
dG      " Delete to end of file
dgg     " Delete to start of file

Change Commands#

cw      " Change word (delete & enter insert mode)
cc      " Change line
C       " Change to end of line
ciw     " Change inner word (regardless of cursor position)
ci"     " Change inside quotes
ci(     " Change inside parentheses
ci{     " Change inside braces

Copy (Yank) and Paste#

yy      " Yank (copy) line
yw      " Yank word
y$      " Yank to end of line

p       " Paste after cursor
P       " Paste before cursor

"*y     " Yank to system clipboard
"*p     " Paste from system clipboard
"+y     " Yank to clipboard (alternative)
"+p     " Paste from clipboard (alternative)

Undo and Redo#

u       " Undo
Ctrl-r  " Redo
.       " Repeat last command (SUPER powerful!)

6. Text Objects: The Vim Superpower#

Understanding Text Objects#

Pattern: [verb][scope][text-object]

" Verbs:
d    " Delete
c    " Change
y    " Yank
v    " Visual select

" Scope:
i    " Inner (inside, excluding delimiters)
a    " Around (including delimiters)

" Text objects:
w    " Word
s    " Sentence
p    " Paragraph
"    " Quoted string
'    " Single quoted string
`    " Backtick string
(    " Parentheses
[    " Brackets
{    " Braces
<    " Angle brackets
t    " HTML/XML tag

Examples#

# Cursor anywhere in the word "function"
def function(arg1, "hello world", arg3):
    return True

ciw    # Change inner word โ†’ changes "function"
ci"    # Change inside quotes โ†’ changes "hello world"
ci(    # Change inside parens โ†’ deletes all arguments
ca(    # Change around parens โ†’ deletes () and arguments
di{    # Delete inside braces โ†’ delete function body

7. Visual Mode: Selection#

v       " Character-wise visual mode
V       " Line-wise visual mode
Ctrl-v  " Block visual mode (column selection)

" After selecting:
d       " Delete selection
c       " Change selection
y       " Yank selection
>       " Indent right
<       " Indent left
=       " Auto-indent

Block Mode Example#

# Add comments to multiple lines:
print("Line 1")
print("Line 2")
print("Line 3")

# Steps:
# 1. Ctrl-v (enter block mode)
# 2. jj (select 3 lines)
# 3. I# (insert # at start)
# 4. Esc (apply to all lines)

# Result:
# print("Line 1")
# print("Line 2")
# print("Line 3")

8. Command Mode: Power Features#

Search and Replace#

:s/old/new/        " Replace first on current line
:s/old/new/g       " Replace all on current line
:%s/old/new/g      " Replace all in file
:%s/old/new/gc     " Replace all with confirmation
:10,20s/old/new/g  " Replace in lines 10-20

File Operations#

:w              " Write (save)
:w filename     " Save as filename
:wq             " Write and quit
:q!             " Quit without saving

:e filename     " Edit (open) file
:e!             " Reload current file (discard changes)
:bn             " Next buffer
:bp             " Previous buffer
:bd             " Delete buffer (close file)

Multiple Files#

:split file     " Horizontal split
:vsplit file    " Vertical split
Ctrl-w w        " Switch windows
Ctrl-w h/j/k/l  " Navigate splits
Ctrl-w q        " Close current split

:tabnew file    " Open in new tab
gt              " Next tab
gT              " Previous tab
:tabclose       " Close tab

9. Configuration: .vimrc#

Essential Settings#

# Create a basic .vimrc
vimrc_content = '''" Basic Settings
set number              " Show line numbers
set relativenumber      " Relative line numbers
set tabstop=4           " Tab width
set shiftwidth=4        " Indent width
set expandtab           " Use spaces instead of tabs
set autoindent          " Auto indent
set smartindent         " Smart indent

" Search Settings
set hlsearch            " Highlight search results
set incsearch           " Incremental search
set ignorecase          " Case insensitive search
set smartcase           " Unless uppercase in search

" UI Improvements
set showcmd             " Show command in status line
set showmatch           " Show matching brackets
set wildmenu            " Command line completion
set cursorline          " Highlight current line
syntax on               " Syntax highlighting

" Quality of Life
set mouse=a             " Enable mouse
set clipboard=unnamedplus  " Use system clipboard
set hidden              " Allow hidden buffers
set nobackup            " No backup files
set noswapfile          " No swap files
'''

with open('example.vimrc', 'w') as f:
    f.write(vimrc_content)

print("โœ… Created example.vimrc")
print("\nTo use: cp example.vimrc ~/.vimrc")

Key Remapping Examples#

" Leader key (space bar)
let mapleader = " "

" Save with Space+w
nnoremap <leader>w :w<CR>

" Quit with Space+q
nnoremap <leader>q :q<CR>

" Clear search highlighting
nnoremap <leader>h :nohlsearch<CR>

" Navigate splits easily
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l

10. Plugins: Extending Vim#

Plugin Managers#

vim-plug (recommended for beginners):

# Install vim-plug
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

Add to .vimrc:

call plug#begin('~/.vim/plugged')

Plug 'preservim/nerdtree'           " File explorer
Plug 'junegunn/fzf.vim'             " Fuzzy finder
Plug 'tpope/vim-commentary'         " Easy commenting
Plug 'tpope/vim-surround'           " Surround text
Plug 'vim-airline/vim-airline'      " Status bar
Plug 'morhetz/gruvbox'              " Color scheme

call plug#end()

Then run: :PlugInstall in Vim

Essential Plugins#

Plugin

Purpose

Key Commands

NERDTree

File explorer

:NERDTree, Ctrl+n

fzf.vim

Fuzzy file finder

:Files, :Rg

vim-commentary

Comment code

gcc (line), gc (visual)

vim-surround

Manipulate surroundings

cs"' (change โ€œ to โ€˜)

coc.nvim

LSP/autocomplete

Tab (complete)

vim-gitgutter

Git diff in gutter

Shows changes

ale

Linting

Auto-lint on save


11. Modern Alternatives#

Neovim#

Modern Vim fork with better defaults:

# Install
sudo apt install neovim   # Ubuntu
brew install neovim       # macOS

# Use
nvim filename.txt

Benefits:

  • Better plugin architecture (Lua-based)

  • Built-in LSP client

  • Faster

  • Active development

  • Compatible with Vim configs

Popular Neovim Distributions:

  • LunarVim

  • AstroNvim

  • NvChad

Helix#

Modern editor with Vim-like keybindings:

# Install
cargo install helix-term

# Use
hx filename.txt

Advantages:

  • Multiple cursors built-in

  • LSP out of the box

  • Tree-sitter syntax highlighting

  • No configuration needed

  • Selection-first (vs Vimโ€™s action-first)

Vim Keybindings in Other Editors#

Editor

Plugin/Mode

VS Code

Vim extension

IntelliJ/PyCharm

IdeaVim

Emacs

Evil mode

Jupyter

Vim mode extension

Chrome

Vimium extension

Firefox

Tridactyl extension


12. Practical Workflows#

Editing Code#

" Jump to function definition
gd          " Go to definition (with plugins)
Ctrl-]      " Jump to tag
Ctrl-o      " Jump back

" Code navigation
*           " Find next occurrence of word
#           " Find previous occurrence
%           " Jump to matching bracket

" Indentation
>>          " Indent line
<<          " Unindent line
==          " Auto-indent line
gg=G        " Auto-indent entire file

Macros: Record and Replay#

qa          " Start recording to register 'a'
" ... perform actions ...
q           " Stop recording
@a          " Replay macro 'a'
@@          " Replay last macro
10@a        " Replay macro 'a' 10 times

Example: Add quotes around each word:

qa          " Start recording
ciw"<C-r>""<Esc>  " Change inner word, add quotes
w           " Move to next word
q           " Stop
100@a       " Apply to next 100 words

๐ŸŽฏ Hands-On Exercises#

Exercise 1: Basic Navigation#

Practice file: vim_practice.txt

Tasks:

  1. Open the file: vim vim_practice.txt

  2. Navigate to line 3 using 3G

  3. Jump to end of file with G

  4. Return to start with gg

  5. Search for โ€œfoxโ€ using /fox

  6. Quit without saving: :q!

Exercise 2: Editing Text#

Tasks:

  1. Open vim_practice.txt

  2. Change โ€œVimโ€ to โ€œNeovimโ€ on line 1

    • Navigate to line 1: gg

    • Find โ€œVimโ€: /Vim

    • Change word: cw then type โ€œNeovimโ€ and Esc

  3. Delete line 2 completely: dd

  4. Add a new line after line 3: o

  5. Save and quit: :wq

Exercise 3: Text Objects#

Create a Python file and practice:

# Create practice code
code = '''def greet(name="World"):
    message = "Hello, " + name + "!"
    print(message)
    return True
'''

with open('practice.py', 'w') as f:
    f.write(code)

print("โœ… Created practice.py")
print("\nPractice these commands:")
print("1. ciw on 'name' โ†’ change variable name")
print('2. ci" on "Hello" โ†’ change string content')
print("3. ci( on parameters โ†’ change function args")
print("4. di{ โ†’ delete function body")

Exercise 4: Search and Replace#

Practice substitution:

  1. Open practice.py

  2. Replace all โ€œnameโ€ with โ€œusernameโ€: :%s/name/username/g

  3. Replace โ€œHelloโ€ with โ€œHiโ€: :%s/Hello/Hi/

  4. Undo all changes: u (repeatedly) or :e!

Exercise 5: Workflow Challenge#

Goal: Refactor a Python list to dictionary

Starting code:

users = [
    "Alice",
    "Bob",
    "Charlie"
]

Target:

users = {
    "Alice": True,
    "Bob": True,
    "Charlie": True
}

Approach:

  1. Record macro: qa

  2. Move to line: j

  3. Append to end: A

  4. Add : True

  5. Press Esc and q

  6. Replay: 2@a


๐Ÿ“ Vim Cheat Sheet#

Most Important Commands#

MOVEMENT              EDITING               VISUAL
h j k l  arrows       i a o    insert       v V ^V   select
w b e    words        x dd     delete       d c y    operations
0 $ ^    line         u ^R     undo/redo
gg G     file         .        repeat       COMMAND
f t F T  find char    /pattern search       :w :q :wq  save/quit
/search  search       ciw ci" ci(           :%s/old/new/g

๐Ÿ“ Self-Check Quiz#

  1. How do you quit Vim without saving?

    • :q! or ZQ

  2. Whatโ€™s the difference between i and a?

    • i inserts before cursor, a appends after

  3. How to delete a word?

    • dw or diw (inner word)

  4. What does ci" do?

    • Change inside quotes

  5. How to search for โ€œTODOโ€?

    • /TODO then n for next match

  6. Replace all โ€˜fooโ€™ with โ€˜barโ€™ in file?

    • :%s/foo/bar/g

  7. Jump to line 42?

    • 42G or :42

  8. Copy entire line?

    • yy

  9. What does . do?

    • Repeat last command

  10. Indent multiple lines?

    • Select with V, then > or <


๐ŸŽ“ Key Takeaways#

  1. Modal editing is different but powerful

  2. Text objects (ciw, ci", ci() are the secret sauce

  3. Repeat with . is incredibly efficient

  4. Learn gradually: Master basics, then add advanced features

  5. Muscle memory takes time: 2-3 weeks to become proficient

  6. Vim is everywhere: Servers, containers, emergency situations

  7. Vim motions work in many tools: VS Code, IntelliJ, Chrome

  8. Start with .vimrc: Configure for your needs

The learning investment pays dividends for decades!


๐Ÿš€ Next Steps#

  1. Run vimtutor: Built-in interactive tutorial

  2. Use Vim for one week: Force yourself, even if slower

  3. Add to .vimrc gradually: One setting at a time

  4. Install plugins: Start with NERDTree and fzf

  5. Learn macros: Automate repetitive tasks

  6. Next lesson: 05_build_systems_cicd.ipynb


๐Ÿ“š Resources#

# Cleanup
import os
for f in ['vim_practice.txt', 'practice.py', 'example.vimrc']:
    if os.path.exists(f):
        os.remove(f)

print("โœ… Cleanup complete!")
print("\n๐ŸŽ‰ You've completed Text Editors!")
print("\n๐Ÿ’ก Remember: vimtutor is your next step!")
print("   Run: vimtutor")