dotfiles/dot_config/nvim/langprefs/run.vim

74 lines
2.7 KiB
VimL
Raw Permalink Normal View History

2024-07-13 13:41:00 +03:00
function s:TraverseBackwardsUntilFound(path, glob)
let cur_path = resolve(fnamemodify(a:path, ':p:h'))
while cur_path != "/"
let result = globpath(cur_path, a:glob)
if result != ""
return result
endif
let cur_path = resolve(cur_path.."/..")
endwhile
return ""
endfunction
function! ExecuteCurrentFile()
let file_wd = expand('%:p:h')
let file_name = expand('%:t')
echom "Running ".file_name
let lines = readfile(expand('%'))
let ndx = match(lines, "x-run: .*")
let makefile_path = s:TraverseBackwardsUntilFound(file_wd, "Makefile")
if ndx != -1
let cmd = matchstr(lines[ndx], "x-run: .*")[7:]
exec 'FloatermNew --autoclose=0 cd '.fnameescape(file_wd).'; '
\ . substitute(cmd, '%', fnameescape(file_name), '')
elseif &filetype == 'python'
exec 'FloatermNew --autoclose=0 cd '.fnameescape(file_wd).'; '
\ . 'python3 '.fnameescape(file_name)
elseif &filetype == 'lua'
exec 'FloatermNew --autoclose=0 cd '.fnameescape(file_wd).'; '
\ . 'lua '.fnameescape(file_name)
elseif &filetype == 'c'
let exec_name = expand('%:t:r')
exec 'FloatermNew --autoclose=0 cd ' . fnameescape(file_wd) . '; '
\ . 'cc -o '.fnameescape(exec_name).' '.fnameescape(file_name)
\ . ' -lm'
\ . ' && '
\ . 'exec '.fnameescape(exec_name)
elseif &filetype == 'rust'
let cargo_file = s:TraverseBackwardsUntilFound(file_wd, "Cargo.toml")
if cargo_file != ""
exec 'FloatermNew --autoclose=0 cd '.fnameescape(file_wd).'; cargo run'
else
let exec_name = expand('%:t:r')
exec 'FloatermNew --autoclose=0 cd ' . fnameescape(file_wd) . '; '
\ . 'rustc '.fnameescape(file_name)
\ . ' && '
\ . 'exec '.fnameescape(exec_name)
endif
elseif &filetype == 'vim'
exec 'source '.expand('%')
elseif &filetype == 'dot'
let img_name = expand('%:t:r') . ".png"
exec '! cd ' . fnameescape(file_wd) . '; '
\ . 'dot -Tpng '.fnameescape(file_name).' >'.fnameescape(img_name)
\ . ' && '
\ . 'sxiv '.fnameescape(img_name)
elseif &filetype == 'sh'
exec 'FloatermNew --autoclose=0 cd ' . fnameescape(file_wd) . '; '
\ . '/bin/bash ' . fnameescape(file_name)
elseif makefile_path != ""
let makefile_dir = fnamemodify(makefile_path, ":p:h")
exec 'FloatermNew --autoclose=0 cd '.fnameescape(makefile_dir).'; '
\ . 'make run'
else
echohl ErrorMsg
echom "Unknown file type: ".&filetype
echohl None
endif
endfunction
nnoremap <F12> :w<CR>:call ExecuteCurrentFile()<CR>
inoremap <F12> <ESC>:w<CR>:call ExecuteCurrentFile()<CR>a