-
Notifications
You must be signed in to change notification settings - Fork 17
/
pair-checker.js
82 lines (82 loc) · 2.64 KB
/
pair-checker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// LICENSE : MIT
"use strict";
/**
* 「と」といったペアがちゃんと閉じられているかをチェックします
* @param {object} context
* @param {string} left
* @param {string} right
* @returns {object}
*/
import assert from "assert";
import { RuleHelper } from "textlint-rule-helper";
export function checkPair(context, { left, right }) {
assert(left);
assert(right);
let { Syntax, RuleError, report, getSource } = context;
let helper = new RuleHelper(context);
let isInParagraph = false;
let currentStrInParagraph = [];
/**
* `Str` nodeの配列を受け取り、pairが見つからないnodeを返す
* @param {Object} currentStrInParagraph
* @returns {{node, index}[]}
*/
const foundMissingPairNodes = (currentStrInParagraph) => {
let foundLeft = false;
let matchParentheses = [];
currentStrInParagraph.forEach((node) => {
const text = getSource(node);
// left を探す
let leftIndex = -1;
if (!foundLeft) {
leftIndex = text.indexOf(left);
if (leftIndex !== -1) {
matchParentheses.push({
node,
index: leftIndex
});
foundLeft = true;
}
}
// right を探す
let pairIndex = text.indexOf(right, leftIndex + 1);
if (pairIndex !== -1) {
matchParentheses.pop();
foundLeft = false;
}
});
return matchParentheses;
};
return {
[Syntax.Paragraph](node) {
if (helper.isChildNode(node, [Syntax.BlockQuote])) {
return;
}
currentStrInParagraph = [];
isInParagraph = true;
},
[Syntax.Str](node) {
if (!isInParagraph) {
return;
}
currentStrInParagraph.push(node);
},
[`${Syntax.Paragraph}:exit`]() {
const missingPairList = foundMissingPairNodes(currentStrInParagraph);
// 探索おわり
isInParagraph = false;
// 全ての対が見つかったなら配列は空になる
if (missingPairList.length === 0) {
return;
}
missingPairList.forEach(({ node, index }) => {
report(
node,
new RuleError(`${left}の対となる${right}が見つかりません。${left}${right}`, {
index
})
);
});
}
};
}