We have written numerous tips about pattern matching, mostly because it’s such a valuable skill to develop. A few popular ones include Repeat last substitution, Stay in search mode, and Count occurrences.
But there also just seems to be so much to learn about this corner of Vim. Here’s a trick I learned recently: An ampersand, &
, in your replacement pattern will insert the matched pattern into the replacement text. This could be useful in a lot of places, such as surrounding text with something. (Although you are using Surround.vim, right?)
Take a look at the gif at the bottom of this post. In the demo, I use this tip to match URLs and replace them with markdown syntax. The substitution looks like so:
%s/https.*/[&]()/g
Here’s what this does:
%
- set the range to the entire files
- substitution/https.*/
- regex to match https and anything else after it[&]()
- The&
is the magic here and inserts the matched text. In this case, the URL. The rest of the characters are interpreted literally, giving us the linked URL in the resulting markdown.
VimTricks Happenings
👉 Like this tip? We have written 65 so far and plan to write hundreds more! Follow us on Twitter for a steady drip of Vim tips from our archives. We are also working on a brand new website. Stay tuned for that big announcement.
🎉 You might also consider supporting us with a purchase of Git Better with Vim, our brand-new, just-launched email-based course about using Git inside of Vim. We’ve got 24 lessons that are going take you from 0️⃣ to 💯 with Vim and Git.
🚀 Don’t forget to use code “launch” for 30% off of Git Better with Vim. This code is valid till November 15th.
👩🏫 Our two other courses are available for pre-order: Vim for Rubyists and Master Vim Note-Taking. Use code “presale” for 50% off of those.
Now onto the demo gif…
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote:
One plugin I like is vim-over, where you can live preview the substitution
Great trick! Note that you don't need /g on this substitution (: