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
makeprgdefines the shell command that:makeruns%inmakeprgis 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
:copento view it - To navigate errors:
:cnext/:cprev(requires a matchingerrorformat)
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
%:Smodifier shell-escapes the filename, safer if it contains spaces::set makeprg=python3\ %:S - Combine with
set autowriteto auto-save before running:make