gturri
gturri

Reputation: 14629

TypeScript file is considered as xml when indenting

In a nutshell:

In my .vimrc I have the following line to have vim indent xml files correctly:

autocmd FileType xml set equalprg=xmllint\ --format\ -

the weird thing is that now vim tries to use xmllint when I try to indent TypeScript files, and I don't understand why...

More details

When I open test.ts in vim, I can see that vim correctly detects the type (ie: set filetype? returns filetype=typescript).

But when I'm trying to indent this block of code

for(var i=0 ; i < 1 ; i++){
console.log(i);
}

by putting the cursor on a curly bracket and pressing =%, then this block is replaced with

Exception : System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
 at System.Xml.XmlTextReaderImpl.Throw(Exception e)
 [... eluded for brievity ...]
 at xmllint.Program.Main(String[] args)

(which means that vim launched the xmllint command and that this command failed (that failure is expected since it's not xml. But vim shouldn't have launched xmllint in the first place)).

Two other observations which might be useful are:

Even more details

Upvotes: 2

Views: 570

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172768

I'm not sure why your TypeScript is first detected as XML (maybe some other answer can dive into that), but it can happen that a generic (default, built-in) filetype is first detected, and then revised by a more specific detection (as in your case, via the TypeScript plugin). The problem you have is that the 'equalprg' lingers one, because you used the shortcut :autocmd instead of a proper filetype plugin:

autocmd FileType xml set equalprg=xmllint\ --format\ -

If you only want to enable an option for certain filetypes, use :setlocal option=value (your use of :set would make the setting be inherited by new buffers opened from that one, which is wrong), and put the corresponding :setlocal commands into ~/.vim/after/ftplugin/{filetype}.vim, where {filetype} is the actual filetype (e.g. xml here). (This requires that you have :filetype plugin on; use of the after directory allows you to override any default filetype settings done by $VIMRUNTIME/ftplugin/{filetype}.vim.) Proper plugins also undo any settings via the :help undo_ftplugin mechanism.

So, a proper configuration in your case would replace the :autocmd with ~/.vim/after/ftplugin/xml.vim:

setlocal equalprg=xmllint\ --format\ -
let b:undo_ftplugin = (exists('b:undo_ftplugin') ? b:undo_ftplugin . '|' : '') . 'setlocal equalprg<'

With that, 'equalprg' would still be briefly set as long as the filetype is XML, but it would then be undone by the command defined in b:undo_ftplugin, which Vim executes automatically when the filetype changes to typescript.

Upvotes: 3

Related Questions