1

To execute and debug different kind of programs, I mapped the function keys in the .vimrc-file.

E.g.

" save and execute perl
:noremap <F5> :w<CR>:!./%<CR>
" save and execute aql
:noremap <F9> :w<CR>:!db<%<CR>
" ...

Works so far. But I would like do press always F5 to save and execute. No matter which programming language!

So I tried to set a "syn_exec" variable in the syntax file (e.g. ~/.vim/syntax/dbquery.vim ~/.vim/after/syntax/perl.vim)

There I have:

" -- Syntax-File --
let syn_exec = [ '', '', '', '', '!db < %', '!db -E < %', '!db -csv < % | ~/db_tools/dev.pl' ]
" -- .vimrc --
:noremap <F5> :w<CR>:execute syn_exec[4]<CR>
:noremap <F6> :w<CR>:execute syn_exec[5]<CR>
" ...

So far so good. If I open a file, syn_exec is set and F5 executes the code.

If I open another file with another code type (:tabe ~/foo.pl), the syntax-file overwrites the "syn_exec" variable. Then I can execute the code of new opened file.

But if I change back to the previous tab, the "syn_exec" doesn't change again...

I think there is a very easy solution to map key concerning to the file-type / code-type. But I don't get it.

2 Answers 2

1

I would suggest you to define the variable syn_exec as a buffer variable

" -- Syntax-File --
let b:syn_exec = [ '', '', '', '', '!db < %', '!db -E < %', '!db -csv < % | ~/db_tools/dev.pl' ]
" -- .vimrc --
:noremap <F5> :w<CR>:execute b:syn_exec[4]<CR>
:noremap <F6> :w<CR>:execute b:syn_exec[5]<CR>
" ...
0

I am not sure if this is what you are looking for, but you can combine the keyword FileType with autocmd. Inside of a .vimrc:

autocmd FileType python map [COMMAND]
autocmd FileType cpp map [COMMAND]

If it recognizes that I have a python file (.py), the first key mapping is taken, and if it is C++, the second one is taken


In my .vimrc file:

autocmd FileType python map <buffer> <F9> :w<CR>:exec '!python3' shellescape(@%, 1)<CR>
autocmd FileType cpp    map <buffer> <F9> :w<CR>:!g++ % -std=c++20 -o %< && ./%< <CR>

Like this, it executes the program based on the FileType.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.