PROgram52bc
PROgram52bc

Reputation: 98

vim indent html tags with attributes on separate lines

I am writing some html/vue code with vim, but I found the auto-indent functionality not working as expected, especially with nested tags and attributes broken into multiple lines.

I read the coding standard agreed upon for long html tags, and I reason it would be nice if vim can support such indentation style. I found multiple similar questions asked like this, but they don't give satisfactory answers. I have also tried the html5 plugin for vim, but it doesn't seem to help much.

For example, I would like vim to indent like following:

<template>
    <my-tag 
        attr1
        attr2
        attr3>
        <my-sub-tag
            attr1
            attr2
            attr3>
        </my-sub-tag>
    </my-tag>
</template>

But currently, when I press gg=G, it indents to something like this:

<template>
    <my-tag 
     attr1
     attr2
     attr3>
        <my-sub-tag
      attr1
      attr2
      attr3>
        </my-sub-tag>
    </my-tag>
</template>

Is there a relatively quick way to fix it (like a nice plugin), or is it not yet a primary concern for vim?

Upvotes: 0

Views: 1219

Answers (1)

Harish
Harish

Reputation: 1441

You don't have to use a plugin for this! When you use gg=G the equalprg (see :h 'equalprg') is run. When this option is not set it uses the default or builtin equalprg and that is why you see the odd indentation as they're not built for html.

You could use an external program that is more capable of formatting specific file types. For example, for html you could use html-beautify (npm install --global html-beautify) for css, json and others you use prettier

You can do the following to use an external program.

:setlocal equalprg=html-beautify -f - -I -s 2

newer versions of prettier also supports html formatting.

:setlocal equalprg=prettier\ --stdin\ --parser=html

add this to ~/.vim/after/ftplugin/html.vim and use the same command gg=G for formatting the lines.

Also see :h 'formatprg' and the :h gq commands.

Upvotes: 1

Related Questions