remarkを使ってFront MatterのLinter・Formatterを実装する
昨年12月より、TOKIUMはプロダクト本部の発信文化づくりに力を入れており、様々な施策に取り組んでいます。
今年に入ってからZenn Publication Proも契約し、Publicationに記事管理のための共通リポジトリを紐づけることができるようになりました。開発業務の合間を縫って、リポジトリの環境整備も着々と進めています。
リポジトリで記事を管理する以上、Linter・Formatterの整備は欠かせません。Markdown本文の体裁チェックにはmarkdownlintの利用が鉄板かと思いますが、Zennの記事はカテゴリーやトピック、公開設定などの情報をFront Matterに記載するため、純粋なMarkdownの構造検査・自動修正だけでは不十分です。
この問題を解決するため、現在TOKIUMのZenn Publicationリポジトリはmarkdownlintとremark-lintを併用する形でLinter・Formatterを整備しています。
| 系統 | 役割 |
|---|---|
markdownlint |
Markdown本文のフォーマット(見出しスタイル、リスト記法、空行ルールなど) |
remark-lint |
Front Matterの構造検査・自動修正 |
この記事ではremark-lint側にフォーカスし、Custom Linter・Formatterの実装方法を解説します。remark-lintが依存するremarkの簡単な解説や、markdownlintと併用する方針に至った経緯についても、背景情報として触れていきたいと思います。
前提知識 - remark-lint
remark・remark-lintに触れるまえに、その土台となるunifiedエコシステムについて軽く説明します。
unifiedについて
unifiedは、テキストコンテンツをAST(抽象構文木)に変換し、プラグインで操作し、再びテキストに戻すという一貫したパイプラインを提供するフレームワークです。Markdown・HTML・自然言語といった異なるフォーマットに対して共通のインターフェースを提供し、プラグインの組み合わせで処理を構成します。
remarkの本来の役割と、remark-lintの立ち位置
remarkは、unifiedのMarkdown担当です。 MarkdownテキストとMDAST(Markdown AST)の相互変換を担います。
remarkは元来「Markdownを読み取り、変換し、書き出す」ためのツールです。Lint機能はremark本体には含まれておらず、別パッケージのremark-lintがremarkの上に構築する形で提供しています。
前提知識 - markdownlintについて
markdownlintの基本的な仕組み
markdownlintは、行ベースとトークンベースの両方を組み合わせてMarkdownを検査するツールです。
カスタムルールはnames、description、tags、parser、functionといったプロパティを持つオブジェクトをエクスポートする形で作成できます。
そしてmarkdownlintには、Formatterの仕組みとしてfixInfoオブジェクトが用意されています。ただし、この仕組みには設計上の制約があります。
fixInfoの設計制約 — 複数行にまたがる修正が困難
fixInfoはeditColumn、deleteCount、insertText、lineNumberといったプロパティを持ち、1つの違反に対して1つの行内編集を指定する設計になっています。
※リンク先はmarkdownlint作者であるDavid Anson氏本人のブログ記事
この制約により、複数行にまたがる修正は仕様上不可能です。たとえば、ZennのFront Matterにも存在するtopics: ["React", "TypeScript"]というフロースタイルの配列を複数行のブロックスタイルに変換するには、1行を削除して3行を挿入する必要がありますが、fixInfoの仕組みではこれを表現できません。
実際、MD013(行長制限)のautofix要望も同様の理由で長く未実現のままです。Front Matterの構造的な自動修正を実現するには、別のアプローチが必要でした。
本題 - remark-lintによるCustom Linter・Formatterの実装
markdownlintでは困難なFront Matterの複数行修正に対応するため、Front Matter部分のLinter・Formatterにはremark・remark-lintを採用することとしました。元々がテキストコンテンツをASTに変換し、操作するツールであるため、複数行にまたがる修正もバッチリ対応できます👌
長い前置きでしたが、ここから具体的なCustom Linter・Formatterの実装紹介へと入ります🔥
題材として、Front Matterのtopicsフィールドなどで使われるフロースタイル配列の検知・修正ルールを取り上げます。
# フロースタイル(検知対象)
topics: ["React", "TypeScript"]
# ブロックスタイル(期待する形式)
topics:
- "React"
- "TypeScript"
このルールを選んだのは、Linter・Formatter・Custom Compilerの3要素すべてを使う好例であり、Front Matter特有の課題(複数行にまたがる書き換え)を端的に示せるためです。
以下、Linter → Formatter → Custom Compilerの順に、段階的に実装していきます。
Custom Linterの作成
remark-lintのCustom Linterは、unified-lint-ruleとunist-util-visitを組み合わせて実装します。Front Matterを検査対象にするには、remark-frontmatterプラグインと併用してyamlタイプのノードを対象にします。
remark-lintのカスタムルール作成については、公式のガイドも参考になります。
import type { Root } from "mdast";
import type { Yaml } from "mdast";
import { lintRule } from "unified-lint-rule";
import { visit } from "unist-util-visit";
type Options = {
ignore?: string[];
};
const rule = lintRule<Root, Options>(
"remark-lint:no-flow-style-array-in-frontmatter",
(tree, file, options) => {
const ignoreKeys = options?.ignore ?? [];
visit(tree, "yaml", (node: Yaml) => {
for (const line of node.value.split("\n")) {
const match = line.match(/^(\w+):\s*\[/);
if (match) {
const key = match[1];
if (ignoreKeys.includes(key)) continue;
file.message(
`${key}はフロースタイル([...])ではなくブロックスタイル(- ...)で記述してください`,
node,
);
}
}
});
},
);
export default rule;
いくつかポイントを補足します。
-
lintRuleの第1引数"remark-lint:no-flow-style-array-in-frontmatter"がルール名です。出力メッセージでの識別や、Markdown内の<!--lint disable no-flow-style-array-in-frontmatter-->コメントで警告を個別に無効化する際にこの名前が使われます。 -
visit(tree, "yaml", ...)でFront Matter(yamlノード)だけを対象にしています。このノードはremark-frontmatterプラグインがParseフェーズで生成するもので、remark-frontmatterを併用しないとyamlノードはAST上に存在しません。 - yamlノードの
valueプロパティには---の内側のテキストが格納されています。これを行ごとに分割し、正規表現/^(\w+):\s*\[/でフロースタイルの配列記法を検知します。 -
file.message()で警告を出力します。第2引数にノードを渡すと、ファイル内の位置情報が付与されます。また、ignoreオプションを設けて特定のキーを除外可能にしています。
Custom Formatterの作成(と注意点)
remark-lintはLintフレームワークであり、公式にはFixable rules(自動修正)をサポートしていません。検出と警告のみが本来の役割です。
そのため、Formatterを自作するにはremark-lintのlintRuleではなく、テキストをASTに変換し、操作するremarkの機能を活用したremarkプラグインとして実装します。シグネチャは(options) => (tree) => { ... }という形式です。
import type { Root } from "mdast";
import type { Yaml } from "mdast";
import { visit } from "unist-util-visit";
const FLOW_ARRAY_RE = /^(\w+):\s*\[(.*)\]\s*$/;
type Options = {
ignore?: string[];
};
export default function fixFlowStyleArrayInFrontmatter(options?: Options) {
const ignoreKeys = options?.ignore ?? [];
return (tree: Root) => {
visit(tree, "yaml", (node: Yaml) => {
const lines = node.value.split("\n");
let modified = false;
const newLines: string[] = [];
for (const line of lines) {
const flowMatch = line.match(FLOW_ARRAY_RE);
if (flowMatch) {
const key = flowMatch[1];
if (ignoreKeys.includes(key)) {
newLines.push(line);
continue;
}
const items = flowMatch[2]
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0);
newLines.push(`${key}:`);
for (const item of items) {
newLines.push(` - ${item}`);
}
modified = true;
} else {
newLines.push(line);
}
}
if (modified) node.value = newLines.join("\n");
});
};
}
Linterとの違いは明確です。file.message()は呼ばず、代わりにASTを直接変更します(node.value = ...)。unified-lint-ruleにも依存しません。
ただし、yamlノードのvalueを書き換えただけでは、Front Matterだけを正しく更新することはできません。なぜでしょうか?
remarkの処理パイプライン: parse → run → stringify
理由を理解するために、remarkの処理パイプラインを整理しておきます。unifiedの処理は以下の3つのフェーズで構成されます。
| フェーズ | 担当 | 役割 |
|---|---|---|
| parse | Parser(remark-parse) |
MarkdownテキストをMDASTに変換する。Front Matterを扱うにはremark-frontmatterプラグインが必要で、これによりyamlタイプのノードがASTに追加される |
| run | Transformers(各プラグイン) | ASTに対してプラグインが順番に適用されるフェーズ。remark-lintのLinterや、先ほど作成したFormatterもここで動作する |
| stringify | Compiler(remark-stringify) |
MDASTをMarkdownテキストに再変換する |
先ほどのFormatterはrunフェーズでASTを書き換えましたが、実際のファイルに反映するにはstringifyフェーズでcompilerが書き戻す必要があります。しかし、remark-stringifyはAST全体を再直列化するため、Front MatterだけでなくMarkdown本文のフォーマットまで変わってしまいます。 これを避けるために、次に紹介するCustom Compilerが必要です。
Custom Compilerによるhack — Front Matterだけを書き換える
remark-stringifyはMDAST全体をMarkdownテキストに再構築します。つまり、Front Matterだけを書き換えたくても、本文のMarkdownまで再生成されてしまいます。その結果、連続空行の正規化、リストマーカーや強調記号の変換(- → *、_ → *)、番号付きリストのリナンバリングなど、元のMarkdownと微妙にフォーマットが変わってしまう問題があります。
これを回避するために、remark-stringifyの代わりに動作するCustom Compilerを実装しました。
import type { Root } from "mdast";
import type { Yaml } from "mdast";
import type { Processor } from "unified";
export default function compileFrontmatter(this: Processor) {
Object.assign(this, {
compiler: (tree: Root, file: { value: string; toString(): string }) => {
const original = String(file);
const yamlNode = tree.children.find(
(n): n is Yaml => n.type === "yaml",
);
if (!yamlNode?.position) return original;
const { start, end } = yamlNode.position;
return (
original.slice(0, start.offset!) +
"---\n" +
yamlNode.value +
"\n---" +
original.slice(end.offset!)
);
},
});
}
Object.assign(this, { compiler: ... })でプロセッサのcompilerを上書きし、remark-stringifyの代わりにこのCustom Compilerが動作するようにしています。
処理の流れはシンプルです。String(file)で元のファイル内容を取得し、yamlノードのposition(開始・終了オフセット)を使ってFront Matter部分だけを差し替えます。本文部分は元のテキストをそのまま返すため、意図しないフォーマット変更が起きません。
この手法はremarkの公式APIとしてサポートされているものではなく、thisにcompilerプロパティを直接代入する内部実装に依存したhackです。とはいえ約20行で実現でき、実用上は問題なく動作しています。
最終的な構成
設定ファイルの分離: Lint用とFix用
Lint用(.remarkrc.lint.mjs)とFix用(.remarkrc.fix.mjs)で設定ファイルを分離しています。LintとFixでは読み込むプラグインが異なるため、設定を分けることで各ファイルの責務が明確になります。
Lint用: .remarkrc.lint.mjs
Lint用の設定には、remark-frontmatter(parseフェーズでyamlノードを生成)、remark-lint(Lintフレームワーク本体)、各Linterルールを登録します。
import remarkFrontmatter from "remark-frontmatter";
import remarkLint from "remark-lint";
import noFlowStyleArrayInFrontmatter from "./rules/dist/src/remark/no-flow-style-array-in-frontmatter.js";
// ...
export default {
plugins: [
remarkFrontmatter,
remarkLint,
noFlowStyleArrayInFrontmatter,
// ...
],
};
Fix用: .remarkrc.fix.mjs
Fix用の設定には、remark-frontmatter、各Formatterプラグイン、そしてcompile-frontmatter(Custom Compiler)を登録します。remark-lintは含めません。
import remarkFrontmatter from "remark-frontmatter";
import fixFlowStyleArrayInFrontmatter from "./rules/dist/src/remark/fix-flow-style-array-in-frontmatter.js";
// ...
import compileFrontmatter from "./rules/dist/src/remark/compile-frontmatter.js";
export default {
plugins: [
remarkFrontmatter,
fixFlowStyleArrayInFrontmatter,
// ...
compileFrontmatter, // 必ず末尾に配置
],
};
Fix用にはremark-lintを含めません。修正処理に検出は不要なためです。また、compile-frontmatterは必ずプラグイン配列の末尾に置く必要があります。最後に登録されたcompilerが有効になるため、他のプラグイン(remark-stringifyなど)にcompilerを上書きされないよう末尾に置く必要があるからです。
実行コマンド
# Lint: 警告・エラーの出力のみ
remark --rc-path .remarkrc.lint.mjs --quiet -- .
# Fix: ファイルを上書き修正
remark --rc-path .remarkrc.fix.mjs --output -- .
まとめ
この記事では、Zenn記事のFront Matter体裁チェックを題材に、remark-lintでCustom Linter・Formatterを実装する方法を紹介しました。ポイントを整理します。
-
Custom Lineterは
unified-lint-rule+unist-util-visitで実装し、file.message()で警告を出力する -
Custom Formatterは
remark-lintの枠組みではなく、素のremarkプラグイン(Transformer)として実装し、ASTを直接書き換える -
Front Matterだけを書き換えたい場合は、
remark-stringifyを迂回するCustom Compilerが必要になる -
markdownlintとremark-lintは得意分野が異なるため、2系統を併用する構成が実用的
自分のプロジェクトでMarkdownのFront Matterに独自の制約を設けたい場合は、この記事のパターンを参考にカスタムルールを実装してみてください。