vimtricks.wiki Concise Vim tricks, one at a time.

How do I configure :make to run the current file as a script with a specific interpreter?

Answer

:set makeprg=python3\ %

Explanation

Setting makeprg to include % lets :make always execute the file you're currently editing. The % is a special Vim filename modifier that expands to the current buffer's filename at the time :make is called — so you never have to hardcode a filename.

How it works

  • makeprg defines the shell command that :make runs
  • % in makeprg is expanded to the current buffer's filename before execution
  • The backslash escapes the space in the shell command (needed in Vim option strings)
  • Any output goes to the quickfix list; use :copen to view it
  • To navigate errors: :cnext / :cprev (requires a matching errorformat)

Example

For a Python project:

:set makeprg=python3\ %
:make
" Runs: python3 /path/to/current/file.py

For other languages:

:set makeprg=node\ %      " JavaScript
:set makeprg=go\ run\ %   " Go
:set makeprg=ruby\ %      " Ruby

Tips

  • Put this in a filetype autocmd to make it automatic:
    autocmd FileType python setlocal makeprg=python3\ %
    
  • Use :set makeprg? to inspect the current value
  • The %:S modifier shell-escapes the filename, safer if it contains spaces: :set makeprg=python3\ %:S
  • Combine with set autowrite to auto-save before running :make

Next

How do I open the directory containing the current file in netrw from within Vim?