Skip to content

Pre launch building strategies

jclsn edited this page Apr 4, 2023 · 12 revisions

In many cases you will want to rebuild your project before starting a new debugging session. Vimspector has no built-in pre-launch task feature. However, there are some strategies to achieve similar functionality.

To use Vim's built-in make command (:h make) to rebuild and run the debugger afterwards you can create a simple mapping like (if you use the human mode mapping F12 is already mapped to <Plug>VimspectorStepOut though):

nnoremap <F12> :make | vimspector#Launch()<CR>

Since this solution requires you to press enter every time you want to debug, it is not optimal. Here is one proposal for a more convenient solution:

Install the vim-dispatch plugin, which provides an asynchronous :Make alternative to :make. Since :Make is asynchronous, its successful completion has to be checked differently.

Using this Vimscript snippet, you will get a very convenient :Debug command, that only runs when compilations was successful:

" Creates a function to run :Make, close the quickfix window and run a callback function                                         
function! RebuildAndDebug()                                                    
  Make                                                                       
  cclose                                                                     
  autocmd QuickFixCmdPost make ++once call RunVimspectorIfBuilt()          
endfunction                                                                  
                                                                             
" Catch the status value of :Make to no launch when building was unsuccessful
function! RunVimspectorIfBuilt()                                             
  let status = +readfile(dispatch#request().file . '.complete', 1)[0]        
  if status == 0                                                             
    call vimspector#Launch()                                                 
  endif                                                                      
endfunction                                                                  
                                                                             
" Finally, create a :Debug command to run all the above                      
command! Debug call RebuildAndDebug()                                          

You can now map the :Debug command to F12 in addition to the Visual Studio mapping or whatever else you prefer.