Creating multiple .vimrc for multiple languages?

3.7k views Asked by At

I am starting to learn programming and saw that it is possible to configure vim through the .vimrc file. But I'm having trouble creating more than one setting. I want a configuration for java and another for C, but I do not know how to only enable a configuration when programming in a particular language.

I found the following solution to my problem:

If it's okay to configure the local exceptions centrally, you can put such autocmds into your ~/.vimrc:

:autocmd BufRead,BufNewFile /path/to/dir/* setlocal ts=4 sw=4

(How to load different .vimrc file for different working directory?)

But I did not understand that solution.

I figured I should do the following:

  1. I wanted to create a C language setting on the Desktop. So I put in Shell (I'm using Mac OS) the following command vim ~/Desktop/.vimrc and put the desired configuration in this file.

  2. Then I put the following command in the file ~/.vimrc: autocmd BufRead,BufNewFile ~/Desktop/.vimrc setlocal ts=4 sw=4

  3. Then I went into the Shell and created a C file vim ~/Desktop/myprogram.c, but I realized that my setup had not worked.

Obviously I did something wrong, but I could not find the error, because I'm still noob.

2

There are 2 answers

16
Meninx - メネンックス On BEST ANSWER

For that you need 3 files: ~/.vimrc and two scripts let's say C-settings.vim and java-settings.vim

In the first file, the ~/.vimrc, you need to include these autocommands:

"To enable file type detection"
filetype on
augroup Java_C_Settings
    "the command below execute the script for the specific filetype C
    autocmd FileType c source /path-for-C-settings/C-settings.vim

    "the command below execute the script for the specific filetype Java
    autocmd FileType java source /path-for-Java-settings/Java-settings.vim
augroup END 

In the other files (C-settings.vim & Java-settings.vim) you put the settings that you need for every type of file *.c and *.java

Example:

C-settings.vim

set number
colorscheme blue

Java-settings.vim

set number
colorscheme evening

Whenever you open a file with vim the latter will check the filetype first and the settings will be automatically configured.


Note: if the setting files are not in the same directory you can rename them .exrc.

0
Luc Hermitte On

Use ftplugins they are meant for this.

Drop your C config in ~/.vim/ftplugin/c and so on. And don't forget to activate their support.

(This is actually a duplicate question)