Reputation: 22254
I'm looking to write a vim macro (not that I know how yet) eventually, as I'm sure I can do this in vim, but I don't know the basics yet.
I want to grab the branch name (or part of it anyway - that part of the regex should be straightforward) from a git commit message, and paste it, with a colon, to the top of the file, and hopefully leave the cursor at the end of that.
So the file looks a bit like this when I start:
$ <-- cursor here
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch JIRA-1234-some-description-here
# Your branch is up to date with ...
I want to capture the /On branch \([A-Z]*-[0-9]*\)/
, move back up to the top, paste it, and a colon, leaving the cursor after the colon, e.g.:
JIRA-1234: $ <-- cursor here
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch JIRA-1234-some-description-here
# Your branch is up to date with ...
Ideally, also leave me in insert mode there.
Upvotes: 0
Views: 255
Reputation: 7627
You could use this function:
function! MyFunction()
g/On branch \([A-Z]*-[0-9]*\)/exe "co0 | 1s/.* \\(.*-\\d\\+\\).*/\\1:/g"
normal $
endfunction
and then map it:
nmap <leader>f :call MyFunction()<cr>
Explanation of function: the global command g/{pat}/[cmd]
executes the command [cmd]
on lines where pattern {pat}
matches. You've already provided {pat}
in your question. Then, to execute more than one command I recommend to use exe
. Here exe
copies the matched line to the first line (co0
) and performs the replacement (1s/.../\\1:/g
).
Upvotes: 1
Reputation: 45087
Assuming you are using fugitive.vim you can use fugitive#head()
to get the current branch name. You can probably do something like this (put in vimrc
file):
augroup MyCommit
autocmd!
autocmd FileType gitcommit call setline(1, substitute(fugitive#head(), '^\([A-Z]\+-[0-9]\+\).*', '\1: ', ''))
augroup END
Note: I have not tested this in anyway.
Upvotes: 1