emacs で HTMLのコーディングチェックを行う方法です
- flycheck を使います
- HTMLの解析ツールは htmllint を使います
- tidy より htmllint の方が使い勝手が良いように思います
手順1: htmllint のインストール
npm で htmllint-cli をインストールします
ひとまず適当なディレクトリ path/to を用意して,その下にインストールする場合は
$ cd path/to
$ npm install htmllint-cli
とします
インストールに成功すると path/to/bin/htmllint という実行ファイルが出来ます
手順2: htmllint の動作確認
htmllint を実際に動かしてみます
チェックしたい HTML があるディレクトリに移動して, htmllint の設定ファイル .htmllintrc を作成します
$ cd hogehoge
$ path/to/bin/htmllint init
$ ls -la .htmllint
.htmlintrc というファイルが生成されます
設定に関する詳細は
あたりが参考になります
ひとまずデフォルトの .htmllintrc で HTMLファイルをチェックしてみます
$ path/to/htmllint index.html
index.html: line 13, col 11, the `title` attribute is not double quoted
index.html: line 23, col 13, attribute value contains an unescaped angle bracket: >
[htmllint] found 2 errors out of 1 files
という感じで,13行目,23業目にエラーがあるよ,とチェック結果を出力してくれます
設定: emacs のflycheck のインストール
次に emacs 側の設定です
まず flycheck を設定します
use-packageが使えるようになっていれば,最低限必要な設定はこれだけです
(use-package flycheck
:ensure t
:init (global-flycheck-mode))
設定: flycheck 経由で htmllint を使う設定
最後に flycheck に htmllint を登録します
(flycheck-define-checker html-htmllint
"A HTML syntax and style checker using htmllint."
:command ("path/to/htmllint" source)
:standard-input t
:error-patterns ((error line-start (file-name) ": line " line ", col " column ", " (message) line-end))
:modes (web-mode))
(add-to-list 'flycheck-checkers 'html-htmllint)
(flycheck-add-mode 'html-htmllint 'web-mode)
これで
- path/to/htmllint を flycheck に登録.名前は html-htmllint
- web-mode で html-htmllint を使うように登録
しています
使い方
HTMLファイルを web-mode で開くだけです
あとは自動で構文チェックが走り,flycheckが逐次エラーを出してくれるようになります.
htmllint-cli は,カレントディレクトリから上流に遡って .htmllintrc を探す仕様なので,プロジェクトのルートディレクトリに .htmllintrc を配置して,プロジェクトごとにコーディング規則を切り替える,ということが簡単に出来ます.便利です