Reputation: 4014
I want to do something like this : I select some piece of text and then press Ctrl-B and selected text is surrounded by ** or some other symbol of my choice. I was thinking that if I could mark the start and end positions of the selection somehow, I could map Ctrl-B to some key combination in visual mode that moves over these marks and puts the required text.
How can I do so?
Upvotes: 3
Views: 990
Reputation: 17333
No need to define your own mapping- Tim Pope's surround.vim is made for this sort of thing! The plugin provides mappings to easily delete, change and add surroundings to text.
In your case, after you've made your selection in visual mode, just type S*, and your code will be surrounded by asterisks.
Surround commands work with standard motions, and in normal mode as well. If you want to change the surrounding characters (say, from *
to '
), you can do cs*'.
The README covers a lot of general-use cases that are worth trying.
Upvotes: 7
Reputation: 15715
The start and end of a visual selection are automatically marked with the '<
and '>
marks respectively. These persist until another visual selection is made, so it is quite possible to use them for navigation in functions and mappings.
However, as @David has said, it sounds like the surround plugin does exactly what you describe.
Upvotes: 4
Reputation: 1439
If you go through VIM tutorial, you will find this for Visual-Mode:
Ex for inserting ' for visually selected text.
Set the following command
:vnoremap qq <Esc>`>a'<Esc>`<i'<Esc>
after that select visually and press "qq"
Upvotes: 0