Vim [编译和] 运行快捷方式

2021-12-24 00:00:00 python shell c vim c++

基本上我想要的是 vim 中的键盘快捷键,让我[编译和]运行当前正在编辑的 C、C++ 或 Python 程序.在伪代码中:

Basically what I want is a keyboard shortcut in vim that lets me [compile and] run the currently being edited C, C++ or Python program. In psuedocode:

when a shortcut key is pressed:
    if current_extension == 'c' then
        shell: gcc this_filename.c -o this_filename_without_extension
        if retcode == 0 then shell: ./this_filename_without_extension
    else if current_extension == 'cpp' then
        shell: g++ this_filename.cpp -o this_filename_without_extension
    if retcode == 0 then shell: ./this_filename_without_extension
    else if current_extension == 'py' then
        shell: python this_filename.py
    end if
end key

我意识到我的要求可能有点高,但如果可能的话我会很喜欢的!

I realise I might be asking a bit much but would love it if this was possible!

推荐答案

这样的事情会起作用.只需创建映射 或任何您想保存并编译和运行程序的文件类型 autocmd.它使用 exec 来构建字符串并使用 shellescape 来转义文件名.

Something like this would work. Just create filetype autocmd that map <F4> or whatever you want to save and compile and run the program. It uses exec to build the string and uses shellescape to escape the file name.

autocmd filetype python nnoremap <F4> :w <bar> exec '!python '.shellescape('%')<CR>
autocmd filetype c nnoremap <F4> :w <bar> exec '!gcc '.shellescape('%').' -o '.shellescape('%:r').' && ./'.shellescape('%:r')<CR>
autocmd filetype cpp nnoremap <F4> :w <bar> exec '!g++ '.shellescape('%').' -o '.shellescape('%:r').' && ./'.shellescape('%:r')<CR>

% 是当前缓冲区文件名.%:r 是没有扩展名的缓冲区文件名

% is the current buffer filename. %:r is the buffer filename without extension

相关文章