Grzegorz Wierzowiecki
Grzegorz Wierzowiecki

Reputation: 10843

Changing Vim behavior by file type using single `.vimrc` (without ftplugin)

How to change Vim behaviour using single .vimrc file (without ftplugin) in elegant way ?

What do I mean is ... if I run many commends for C/C++ file , e.g.:

set nu
set cin
set ai
set mouse=a
color elflord

and another bunch of commends for AsciiDoc files, e.g.:

set syntax=asciidoc
set nocin
set spell spl=en

Not mentioning about Python, LaTeX etc....

There is solution presented https://stackoverflow.com/a/159065/544721 for putting autocommand before every custom command.

Is there a nice way to group them for autocommand without using ftplugin - in order to keep everything in single .vimrc file (better for moving around many machines, etc.) ? Something equivalent to if statement with brackets {} ?

Upvotes: 3

Views: 785

Answers (2)

dash-tom-bang
dash-tom-bang

Reputation: 17843

I'd probably do per-filetype functions to do the setup for me. Shamelessly ripping off @Derek...

function! SetUpLispBuffer()
    set lisp
    set showmatch
    set cpoptions-=m
    set autoindent
endfunction

function! SetUpCBuffer()
    set formatprg=c:\\AStyle\\bin\\AStyle.exe\ -A4Sm0pHUk3s4
    set tw=80
endfunction

if has("autocmd")
    augroup LISP
        au!
        au BufReadPost *.cl call SetUpLispBuffer()
    augroup END
    augroup C
        au!
        autocmd BufNewFile,BufRead *.{cpp,c,h} call SetUpCBuffer
    augroup END
endif

A lot less to change when you want to make changes and much less cut&paste too.

Upvotes: 3

Derek
Derek

Reputation: 3137

You can use the following:

if has("autocmd")
    augroup LISP
        au!
        au BufReadPost *.cl :set lisp
        au BufReadPost *.cl :set showmatch
        au BufReadPost *.cl :set cpoptions-=m
        au BufReadPost *.cl :set autoindent
    augroup END
    augroup C
        au!
        autocmd BufNewFile,BufRead *.cpp set formatprg=c:\\AStyle\\bin\\AStyle.exe\ -A4Sm0pHUk3s4
        autocmd BufNewFile,BufRead *.c set formatprg=c:\\AStyle\\bin\\AStyle.exe\ -A4Sm0pHUk3s4
        autocmd BufNewFile,BufRead *.h set formatprg=c:\\AStyle\\bin\\AStyle.exe\ -A4Sm0pHUk3s4
        autocmd BufNewFile,BufRead *.cpp set tw=80
        autocmd BufNewFile,BufRead *.c set tw=80
        autocmd BufNewFile,BufRead *.h set tw=80
    augroup END
endif

This created grouping of commands depending on the type of file that is opened, which is specified in the autocmd section. You still need to specify autocmd or au before each one, but they are nicely grouped.

Upvotes: 3

Related Questions