0

I usually format xml or html by doing:

  • =G

However, this doesn't work if the file is minified to one line only, which I very commonly have with xml. Is there a way to format one-lined html or html in vim easily (i.e., without a plugin)?

Additionally, the block formatting is pretty crude in vim ('formatting' might be an ambitious word, as it seems more to be an 'indenter'), for example the following:

  <footer>
    <div class="container"><div class="row"><div class="col-md-12">
      <small id="copyright">&copy; 2016 MySite
      </small>
    </div></div></div>
  </footer>

Gets formatted as the following in vim:

  <footer>
      <div class="container"><div class="row"><div class="col-md-12">
                  <small id="copyright">&copy; 2016 MySite
                  </small>
              </div></div></div>
  </footer>

Whereas here is what it does in TextMate:

    <footer>
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <small id="copyright">© 2016 MySite</small>
                </div>
            </div>
        </div>
    </footer>
D. Ben Knoble
  • 4,273
  • 1
  • 20
  • 38
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

1

As far as I know, there is not built-in vim feature to split lines while indenting. So you have to do it before indenting.

As noticed here you can use external tool tidy. It indents and splits for you (use "-html" for HTML).

:!tidy -mi -xml -wrap 0 %

Also you can reformat it manually. Join all to one line, split with subst and indent.

ggVGgJ
:%s/>\s*</>\r</g
gg=G
Dmitry
  • 436
  • 2
  • 7
  • Using external tidy is a good suggestion. Unfortunately your answer only has external links. It would be good if you could summarize how to implement tidy as an external tool and an example of what it would do to the sample HTML snippet in the question. – filbranden May 17 '20 at 22:19
  • While parsing HTML with regex is indeed a bad practice, using regexes to help formatting in text editors is often a common practice. In part because they're being used mostly in heuristics and helping figure out what a good indentation would be... Furthermore, the point of using tools to help editing HTML is to produce sane and readable HTML, in which case using regexes will work fairly well, since you'd expect you're producing readable, well structured HTML. Third, regexes are usually not the *only* mechanism matching tags and components, usually you get other Vim features to help. – filbranden May 17 '20 at 22:23
  • In short, I'd drop the "pure evil" reference from the answer. I find it too opinionated. I don't think it really helps make a point. If you really think that's the case, then just don't mention using regexes at all... – filbranden May 17 '20 at 22:24
  • filbranden, thanks for advices! Edited answer. I agree, in this case regex are safe to use. – Dmitry May 19 '20 at 17:26