mrwooster
mrwooster

Reputation: 24207

Run terminal command from VIM?

I wish to write a function which I can add to my .vimrc file that will call a terminal command, and then bind it to <leader>u.

I cant seem to get it to work tho. I believe that I can use the system() function, but there is very little documentation available and I cant seem to get it to work.

The terminal command in question is 'git push origin master'.

I know that there are plugins available for git but I am not looking for any of these, just a simple function to bind a terminal command to a key combination.

function gitPush()
 system("git push origin master")
endfunction
:nmap <leader>u :call gitPush()

I know this is waaay out, but vim doesnt seem to want to make documentation very available.

Ty

Upvotes: 2

Views: 2699

Answers (2)

ZyX
ZyX

Reputation: 53604

Why do you use call to call your own function and fail to use it for builtin? It is one of three errors, other was mentioned by @Richo: user-defined function must either start with a capital or with b:, w:, t: (note that neither of these are local functions), g:, s: (only inside scripts, and you will have to replace s: with <SID> in mappings), even \w: (for example, function _:foo() works) or with {filename_without_extension}# (if filename matches \w+.vim). If it is anonymous function:

let dict={}
function dict["foo"]()
endfunction
function dict.bar()
endfunction

it also does not require to start with a capital. So the correct solution is:

function g:gitPush()
  call system("git push origin master")
endfunction
nnoremap <leader>u :call g:gitPush()<CR>

Third error is omitting <CR>. I changed nmap to nnoremap because it is good to use nore where possible. Having : at the start of the command does not hurt and is not an error, but I just do not write it: it is required in normal mode mappings to start command mode, but not inside scripts.

Upvotes: 1

richo
richo

Reputation: 8989

function GitPush()
    !git push origin master
endfunction

Is the way to run a command in a subshell.

EDIT: User defined functions must begin with a capital letter too ;)

Upvotes: 7

Related Questions