Are you committing from Vim the fast way?

A smol commit shortcut for vim

vim, linux

Sometimes I just change 1 or 2 lines and want to commit & push straight away. Its times like these where I don't really want to have to check the diff and stage each file etc... But I still want to enforce some kind of commit message convention, namely:

<BRANCH_NAME> <COMMIT_TYPE> <MESSAGE>
e.g. main fix: made background white

So <COMMIT_TYPE> is fix in this case.
Because I use vim, I want to introduce a shortcut into my workflow in order to make this process easier. So my goal is to press a key combination in vim and the below command to populate the command input box:

VIM
:G commit -am "<BRANCH_NAME> fix: <cursor here>"

It should show up like this:

Git commit command generated in vim command barGit commit command generated in vim command bar

First of all lets decide what the keybinding will be.
I'm a simple man, I'm gonna bind it to ,f so I remember it.
(because its f for fix XD)

VIM
noremap ,f ...

Next we need to create the git command. I am using :G that comes from the vim-fugitive plugin by tpope. Its basically just a shortcut for :!git so feel free to do that instead.

Next is commit -am. Most people know about -m but fewer have heard of -am.
It basically is the same as -m but it automatically stages all the changes you have in the repo.

VIM
noremap ,f :G commit -am ""

Now we just need to generate the commit message, and for that we need to know what the name of the current branch is. Usually we can do that with git branch --show-current however, since git is external to vim we need some special syntax.

To execute an external command we can use the system function like so:

VIM
..."<C-R>=system("git branch --show-current")<CR>

For some reason ^@ gets stuck to the end of whatever the branch name is. To get rid of that we can backspace <BS> once. Now we press the <Left> key to move the cursor one space left inside the quotes.

VIM
..."<C-R>=system("git branch --show-current")<CR><BS>"<Left>

Now leave a <Space> and write the commit type, in this case fix.
Finally add a colon and another <Space> for the commit message and we are done.

VIM
..."<C-R>=system("git branch --show-current")<CR><BS>"<Left><Space>fix:<Space>

Putting it altogether we get the finished product:

VIM
noremap ,f :G commit -am "<C-R>=system("git branch --show-current")<CR><BS>"<Left><Space>fix:<Space>

Now you too can make a smol commit from vim with just a few keystrokes!

Subscribe

No Webmentions for this post yet!