I've found the following command to execute Python or Matlab or any other language as far as I understand to execute code

nnoremap <buffer> <F9> :exec '!python' shellescape(@%, 1)<cr>



map <F5> <Esc>:w<CR>:!%:p<CR>

(source; supposedly should work for all scripts as it uses vim expand however I had this working before but now is giving me a shell returned 126 error)

Is there a way to automatically execute the code without explicitly specifying the command?

In other words, if I have any script (Matlab, Python, Latex, ...) open and I press F9 the script is executed?

Or maybe there's a package for such a thing?

2 Answers 2


You are looking for the makeprg option, :h 'makeprg':

                                    *'makeprg'* *'mp'*
'makeprg' 'mp'                      string    (default "make", VMS: "MMS")
                                    global or local to buffer |global-local|
                                    {not in Vi}
    Program to use for the ":make" command.  See :make_makeprg.

    This option may contain '%' and '#' characters, 
    which are expanded to the current and alternate file name.  Use |::S| 
    to escape file names in case they contain special characters.
    Environment variables are expanded |:set_env|.  See |option-backslash|
    about including spaces and backslashes.

    Note that a '|' must be escaped twice: once for ":set" and once for
    the interpretation of a command.  When you use a filter called
    "myfilter" do it like this:

        :set makeprg=gmake\ \\\|\ myfilter

    The placeholder "$*" can be given (even multiple times) to specify
    where the arguments will be included, for example:

        :set makeprg=latex\ \\\\nonstopmode\ \\\\input\\{$*}

    This option cannot be set from a |modeline| or in the |sandbox|, for
    security reasons.

The best way to use it is to define the option in an ftplugin. For example for python create ~/.vim/after/ftplugin/python.vim containing:

setlocal makeprg=python\ %

Create a new ftplugin and adapt the makeprg for each filetype you want to handle.

Then you can simply use the command :make in the file you want to source or create a mapping like nnoremap <F5> :make<CR>.

Some related help topics:


Surprisingly, the problem had nothing to do with the command listed in the question. Apparently, the order of the commands in .vimrc matters.

I moved the mapping to the top of the file and it worked.

Hope this helps others while the downvoters continue their greedy search for more points.

Update: It is no longer at the top of the vimrc however at the time it seemed like something else was interfering with it.

Your Answer

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

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