I'm new to scripting in Vim. I need to write a script that surrounds a piece of text with other text. For example:
\surroundingtext{surrounded text}
(yes it is for LaTeX). I want to either highlight "surrounded text" and issue the command, or have "surrounded text" the result of a regular expression command.
I guess the question is, how to put this in a function?
Thanks, Jeremy
Here's what I do:
vnoremap <buffer> <leader>sur "zc\surroundingtext{<C-R>z}<Esc>
This creates a visual-mode mapping where you can characterwise-visual select (v
) the text that you want to surround, type \sur
(assuming a default mapleader
of \
) and the text will be surrounded by the text you specified.
"z
specifies register 'z'c
tells vim to change the visually selected text, placing the original text in register 'z'\surroundingtest
is the left-side<C-R>z
tells Vim to paste register 'z'}
is the right-side<Esc>
puts you back in normal-modeI also take it a step further and create normal-mode and insert-mode mappings as well:
nnoremap <buffer> <leader>sur i\surroundingtext{}<Esc>i
inoremap <buffer> <leader>sur \surroundingtext{}<Esc>i
You could place these mappings in your ~/.vimrc
file but they would be mapped for every filetype
.
A better place for them would be your ~/.vim/after/ftplugin/tex.vim
file so they're only mapped when your filetype
is tex
. Create the parent directories if they don't already exist.
This assumes that the filetype is correctly set to tex
and you have filetype plugins enabled:
filetype plugin on
I asked a very similar question a few weeks ago. How to repeatedly add text on both sides of a word in vim? There are good starting points in the answers.
I would recommend using visual selection since you need to surround arbitrary chunks of text instead of a single word. Enter visual selection mode by pressing v
, then select the text you wish to surround. Next record a macro with the desired modification using the following key strokes:
qa " record a macro in buffer a
x " cut the selected text
i " enter insert mode
prefix " type the desired prefix
<esc> " exit insert mode
p " paste the cut text
a " enter insert mode after the pasted text
postfix " type the desired postfix
<esc> " exit insert mode
q " stop recording
To reuse the macro simply visually select the next block you would like to modify and press @a
.
This may be too cumbersome if the surrounding text varies frequently, or if you want this to persist across editing sessions. In that case you would probably want to write a vim script function to handle it in a more robust way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With