ghayalcoder
ghayalcoder

Reputation: 1735

Autocommand not working in Vim, how to set makeprg based upon the filetype?

I use Vim editor for programming and here's the problem that I am facing.

I am using multiple tabs to edit C++ and Python files simultaneously and I have added the following in my .vimrc file

filetype plugin indent on
au filetype python set mp=python3\ %
au filetype cpp set mp=g++\ -Werror\ -Wextra\ -Wall\ -ansi\ -pedantic-errors\ -g\ %

i.e all I want is that when I switch to a tab with a Python file and run :make, it should run :!python3 %, and when I switch to a tab with a C++ file and run :make it should run :!g++ -Werror -Wextra -Wall -ansi -pedantic-errors -g %

However it's not working, and everytime I switch the tab and run :make, it tries to execute !g++ -Werror -Wextra -Wall -ansi -pedantic-errors -g % and when I run :set ft? on the 2 files(i.e Python and C++) to check whether the filetypes have been correctly identified or not, I get the correct result i.e python and cpp.

Then why is this autocommand not working? Am I missing something? Thanks for your patience

Upvotes: 3

Views: 2318

Answers (1)

nelstrom
nelstrom

Reputation: 19542

Try using setlocal instead of set. e.g.:

filetype plugin indent on
au filetype python setlocal mp=python3\ %
au filetype cpp setlocal mp=g++\ -Werror\ -Wextra\ -Wall\ -ansi\ -pedantic-errors\ -g\ %

If you read :help mp, you'll see that the setting is 'global or local to buffer global-local'. This means that you can use set to apply a makeprg globally, or setlocal to override it for a single buffer.

Upvotes: 9

Related Questions