Compiling code from vim
Solution 1
Write a Makefile
, then you can simply:
:make
from inside vim. And if compilation fails:
:copen
will show you warning and errors. Selecting them will take you to the appropriate file and line.
Solution 2
In vim, the current file can be referred to as %, so
:!python %
See :he cmdline-special
(or here)
Solution 3
If you don't like makefiles for some reason you can call any command with :!
For example you can use ":!javac *.java && java Foo" to compile and run a simple java program. You can also call other build systems (scons, cmake, ...) this way.
Solution 4
Vim can be used to compile using gnu make on the current file - even if there's no Makefile for the file (for more details see here):
:make %:r
This way vim provides you with access to the quickfix error feedback from the compiler (:help quickfix
) list - :cn
Next error, :cp
Previous error, :cw
New window listing errors.
If you've not got gnu make then you can set the makeprg variable (change to g++ if you're compile C++):
:se makeprg=gcc\ -o\ %<\ %
and then use the vim make command to compile the current file and get a quickfix list of errors in vim:
:make
EDIT: If you also want to run the compiled executable from within vim you can do ('!' executes, '%:r' is the filename without its suffix):
:!./%:r
Solution 5
I use a vim that has Python interpreter compiled in.
I source a python file that has this function:
def pyterm(filename="", interactive=1):
cmd = "%s %s %s " % (PYTHON, "-i" if interactive else "", filename)
if "DISPLAY" in os.environ:
return run_config(os.environ.get("XTERM"), cmd)
else:
return os.system(cmd)
And map it to a keyboard shortcut:
nmap ;ru :update<CR>:python pyterm(vim.current.buffer.name, 0)<CR>
nmap ;ri :update<CR>:python pyterm(vim.current.buffer.name, 1)<CR>
I had previous set some environment variables to determine the exact terminal to run in if using gvim, or in the same terminal if not in a X.
Then I usually just type ';ri' in a Python buffer to run it (usually to test it).
Related videos on Youtube
phunehehe
Updated on September 17, 2022Comments
-
phunehehe over 1 year
New to
vim
and and I want to be able to compile code from withinvim
without running a new terminal and calling the compiler.How do I go about doing this? Note that this requirement is not restricted to
gcc
only, I sometimes need to callpython
also on the current script I am working on, so you get the idea...-
elig about 3 yearsCheck out github.com/tpope/vim-dispatch it allows you to set different compiler commands per file type and invoke them easily
-
-
Pierz over 9 yearsA more complete answer would include the ':', and to make it more versatile you could change 'file.c' for the current file operator '%' :
:!gcc % && ./a.out
-
user15269806 over 7 yearsI'm doing something similar in my
.vimrc
, I mapCommand + Shift + R
to:map <D-R> :exe '!gcc %:p' <bar> exe '!'.getcwd().'/a.out'<cr>