2

I'm trying to write an autocmd to make a commit to a git repository. Here is some non-functional code that should illustrate what I'm trying to do:

let g: CommMsg = ''

augroup misc
  autocmd!
  autocmd nmap <buffer> gc :call GetCommMsg()<CR>!git commit -m '=CommMsg'<CR>
augroup END

function! GetCommMsg()
  let curline = getline('.')
  call inputsave()
  let name = input('Enter message: ')
  call inputrestore()
  let CommMsg = call setline(',', curline . ' ' . name)
endfunction

The intention here is to use the GetCommMsg() function to get the message from the user, set a global variable to this value and then pass it to the git commit command as the message argument.

Is this possible?

2 Answers 2

5

Maybe this is what you're aiming for?

nnoremap gc :execute '!git commit -m "'.input('Enter message: ').'"'<cr>

The only parts of your script that would do anything useful is the first line and the nmap line. The rest of it would either do nothing or not run at all.

Since you're starting to learn VimL, here's a tip: Test simple ideas in the command line. Every line in a VimL script is something that you can type verbatim in the command line. You would've seen that the '=CommMsg' part of your script would end up being your commit message.

2
  • Oops, I accidentally deleted the autocmd from my sample script. Fixed. Your suggestion did not work. Thanks for your input, though. I did get this to work. I'll post in answer.
    – StevieD
    Feb 13, 2017 at 3:19
  • 1
    It does work. I just forgot to add <cr> at the end.
    – Tommy A
    Feb 13, 2017 at 3:24
1

So this seems to work pretty well:

augroup misc
  autocmd!
  autocmd BufEnter * nmap <buffer> gc :call GetCommMsg()<CR>
augroup END

function! GetCommMsg()
  let curline = getline('.')
  call inputsave()
  let msg = input('Enter commit message: ')
  call inputrestore()
  call system("git commit -m '" . msg . "'")
endfunction

Not sure if there are any downsides to doing it this way or not.

1
  • I think it's probably better to just map to vim-fugitive's :Gcommit e.g. nnoremap <Leader>gc :Gcommit<CR> Feb 13, 2021 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.