Search code examples
vimfile-type

What exactly happens when you change a file type in vim?


If I have an apache file in /etc/apache2/sites-available/www.example.com and I set its filetype like so

:set filetype=apache

What does that do? Does that change the file at all? Is it only reflected in the instance of vim? The session of vim? I can manually set the filetype, but then vim warns me that I am in read only mode (/etc/apache2 needs root access). If I open vim as root, I won't get the warning, but if I leave and open it again (as normal or root), the filetype is gone. How do I make this more permanent, at least when called from the same session file


Solution

  • set filetype changes the way vim handles the file, by invoking all the FileType autocommands. It does not persist. If you want to always open that file with filetype=apache, try adding this into your .vimrc:

    au BufRead,BufNewFile /etc/apache2/sites-available/www.example.com set filetype=apache
    

    You can read more about it in:

    :help 'filetype'
    :help filetypes
    :help :autocmd
    :help .vimrc
    

    EDIT: as found in my /usr/share/vim/vim73/filetype.vim:

    au BufNewFile,BufRead access.conf*,apache.conf*,apache2.conf*,httpd.conf*,srm.conf* call s:StarSetf('apache')
    au BufNewFile,BufRead */etc/apache2/*.conf*,*/etc/apache2/conf.*/*,*/etc/apache2/mods-*/*,*/etc/apache2/sites-*/*,*/etc/httpd/conf.d/*.conf*        call s:StarSetf('apache')
    

    s:StarSetf will setfiletype to apache if the filetype doesn't match an ignored pattern. On my system, :echo g:ft_ignore_pat will show only archive file extensions as ignored. setfiletype does set filetype, but only once.

    So, at least on my system, the pattern */etc/apache2/sites-*/* would catch your filename and make it an apache file.