Reputation: 1770
Is there a way to enclose some text in parentheses (or curly brackets) in vim?
In other words, how would you do this?
Initial string:
It is sunny outside.
Final string:
It is (sunny) outside.
On a funny note, I just hit :w
to submit this question.
Happy vim-ing, SOCommunity!
Upvotes: 114
Views: 94959
Reputation: 71
I would add another way, in normal mode write:
ciw
which is "change inner word", then in edit mode write both parentheses "()", press escape and just paste the word with:
P
In summary
ciw()<ESC>P
Upvotes: 7
Reputation: 77
Ok vim-surround is cool.
But have you used to use less 3rd party code?
I use this following keybindings to create my own surroundings with nvim.lua
local keymap = vim.api.nvim_set_keymap
local opts = { noremap = true, silent = true }
keymap("v", "\"", ":s/\\%V\\(.*\\)\\%V/\"\\1\"/<CR>", opts)
keymap("v", "\'", ":s/\\%V\\(.*\\)\\%V/\'\\1\'/<CR>", opts)
keymap("v", "(", ":s/\\%V\\(.*\\)\\%V/(\\1)/<CR>", opts)
keymap("v", "[", ":s/\\%V\\(.*\\)\\%V/[\\1]/<CR>", opts)
keymap("v", "{", ":s/\\%V\\(.*\\)\\%V/{\\1}/<CR>", opts)
Highlight what you want to enclose (so you are in VISUAL MODE) and then press the key you want to enclose with!
Super easy super,super reproducible
Upvotes: 0
Reputation: 138
I know this is an old question, but such a complex solution like this has not been mentioned here yet and I am sure it could help someone. In my .vimrc file I have a line like this:
xnoremap <silent> ( <ESC>:let p = &paste<CR>:set paste<CR>:let a = line2byte(line('.')) + col('.')<CR>gvc()<ESC>:if getregtype() ==# 'V'<CR>call setreg('"', substitute(@", '\n$', '', ''), 'c')<CR>endif<CR>P:exe "goto ".a<CR>:exe "let &paste=".p<CR>
It is enough to select some text in visual mode and to press (
. This mapping works also for linewise and blockwise visual mode.
How does it work?
<ESC>
will quit the visual mode
:let p = &paste<CR>:set paste<CR>...:exe "let &paste=".p<CR>
will make sure that the macro will be executed in paste mode (because autoindent and similar improvements could include some extra spaces we do not want) while paste status after macro will stay the same as before macro was executed
:let a = line2byte(line('.')) + col('.')<CR>
will find the current byte offset (1-based)
gv
will reselect the previously selected text
c
will delete selection and brings us to insert mode to replace the selection
()<ESC>
will put in our desired parentheses and quit insert mode
:if getregtype()==#'V'<CR>call setreg('"',substitute(@",'\n$','',''),'c')<CR>endif<CR>
will remove trailing \n
from unnamed ("
) register and change its type to characterwise, but only if it was linewise before (to make it possible to paste from the registry within the parentheses)
P
will paste previously replaced text within the parentheses
:exe "goto ".a<CR>
will bring cursor back on the previous position (goto
uses 0-based offset, so we do not have to increment previously recorded position by one because of inserted left parenthesis)
Upvotes: 1
Reputation:
Check out vim-sandwich
If you've used surround.vim before, you can even make vim-sandwich use surround.vim keymaps
Tbh the only thing that made me switch from surround.vim is that vim-sandwich has the "closest pair" operator.
Below is the result of subsequently writing "dsb" on a few parentheses . "dsb" is the default "remove nearest bracket pair" binding when using vim-sandwich with surround.vim keybindings. The standard sandwich.vim keybinding though is "sdb" (sandwich delete bracket)
X - cursor
Text | User input in normal mode |
---|---|
[ { ( X ) } ] |
dsb |
[ { X } ] |
dsb |
[ X ] |
dsb |
Upvotes: 1
Reputation: 11144
Why not use :s//
(search and replace) ?
Eg:
:s/sunny/(&)/
You probably have something else in mind, but I can't tell from your question what it is.
(&
is shorthand for the matched text)
Aside: To automate this, you could record a macro like so:
(with cursor at start of sunny
):
qq
- start recording macro in register q
ye
- yank to the end of the word (sunny
, in this case) - could also yE
, etc.:s/
- enter command mode, and start a search-and-replace commandCtrl+R, "
, paste the yanked text/(&)/
- finish the command, as described above. The command line will now read :s/sunny/(&)/
enter
- run the command, which adds the parentheses.q
- stop recording macroNow, if you go to the start a different word, you can type @q
to run the macro. Nothing in the macro is specific to the word sunny
, so it should work on anything.
You could update it to work in the middle of a word by first doing b
, or so. You get the idea. You might also want to save and restore the cursor position, which is easy to add (eg: mz
at start and `z at end).
Upvotes: 9
Reputation: 11144
Another useful tidbit I haven't seen in other answers, yet:
In a mapping, use expand("<cword>")
(or any of the other similar <cWORD>
, <cexpr>
, etc.). This gives you access to the "word under the cursor."
For instance, to replace all occurrences on the current line of "word under the cursor" with parenthesized versions:
nnoremap <leader>( :execute "s!" . expand("<cword>") . "!(&)!g"<CR>
There are some downsides:
<cword>
has an exclamation mark in it, this breaks (you can choose a different s///
character, of course)./g
flag). You could even do all occurrences in a file with %s...
.Upvotes: 1
Reputation: 4124
Here's examples using surround.vim. On vim normal mode, place your cursor over the desired word (sunny in this case) and type:
ysiw
Then type )
So:
initial string:
It is sunny outside.
Final string:
It is (sunny) outside.
Extra space:
Use the opening paren, or bracket, like ysiw(
to surround with parens and a space between paren and start + end of word)
Easier in Visual mode
Enter visual mode by pressing v
. Now if you type S(
, the word will be surrounded by spaces. However if you use the closing )
instead S)
it will not be surrounded by spaces.
This applies to all bracket pair surroundings, <> [] {} ()
, not merely to ()
. The behavior of S<
is such that it expects a tag enclosure so only S>
is able to surround as <>
.
More:
Type ysiw
followed by }
to do the same for curlies
Might as well add some more examples here:
type cs('
to [c]hange [s]urroundings from ( to '
cs'(
to change from ' surroundings to ()
ds(.
to [d]elete (
[s]urroundings altogether
Even more:
And why not quote the rest of Tpope's page to save us from clicking through to the link?
//begin quote:
It's easiest to explain with examples.
Press
cs"'
inside"Hello world!" to change it to
'Hello world!'
--
Now press
cs'<q>
to change it to
<q>Hello world!</q>
--
To go full circle, press
cst"
to get
"Hello world!"
--
To remove the delimiters entirely, press
ds".
Hello world!
--
Now with the cursor on "Hello", press
ysiw]
(iw is a text object).
[Hello] world!
Let's make that braces and add some space (use } instead of { for no space):
cs]{
{ Hello } world!
--
Now wrap the entire line in parentheses with
yssb
oryss)
.
({ Hello } world!)
--
Revert to the original text:
ds{ds)
Hello world!
--
Emphasize hello:
ysiw<em>
<em>Hello</em> world!
--
Finally, let's try out visual mode. Press a capital
V
(for linewise visual mode) followed byS<p class="important">
.<p class="important"> <em>Hello</em> world! </p>
This plugin is very powerful for HTML and XML editing, a niche which currently seems underfilled in Vim land. (As opposed to HTML/XML inserting, for which many plugins are available). Adding, changing, and removing pairs of tags simultaneously is a breeze.
The .
command will work with ds
, cs
, and yss
if you install repeat.vim.
Upvotes: 81
Reputation: 71
You can use the following commands:
cw(<C-r><C-o>")<ESC>
The advantage is that you can use the dot command for repeat this action for different words. This works for custom encloses too, for example:
Before change:
word
then use the command:
cw\enquote{<C-r><C-o>"}<ESC>
Final result:
\enquote{word}
Upvotes: 7
Reputation: 5681
I prefer not to use any plugins and want to keep everything restricted to my dotfiles for easy portability. The easiest way I can think of is to simply record it and replay it. If you plan to use it more often across sessions, you can map the key in your .vimrc as well but I didn't need to (and I'm really bad at figuring out which keystroke to map to).
Assuming you have a novice level understanding of vim, let's say I have a line (for simplicity) that I want to surround with square brackets. e.g.
hello world
Go into normal mode. q1
to start recording. Now do the following
ESC ^i[ ESC $a] ESC
This will leave the current line parenthesized. Now you can choose any line and press @1
to repeat it.
If for example you would want the current word to be paranthesised then simply record and playback the following recipe:
ESC bi[ ESC ea] ESC
You can ofcourse try to optimise for keystrokes but this serves for me for now.
Upvotes: 1
Reputation: 1391
For one word, I've been using:
bcw()<Esc>P
That is, go to the start of the word, cut the word and go into insert mode, type the brackets and then exit insert mode and paste the word back in.
Keep in mind that this will overwrite your yank register.
You can, of course replace bcw with whatever movement and selection types you need, like
5cc{<Enter>}<Esc>P
Upvotes: 138
Reputation: 627
For something like this it's probably better to play with ranges and groups than to employ external plugins:
:%s~\v(\w{5}) ~(\1) ~g
the above searches for a 5 letter word followed by a space, groups the match using (), and substitutes it with surrounding parentheses around the grouped match.
Upvotes: 0
Reputation: 1285
Surround.vim should do the trick. If you want to repeat that with '.', see here.
Upvotes: 44
Reputation: 62578
You can define a simple mapping for that sort'a thing. This ought to do it. While in normal mode type z to surround a word in parenthesis.
:nnoremap <leader>z viw<esc>a)<esc>hbi(<esc>lel
Upvotes: 10