vim automatic upward search for make and scons build scripts

If you happen to have your vim configured to change the current directory to the one where the edited file is stored(e.g. “autocmd BufEnter * :cd %:p:h”) you might find the following vim script handy.

Just put the code below somewhere into your .vimrc:

function! Compile()
  let origcurdir = getcwd()
  let curdir     = origcurdir

  while curdir != "/"
  if filereadable("Makefile")
    break
  elseif filereadable("SConstruct")
    break
  endif
  cd ..
  let curdir= getcwd()
  endwhile

  if filereadable('Makefile')
    set makeprg=make -j3 -k
  elseif filereadable('SConstruct')
    set makeprg=scons
  else
    set makeprg=make
  endif
  echo "building ... wait please!"
  silent w
  silent make
  redraw!
  cc!
endfunction

map <F9> :call Compile()<CR>

In short, once you press <F9>(which you can remap, of course) the Compile function searches upwards for any SConstruct or Makefile script and once found starts the build process using the proper build tool.

2 Responses to “vim automatic upward search for make and scons build scripts”

  1. Jim Says:

    Thanks for the post! This is a really handy vim function. So I take it you prefer scons then to make? I discovered scons about the same time you posted this last year. Won’t ever look back at make.

  2. pachanga Says:

    Yep, I’m currently a scons fan, however I’m also looking at CMake which is quite interesting for its ability to generate native build files(Makefile, KDevelop project, etc) for many platforms. This is really nice since end users won’t have to install CMake in order to build the application - standard tools(like make) should suffice.

Leave a Reply