How to Tidy Up an HTML File's Indentation in Vi

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

With filetype indent on inside my .vimrc, Vim indents HTML files quite nicely.

Simple example with a shiftwidth of 2:

<html>
<body>
<p>
text
</p>
</body>
</html>

How do I fix the indentation of an entire file in Vi?

=, the indent command can take motions. So, gg to get the start of the file, = to indent, G to the end of the file, gg=G.

Format and Indent HTML in Vim

One way to start it is to split all tags onto their own lines.

:s/<[^>]*>/\r&\r/g
:g/^$/d

If you have floating < or > symbols (e.g. invalid HTML, JavaScript comparison operators, CSS direct descendant selector part), this won't work properly and you could switch to something like just doing end tags - <\/[^>]*>. It provides a solid start, anyway.

Demonstration:

With a idealised document like this,

<!DOCTYPE html><html><head><title>hello</title></head><body>world</body></html>

This produces this:

<!DOCTYPE html>
<html>
<head>
<title>
hello
</title>
</head>
<body>
world
</body>
</html>

Then, = will produce what you want:

<!DOCTYPE html>
<html>
<head>
<title>
hello
</title>
</head>
<body>
world
</body>
</html>

vim / vi / linux: properly indent html file

If your vim knows it's an html file (:se filetype=html), you can use the default indentation method (gg=G). I would have a look at :help =, it's quite powerful

Indent multiple lines quickly in vi

Use the > command. To indent five lines, 5>>. To mark a block of lines and indent it, Vjj> to indent three lines (Vim only). To indent a curly-braces block, put your cursor on one of the curly braces and use >% or from anywhere inside block use >iB.

If you’re copying blocks of text around and need to align the indent of a block in its new location, use ]p instead of just p. This aligns the pasted block with the surrounding text.

Also, the shiftwidth setting allows you to control how many spaces to indent.

Change depth of indentation in vi

In vim (not sure if this applies to you too), you use >> to indent one line. As with nearly every command in vim, type in a number before the command to perform is multiple times. So to indent the next 50 lines, type 50>>.

vim indent html code inside javascript file

You may use mxw/vim-jsx. This plugin requires pangloss/vim-javascript, so you should install both of them.

This is a minimal .vimrc I used with vim-plug:

set nocompatible
filetype off

call plug#begin()
Plug 'pangloss/vim-javascript'
Plug 'mxw/vim-jsx'
call plug#end()

let g:jsx_ext_required = 0

Note that I set g:jsx_ext_required to 0 because you want to edit JSX tags in .js files.



Related Topics



Leave a reply



Submit