Extract Variable Mini Refactor with CTRL-A
Insert mode’s CTRL-A was one of those Vim features that I knew about for ages but didn’t get the point of until someone showed me this ONE WEIRD TRICK1 that uses it to ASTONISHING effect2. I added it to my toolkit, and after a while found myself using CTRL-A in loads of other scenarios too!
The :help for CTRL-A in insert mode is… shall we say… concise:
CTRL-A Insert previously inserted text.
The “previously” here is referring to the last time you were in insert mode.
So what is this good for? Let’s say I’ve just typed the line:
print("I love Vim it's the best")
But then I realise I’m also going to need to pass that string into a different function slightly later on in my code. I should have made it a variable!
The fix is simple. After placing the cursor somewhere inside the string, I type:
- ca"
- Change “a quoted string”
- vimIsTheBest
- Enter the new variable name
- <Esc>
- Exit insert mode
- O
- Start a new line above
- <C-A>
- “Insert previously inserted text.” i.e. the variable name we just typed
- <Space>=<Space><Esc>
- Add an equals sign and then exit insert mode.
- p
- Paste the variable’s value
Resulting in this:
vimIsTheBest = "I love Vim it's the best"
print(vimIsTheBest)
Refactor complete!