Use HTML Tidy to just indent HTML code?

cwd picture cwd · Aug 22, 2011 · Viewed 24.3k times · Source

Is it possible to use HTML Tidy to just indent HTML code?

Sample Code

<form action="?" method="get" accept-charset="utf-8">

<ul>
<li>
<label class="screenReader" for="q">Keywords</label><input type="text" name="q" value="" id="q" />
</li>
<li><input class="submit" type="submit" value="Search" /></li>
</ul>


</form>

Desired Result

<form action="?" method="get" accept-charset="utf-8">
    <ul>
        <li>
        <label class="screenReader" for="q">Keywords</label><input type="text" name="q" value="" id="q"/>
        </li>
        <li><input class="submit" type="submit" value="Search"/></li>
    </ul>
</form>

If I run it with the standard command, tidy -f errs.txt -m index.html then I get this

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta name="generator" content=
"HTML Tidy for Mac OS X (vers 31 October 2006 - Apple Inc. build 15.3.6), see www.w3.org">
<title></title>
</head>
<body>
<form action="?" method="get" accept-charset="utf-8">
<ul>
<li><label class="screenReader" for=
"q">Keywords</label><input type="text" name="q" value="" id=
"q"></li>
<li><input class="submit" type="submit" value="Search"></li>
</ul>
</form>
</body>
</html>

How can I omit all the extra stuff and actually get it to indent the code?

Forgive me if that's not a feature that it's supposed to support, what library / tool am I looking for?

Answer

Paul Sweatte picture Paul Sweatte · Jan 20, 2012

Use the indent, tidy-mark, and quiet options:

tidy \
  -indent \
  --indent-spaces 2 \
  -quiet \
  --tidy-mark no \
  index.html

Or, using a config file rather than command-line options:

indent: auto
indent-spaces: 2
quiet: yes
tidy-mark: no

Name it tidy_config.txt and save it the same directory as the .html file. Run it like this:

tidy -config tidy_config.txt index.html

For more customization, use the tidy man page to find other relevant options such as markup: no or force-output: yes.