HTML や XML の整形ツールとして有名なものに HTML Tidy(以下、単に tidy と呼ぶ) がある。このツールは既に 10 年以上の歴史を持つが、最近では更新頻度がだいぶ落ちてた。tidy を Perl 上から使うには HTML::Tidy というモジュールを使うのだが、tidy の最新版がうちの環境(Mac OS X 10.6 + Perl 5.10.1)ではうまく動かず、えらい苦労させられた。
【MovableType】Tidy を使って HTML を整形するプラグイン | blog.delphinus.dev
https://blog.delphinus.dev/2010/03/tiding-movabletype.htmlHTML::Tidyについて追試 | blog.delphinus.dev
https://blog.delphinus.dev/2010/03/resit-html-tidy-install.html
こうした中、HTML::Tidy の作者は一向に更新されぬ tidy に業を煮やしたのか、自ら互換プロダクトを開発することにしたらしい。それが tidyp だ。
tidyp
http://tidyp.com/Downloads for petdance’s tidyp – GitHub
http://github.com/petdance/tidyp/downloads
$ wget http://github.com/downloads/petdance/tidyp/tidyp-1.02.tar.gz $ tar zxvf tidyp-1.02.tar.gz $ cd tidyp-1.02 $ ./configure $ make $ sudo make install
さくっとインストール終了。続いて HTML::Tidy の最新版も入れておこう1。
$ cpan -i HTML::Tidy
何の問題もなく最新版の HTML::Tidy 1.52 が入ってしまった。これまでの苦労を思えば感動ものだ。簡単にテストしてみよう。
tidyp のテスト
$ echo '<p>テスト</p>' | tidyp -utf8 --output-xhtml 1 -o test1.html
HTML::Tidy のテスト
$ perl -MHTML::Tidy -e 'print HTML::Tidy->new({ wrap => 72, output_xhtml => 1 })->clean( "<p>テスト</p>" )' > test2.html
どちらもまったく同じファイルを生成する
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"tidyp for Mac OS X (v1.02), see www.w3.org" />
<title></title>
</head>
<body>
<p>テスト</p>
</body>
</html>
tidyp には tidy と同じオプションが使えるようだ。詳しいリストは以下のリンクにあるが、シェルからも一覧を確認できる。
HTML Tidy Configuration
http://tidy.sourceforge.net/docs/quickref.html
$ tidyp -help-config
(中略)
Name Type Allowable values
=========================== ========= ========================================
accessibility-check enum 0 (Tidy Classic), 1 (Priority 1 Checks),
2 (Priority 2 Checks), 3 (Priority 3
Checks)
add-xml-decl Boolean y/n, yes/no, t/f, true/false, 1/0
add-xml-space Boolean y/n, yes/no, t/f, true/false, 1/0
alt-text String -
anchor-as-name Boolean y/n, yes/no, t/f, true/false, 1/0
ascii-chars Boolean y/n, yes/no, t/f, true/false, 1/0
(以下略)
Perl スクリプトから HTML::Tidy を使ってアクセスするときは、ハイフンをアンダーバーに換えてコンストラクタに渡せば良い。以下の例はこのサイトの HTML を整形する際に使っているオプションである。
$ tidyp --output-xhtml 1 --indent auto --indent-attributes yes --wrap 80 --break-before-br yes --replace-color yes
use HTML::Tidy;
my $tidy = HTML::Tidy->new( {
output_xhtml => "yes",
indent => "auto",
indent_attributes => "yes",
wrap => 80,
break_before_br => "yes",
replace_color => "yes",
} );
- 今回は MacPorts 版の Perl 5.12.0 を使っている。 ↩
