Smarter vim filetype detection

Posted by pulkomandy on Tue Jan 3 20:46:05 2012  •  Comments (0)  • 

Vim is, as you may know, is my favorite editor for all development purposes. The syntax highlighting is powerful and extensible easily. Most of the time, the file type detection for this is based on file extensions. Works well, unless you have files named .src or .asm for assembly language on different CPUs...

Vim documentation only shows how to set the filetype guessing from the file extension. Here's an example of doing something a bit more smart.

The idea is to put the CPU name on the first line of the file (in a comment). Then use the powerful regexp match features of vim to detect it:

; vimfiles/ftdetect/z80.vim
au BufRead,BufNewFile *.z80	set filetype=z80
	; The usual way to do it for clear file extensions

func! s:detect()
	if getline(1) =~ z80
		set filetype=z80

au BufRead *.src	call s:detect()
au BufRead *.asm	call s:detect()
	; And the smart one. Note it is useless on BufNewFile,
	; as the file will not have the header yet.

Do a similar file for each of your CPUs.

Note, it should be possible to scan fr the use of particular mnemonics to go without the header, but that requires a bit more work to identify many CPUs. Any volunteer ?

Leave a comment

Name: Mail: