how to temporarily set makeprg in vim

vim

Solution

If you want to save and restore an option before/after a function call in vim, you would do it like this:

let oldmakeprg = &l:makeprg
try
  " set new value of makeprg and call the function
  set makeprg=new\ value
  call MyFunction()
finally
  " set makeprg back to old value
  let &l:makeprg = oldmakeprg
endtry

You could also put your 'foobar' code in a special folder and have a separate autocommand to set makeprg separately for that:

" normal settings for makeprg
au FileType c set makeprg=gcc\ %
au FileType cpp set makeprg=g++\ %

" special settings for foobar code
au BufRead,BufNewFile **/foobar/**.c set makeprg=gcc\ %
au BufRead,BufNewFile **/foobar/**.cpp set makeprg=g++\ %

Problem

In the normal case I use vim's make utility I will set makeprg to the Makefile of the project I'm currently working for. Since usually the project will last for weeks or even longer, I don't need to change the setting of makeprg very often . But sometimes I need to write some "foobar" code either for practicing my c++ skill or for prototyping some primitive ideas in my mind. So whenever I switch to the "foobar" mode of vim usage, I need to comments the original makeprg setting add the new setting as following : ``` au FileType c set makeprg=gcc\ % au FileType cpp set makeprg=g++\ % ``` which is really very very inconvenient . when I back to the "normal project mode" of vim usage, I need to change back to the original setting . back and forth .... what I want to know from you guys is that : is it possible to make the setting of makeprg temporarily . for example , define a function in which first set a local value of makeprg and then call make before return form the function call automatically restore makeprg to the value before the function call.

Original source