Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim indentation: multiple languages in file

Tags:

vim

Lets say I have the following file: temp.html properly indented, it would look like this:

<html>
    <head>
    </head>
    <body>
        <script type="text/javascript>
            function blahblahblah(...) {
                doSomething();
            }
            function something else() {
                etc...;
            }
        </script>
    </body>
</html>

However, when I type gg=G, I get something like this:

<html>
    <head>
    </head>
    <body>
        <script type="text/javascript>
            function blahblahblah(...) {
            doSomething();
            }
            function something else() {
            etc...;
            }
        </script>
    </body>
</html>

as in, my javascript indentation gets messed up. I have filetype plugin indent on in my .vimrc, and it seems to work well for my HTML. However, the javascript section of my code is not getting indented properly. How can I properly indent files with multiple languages of code in them using vim?

like image 376
Trevor Avatar asked Jun 01 '26 00:06

Trevor


1 Answers

Indenting mixed filetypes never really works in Vim unless you use a (generally language-specific) external program more suited to that task.

I recommend js-beautify which can format JavaScript in HTML just fine.

Here is the command I use for formatting pure JS (put it in ~/.vim/after/ftplugin/javascript.vim):

command! -buffer -range=% Format let b:winview = winsaveview() |
  \ execute <line1> . "," . <line2> . "!js-beautify -f - -j -B -s " . &shiftwidth |
  \ call winrestview(b:winview)

Here is the command I use for formatting HTML with optionally embedded JS (put it in ~/.vim/after/ftplugin/html.vim):

command! -buffer -range=% Format let b:winview = winsaveview() |
  \ execute <line1> . "," . <line2> . "!html-beautify -f - -I -s " . &shiftwidth |
  \ call winrestview(b:winview)

Those commands both work the same way:

:Format      " formats the whole buffer
:5,23Format  " formats lines 5 to 23
:'<,'>Format " formats the visually selected lines
like image 93
romainl Avatar answered Jun 02 '26 16:06

romainl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!