vl_stackoverflow
vl_stackoverflow

Reputation: 113

.vimrc script for compiling with g++

I want to write a short script in my .vimrc to compile .cpp files with g++ in vim and open the errors/output in a new vertical buffer to my actual file like this:

  1. create a vim command ":set vimcompiling" that induces the following steps
  2. save the file: ":w"
  3. compile it: ":make ./name" (without leaving vim!)
  4. open the file in a new buffer: if there are errors: ":vert copen n" else: execute the file in a new vertical buffer
  5. map these steps (2-4) to "F5" so I can execute step 2-4 any time I want to compile

Can anyone give me some tips on how to write such a script?

Upvotes: 0

Views: 394

Answers (1)

Luc Hermitte
Luc Hermitte

Reputation: 32926

BuildToolsWrappers already has this built in and bound to F5.

Executing :make %< is easy. However detecting errors to open the quickfix window or not is more tricky. In BTW I use the following

" Function: lh#btw#build#_show_error([cop|cwin])      {{{3
function! lh#btw#build#_show_error(...) abort
  let qf_position = lh#option#get('BTW_qf_position', '', 'g')

  if a:0 == 1 && a:1 =~ '^\%(cw\%[window]\|copen\)$'
    let open_qf = a:1
  else
    let open_qf = 'cwindow'
  endif

  " --- The following code is borrowed from LaTeXSuite
  " close the quickfix window before trying to open it again, otherwise
  " whether or not we end up in the quickfix window after the :cwindow
  " command is not fixed.
  let winnum = winnr()
  cclose
  " cd . is used to avoid absolutepaths in the quickfix window
  cd .
  exe qf_position . ' ' . open_qf

  setlocal nowrap

  " if we moved to a different window, then it means we had some errors.
  if winnum != winnr()
    " resize the window to just fit in with the number of lines.
    let nl = 15 > &winfixheight ? 15 : &winfixheight
    let nl = lh#option#get('BTW_QF_size', nl, 'g')
    let nl = line('$') < nl ? line('$') : nl
    exe nl.' wincmd _'

    " Apply syntax hooks
    let syn = lh#option#get('BTW_qf_syntax', '', 'gb')
    if strlen(syn)
      silent exe 'runtime compiler/BTW/syntax/'.syn.'.vim'
    endif
    call lh#btw#filters#_apply_quick_fix_hooks('syntax')
  endif
  if lh#option#get('BTW_GotoError', 1, 'g') == 1
  else
    exe origwinnum . 'wincmd w'
  endif
endfunction

Upvotes: 1

Related Questions