Monday, September 19, 2016

Change File Type in Vim

Recently I had to write a few lines of code in assembly language. Vim and GAS were chosen as suitable tools to use. I downloaded vim-gas plugin, installed it using vim-plug (Vim plugin manager that I prefer) and started coding. Unfortunately Vim detected file type as 'vmasm' by default, not as 'gas', so syntax highlighting was incorrect. In this post I describe several solutions to this problem.

Set File Type Manually

The first obvious solution which comes to mind is to set file type manually. This can be done via the following Vim command:
:set filetype=gas
This definitely works, but setting the file type manually every time it is opened seems awkward and impractical. Fortunately there are better alternatives.

Override File Type Using Auto Commands

There are several automatic commands (autocmd) which can be added to .vimrc in order to set file type:
au BufRead,BufNewFile *.s   setfiletype gas
au BufRead,BufNewFile *.s   set filetype=gas
The first option didn't work for me, because it is used to set the file type only if it hasn't been detected yet. As I mentioned earlier, in my case file type was detected as 'vmasm'.

The second option worked as expected and Vim detected the file type as 'gas'.

Override File Type Using Modelines

Another way to influence Vim filetype detection is to use modelines. Looks like the modelines are disabled by default. In order to turn them on the following lines should be added to .vimrc:
set modeline
set modelines=5
The first line enables modelines and the second one sets the max number of modelines which Vim takes into account. Look at the Vim docs for more details.

The following modeline can be added to the *.s file in order to help Vim to detect file type as 'gas':
/* vim: set filetype=gas: */
Apparently modelines approach requires adding a special line in every *.s file while autocmd approach can be configured solely in .vimrc. So I decided to stick to the latter which suits my needs just fine.

That's all there is to it.
Thanks for reading!

No comments:

Post a Comment