How do I restrict a substitution to the range between two named marks?
Answer
:'a,'bs/old/new/g
Explanation
Named marks can serve as range endpoints for any Ex command, including :substitute. Setting two marks at the boundaries of a region lets you confine a substitution to just those lines — even after you've moved the cursor elsewhere. This is more flexible than a visual selection because marks persist until you explicitly change them.
How it works
m{a-z}— set a lowercase mark at the current line'ain a range — refers to the line where markawas set'a,'b— the range from markato markb(inclusive)- The substitution only runs on lines within this range
Example
Suppose you have a function and want to rename localVar to count only inside it:
function setup() {
localVar = 0
localVar += 1
localVar *= 2
}
localVar = 99 ← outside function
- Move to the
functionline, pressma - Move to the closing
}line, pressmb - Run
:'a,'bs/localVar/count/g
Result:
function setup() {
count = 0
count += 1
count *= 2
}
localVar = 99 ← unchanged
Tips
- Works with any Ex command:
:'a,'bddeletes lines,:'a,'b>indents them - Combine with
:g::'a,'bg/pattern/ddeletes matching lines only within the marked region - Use
`a(backtick) instead of'a(single-quote) to operate at the exact column, not just the line - Marks survive across buffer switches, making this useful for cross-session edits