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:
- Change “a quoted string”
- Enter the new variable name
- Exit insert mode
- Start a new line above
- “Insert previously inserted text.” i.e. the variable name we just typed
- Add an equals sign and then exit insert mode.
- Paste the variable’s value
Resulting in this:
vimIsTheBest = "I love Vim it's the best" print(vimIsTheBest)