If I understand correctly, Maxim Kim's solution was close to perfect, the only missing thing is that the exact command to run should be specific to the current project. IOW, the value to use should be buffer local.
As this is something I do a lot in my plugins, I've factorized everything regarding option fetching to option toggling (I also have a :Toggle
command).
Anyway. A poor man's solution could be the following.
" ~/ftplugin/cpp/cpp_yourmappings.vim
" When I have several ft-specific things to define I avoid polluting the .vimrc
" Little helper that simplifies my lh#option#get() command
" See https://old.reddit.com/r/vim/comments/p5zgdp/can_someone_explain_variables_to_me/h9cx7f5/
let s:GET_OR = { key, default -> filter([w:, b:, t:, g:, {key : default}], {_,v -> has_key(v, key)})[0][key]}
let s:k_option_name = 'run_cpp_with_options'
" yap + p from Maxim Kim's solution
function! s:RunCpp() abort
let with_options = s:GET_OR(s:k_option_name, 0)
if with_options
let cmd = ":RunWithFile ~/Downloads/ > output.txt && cat output.txt\<s-left>\<s-left>\<s-left>\<s-left>\<s-left>\<left>"
else
let cmd = ":RunWithFile"
endif
call feedkeys(cmd)
endfunction
function! s:toggle(scope) abort
let dict = a:scope == 'b' ? (b:) : (g:)
let dict[s:k_option_name] = ! s:GET_OR(s:k_option_name, 0)
echo printf('%s:%s <- %s', a:scope, s:k_option_name, dict[s:k_option_name])
" I haven't tried to handle cases like b:foo and g:foo exist and we want to toggle g:foo
endfunction
" To execute
nnoremap <buffer> <silent> <F4> :<c-u>call <sid>RunCpp()<cr>
" To toggle locally
nnoremap <buffer> <silent> <F5> :<c-u>call <sid>toggle('b')<cr>
" To toggle globally, without resetting any previously existing b:values
nnoremap <buffer> <silent> <F6> :<c-u>call <sid>toggle('g')<cr>
Note: I haven't tested the code. If the feedkeys()
part doesn't work, I'll revert to old solutions that always work: a simple return cmd
+ <c-r>=
should do. (I've learned to avoid feedkeys()
but I've trusted previous answer)
\X
i could access to<F4>
..:RunWithFile
was not by default .. but toggle was great :)