Daryl Lee wrote:
I'm fairly new to Vim scripting and totally new to filetype
automation, so this problem has me stumped. I'm running Vim 7 in a
Windows environment.
My project has decided to use XML for configuration files, and the
file extension is .cfg. Because of the extension, Vim wants to "setf
cfg" in filetype.vim, but I'd like to override that with a "setf xml".
I can do so manually with ":setf xml" after the file loads, but I'd
love to automate that. And, of course, I have other .cfg files that
are not XML, so I can't use file extension for type detection. I'd
like to automate this.
The first line of the XML .cfg file looks like:
<?xml version = "1.0" encoding="ISO-8859-1"?>
I have a script (adapted from :help new-filetype-scripts):
if did_filetype() " filetype already set..
finish " ..don't do these checks
endif
if getline(1) =~ '^\<?xml '
setfiletype xml
endif
and I've placed it in ~/vimfiles/scripts.vim. (Windows: ~ =
c:\documents and settings\myusername)
I've tried deleting the opening if statement, but doing so had no
effect.
The filetype keeps coming up 'cfg'. Is my error in the pattern
matching in the script? Is the script in the wrong place? When I
open the config file and then run :scriptnames, my scripts.vim file is
not listed, so it doesn't seem to be loading. Is there another step
I'm missing?
Daryl
The above would work, to detect the filetype of a file whose filetype wasn't
yet known. Here, the filetype has been detected but you want to set something
else. I suggest adding the following (untested) to your vimrc:
autocmd BufReadPost * if getline(1) =~ '<?xml\>'
\ && &filetype !~ 'html$'
\ | setlocal filetype=xml | endif
(The middle part is to avoid changing the file type of XHTML files which have
an XML header line.)
Best regards,
Tony.