vim一键运行Python/C/C++/go

vim一键运行Python、C、C++、go、html

" 用<F5>运行
noremap <silent> <F5> :call CompileRun()<CR>
func! CompileRun()
    exec "w"
    let g:asyncrun_open = 10
    let g:asyncrun_bell = 1
    let l:filename = expand('%:t')          " 文件名,如 main.c
    let l:filepath = expand('%:p')          " 完整路径
    let l:filedir = expand('%:p:h')         " 文件目录
    let l:filenamenoext = expand('%:t:r')   " 无后缀文件名,如 main
    let l:exe = l:filedir . '/' . l:filenamenoext  " 可执行文件路径
    if &filetype == 'c'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 gcc -Wall -O2 \"" . l:filepath . "\" -o \"" . l:exe . "\" && \"" . l:exe . "\""
    elseif &filetype == 'cpp'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 g++ -Wall -O2 -std=c++13 \"" . l:filepath . "\" -o \"" . l:exe . "\" && \"" . l:exe . "\""
    elseif &filetype == 'python'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 python3 \"" . l:filepath . "\""
    ""elseif &filetype == 'html'
        " Linux 下使用 xdg-open,静默打开浏览器
        ""exec ":AsyncRun -mode=term -pos=hide firefox \"" . l:filepath . "\""
    elseif &filetype == 'html'
    if executable('xdg-open')
        exec ":AsyncRun -mode=term -pos=hide nohup xdg-open \"" . l:filepath . "\" > /dev/null 2>&1 &"
    else
        echo "xdg-open not found! Run: sudo apt install xdg-utils"
    endif
    elseif &filetype == 'go'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 go run \"" . l:filepath . "\""
    elseif &filetype == 'javascript'
        exec ":AsyncRun -mode=term -pos=bottom -rows=10 -focus=0 node \"" . l:filepath . "\""
    else
        echo "Unsupported filetype: " . &filetype
    endif
endfunc

提前安装 AsyncRun.vim 插件

可选:清理旧可执行文件(防止缓存) 在函数开头加:

silent! exec “!rm -f \”” . l:exe . “\””

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注