chaffjs 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.ja.md +1 -0
  2. package/README.md +1 -0
  3. package/dist/bound-word-particles.d.ts +1 -0
  4. package/dist/bound-word-particles.d.ts.map +1 -1
  5. package/dist/bound-word-particles.js +1 -1
  6. package/dist/bound-word-particles.js.map +1 -1
  7. package/dist/clause-particles.d.ts +11 -0
  8. package/dist/clause-particles.d.ts.map +1 -0
  9. package/dist/clause-particles.js +20 -0
  10. package/dist/clause-particles.js.map +1 -0
  11. package/dist/detectors/acronym-definition.d.ts.map +1 -1
  12. package/dist/detectors/acronym-definition.js +14 -6
  13. package/dist/detectors/acronym-definition.js.map +1 -1
  14. package/dist/detectors/acronym-expansion.d.ts +2 -0
  15. package/dist/detectors/acronym-expansion.d.ts.map +1 -1
  16. package/dist/detectors/acronym-expansion.js +18 -7
  17. package/dist/detectors/acronym-expansion.js.map +1 -1
  18. package/dist/detectors/acronym-mention.d.ts.map +1 -1
  19. package/dist/detectors/acronym-mention.js +3 -1
  20. package/dist/detectors/acronym-mention.js.map +1 -1
  21. package/dist/detectors/acronym-name.d.ts +2 -2
  22. package/dist/detectors/acronym-name.d.ts.map +1 -1
  23. package/dist/detectors/acronym-name.js +3 -3
  24. package/dist/detectors/acronym-name.js.map +1 -1
  25. package/dist/detectors/acronym-parent-item.d.ts +6 -0
  26. package/dist/detectors/acronym-parent-item.d.ts.map +1 -0
  27. package/dist/detectors/acronym-parent-item.js +50 -0
  28. package/dist/detectors/acronym-parent-item.js.map +1 -0
  29. package/dist/detectors/broken-link.d.ts.map +1 -1
  30. package/dist/detectors/broken-link.js +14 -0
  31. package/dist/detectors/broken-link.js.map +1 -1
  32. package/dist/detectors/char-shape.d.ts.map +1 -1
  33. package/dist/detectors/char-shape.js +11 -4
  34. package/dist/detectors/char-shape.js.map +1 -1
  35. package/dist/detectors/citation-sentence.d.ts +8 -0
  36. package/dist/detectors/citation-sentence.d.ts.map +1 -1
  37. package/dist/detectors/citation-sentence.js +24 -0
  38. package/dist/detectors/citation-sentence.js.map +1 -1
  39. package/dist/detectors/concrete-evidence-density.d.ts.map +1 -1
  40. package/dist/detectors/concrete-evidence-density.js +13 -6
  41. package/dist/detectors/concrete-evidence-density.js.map +1 -1
  42. package/dist/detectors/concrete-evidence.d.ts +14 -1
  43. package/dist/detectors/concrete-evidence.d.ts.map +1 -1
  44. package/dist/detectors/concrete-evidence.js +65 -0
  45. package/dist/detectors/concrete-evidence.js.map +1 -1
  46. package/dist/detectors/doubled-punctuation.d.ts.map +1 -1
  47. package/dist/detectors/doubled-punctuation.js +14 -4
  48. package/dist/detectors/doubled-punctuation.js.map +1 -1
  49. package/dist/detectors/en-shape.d.ts +1 -0
  50. package/dist/detectors/en-shape.d.ts.map +1 -1
  51. package/dist/detectors/en-shape.js +15 -6
  52. package/dist/detectors/en-shape.js.map +1 -1
  53. package/dist/detectors/kanji-name-edge.d.ts +10 -0
  54. package/dist/detectors/kanji-name-edge.d.ts.map +1 -1
  55. package/dist/detectors/kanji-name-edge.js +23 -0
  56. package/dist/detectors/kanji-name-edge.js.map +1 -1
  57. package/dist/detectors/law-governed.d.ts +10 -0
  58. package/dist/detectors/law-governed.d.ts.map +1 -0
  59. package/dist/detectors/law-governed.js +41 -0
  60. package/dist/detectors/law-governed.js.map +1 -0
  61. package/dist/detectors/name-variant-two-things.d.ts +2 -1
  62. package/dist/detectors/name-variant-two-things.d.ts.map +1 -1
  63. package/dist/detectors/name-variant-two-things.js +21 -3
  64. package/dist/detectors/name-variant-two-things.js.map +1 -1
  65. package/dist/detectors/open-end-names.d.ts +7 -2
  66. package/dist/detectors/open-end-names.d.ts.map +1 -1
  67. package/dist/detectors/open-end-names.js +14 -4
  68. package/dist/detectors/open-end-names.js.map +1 -1
  69. package/dist/detectors/reference-entry.d.ts.map +1 -1
  70. package/dist/detectors/reference-entry.js +35 -5
  71. package/dist/detectors/reference-entry.js.map +1 -1
  72. package/dist/detectors/register-set-apart.d.ts +1 -1
  73. package/dist/detectors/register-set-apart.js +4 -4
  74. package/dist/detectors/register-set-apart.js.map +1 -1
  75. package/dist/detectors/register-voice.d.ts +5 -0
  76. package/dist/detectors/register-voice.d.ts.map +1 -1
  77. package/dist/detectors/register-voice.js +17 -0
  78. package/dist/detectors/register-voice.js.map +1 -1
  79. package/dist/detectors/requirement-smell.d.ts.map +1 -1
  80. package/dist/detectors/requirement-smell.js +6 -2
  81. package/dist/detectors/requirement-smell.js.map +1 -1
  82. package/dist/detectors/sentence-counts.d.ts.map +1 -1
  83. package/dist/detectors/sentence-counts.js +2 -1
  84. package/dist/detectors/sentence-counts.js.map +1 -1
  85. package/dist/detectors/sentence-ending.d.ts +2 -2
  86. package/dist/detectors/sentence-ending.d.ts.map +1 -1
  87. package/dist/detectors/sentence-ending.js +3 -1
  88. package/dist/detectors/sentence-ending.js.map +1 -1
  89. package/dist/detectors/sentence-length.d.ts.map +1 -1
  90. package/dist/detectors/sentence-length.js +7 -6
  91. package/dist/detectors/sentence-length.js.map +1 -1
  92. package/dist/detectors/sentence-parts.d.ts +8 -3
  93. package/dist/detectors/sentence-parts.d.ts.map +1 -1
  94. package/dist/detectors/sentence-parts.js +25 -7
  95. package/dist/detectors/sentence-parts.js.map +1 -1
  96. package/dist/detectors/signals.d.ts.map +1 -1
  97. package/dist/detectors/signals.js +3 -0
  98. package/dist/detectors/signals.js.map +1 -1
  99. package/dist/detectors/space-before-punctuation.js +3 -3
  100. package/dist/detectors/space-before-punctuation.js.map +1 -1
  101. package/dist/detectors/speaker-turns.d.ts +4 -0
  102. package/dist/detectors/speaker-turns.d.ts.map +1 -0
  103. package/dist/detectors/speaker-turns.js +28 -0
  104. package/dist/detectors/speaker-turns.js.map +1 -0
  105. package/dist/detectors/token-shape.d.ts.map +1 -1
  106. package/dist/detectors/token-shape.js +21 -5
  107. package/dist/detectors/token-shape.js.map +1 -1
  108. package/dist/detectors/topic-predicate-distance.d.ts.map +1 -1
  109. package/dist/detectors/topic-predicate-distance.js +3 -1
  110. package/dist/detectors/topic-predicate-distance.js.map +1 -1
  111. package/dist/detectors/unbalanced-bracket.d.ts.map +1 -1
  112. package/dist/detectors/unbalanced-bracket.js +31 -6
  113. package/dist/detectors/unbalanced-bracket.js.map +1 -1
  114. package/dist/detectors/vague-density.d.ts +4 -2
  115. package/dist/detectors/vague-density.d.ts.map +1 -1
  116. package/dist/detectors/vague-density.js +17 -9
  117. package/dist/detectors/vague-density.js.map +1 -1
  118. package/dist/document.js +2 -2
  119. package/dist/document.js.map +1 -1
  120. package/dist/name-variant-shapes.d.ts +32 -0
  121. package/dist/name-variant-shapes.d.ts.map +1 -1
  122. package/dist/name-variant-shapes.js +87 -0
  123. package/dist/name-variant-shapes.js.map +1 -1
  124. package/dist/paragraph-length.d.ts.map +1 -1
  125. package/dist/paragraph-length.js +5 -6
  126. package/dist/paragraph-length.js.map +1 -1
  127. package/dist/sentence-load.d.ts.map +1 -1
  128. package/dist/sentence-load.js +20 -6
  129. package/dist/sentence-load.js.map +1 -1
  130. package/dist/set-phrase-particles.js +2 -2
  131. package/dist/set-phrase-particles.js.map +1 -1
  132. package/dist/structure/definition-use.d.ts.map +1 -1
  133. package/dist/structure/definition-use.js +13 -0
  134. package/dist/structure/definition-use.js.map +1 -1
  135. package/dist/structure/universal.d.ts.map +1 -1
  136. package/dist/structure/universal.js +9 -1
  137. package/dist/structure/universal.js.map +1 -1
  138. package/dist/structure/unread-label.d.ts.map +1 -1
  139. package/dist/structure/unread-label.js +3 -1
  140. package/dist/structure/unread-label.js.map +1 -1
  141. package/dist/topic-clause.d.ts +2 -0
  142. package/dist/topic-clause.d.ts.map +1 -1
  143. package/dist/topic-clause.js +12 -5
  144. package/dist/topic-clause.js.map +1 -1
  145. package/package.json +3 -3
  146. package/rules/adverb-overuse.yaml +2 -2
  147. package/rules/bracket-nesting.yaml +2 -2
  148. package/rules/broken-link.yaml +2 -2
  149. package/rules/concrete-evidence-density.yaml +2 -2
  150. package/rules/doubled-punctuation.yaml +2 -2
  151. package/rules/expletive-construction.yaml +2 -2
  152. package/rules/max-kanji-continuous.yaml +5 -3
  153. package/rules/max-sentence-length.yaml +2 -2
  154. package/rules/name-variant.yaml +2 -2
  155. package/rules/ngram-repetition.yaml +2 -2
  156. package/rules/no-doubled-joshi.yaml +2 -2
  157. package/rules/no-mixed-desumasu.yaml +3 -2
  158. package/rules/orthographic-variant.yaml +2 -2
  159. package/rules/requirement-smell.yaml +2 -2
  160. package/rules/space-before-punctuation.yaml +4 -4
  161. package/rules/taigen-dome-in-prose.yaml +2 -2
  162. package/rules/topic-predicate-distance.yaml +3 -3
  163. package/rules/unbalanced-bracket.yaml +4 -4
  164. package/rules/undefined-acronym.yaml +4 -2
  165. package/rules/vague-word-density.yaml +2 -2
  166. package/skills/chaff/SKILL.md +3 -1
  167. package/src/bound-word-particles.ts +2 -1
  168. package/src/clause-particles.ts +35 -0
  169. package/src/detectors/acronym-definition.ts +14 -6
  170. package/src/detectors/acronym-expansion.ts +26 -7
  171. package/src/detectors/acronym-mention.ts +6 -1
  172. package/src/detectors/acronym-name.ts +6 -3
  173. package/src/detectors/acronym-parent-item.ts +60 -0
  174. package/src/detectors/broken-link.ts +16 -0
  175. package/src/detectors/char-shape.ts +18 -3
  176. package/src/detectors/citation-sentence.ts +30 -0
  177. package/src/detectors/concrete-evidence-density.ts +18 -7
  178. package/src/detectors/concrete-evidence.ts +83 -1
  179. package/src/detectors/doubled-punctuation.ts +20 -4
  180. package/src/detectors/en-shape.ts +18 -9
  181. package/src/detectors/kanji-name-edge.ts +27 -0
  182. package/src/detectors/law-governed.ts +50 -0
  183. package/src/detectors/name-variant-two-things.ts +43 -3
  184. package/src/detectors/open-end-names.ts +21 -4
  185. package/src/detectors/reference-entry.ts +36 -6
  186. package/src/detectors/register-set-apart.ts +4 -4
  187. package/src/detectors/register-voice.ts +19 -0
  188. package/src/detectors/requirement-smell.ts +6 -2
  189. package/src/detectors/sentence-counts.ts +2 -1
  190. package/src/detectors/sentence-ending.ts +8 -4
  191. package/src/detectors/sentence-length.ts +10 -8
  192. package/src/detectors/sentence-parts.ts +33 -9
  193. package/src/detectors/signals.ts +3 -0
  194. package/src/detectors/space-before-punctuation.ts +3 -3
  195. package/src/detectors/speaker-turns.ts +37 -0
  196. package/src/detectors/token-shape.ts +27 -7
  197. package/src/detectors/topic-predicate-distance.ts +3 -1
  198. package/src/detectors/unbalanced-bracket.ts +39 -7
  199. package/src/detectors/vague-density.ts +25 -10
  200. package/src/document.ts +2 -2
  201. package/src/name-variant-shapes.ts +103 -0
  202. package/src/paragraph-length.ts +8 -9
  203. package/src/sentence-load.ts +29 -6
  204. package/src/set-phrase-particles.ts +2 -2
  205. package/src/structure/definition-use.ts +15 -0
  206. package/src/structure/universal.ts +10 -1
  207. package/src/structure/unread-label.ts +3 -1
  208. package/src/topic-clause.ts +19 -5
@@ -3,7 +3,8 @@
3
3
  // document's genre ("reasonably" in a contract, "adequately compensate" as the test for an injunction) is not vague
4
4
  // there. The rule speaks once per sentence, about the document's density. Pure: the words come from the language's
5
5
  // lexicons vague-word and vague-word-term-of-art, the genre from the options. The lines of a table of contents are the
6
- // sections' names, not the writer's sentences, and are not read.
6
+ // sections' names, not the writer's sentences, and are not read. A word a law governs ("as required by applicable law")
7
+ // is fixed by that law; the governing words and the law's names come from the lexicon vague-word-law-reference.
7
8
  import { entriesForGenre } from "../lexicon-genres.ts";
8
9
  import { contentsLineNumbers } from "../structure/contents-lines.ts";
9
10
  import { lineNumberAt, linesOf } from "../structure/lines.ts";
@@ -12,10 +13,12 @@ import type { Detector, Finding, Lexicon, LexiconEntry, ProseDocument, Sentence
12
13
  import { comparableText, comparableWords, entryRanges } from "./lexicon-match.ts";
13
14
  import { rateOver } from "./lexicon.ts";
14
15
  import { specifiedByBracket } from "./bracket-specified.ts";
16
+ import { governedByLaw, lawReferenceOf, NO_LAW_REFERENCE, type LawReference } from "./law-governed.ts";
15
17
 
16
18
  const TERMS_OF_ART = "vague-word-term-of-art";
17
19
  /** The words that start an aside giving a name (以下「HR」という, hereinafter): such an aside pins nothing down. */
18
20
  const NAME_MARKERS = "definition-marker";
21
+ const LAW_REFERENCE = "vague-word-law-reference";
19
22
 
20
23
  type Place = { readonly start: number; readonly end: number };
21
24
 
@@ -42,17 +45,28 @@ const covers = (outer: Place, inner: Place): boolean => outer.start <= inner.sta
42
45
 
43
46
  const isLonger = (outer: Match, inner: Match): boolean => outer.place.end - outer.place.start > inner.place.end - inner.place.start;
44
47
 
45
- /** Whether a bracket right after the match pins the word down; token places are in the document, text places in the comparable text. */
46
- const pinnedDown = (sentence: Sentence, match: Match, byTokens: boolean, nameMarkers: readonly string[]): boolean =>
47
- byTokens
48
- ? specifiedByBracket(sentence.text, match.place.end - sentence.span.start, nameMarkers)
49
- : specifiedByBracket(comparableText(sentence), match.place.end, nameMarkers);
48
+ /** The text the match stands in and where it ends there: token places are in the document, text places in the comparable text. */
49
+ const textAround = (sentence: Sentence, match: Match, byTokens: boolean): { readonly text: string; readonly end: number } =>
50
+ byTokens ? { text: sentence.text, end: match.place.end - sentence.span.start } : { text: comparableText(sentence), end: match.place.end };
51
+
52
+ /** Whether the words right after the match pin the word down: a bracket that says what it leaves open, or a law that governs it. */
53
+ const pinnedDown = (sentence: Sentence, match: Match, byTokens: boolean, nameMarkers: readonly string[], law: LawReference): boolean => {
54
+ const { text, end } = textAround(sentence, match, byTokens);
55
+ return specifiedByBracket(text, end, nameMarkers) || governedByLaw(text, end, law);
56
+ };
50
57
 
51
58
  /**
52
59
  * The vague words of one sentence, in the order written, each once: none inside a longer vague word or a term of art,
53
- * and none pinned down by the bracket right after it (一定の事項(…)). nameMarkers: the words that start a name in an aside.
60
+ * and none pinned down by the bracket right after it (一定の事項(…)) or by a law that governs it (as required by law).
61
+ * nameMarkers: the words that start a name in an aside.
54
62
  */
55
- export const vagueWordsIn = (sentence: Sentence, vague: Lexicon, termsOfArt: Lexicon, nameMarkers: readonly string[] = []): string[] => {
63
+ export const vagueWordsIn = (
64
+ sentence: Sentence,
65
+ vague: Lexicon,
66
+ termsOfArt: Lexicon,
67
+ nameMarkers: readonly string[] = [],
68
+ law: LawReference = NO_LAW_REFERENCE,
69
+ ): string[] => {
56
70
  const byTokens = readsTokens(sentence, [...vague, ...termsOfArt]);
57
71
  const matches = matchesOf(sentence, vague, byTokens);
58
72
  const terms = matchesOf(sentence, termsOfArt, byTokens);
@@ -60,7 +74,7 @@ export const vagueWordsIn = (sentence: Sentence, vague: Lexicon, termsOfArt: Lex
60
74
  (match) =>
61
75
  !matches.some((other) => isLonger(other, match) && covers(other.place, match.place)) &&
62
76
  !terms.some((term) => covers(term.place, match.place)) &&
63
- !pinnedDown(sentence, match, byTokens, nameMarkers),
77
+ !pinnedDown(sentence, match, byTokens, nameMarkers, law),
64
78
  );
65
79
  return [...new Set(kept.toSorted((left, right) => left.place.start - right.place.start).map((match) => match.pattern))];
66
80
  };
@@ -78,10 +92,11 @@ const contentsSentences = (doc: ProseDocument): ReadonlySet<Sentence> => {
78
92
  export const vagueDensity: Detector = (doc, options): Finding[] => {
79
93
  const termsOfArt = entriesForGenre(doc.lexicons[TERMS_OF_ART] ?? [], options.genre);
80
94
  const nameMarkers = (doc.lexicons[NAME_MARKERS] ?? []).map((entry) => entry.pattern);
95
+ const law = lawReferenceOf(doc.lexicons[LAW_REFERENCE] ?? []);
81
96
  const contents = contentsSentences(doc);
82
97
  const hits: SentenceHits[] = doc.sentences
83
98
  .filter((sentence) => !contents.has(sentence))
84
- .map((sentence) => ({ sentence, words: vagueWordsIn(sentence, options.lexicon ?? [], termsOfArt, nameMarkers) }))
99
+ .map((sentence) => ({ sentence, words: vagueWordsIn(sentence, options.lexicon ?? [], termsOfArt, nameMarkers, law) }))
85
100
  .filter((hit) => hit.words.length > 0);
86
101
  const count = hits.reduce((sum, hit) => sum + hit.words.length, 0);
87
102
  const density = rateOver(doc, count, options.limit);
package/src/document.ts CHANGED
@@ -25,7 +25,7 @@ import { emailParts, emailVocabulary } from "./email-parts.ts";
25
25
  import { cutTextSpans } from "./span-cut.ts";
26
26
  import { markdownFigures } from "./text-figures.ts";
27
27
  import { documentMarkup } from "./markup.ts";
28
- import { BARE_URL } from "./bare-url.ts";
28
+ import { bareUrls } from "./bare-url.ts";
29
29
  import { lazyCells, tableCellsOf } from "./table-cells.ts";
30
30
  import type { BulletList, LanguageAdapter, Markup, ProseDocument, Sentence, Span, StructureNode, DocumentProfile } from "./plugin.ts";
31
31
 
@@ -81,7 +81,7 @@ const DIRECTIVE = /^[ \t]*:::[^\n]*/gmu;
81
81
  const matchSpans = (source: string, pattern: RegExp): Span[] =>
82
82
  [...source.matchAll(pattern)].map((match) => ({ start: match.index, end: match.index + match[0].length }));
83
83
 
84
- const directiveSpans = (source: string): Span[] => [...matchSpans(source, DIRECTIVE), ...matchSpans(source, BARE_URL)];
84
+ const directiveSpans = (source: string): Span[] => [...matchSpans(source, DIRECTIVE), ...bareUrls(source)];
85
85
 
86
86
  const collectMasks = (root: Node, source: string, anchors: InPageAnchors, syntax: readonly Span[]): Span[] => {
87
87
  const spans: Span[] = [...directiveSpans(source), ...syntax];
@@ -56,3 +56,106 @@ export const isOtherEnding = (name: string, usual: string, endings: readonly Wor
56
56
  const [nameEnd, usualEnd] = [name.slice(-1).toLowerCase(), usual.slice(-1).toLowerCase()];
57
57
  return endings.some(({ ending, insteadOf }) => (ending === nameEnd && insteadOf === usualEnd) || (ending === usualEnd && insteadOf === nameEnd));
58
58
  };
59
+
60
+ /** Whether the document writes word in small letters somewhere (stain beside Stain, vigil beside Vigil): an ordinary word there. */
61
+ export const isWrittenSmall = (text: string, word: string): boolean => {
62
+ const small = word.toLowerCase();
63
+ return ONE_WORD.test(word) && small !== word && new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(small)}(?![\\p{L}\\p{N}])`, "u").test(text);
64
+ };
65
+
66
+ /**
67
+ * Whether a pair of one-word forms holds a word the document writes in small letters: the pointed form (Stain beside stain
68
+ * and Spain), or the usual form when the pointed one is a dictionary word too (Virgil beside Vigil and vigil). A name beside
69
+ * an ordinary word, or two ordinary words, not one name written two ways. A pointed form no dictionary knows beside a word
70
+ * written in small letters (Affliates beside affiliates) is still a slip.
71
+ */
72
+ export const isNameAndWord = (name: string, usual: string, text: string, isKnown: (word: string) => boolean): boolean =>
73
+ isWrittenSmall(text, name) || (isWrittenSmall(text, usual) && isKnown(name.toLowerCase()));
74
+
75
+ const APOSTROPHES = /['’]/gu;
76
+ const APOSTROPHE_WORD = /^\p{L}+(?:['’]\p{L}+)+$/u;
77
+ /** A stem shorter than this (the O of O'Brien) is a name's prefix, not a word. */
78
+ const MIN_CONTRACTED_STEM = 2;
79
+
80
+ /**
81
+ * Whether two one-word forms differ only by an apostrophe and the part before it is a word the document writes in small
82
+ * letters (Look’ee and Lookee, Thank’ee and Thankee): a contraction of an ordinary word printed both ways, not a name.
83
+ */
84
+ export const isContractionPair = (name: string, usual: string, text: string): boolean => {
85
+ const [marked, plain] = APOSTROPHE_WORD.test(name) ? [name, usual] : [usual, name];
86
+ const stem = marked.split(APOSTROPHES)[0] ?? "";
87
+ return (
88
+ APOSTROPHE_WORD.test(marked) &&
89
+ ONE_WORD.test(plain) &&
90
+ marked.replaceAll(APOSTROPHES, "") === plain &&
91
+ stem.length >= MIN_CONTRACTED_STEM &&
92
+ isWrittenSmall(text, stem)
93
+ );
94
+ };
95
+
96
+ /** An acronym in capitals with a plural s (SBLCs). Names in capitals alone are not compared at all. */
97
+ const ACRONYM_PLURAL = /^\p{Lu}{2,}s$/u;
98
+
99
+ /** Whether two forms are acronyms with a plural s (SBLCs and SBDCs): one letter tells two programmes apart. */
100
+ export const isAcronymPair = (name: string, usual: string): boolean => ACRONYM_PLURAL.test(name) && ACRONYM_PLURAL.test(usual);
101
+
102
+ const SPACE = /\s/u;
103
+ /** Marks a file name or a URL may end with in running text (Prosperity.pdf. or 2015.pdf;). */
104
+ const TRAILING_MARKS = ".,;:!?)]";
105
+ /** A file name's extension in small letters after a letter or digit (.pdf, .html), or a URL's scheme. */
106
+ const FILE_OR_URL = /[\p{L}\p{N}]\.\p{Ll}{2,4}$|:\/\//u;
107
+ const EXTENSION = /\.\p{Ll}{2,4}$/u;
108
+
109
+ const runStart = (text: string, offset: number): number => {
110
+ let start = offset;
111
+ while (start > 0 && !SPACE.test(text.charAt(start - 1))) start -= 1;
112
+ return start;
113
+ };
114
+
115
+ const withoutTrailingMarks = (run: string): string => {
116
+ let end = run.length;
117
+ while (end > 0 && TRAILING_MARKS.includes(run.charAt(end - 1))) end -= 1;
118
+ return run.slice(0, end);
119
+ };
120
+
121
+ /**
122
+ * Whether the form at offset is part of a file name or a URL: the text without spaces around it holds more than the form
123
+ * and its extension, and ends with an extension or holds a scheme (Low-Tax-Rates-to-Create-American-Economic-Prosperity.pdf).
124
+ * A name with only a domain after it (Borrowmoney.com) is still the name.
125
+ */
126
+ export const isInFileName = (text: string, offset: number, length: number): boolean => {
127
+ const start = runStart(text, offset);
128
+ const rest = text.slice(offset + length);
129
+ const after = rest.search(SPACE);
130
+ const run = withoutTrailingMarks(text.slice(start, offset + length + (after < 0 ? rest.length : after)));
131
+ return run.replace(EXTENSION, "").length > length && FILE_OR_URL.test(run);
132
+ };
133
+
134
+ /** The word just before a form, with spaces or an opening quotation mark between (A in “A Coiner). */
135
+ const WORD_BEFORE = /(?<!\p{L})(\p{L}+)[\s"“‘']*$/u;
136
+
137
+ /**
138
+ * Whether the one-word form at offset follows an article from the lexicon name-count-article (a, an) and is a dictionary
139
+ * word ("A Coiner, a very good workman" beside Mrs. Coiler): a count noun, not a name.
140
+ */
141
+ export const isAfterCountArticle = (text: string, offset: number, name: string, articles: readonly string[], isKnown: (word: string) => boolean): boolean => {
142
+ const before = WORD_BEFORE.exec(text.slice(text.lastIndexOf("\n", offset - 1) + 1, offset))?.[1]?.toLowerCase();
143
+ return ONE_WORD.test(name) && before !== undefined && articles.includes(before) && isKnown(name.toLowerCase());
144
+ };
145
+
146
+ /** What may stand between a wrong mark and the form it marks: spaces, a colon. */
147
+ const MARK_GAP = /[\s::]/u;
148
+
149
+ const withoutTrailingGap = (text: string): string => {
150
+ const chars = [...text];
151
+ return chars.slice(0, chars.findLastIndex((char) => !MARK_GAP.test(char)) + 1).join("");
152
+ };
153
+
154
+ /**
155
+ * Whether the form at offset follows a wrong mark from the lexicon name-wrong-mark on its own line (× Rspec beside ○ RSpec):
156
+ * a list showing a wrong spelling on purpose, not a use of the name.
157
+ */
158
+ export const isMarkedWrong = (text: string, offset: number, marks: readonly string[]): boolean => {
159
+ const before = withoutTrailingGap(text.slice(text.lastIndexOf("\n", offset - 1) + 1, offset));
160
+ return marks.some((mark) => before.endsWith(mark));
161
+ };
@@ -29,8 +29,8 @@ const MIN_GLUED = 2;
29
29
  export const lostLineBreaks = (sentences: readonly { readonly text: string }[]): boolean =>
30
30
  sentences.reduce((count, sentence) => count + [...sentence.text.matchAll(GLUED_SENTENCES)].length, 0) >= MIN_GLUED;
31
31
 
32
- /** 【】のラベルだけの文(【0001】【技術分野】)。見出しで、文に数えない。 */
33
- const LABELS_ONLY = /^\s*(?:【[^】\n]+】\s*)+$/u;
32
+ /** 【】のラベルだけの文(【0001】【技術分野】、2【沿革】)。見出しで、文に数えない。 */
33
+ const LABELS_ONLY = /^\s*(?:[0-90-9①-⑳]{0,3}【[^】\n]+】\s*)+$/u;
34
34
 
35
35
  /**
36
36
  * 段落の文を、【】の見出しや段落番号だけの行で割った組。読み手にとってはその行が段落の切れ目で、ラベルだけの文は数えない。
@@ -38,13 +38,12 @@ const LABELS_ONLY = /^\s*(?:【[^】\n]+】\s*)+$/u;
38
38
  */
39
39
  export const labelledBlocks = <T extends Spanned>(text: string, start: number, sentences: readonly T[]): T[][] => {
40
40
  const cuts = [...text.matchAll(LABEL_LINE)].map((match) => start + match.index);
41
- if (cuts.length === 0) return sentences.length === 0 ? [] : [[...sentences]];
41
+ const counted = sentences.filter((sentence) => !LABELS_ONLY.test(text.slice(sentence.span.start - start, sentence.span.end - start)));
42
+ if (cuts.length === 0) return counted.length === 0 ? [] : [counted];
42
43
  const blocks = new Map<number, T[]>();
43
- sentences
44
- .filter((sentence) => !LABELS_ONLY.test(text.slice(sentence.span.start - start, sentence.span.end - start)))
45
- .forEach((sentence) => {
46
- const block = cuts.filter((cut) => cut < sentence.span.end).length;
47
- blocks.set(block, [...(blocks.get(block) ?? []), sentence]);
48
- });
44
+ counted.forEach((sentence) => {
45
+ const block = cuts.filter((cut) => cut < sentence.span.end).length;
46
+ blocks.set(block, [...(blocks.get(block) ?? []), sentence]);
47
+ });
49
48
  return [...blocks.values()];
50
49
  };
@@ -44,14 +44,32 @@ const singled = (text: string): string =>
44
44
  export const bracketDepth = (text: string): number => {
45
45
  // The closers still awaited, innermost last. Pushed and popped in place: copying it per character is quadratic on deep nesting.
46
46
  const awaited: string[] = [];
47
- return [...singled(text.replace(FORMULA, " "))].reduce((deepest, char) => {
47
+ const chars = [...singled(text.replace(FORMULA, " "))];
48
+ const heads = lineHeads(chars);
49
+ return chars.reduce((deepest, char, at) => {
48
50
  const innermost = awaited.at(-1);
49
51
  if (innermost !== undefined && (innermost === char || innermost === OTHER_WIDTH[char])) awaited.pop();
50
- else if (BRACKETS[char] !== undefined) awaited.push(BRACKETS[char]);
52
+ else if (BRACKETS[char] !== undefined && !(heads[at] === true && isReopening(char, innermost))) awaited.push(BRACKETS[char]);
51
53
  return Math.max(deepest, awaited.length);
52
54
  }, 0);
53
55
  };
54
56
 
57
+ /** Quoted verse reopens the quotation mark at the head of each line and closes it once at the end: the same quotation goes on. */
58
+ const isReopening = (char: string, innermost: string | undefined): boolean => char === "“" && innermost === "”";
59
+
60
+ const INDENT = new Set([" ", "\t", "\u3000"]);
61
+
62
+ /** Whether each character is the first of its line after the indent (not the first of the text). */
63
+ const lineHeads = (chars: readonly string[]): boolean[] =>
64
+ chars.reduce<{ heads: boolean[]; afterBreak: boolean }>(
65
+ (state, char) => {
66
+ state.heads.push(state.afterBreak && !INDENT.has(char) && char !== "\n");
67
+ state.afterBreak = char === "\n" || (state.afterBreak && INDENT.has(char));
68
+ return state;
69
+ },
70
+ { heads: [], afterBreak: false },
71
+ ).heads;
72
+
55
73
  const PREDICATE = new Set(["VERB", "ADJ", "AUX"]);
56
74
  const COMMA = new Set(["、", ","]);
57
75
 
@@ -168,11 +186,16 @@ const isSettingAt = (tokens: readonly Token[], at: number): boolean => {
168
186
  return before < at - 1 && !narrows(tokens[before], tokens[at - 1]);
169
187
  };
170
188
 
189
+ /** は on a listed noun standing alone (最後は, in the end): an adverb, not a topic. 交渉の最後は is a noun phrase, and a topic. */
190
+ const isAdverbAt = (tokens: readonly Token[], at: number, adverbs: ReadonlySet<string>): boolean =>
191
+ adverbs.has(tokens[at - 1]?.surface ?? "") && !narrows(tokens[at - 2], tokens[at - 1]);
192
+
171
193
  /** The sentence's topic: the first は on a noun, past a setting (今夜は、…死ぬといふことは) when a topic of another kind follows it. -1 when none. */
172
- const firstTopic = (tokens: readonly Token[]): number => {
173
- const first = tokens.findIndex((_, at) => isTopicAt(tokens, at));
194
+ const firstTopic = (tokens: readonly Token[], adverbs: ReadonlySet<string>): number => {
195
+ const isTopic = (at: number): boolean => isTopicAt(tokens, at) && !isAdverbAt(tokens, at, adverbs);
196
+ const first = tokens.findIndex((_, at) => isTopic(at));
174
197
  if (first === -1 || !isSettingAt(tokens, first)) return first;
175
- const after = tokens.findIndex((_, at) => at > first && isTopicAt(tokens, at) && !isSettingAt(tokens, at));
198
+ const after = tokens.findIndex((_, at) => at > first && isTopic(at) && !isSettingAt(tokens, at));
176
199
  return after === -1 ? first : after;
177
200
  };
178
201
 
@@ -184,7 +207,7 @@ const firstTopic = (tokens: readonly Token[]): number => {
184
207
  * topic is said to do anything.
185
208
  */
186
209
  export const topicDistance = (tokens: readonly Token[], words?: TopicClauseWords): number | undefined => {
187
- const topic = firstTopic(tokens);
210
+ const topic = firstTopic(tokens, new Set(words?.adverbs ?? []));
188
211
  const last = tokens.findLastIndex((token) => !TRAILING.has(token.pos));
189
212
  if (topic === -1 || last <= topic) return undefined;
190
213
  return tokens
@@ -18,13 +18,13 @@ const headBefore = (tokens: readonly Token[], at: number): string => {
18
18
  .join("");
19
19
  };
20
20
 
21
- /** Whether the particle at `at`, the words before it and the dictionary form of the word after it spell one of phrases (おそれのある). */
21
+ /** Whether the particle at `at`, the words before it and the dictionary form of the word after it spell one of phrases (おそれのある). A phrase that starts with the particle (のよう) takes any word before it. */
22
22
  const isInPhrase = (tokens: readonly Token[], at: number, phrases: readonly string[]): boolean => {
23
23
  const [particle, after] = [tokens[at], tokens[at + 1]];
24
24
  if (particle === undefined || after === undefined || !touches(particle, after)) return false;
25
25
  const tail = `${particle.surface}${after.lemma ?? after.surface}`;
26
26
  const head = headBefore(tokens, at);
27
- return phrases.some((phrase) => phrase.endsWith(tail) && phrase.length > tail.length && head.endsWith(phrase.slice(0, -tail.length)));
27
+ return phrases.some((phrase) => phrase.endsWith(tail) && head.endsWith(phrase.slice(0, -tail.length)));
28
28
  };
29
29
 
30
30
  /** The counted particles (particles) of a sentence that stand inside one of phrases, each written whole (おそれのある). */
@@ -154,6 +154,20 @@ const sentenceAt = (texts: readonly BodyText[], offset: number): BodyText | unde
154
154
  return undefined;
155
155
  };
156
156
 
157
+ /** 見出しの長さの上限。句点の無い長い行(箇条の項目)は見出しと読まない。 */
158
+ const RUN_IN_HEADING_MAX = 40;
159
+ const ENDS_OPEN = /[^。..!?!?]$/u;
160
+
161
+ /**
162
+ * 句点で終わらない短い文で、間を空けずに定義の文が続く: 本文に流し込んだ節の見出し(一行の報告書の「(1)経営成績等の概要」の
163
+ * すぐ後ろに「…(以下「経営成績等」という。)」が続く)。見出しは本文の語を先取りして名づけるので、定義より前の使い方ではない。
164
+ * 行を改めた項目((2) 本件仮換地の指定等)は、定義の文と離れているので使い方に数える。
165
+ */
166
+ const headsDefiningSentence = (body: BodyText | undefined, defining: number): boolean => {
167
+ const text = body?.text.trim() ?? "";
168
+ return body !== undefined && text.length <= RUN_IN_HEADING_MAX && ENDS_OPEN.test(text) && body.start + body.text.length === defining;
169
+ };
170
+
157
171
  const LETTER = /\p{L}/gu;
158
172
  /** 札の文が語のほかに持ってよい字の数("The Agreement." の The)。 */
159
173
  const LABEL_SLACK = 3;
@@ -412,6 +426,7 @@ export const usesBeforeDefinition = (
412
426
  (offset) =>
413
427
  !(namedFirst !== undefined && namedFirst < offset) &&
414
428
  !isLabel(sentenceAt(texts, offset), defined.term) &&
429
+ !headsDefiningSentence(sentenceAt(texts, offset), defining) &&
415
430
  !insideCaption(sentenceAt(texts, offset), offset) &&
416
431
  !isTitle(offset, defined.span.start) &&
417
432
  !continuesInHan(texts, defined.term, offset) &&
@@ -23,8 +23,17 @@ const MAX_TITLE = 80;
23
23
 
24
24
  const isTopSection = (line: string, rest: string): boolean => TOP_SECTION.test(line) && rest.length <= MAX_TITLE && !SENTENCE_END.test(rest);
25
25
 
26
+ /**
27
+ * A section's first subsection run into its heading's line, as plain text extracted from a contract writes it
28
+ * ("7 Indemnification. 7.1 Each Party shall…"). Only the heading's own number followed by ".1" counts, after a short
29
+ * capitalised title closed by a full stop or a colon, so a decimal in a sentence ("7 days … 7.1 percent") is not read.
30
+ */
31
+ const RUN_IN_SUBSECTION = /^[ \t]{0,3}(?<parent>\d{1,3})[ \t]+\p{Lu}[^.:;\n]{0,80}[.:][ \t]+(?<number>\k<parent>\.1)(?<gap>[ \t]+)(?<rest>\p{Lu}.*)$/u;
32
+
26
33
  const dottedGroups = (line: string, context: NumberingContext): Readonly<Record<string, string | undefined>> | undefined =>
27
- DOTTED.exec(line)?.groups ?? (context.isHeading ? TIGHT_HEADING.exec(line)?.groups : undefined);
34
+ (context.isHeading ? undefined : RUN_IN_SUBSECTION.exec(line)?.groups) ??
35
+ DOTTED.exec(line)?.groups ??
36
+ (context.isHeading ? TIGHT_HEADING.exec(line)?.groups : undefined);
28
37
 
29
38
  /**
30
39
  * closedByDot: 番号を点で閉じたか(「5. 」)。「1.5 万人」の 1.5 は閉じていない。wideGap: 番号と題の間に全角の空白を置いたか
@@ -38,7 +38,9 @@ const setOutIn = (text: string, label: string, lead: string): boolean => {
38
38
  const after = String.raw`(?![0-9A-Za-z])`;
39
39
  const atLineStart = new RegExp(String.raw`^[ \t]*${escapeRegExp(lead)}[ \t]*${escaped}${after}`, "mu");
40
40
  const afterSpaces = new RegExp(String.raw`\S[ \t]{2,}${escaped}${after}`, "u");
41
- if (atLineStart.test(text) || afterSpaces.test(text)) return true;
41
+ // "…as follows: 7.5 7.5.1 General Liability": a dotted label followed at once by its own first subsection opens it.
42
+ const beforeOwnFirst = /\d\.\d/u.test(label) && new RegExp(String.raw`(?<![0-9.])${escaped}[ \t]+${escaped}\.1${after}`, "u").test(text);
43
+ if (atLineStart.test(text) || afterSpaces.test(text) || beforeOwnFirst) return true;
42
44
  const firstLine = text.split("\n", 1)[0] ?? "";
43
45
  const bracketed = BRACKETED.test(label);
44
46
  return bracketed && firstLine.trimStart().startsWith("#") && new RegExp(String.raw`\s${escaped}${after}`, "u").test(firstLine);
@@ -130,6 +130,8 @@ const closesIfNewSubject = (tokens: readonly Token[], at: number): boolean => {
130
130
  export type TopicClauseWords = {
131
131
  /** Words that end a clause right after its predicate (ことから, つつ, としても): the topic-clause-close lexicon. */
132
132
  readonly closers: readonly string[];
133
+ /** Nouns that は makes an adverb of (最後は, in the end): the topic-adverb lexicon. Such a は is no topic. */
134
+ readonly adverbs?: readonly string[];
133
135
  };
134
136
 
135
137
  const NO_WORDS: TopicClauseWords = { closers: [] };
@@ -152,11 +154,17 @@ const subjectBetween = (tokens: readonly Token[], from: number, to: number): boo
152
154
 
153
155
  const isPoliteMasu = (token: Token | undefined): boolean => token?.pos === "AUX" && token.lemma === "ます";
154
156
 
155
- /** 〜ておりますが / 〜しましたが: a polite predicate and the contrastive が. */
157
+ /** The auxiliaries a polite predicate may end on after ます: past (ました), negative (ません), negative past (ませんでした). */
158
+ const POLITE_TAILS: readonly (readonly string[])[] = [[], ["た"], ["ん"], ["ん", "でし", "た"]];
159
+
160
+ const endsPolite = (tokens: readonly Token[], at: number, tail: readonly string[]): boolean =>
161
+ isPoliteMasu(tokens[at - tail.length - 1]) &&
162
+ tail.every((surface, index) => tokens[at - tail.length + index]?.pos === "AUX" && tokens[at - tail.length + index]?.surface === surface);
163
+
164
+ /** 〜ておりますが / 〜しましたが / 〜できませんでしたが: a polite predicate and the contrastive が. */
156
165
  const isPoliteGa = (tokens: readonly Token[], at: number): boolean => {
157
166
  if (tokens[at]?.surface !== "が" || tokens[at]?.pos !== "SCONJ") return false;
158
- const before = tokens[at - 1];
159
- return isPoliteMasu(before) || (before?.pos === "AUX" && before.surface === "た" && isPoliteMasu(tokens[at - 2]));
167
+ return POLITE_TAILS.some((tail) => endsPolite(tokens, at, tail));
160
168
  };
161
169
 
162
170
  const ownGaSubjectBetween = (tokens: readonly Token[], from: number, to: number): boolean =>
@@ -175,15 +183,21 @@ const newNameTopicRunsToEnd = (tokens: readonly Token[], comma: number, last: nu
175
183
  return topic > comma + 1 && wa !== undefined && isParticle(wa, "は") && lastOwnSubject(tokens, last) <= topic;
176
184
  };
177
185
 
186
+ /** A topic on the nominaliser こと after a predicate (公表することは): an act made a noun. */
187
+ const isActTopic = (tokens: readonly Token[], topic: number): boolean =>
188
+ tokens[topic - 1]?.surface === "こと" && tokens[topic - 1]?.pos === "NOUN" && PREDICATE.has(tokens[topic - 2]?.pos ?? "");
189
+
178
190
  /**
179
191
  * 当社は…を営んでおりますが、…の重要性が乏しいため、…の記載は行っておりません: after 〜ますが、 the words up to the next comma
180
192
  * say something of a subject of their own (が) and a new topic takes what comes after, so the predicate before が was the
181
193
  * topic's, when no other subject stands between the topic and it (需要の停滞がありましたが is not). A clause with no subject of
182
- * its own there is read to the end, unless a name stands as a new topic straight after the comma (〜ましたが、B大臣は…).
194
+ * its own there is read to the end, unless a name stands as a new topic straight after the comma (〜ましたが、B大臣は…), or the
195
+ * topic is an act made a noun (つまびらかにすることは差し控えますが、…): what is said of an act ends there, and the rest is the
196
+ * speaker's.
183
197
  */
184
198
  const closesWithPoliteGa = (tokens: readonly Token[], topic: number, at: number, last: number): boolean => {
185
199
  if (!isPoliteGa(tokens, at) || !isComma(tokens[at + 1]) || subjectBetween(tokens, topic, at)) return false;
186
- if (newNameTopicRunsToEnd(tokens, at + 1, last)) return true;
200
+ if (isActTopic(tokens, topic) || newNameTopicRunsToEnd(tokens, at + 1, last)) return true;
187
201
  const comma = tokens.findIndex((token, index) => index > at + 1 && index < last && isComma(token));
188
202
  const clauseEnd = comma === -1 ? last : comma;
189
203
  return ownGaSubjectBetween(tokens, at + 1, clauseEnd) && newTopicAfter(tokens, clauseEnd, last);