Vim Challenge 02
Vim's built-in search and substitute commands are extremely powerful. But what if you are simply changing some literal text and you don't want to type the pattern out?
Search and Replace Current Word
lua
-- Search and replace
-- Helps you change all occurrences of the word the cursor is on
keymap.set(
"n",
"<leader>sr",
[[:%s/\<<C-r><C-w>\>/<C-r><C-w>/gI<Left><Left><Left>]],
{ desc = "[S]earch and [R]eplace Current Word" }
)This keymap, designed for Normal mode, streamlines the process of finding and replacing text. Here's a breakdown of its functionality:
: %s/.../.../gI: This is the core substitution command in Vim.%: Specifies that the command should apply to the entire file.s: Stands for substitute.g: Ensures all occurrences on each line are replaced, not just the first.I: Makes the search case-insensitive.\<and\>: These are word boundary markers. They ensure that if your cursor is on the word "cat", it replaces "cat" but not "caterpillar".<C-r><C-w>: This is a Vim command-line shortcut that inserts the word currently under your cursor. It's used for both the search pattern and the initial replacement text.<Left><Left><Left>: After setting up the command, the cursor is moved three characters to the left. This conveniently places it right after the replacement word, allowing you to immediately type what you want to change it to.
In essence, this keymap automates the setup of a file-wide, case-insensitive, whole-word search and replace for the word under your cursor.
Search and Replace Current Selection
lua
-- Search and replace visual selection
keymap.set(
"v",
"<leader>sr",
'"sy:%s#<C-r>s#<C-r>s#gI<Left><Left><Left>',
{ desc = "[S]earch and [R]eplace Current Selection" }
)This new keymap for Visual mode allows you to replace all occurrences of the selected text. Here’s how it works:
"sy: This command yanks (copies) the visually selected text into a register named "s".:%s#...#...#gI: This is the standard Vim substitute command.%s: It operates on the entire file.#: This is used as a delimiter for the search and replace patterns, which is useful to avoid conflicts if the selection contains the more common/delimiter.<C-r>s: This pastes the content of the "s" register (your visual selection) into the command.gI:gfor global replacement on each line, andIfor case-insensitivity.<Left><Left><Left>: Moves the cursor into position for you to type the replacement text.
Example
Before edit:
[addressbooks]
[[family]]
path = /Users/alowree/.contacts/family/
[[friends]]
path = /Users/alowree/.contacts/friends/
[[work]]
path = /Users/alowree/.contacts/work/After edit:
[addressbooks]
[[family]]
path = ~/.contacts/family/
[[friends]]
path = ~/.contacts/friends/
[[work]]
path = ~/.contacts/work/