Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to create a macro so that if I select a piece of text (either by a keyboard or a mouse) and invoke this macro, it adds [b] and [/b] around the text (for example). I'm familiar with recording macros using q and running them with @, but I couldn't figure out how to connect a macro with current visual selection.

share|improve this question
up vote 4 down vote accepted

Macros are no different from what you would type to achieve your goal. When working with a visual selection, you'd typically use motions like `< and `> to go to the begin and end of the selection, and insert the tags with i and a; gv allows to you re-select the previous selection.

For your particular example, it may be worthwhile to look into the surround.vim - Delete/change/add parentheses/quotes/XML-tags plugin; maybe it already does what you want.

share|improve this answer

Another option to consider is the Ultisnips plugin. It has a special "visual placeholder" mechanism.

Snippets can contain a special placeholder called ${VISUAL}. The ${VISUAL} variable is expanded with the text selected just prior to expanding the snippet.

So you can define a snippet that surrounds visual selection with some particular tag:

snippet b "surrond with [b] tag"
[b]${1:${VISUAL}}[/b]
endsnippet

or you can make a generic snippet which surrounds visual selection with any tag:

snippet tag "surround with a tag"
[${1}]${2:${VISUAL}}[/$1]
endsnippet

or you can go nuts and utilize the power of Python interpolation to do whatever pre-processing you want with visually selected text inside the snippet.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .