I am new to vim and in the process of discovering tons of interesting things that one can using this powerful editor.
One particular thing that I need to do very fr
I would simply do it like this: %r]^or[
.
Here's an explanation:
f(
-- put cursor on first parenthesis you want to change (if it's not already there).%
-- jump to the matching parenthesis.r]
-- replace the parenthesis with a bracket.CTRL-O
-- jump back to to first parenthesis.r[
-- replace the parenthesis with a bracket.With lh-brackets, I would use <m-b>(
to change any pair of bracket-like characters (cursor on the first/last character of the pair) to a pair of parenthesis. <m-b>{
-> curly-brackets, and so on.
For the curious ones, this is how it works -- see s:ChangeTo()
. Internally, I do a %r]``r[
, and I have a dedicated treatment for quote characters.
surround.vim https://github.com/tpope/vim-surround
with this plugin, you can (cursor on or in (
), cs([
to achieve your goal.
I personally use https://github.com/tpope/vim-surround as it provides everything I could ever need, reading through the source you can see the solution is non-trivial.
A typical example:
Hello("World")
with the cursor somewhere between the ()
, you can type cs([ in normal mode to get:
Hello["World"]
surround.vim
is easily installed with either Pathogen or Vundle, personally I prefer vundle. https://github.com/VundleVim/Vundle.vim
adding the important commented point:
cs([ adds spaces in the block, this should be cs)]
Without any plugin it can be done by deleting the content inside the parenthesis and yanking in the new bracket (from anywhere within the bracket):
di(a[]<esc>P%2X
Obviously more key that using surround
but but not that many ;-)
There is no need to remember the sequence of key but only to start by deleting the inside of the brackets. Then it's just normal vim fu.
Based on a few of the SO's around this matter (see my comment in the @mb14 answer here), I was thinking of muscle-memorizing something like this:
di(a<bkspace><bkspace>[]<Esc>P
but what I really wanted to do was this:
di(c%[]<Esc>P
You will see that you cannot do that because the c
puts the ()
brackets into your 0
register and therefore you actually need to do this:
di("_c%[]<Esc>P
or (I was also trying out a 'yank' approach and came up with) this:
yi(ca([]<Esc>"0P
Okay, neither is too bad, but it occurred to me that this is going to all go much better if I map <leader>c
to "_c
so that I have a real delete and can do this:
di(\c%[]<Esc>P
or this:
yi(\ca([]<Esc>P
Both are pretty close to what I wanted to do, and the thought process has given me one of the most valuable lines in my $MYVIMRC
:
noremap <leader>c "_c