Explain Codes LogoExplain Codes Logo

How do I tidy up an HTML file's indentation in VI?

html
indentation
vim
best-practices
Nikita BarsukovbyNikita Barsukov·Nov 17, 2024
TLDR

To instantly refactor the HTML indentation in Vim, enter the command gg=G. First, press Esc to navigate to normal mode, then input gg=G to apply auto-indent from the **first (gg) to the last line (G). To align with HTML syntax, set the filetype using :set filetype=html.

# Normal mode activation a.k.a. the 'business' mode Esc # Let Vim know we're dealing with HTML, not a pizza recipe :set filetype=html # The 'curry' command of Vim, adds flavour to your HTML gg=G

Remember, Vim's settings are utilised here. For particular style requirements, consider Vim's indentexpr configurations or look for a formatting plugin.

The bouncer and beautician: Tools for refined HTML

Vim's indentation commands can do the initial clean-up, but when the mess grows more complex, we need a professional touch. If you deal with non-HTML or irregularly indented files, try changing your filetype to XML with :set filetype=xml.

To automate the indentation detection, check your .vimrc settings for filetype indent on. If the party isn't starting, there's tidy, the most organised bouncer ever. Run :!tidy -mi -html -wrap 0 % in VI and watch it clean up like a pro. Here's a link to the bouncer school.

Tailoring your tux: Fine-tuning indentation

Tailoring your Vim for personal taste or project demands is a breeze. Set a two-space indentation preference by adding set shiftwidth=2 in your .vimrc.

For selective indentation, the = command in visual mode is your handy tool. Selected some text? Just press = and watch the magic happen.

Starting fresh: Prepping for indentation

If your HTML is one long, painful line, break elements onto new lines. Use a substitution command like :%s/></>\r</g to ensure gg=G correctly formats your HTML elements.

For intelligent auto-indenting, use Vim’s smartindent feature (:set smartindent). It’s like speaking to a teenager who surprisingly makes sense.

Playing it safe: Tackling potential setbacks

Watch out for default Vim settings that may not handle custom HTML tags or certain HTML5 elements well. Your indentation scripts need constant love and care, just like your pet turtle.

Before tuning your .vimrc, think about the ramifications. Even the gg=G command can backfire if not used wisely (like eating dessert before the main course).