chaffjs 0.43.0 → 0.44.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 (198) hide show
  1. package/dist/bound-word-particles.d.ts +9 -0
  2. package/dist/bound-word-particles.d.ts.map +1 -0
  3. package/dist/bound-word-particles.js +16 -0
  4. package/dist/bound-word-particles.js.map +1 -0
  5. package/dist/derived/stays.d.ts +0 -1
  6. package/dist/derived/stays.d.ts.map +1 -1
  7. package/dist/derived/stays.js +3 -1
  8. package/dist/derived/stays.js.map +1 -1
  9. package/dist/detectors/absolute-exception.d.ts.map +1 -1
  10. package/dist/detectors/absolute-exception.js +10 -4
  11. package/dist/detectors/absolute-exception.js.map +1 -1
  12. package/dist/detectors/agreement-slip.d.ts +2 -0
  13. package/dist/detectors/agreement-slip.d.ts.map +1 -1
  14. package/dist/detectors/agreement-slip.js +22 -8
  15. package/dist/detectors/agreement-slip.js.map +1 -1
  16. package/dist/detectors/bold-label.d.ts +5 -1
  17. package/dist/detectors/bold-label.d.ts.map +1 -1
  18. package/dist/detectors/bold-label.js +22 -3
  19. package/dist/detectors/bold-label.js.map +1 -1
  20. package/dist/detectors/bold-quoted.d.ts +4 -0
  21. package/dist/detectors/bold-quoted.d.ts.map +1 -0
  22. package/dist/detectors/bold-quoted.js +17 -0
  23. package/dist/detectors/bold-quoted.js.map +1 -0
  24. package/dist/detectors/caps-caption.d.ts +5 -0
  25. package/dist/detectors/caps-caption.d.ts.map +1 -1
  26. package/dist/detectors/caps-caption.js +7 -0
  27. package/dist/detectors/caps-caption.js.map +1 -1
  28. package/dist/detectors/count-per-section.d.ts.map +1 -1
  29. package/dist/detectors/count-per-section.js +7 -4
  30. package/dist/detectors/count-per-section.js.map +1 -1
  31. package/dist/detectors/defined-term-form.d.ts.map +1 -1
  32. package/dist/detectors/defined-term-form.js +2 -1
  33. package/dist/detectors/defined-term-form.js.map +1 -1
  34. package/dist/detectors/emoticon.d.ts +6 -0
  35. package/dist/detectors/emoticon.d.ts.map +1 -0
  36. package/dist/detectors/emoticon.js +19 -0
  37. package/dist/detectors/emoticon.js.map +1 -0
  38. package/dist/detectors/en-shape.d.ts +6 -1
  39. package/dist/detectors/en-shape.d.ts.map +1 -1
  40. package/dist/detectors/en-shape.js +9 -1
  41. package/dist/detectors/en-shape.js.map +1 -1
  42. package/dist/detectors/katakana-density.d.ts +6 -1
  43. package/dist/detectors/katakana-density.d.ts.map +1 -1
  44. package/dist/detectors/katakana-density.js +14 -1
  45. package/dist/detectors/katakana-density.js.map +1 -1
  46. package/dist/detectors/lexicon.d.ts.map +1 -1
  47. package/dist/detectors/lexicon.js +2 -1
  48. package/dist/detectors/lexicon.js.map +1 -1
  49. package/dist/detectors/mark-shape.d.ts +2 -2
  50. package/dist/detectors/mark-shape.d.ts.map +1 -1
  51. package/dist/detectors/mark-shape.js +24 -5
  52. package/dist/detectors/mark-shape.js.map +1 -1
  53. package/dist/detectors/mentioned-phrase.d.ts +3 -1
  54. package/dist/detectors/mentioned-phrase.d.ts.map +1 -1
  55. package/dist/detectors/mentioned-phrase.js +9 -0
  56. package/dist/detectors/mentioned-phrase.js.map +1 -1
  57. package/dist/detectors/number-style.d.ts.map +1 -1
  58. package/dist/detectors/number-style.js +13 -1
  59. package/dist/detectors/number-style.js.map +1 -1
  60. package/dist/detectors/obligation-without-deadline.d.ts +10 -2
  61. package/dist/detectors/obligation-without-deadline.d.ts.map +1 -1
  62. package/dist/detectors/obligation-without-deadline.js +47 -2
  63. package/dist/detectors/obligation-without-deadline.js.map +1 -1
  64. package/dist/detectors/open-end-names.d.ts +2 -0
  65. package/dist/detectors/open-end-names.d.ts.map +1 -1
  66. package/dist/detectors/open-end-names.js +8 -1
  67. package/dist/detectors/open-end-names.js.map +1 -1
  68. package/dist/detectors/orthographic-variant.d.ts.map +1 -1
  69. package/dist/detectors/orthographic-variant.js +5 -3
  70. package/dist/detectors/orthographic-variant.js.map +1 -1
  71. package/dist/detectors/paragraph-pointer.d.ts +4 -0
  72. package/dist/detectors/paragraph-pointer.d.ts.map +1 -0
  73. package/dist/detectors/paragraph-pointer.js +22 -0
  74. package/dist/detectors/paragraph-pointer.js.map +1 -0
  75. package/dist/detectors/phrase-match.d.ts +4 -1
  76. package/dist/detectors/phrase-match.d.ts.map +1 -1
  77. package/dist/detectors/phrase-match.js +12 -5
  78. package/dist/detectors/phrase-match.js.map +1 -1
  79. package/dist/detectors/redundant-pair.d.ts +5 -0
  80. package/dist/detectors/redundant-pair.d.ts.map +1 -0
  81. package/dist/detectors/redundant-pair.js +18 -0
  82. package/dist/detectors/redundant-pair.js.map +1 -0
  83. package/dist/detectors/registry/redundant-pair.d.ts +3 -0
  84. package/dist/detectors/registry/redundant-pair.d.ts.map +1 -0
  85. package/dist/detectors/registry/redundant-pair.js +3 -0
  86. package/dist/detectors/registry/redundant-pair.js.map +1 -0
  87. package/dist/detectors/request-owner.d.ts +1 -0
  88. package/dist/detectors/request-owner.d.ts.map +1 -1
  89. package/dist/detectors/request-owner.js +6 -3
  90. package/dist/detectors/request-owner.js.map +1 -1
  91. package/dist/detectors/structure-tree.d.ts.map +1 -1
  92. package/dist/detectors/structure-tree.js +1 -0
  93. package/dist/detectors/structure-tree.js.map +1 -1
  94. package/dist/detectors/structure.js +3 -3
  95. package/dist/detectors/structure.js.map +1 -1
  96. package/dist/detectors/superlative-context.d.ts +7 -0
  97. package/dist/detectors/superlative-context.d.ts.map +1 -1
  98. package/dist/detectors/superlative-context.js +9 -0
  99. package/dist/detectors/superlative-context.js.map +1 -1
  100. package/dist/detectors/token-shape.d.ts.map +1 -1
  101. package/dist/detectors/token-shape.js +7 -5
  102. package/dist/detectors/token-shape.js.map +1 -1
  103. package/dist/detectors/unbalanced-bracket.d.ts.map +1 -1
  104. package/dist/detectors/unbalanced-bracket.js +2 -1
  105. package/dist/detectors/unbalanced-bracket.js.map +1 -1
  106. package/dist/paragraph-length.d.ts +4 -0
  107. package/dist/paragraph-length.d.ts.map +1 -1
  108. package/dist/paragraph-length.js +6 -0
  109. package/dist/paragraph-length.js.map +1 -1
  110. package/dist/plugin.d.ts +2 -0
  111. package/dist/plugin.d.ts.map +1 -1
  112. package/dist/rule-of-three.d.ts +7 -0
  113. package/dist/rule-of-three.d.ts.map +1 -1
  114. package/dist/rule-of-three.js +22 -1
  115. package/dist/rule-of-three.js.map +1 -1
  116. package/dist/structure/build.d.ts.map +1 -1
  117. package/dist/structure/build.js +2 -1
  118. package/dist/structure/build.js.map +1 -1
  119. package/dist/structure/negated-act.d.ts +1 -0
  120. package/dist/structure/negated-act.d.ts.map +1 -1
  121. package/dist/structure/negated-act.js +1 -1
  122. package/dist/structure/negated-act.js.map +1 -1
  123. package/dist/structure/own-name.d.ts +4 -0
  124. package/dist/structure/own-name.d.ts.map +1 -0
  125. package/dist/structure/own-name.js +20 -0
  126. package/dist/structure/own-name.js.map +1 -0
  127. package/dist/structure/percent-sum-prose.d.ts.map +1 -1
  128. package/dist/structure/percent-sum-prose.js +9 -1
  129. package/dist/structure/percent-sum-prose.js.map +1 -1
  130. package/dist/structure/percent-sum.d.ts +2 -0
  131. package/dist/structure/percent-sum.d.ts.map +1 -1
  132. package/dist/structure/percent-sum.js.map +1 -1
  133. package/dist/structure/reference-text.d.ts.map +1 -1
  134. package/dist/structure/reference-text.js +3 -1
  135. package/dist/structure/reference-text.js.map +1 -1
  136. package/dist/te-form-helper.d.ts +22 -0
  137. package/dist/te-form-helper.d.ts.map +1 -0
  138. package/dist/te-form-helper.js +35 -0
  139. package/dist/te-form-helper.js.map +1 -0
  140. package/dist/word-use.d.ts +7 -0
  141. package/dist/word-use.d.ts.map +1 -1
  142. package/dist/word-use.js +11 -0
  143. package/dist/word-use.js.map +1 -1
  144. package/package.json +3 -3
  145. package/rules/absolute-exception.yaml +3 -3
  146. package/rules/all-caps-shouting.yaml +2 -2
  147. package/rules/bold-label-list.yaml +9 -2
  148. package/rules/duration-mismatch.yaml +2 -2
  149. package/rules/katakana-density.yaml +3 -3
  150. package/rules/no-doubled-joshi.yaml +2 -2
  151. package/rules/number-style-consistency.yaml +2 -2
  152. package/rules/obligation-without-deadline.yaml +2 -2
  153. package/rules/padded-intro.yaml +1 -1
  154. package/rules/redundant-expression.yaml +1 -1
  155. package/rules/request-without-deadline.yaml +2 -2
  156. package/rules/requirement-smell.yaml +2 -2
  157. package/rules/rule-of-three.yaml +2 -2
  158. package/src/bound-word-particles.ts +23 -0
  159. package/src/derived/stays.ts +4 -1
  160. package/src/detectors/absolute-exception.ts +11 -5
  161. package/src/detectors/agreement-slip.ts +35 -10
  162. package/src/detectors/bold-label.ts +25 -4
  163. package/src/detectors/bold-quoted.ts +21 -0
  164. package/src/detectors/caps-caption.ts +10 -0
  165. package/src/detectors/count-per-section.ts +9 -4
  166. package/src/detectors/defined-term-form.ts +2 -1
  167. package/src/detectors/emoticon.ts +21 -0
  168. package/src/detectors/en-shape.ts +10 -1
  169. package/src/detectors/katakana-density.ts +17 -2
  170. package/src/detectors/lexicon.ts +2 -1
  171. package/src/detectors/mark-shape.ts +28 -7
  172. package/src/detectors/mentioned-phrase.ts +13 -1
  173. package/src/detectors/number-style.ts +14 -1
  174. package/src/detectors/obligation-without-deadline.ts +69 -5
  175. package/src/detectors/open-end-names.ts +21 -2
  176. package/src/detectors/orthographic-variant.ts +20 -15
  177. package/src/detectors/paragraph-pointer.ts +28 -0
  178. package/src/detectors/phrase-match.ts +13 -5
  179. package/src/detectors/redundant-pair.ts +25 -0
  180. package/src/detectors/registry/redundant-pair.ts +4 -0
  181. package/src/detectors/request-owner.ts +6 -3
  182. package/src/detectors/structure-tree.ts +1 -0
  183. package/src/detectors/structure.ts +3 -3
  184. package/src/detectors/superlative-context.ts +12 -0
  185. package/src/detectors/token-shape.ts +10 -7
  186. package/src/detectors/unbalanced-bracket.ts +2 -1
  187. package/src/paragraph-length.ts +10 -0
  188. package/src/plugin.ts +2 -0
  189. package/src/rule-of-three.ts +27 -1
  190. package/src/structure/build.ts +2 -1
  191. package/src/structure/negated-act.ts +1 -1
  192. package/src/structure/own-name.ts +28 -0
  193. package/src/structure/percent-sum-prose.ts +12 -1
  194. package/src/structure/percent-sum.ts +2 -0
  195. package/src/structure/reference-text.ts +5 -1
  196. package/src/te-form-helper.ts +52 -0
  197. package/src/word-use.ts +13 -0
  198. package/src/honorific-group.ts +0 -22
@@ -1,6 +1,7 @@
1
1
  import type { LexiconEntry, ProseDocument, Sentence, Token } from "../plugin.ts";
2
2
  import { escapeRegExp } from "../orthography.ts";
3
3
  import { entryRanges, type TokenRange } from "./lexicon-match.ts";
4
+ import { inDocumentOrder } from "../structure/issues.ts";
4
5
 
5
6
  // A word that leaves a list open (等, etc.) is also part of names a document gives itself: 「業務執行取締役等」,
6
7
  // 銀行等(…をいう。), the head of a definition item (四の二 親会社等 …をいう。), and longer nouns built on them
@@ -43,7 +44,13 @@ type QuotedName = { readonly name: string; readonly at: readonly number[] };
43
44
  * The names a document gives that contain an open-end word: the ones it quotes, the ones it defines in an aside right
44
45
  * after them (whole, as written there), and the heads of its definition items (which may run on into the definition).
45
46
  */
46
- export type OpenEndNames = { readonly quoted: readonly QuotedName[]; readonly defined: ReadonlySet<string>; readonly heads: readonly string[] };
47
+ export type OpenEndNames = {
48
+ readonly quoted: readonly QuotedName[];
49
+ readonly defined: ReadonlySet<string>;
50
+ readonly heads: readonly string[];
51
+ /** Every term the document defines (「秘密情報」): the word right after one (秘密情報等) widens a named thing, not an open list. */
52
+ readonly terms: ReadonlySet<string>;
53
+ };
47
54
 
48
55
  const attached = (left: Token | undefined, right: Token | undefined): boolean =>
49
56
  left !== undefined && right !== undefined && left.span.end === right.span.start;
@@ -129,12 +136,19 @@ const quotedNames = (source: string, words: readonly LexiconEntry[]): QuotedName
129
136
  return at.length === 0 ? [] : [{ name, at }];
130
137
  });
131
138
 
139
+ const definedTerms = (doc: ProseDocument): Set<string> =>
140
+ new Set(
141
+ doc.structure === undefined
142
+ ? []
143
+ : inDocumentOrder(doc.structure).flatMap((node) => (node.kind === "definition" && typeof node.attrs["term"] === "string" ? [node.attrs["term"]] : [])),
144
+ );
145
+
132
146
  /** The names a document gives that contain an open-end word. statements: the language's words of a definition (をいう, means). */
133
147
  export const openEndNames = (doc: ProseDocument, words: readonly LexiconEntry[], statements: readonly string[]): OpenEndNames => {
134
148
  const occurrences = doc.sentences.flatMap((sentence) => words.flatMap((word) => occurrencesIn(sentence, word)));
135
149
  const defined = occurrences.filter((occurrence) => definedInAside(doc.source, occurrence, statements)).map((occurrence) => nounOf(doc.source, occurrence));
136
150
  const heads = occurrences.filter((occurrence) => headsItem(doc.source, occurrence, statements)).map((occurrence) => nounOf(doc.source, occurrence));
137
- return { quoted: quotedNames(doc.source, words), defined: new Set(defined), heads: [...new Set(heads)] };
151
+ return { quoted: quotedNames(doc.source, words), defined: new Set(defined), heads: [...new Set(heads)], terms: definedTerms(doc) };
138
152
  };
139
153
 
140
154
  /** Whether a quoted name holds this occurrence: the text around it reads the whole name (当該責任追及等 holds 「責任追及等」). */
@@ -152,8 +166,13 @@ const partsHoldingWord = (source: string, occurrence: Occurrence): string[] => {
152
166
  return starts.flatMap((start) => ends.map((end) => source.slice(start, end)));
153
167
  };
154
168
 
169
+ /** Whether the word follows a defined term written whole (秘密情報等 where 「秘密情報」 is defined). */
170
+ const followsTerm = (source: string, occurrence: Occurrence, terms: ReadonlySet<string>): boolean =>
171
+ occurrence.tokens.slice(occurrence.first, occurrence.range.start).some((token) => terms.has(source.slice(token.span.start, occurrence.start)));
172
+
155
173
  const isNamed = (source: string, occurrence: Occurrence, names: OpenEndNames): boolean =>
156
174
  inQuotedName(source, occurrence, names.quoted) ||
175
+ followsTerm(source, occurrence, names.terms) ||
157
176
  partsHoldingWord(source, occurrence).some((part) => names.defined.has(part) || names.heads.some((head) => head.startsWith(part)));
158
177
 
159
178
  /** Whether the words around an occurrence bound its list; range: the tokens the word covers. */
@@ -27,24 +27,26 @@ import {
27
27
  } from "../word-use.ts";
28
28
  import { titleCaseNameRuns } from "../title-case-name.ts";
29
29
  import { withoutQuotedSpellings, type Quoted } from "../quoted-spelling.ts";
30
+ import { teFormOf, withTeFormFullVerbs, type TeForm } from "../te-form-helper.ts";
30
31
  import { citedSpans, isOpenIn, namesOf, patternsOf, type IsOpen, type Names } from "./orthographic-variant-open.ts";
31
32
 
32
33
  /**
33
34
  * A word found in the document: where it is, which sentence it is in, its key and spelling, how it is written when that differs, and
34
35
  * whether it is written onto the noun after it (取扱事業者).
35
36
  */
36
- type Placed = KeyedWord & {
37
- readonly sentence: Sentence;
38
- readonly offset: number;
39
- readonly shown?: string;
40
- readonly compoundHead?: boolean;
41
- /** Where a run of words ends (タイヤレバー). */
42
- readonly end?: number;
43
- /** Whether a Latin word stands in a name of capitalised words (the Interagency Group) or in a cited work. */
44
- readonly quoted?: Quoted | undefined;
45
- /** The name a word stands in, as written. */
46
- readonly name?: string | undefined;
47
- };
37
+ type Placed = KeyedWord &
38
+ TeForm & {
39
+ readonly sentence: Sentence;
40
+ readonly offset: number;
41
+ readonly shown?: string;
42
+ readonly compoundHead?: boolean;
43
+ /** Where a run of words ends (タイヤレバー). */
44
+ readonly end?: number;
45
+ /** Whether a Latin word stands in a name of capitalised words (the Interagency Group) or in a cited work. */
46
+ readonly quoted?: Quoted | undefined;
47
+ /** The name a word stands in, as written. */
48
+ readonly name?: string | undefined;
49
+ };
48
50
 
49
51
  /** Parts of speech that carry a word of their own. Particles and endings are written one way by the grammar. */
50
52
  const CONTENT = new Set(["NOUN", "VERB", "ADJ", "ADV", "PRON", "CCONJ", "DET"]);
@@ -155,11 +157,12 @@ const readingWords = (sentence: Sentence, isOpen: IsOpen, skips: Skips): Placed[
155
157
  if (inRun.has(at)) return [];
156
158
  const next = tokens[at + 1];
157
159
  const token = asNounWhereNominal(written, next, skips.phraseSuffixes, skips.nouns);
158
- const key = readingKeyOf({ token, previous: tokens[at - 1], before: tokens[at - 2], following: tokens.slice(at + 1, at + 3) }, skips);
160
+ const word = { token, previous: tokens[at - 1], before: tokens[at - 2], following: tokens.slice(at + 1, at + 3) };
161
+ const key = readingKeyOf(word, skips);
159
162
  const local = token.span.start - sentence.span.start;
160
163
  if (key === undefined || token.lemma === undefined || !isOpen(local, local + token.surface.length)) return [];
161
164
  const compoundHead = isCompoundHead(token, tokens, at, skips.phraseSuffixes);
162
- return [{ key, spelling: token.lemma, sentence, offset: token.span.start, compoundHead }];
165
+ return [{ key, spelling: token.lemma, sentence, offset: token.span.start, compoundHead, ...teFormOf(word, tokens, at) }];
163
166
  }),
164
167
  ];
165
168
  };
@@ -319,7 +322,9 @@ const cellPlace = (cell: TableCell, names: Names): Place => {
319
322
 
320
323
  /** The odd spellings among places that speak in one voice. */
321
324
  const findingsIn = (placed: readonly Place[], skips: Skips, { isWord, nameJoiners }: Reading, limit: number): Finding[] => {
322
- const reading = byKanji(placed.flatMap(({ sentence, isOpen }) => readingWords(withCutNounsJoined(sentence, skips.nouns), isOpen, skips)));
325
+ const reading = byKanji(
326
+ withTeFormFullVerbs(placed.flatMap(({ sentence, isOpen }) => readingWords(withCutNounsJoined(sentence, skips.nouns), isOpen, skips))),
327
+ );
323
328
  const katakana = placed.flatMap(({ sentence, isOpen }) => katakanaWords(sentence, isOpen));
324
329
  const runs = placed.flatMap(({ sentence, isOpen }) => katakanaRunWords(sentence, isOpen));
325
330
  const latin = withoutQuotedSpellings(
@@ -0,0 +1,28 @@
1
+ import { escapeRegExp } from "../orthography.ts";
2
+ import type { LexiconEntry } from "../plugin.ts";
3
+
4
+ // A sentence that points at another paragraph of its own article: the one before it (前項), or one by its number
5
+ // (本条1項). The words come from the language's paragraph-pointer word list: an entry in the group "previous" points at
6
+ // the paragraph before, and one with … in it is a frame whose … is the paragraph's number. Pure.
7
+
8
+ const FRAME = "…";
9
+ const PREVIOUS = "previous";
10
+ const NUMBER = "([0-90-9]+)";
11
+ const FULL_WIDTH_OFFSET = 0xfee0;
12
+
13
+ const halfWidth = (digits: string): string =>
14
+ [...digits].map((char) => (/[0-9]/u.test(char) ? String.fromCharCode(char.charCodeAt(0) - FULL_WIDTH_OFFSET) : char)).join("");
15
+
16
+ const numberedIn = (text: string, frame: string): number[] => {
17
+ const pattern = new RegExp(frame.split(FRAME).map(escapeRegExp).join(NUMBER), "gu");
18
+ return [...text.matchAll(pattern)].map((match) => Number(halfWidth(match[1] ?? "")));
19
+ };
20
+
21
+ /** The paragraphs of its article a sentence in paragraph own points at. */
22
+ export const pointedParagraphs = (text: string, own: number, pointers: readonly LexiconEntry[]): number[] =>
23
+ pointers
24
+ .filter((entry) => entry.pattern !== "")
25
+ .flatMap((entry) => {
26
+ if (entry.pattern.includes(FRAME)) return numberedIn(text, entry.pattern);
27
+ return entry.group === PREVIOUS && text.includes(entry.pattern) ? [own - 1] : [];
28
+ });
@@ -1,6 +1,7 @@
1
1
  import type { Detector, DetectorOptions, Finding, Lexicon, LexiconEntry, ProseDocument, Sentence } from "../plugin.ts";
2
- import { entryEnds, entryIn } from "./lexicon-match.ts";
3
- import { mentionCuesOf, onlyMentioned } from "./mentioned-phrase.ts";
2
+ import { entryEnds, entryIn, entryOpens } from "./lexicon-match.ts";
3
+ import { externalLinkTitleSpans } from "../link-title.ts";
4
+ import { mentionCuesOf, onlyInTitles, onlyMentioned } from "./mentioned-phrase.ts";
4
5
  import { closingSentences } from "../closing-paragraph.ts";
5
6
  import { quotedPattern } from "./quoted-pattern.ts";
6
7
 
@@ -22,9 +23,12 @@ type Hit = { readonly sentence: Sentence; readonly matched: string };
22
23
  /** Whether the entry's words in the sentence count as a use. phrase-match counts every one. */
23
24
  type IsUsed = (sentence: Sentence, entry: LexiconEntry) => boolean;
24
25
 
26
+ /** An entry marked opens counts only at the head of the sentence: 「近年、」 opens a stock opening, 「その後、近年の」 is a plain word. */
27
+ const writtenIn = (sentence: Sentence, entry: LexiconEntry): boolean => (entry.opens === true ? entryOpens(sentence, entry) : entryIn(sentence, entry));
28
+
25
29
  const hitsIn = (sentences: readonly Sentence[], lexicon: Lexicon, isUsed: IsUsed = () => true): Hit[] =>
26
30
  sentences.flatMap((sentence) => {
27
- const matched = lexicon.find((entry) => entryIn(sentence, entry) && isUsed(sentence, entry));
31
+ const matched = lexicon.find((entry) => writtenIn(sentence, entry) && isUsed(sentence, entry));
28
32
  return matched === undefined ? [] : [{ sentence, matched: quotedPattern(matched.pattern) }];
29
33
  });
30
34
 
@@ -58,10 +62,14 @@ export const phraseMatchWhere = (doc: ProseDocument, options: DetectorOptions, i
58
62
  return hits.length < options.limit ? [] : findingsOf(hits, options.limit);
59
63
  };
60
64
 
61
- /** phrase-match の、言葉として名指しただけの言い回し(the phrase "…", 「…」という言い方)を数えない版(mentioned-phrase.ts)。 */
65
+ /**
66
+ * phrase-match の、言葉として名指しただけの言い回し(the phrase "…", 「…」という言い方)を数えない版(mentioned-phrase.ts)。
67
+ * 参考文献のリンクに写した外のページの題名([文章の極意は…](https://…))の言い回しも、書き手の言葉ではないので数えない。
68
+ */
62
69
  export const phraseInUse: Detector = (doc, options): Finding[] => {
63
70
  const cues = mentionCuesOf(doc.lexicons["mention-cue"] ?? []);
64
- const hits = phraseHits(doc, options, (sentence, entry) => !onlyMentioned(sentence, entry, cues));
71
+ const titles = externalLinkTitleSpans(doc.source, doc.links);
72
+ const hits = phraseHits(doc, options, (sentence, entry) => !onlyMentioned(sentence, entry, cues) && !onlyInTitles(sentence, entry, titles));
65
73
  return hits.length < options.limit ? [] : findingsOf(hits, options.limit);
66
74
  };
67
75
 
@@ -0,0 +1,25 @@
1
+ // redundant-expression: phrase-match over the language's pairs, except a pair whose last word starts a hyphenated compound
2
+ // ("true fact-check" is a fact-check whose verdict is true, not a true fact).
3
+ import type { Detector, LexiconEntry, Sentence, Token } from "../plugin.ts";
4
+ import { entryRanges } from "./lexicon-match.ts";
5
+ import { phraseMatchWhere } from "./phrase-match.ts";
6
+
7
+ const HYPHENS: ReadonlySet<string> = new Set(["-", "‐"]);
8
+
9
+ const joined = (left: Token | undefined, right: Token | undefined): boolean => left !== undefined && right !== undefined && left.span.end === right.span.start;
10
+
11
+ /** The token at end is a hyphen that ties the word before it to the next word, with no space on either side. */
12
+ export const hyphenatedOnward = (tokens: readonly Token[], end: number): boolean => {
13
+ const hyphen = tokens[end];
14
+ const next = tokens[end + 1];
15
+ return hyphen !== undefined && HYPHENS.has(hyphen.surface) && joined(tokens[end - 1], hyphen) && joined(hyphen, next) && /^\p{L}/u.test(next?.surface ?? "");
16
+ };
17
+
18
+ /** Some place of the pair in the sentence ends a phrase rather than running on into a compound. Without tokens every place counts. */
19
+ const standsAsPair = (sentence: Sentence, entry: LexiconEntry): boolean => {
20
+ const tokens = sentence.tokens ?? [];
21
+ const ranges = entryRanges(sentence, entry);
22
+ return ranges.length === 0 || ranges.some((range) => !hyphenatedOnward(tokens, range.end));
23
+ };
24
+
25
+ export const redundantPair: Detector = (doc, options) => phraseMatchWhere(doc, options, standsAsPair);
@@ -0,0 +1,4 @@
1
+ import type { Detector } from "../../plugin.ts";
2
+ import { redundantPair } from "../redundant-pair.ts";
3
+
4
+ export const detector: Detector = redundantPair;
@@ -21,6 +21,7 @@ export const REQUEST_LEXICONS = {
21
21
  prohibition: "request-prohibition",
22
22
  deadlineSection: "request-deadline-section",
23
23
  noDeadlineTitle: "request-no-deadline-title",
24
+ decision: "request-decision",
24
25
  } as const;
25
26
 
26
27
  type Words = Readonly<Record<keyof typeof REQUEST_LEXICONS, readonly string[]>>;
@@ -44,6 +45,7 @@ const wordsOf = (doc: ProseDocument): Words => ({
44
45
  prohibition: patternsOf(doc.lexicons[REQUEST_LEXICONS.prohibition]),
45
46
  deadlineSection: patternsOf(doc.lexicons[REQUEST_LEXICONS.deadlineSection]),
46
47
  noDeadlineTitle: patternsOf(doc.lexicons[REQUEST_LEXICONS.noDeadlineTitle]),
48
+ decision: patternsOf(doc.lexicons[REQUEST_LEXICONS.decision]),
47
49
  });
48
50
 
49
51
  /** How far apart, in characters, the action word and the request ending may be: the action must be what is requested. */
@@ -224,14 +226,15 @@ const withoutDates = (source: string, span: Span, inside: readonly Span[]): stri
224
226
  source.slice(span.start, span.end),
225
227
  );
226
228
 
229
+ /** A date with a deadline word, or with the decision step (a schedule's 「12月:経営会議にて承認」 says when the decision is made). */
227
230
  const statesDeadline = (source: string, sentence: Sentence, words: Words, dates: readonly Span[]): boolean => {
228
231
  const inside = datesInside(sentence.span, dates);
229
- return inside.length > 0 && containsAny(withoutDates(source, sentence.span, inside), words.deadline);
232
+ return inside.length > 0 && containsAny(withoutDates(source, sentence.span, inside), [...words.deadline, ...words.decision]);
230
233
  };
231
234
 
232
235
  /**
233
- * The section headed only by a deadline-section word (a notice's "DATES:", "2. Deadline") that states a date with a
234
- * deadline word: the document gives its deadline once there. -1 without one.
236
+ * The section headed only by a deadline-section word (a notice's "DATES:", "2. Deadline", a proposal's schedule) that
237
+ * states a date with a deadline or decision word: the document gives its deadline once there. -1 without one.
235
238
  */
236
239
  const documentDeadlineSection = (source: string, sections: readonly Section[], words: Words, dates: readonly Span[]): number =>
237
240
  sections.findIndex(
@@ -336,6 +336,7 @@ const shareWordsOf = (doc: ProseDocument): ShareWords => ({
336
336
  exceptions: (doc.lexicons["share-exception"] ?? []).map((entry) => entry.pattern),
337
337
  rests: (doc.lexicons["share-rest"] ?? []).map((entry) => entry.pattern),
338
338
  changes: (doc.lexicons["change-direction"] ?? []).map((entry) => entry.pattern),
339
+ joiners: [...(doc.lexicons["range-connector"] ?? []), ...(doc.lexicons["quantity-range-word"] ?? [])].map((entry) => entry.pattern),
339
340
  units: (doc.lexicons["percent-unit"] ?? []).map((entry) => entry.pattern),
340
341
  totalLabels: (doc.lexicons["total-label"] ?? []).map((entry) => entry.pattern),
341
342
  });
@@ -4,7 +4,7 @@ import type { Detector, DetectorOptions, Finding, LengthUnit, Paragraph, ProseDo
4
4
  import { dateStampIndexes, stampCandidates } from "../date-stamp.ts";
5
5
  import { inDocumentOrder } from "../structure/issues.ts";
6
6
  import { preambleParagraphs } from "../preamble-paragraphs.ts";
7
- import { isTooLongParagraph, labelledBlocks, opensWithFusedHeading } from "../paragraph-length.ts";
7
+ import { isTooLongParagraph, labelledBlocks, lostLineBreaks, opensWithFusedHeading } from "../paragraph-length.ts";
8
8
  import { bodySectionOf } from "../body-section.ts";
9
9
  import { threeShare } from "../rule-of-three.ts";
10
10
  import { isInterview, sectionLevels } from "../section-levels.ts";
@@ -65,12 +65,12 @@ const sentenceSize = (sentence: Sentence, unit: LengthUnit): number =>
65
65
  type Block = { readonly start: number; readonly sentences: readonly Sentence[] };
66
66
 
67
67
  /**
68
- * 段落の中の、長さを測る文の組と、その頭の位置(最初の組は段落の頭)。見出しが本文に溶けた段落(改行の落ちた文書)は測らない。
68
+ * 段落の中の、長さを測る文の組と、その頭の位置(最初の組は段落の頭)。見出しが本文に溶けた段落や、文どうしが空白なしでつながった段落(改行の落ちた文書)は測らない。
69
69
  * 【】の見出しや段落番号だけの行で段落を割る。
70
70
  */
71
71
  const measuredBlocks = (doc: ProseDocument, paragraph: Paragraph): Block[] => {
72
72
  const text = doc.source.slice(paragraph.span.start, paragraph.span.end);
73
- if (opensWithFusedHeading(text)) return [];
73
+ if (opensWithFusedHeading(text) || lostLineBreaks(paragraph.sentences)) return [];
74
74
  return labelledBlocks(text, paragraph.span.start, paragraph.sentences).map((sentences, index) => ({
75
75
  start: index === 0 ? paragraph.span.start : (sentences[0]?.span.start ?? paragraph.span.start),
76
76
  sentences,
@@ -12,6 +12,8 @@ export type Context = {
12
12
  readonly viewpoints: Lexicon;
13
13
  /** 全体の部分を言う名詞(part・role・step)。 */
14
14
  readonly parts: Lexicon;
15
+ /** 前に名指した名詞の代わりに立つ語(one・ones)。 */
16
+ readonly proForms: Lexicon;
15
17
  };
16
18
 
17
19
  /** 語彙表の語が最上級まで届く語の数。これより離れた動詞は、間に別の目的語や節がある。 */
@@ -33,6 +35,7 @@ export const contextOf = (lexicons: Readonly<Record<string, Lexicon>>): Context
33
35
  referents: lexicons["superlative-referent"] ?? [],
34
36
  viewpoints: lexicons["superlative-viewpoint"] ?? [],
35
37
  parts: lexicons["superlative-part"] ?? [],
38
+ proForms: lexicons["superlative-pro-form"] ?? [],
36
39
  });
37
40
 
38
41
  const isPunct = (token: Token | undefined): boolean => token === undefined || token.pos === "PUNCT";
@@ -105,3 +108,12 @@ export const ranksParts = (tokens: readonly Token[], range: TokenRange, parts: L
105
108
  const at = phraseEnd(tokens, range.end);
106
109
  return at > range.end && isWord(tokens[at - 1], parts);
107
110
  };
111
+
112
+ /**
113
+ * 最上級の名詞が、前に名指した名詞の代わりの語か(ten topics … the best-scoring one)。比べている集まりは文章が先に
114
+ * 名指したもので、世の中のものと比べた主張ではない。名詞は最上級の修飾の後ろに来る(英語)。
115
+ */
116
+ export const picksFromNamedSet = (tokens: readonly Token[], range: TokenRange, proForms: Lexicon): boolean => {
117
+ const at = phraseEnd(tokens, range.end);
118
+ return at > range.end && isWord(tokens[at - 1], proForms);
119
+ };
@@ -4,7 +4,7 @@ import { chronologyRows } from "../chronology-rows.ts";
4
4
  import { externalLinkTitleSpans } from "../link-title.ts";
5
5
  import type { Detector, Finding, Span, Token } from "../plugin.ts";
6
6
  import { countedTokens, uncountedWordsOf, type UncountedWords } from "../uncounted-particles.ts";
7
- import { honorificGroupParticles } from "../honorific-group.ts";
7
+ import { boundWordParticles } from "../bound-word-particles.ts";
8
8
  import { setPhraseParticles } from "../set-phrase-particles.ts";
9
9
  import { noteSentences } from "../note-paragraphs.ts";
10
10
  import { documentNameSpans } from "./particle-run-names.ts";
@@ -100,15 +100,18 @@ const RUN_BREAK_LEXICON = "particle-run-break";
100
100
  /** 人の集まりを敬って呼ぶ語(国民の皆様の「皆様」)。直前の助詞は呼び方の一部で、入れ子の輪に数えない。 */
101
101
  const HONORIFIC_GROUP_LEXICON = "honorific-group";
102
102
 
103
+ /** 置き場所を言う語(ラックの下の「下」)。直前の助詞は「ラックの下」という一つの場所の名前の中にあり、入れ子の輪に数えない。 */
104
+ const POSITION_LEXICON = "particle-run-position";
105
+
103
106
  /** 助詞を挟んで一語のように読む決まった言い回し(おそれのある)。中の助詞は入れ子の輪に数えない。 */
104
107
  const SET_PHRASE_LEXICON = "particle-run-set-phrase";
105
108
 
106
- /** 敬って呼ぶ語(皆様)と決まった言い回し(おそれのある)。 */
107
- type Phrases = { readonly groups: readonly string[]; readonly setPhrases: readonly string[] };
109
+ /** 前の語と組んで一つの名前になる語(皆様、下)と決まった言い回し(おそれのある)。 */
110
+ type Phrases = { readonly boundWords: readonly string[]; readonly setPhrases: readonly string[] };
108
111
 
109
- /** 数えない助詞(番号をつなぐ「の」、敬って呼ぶ語の前の「の」、決まった言い回しの中の「の」)を除いた語。 */
110
- const chainTokens = (tokens: readonly Token[], numbering: UncountedWords, { groups, setPhrases }: Phrases): readonly Token[] => {
111
- const uncounted = new Set([...honorificGroupParticles(tokens, numbering.particles, groups), ...setPhraseParticles(tokens, numbering.particles, setPhrases)]);
112
+ /** 数えない助詞(番号をつなぐ「の」、敬って呼ぶ語や置き場所を言う語の前の「の」、決まった言い回しの中の「の」)を除いた語。 */
113
+ const chainTokens = (tokens: readonly Token[], numbering: UncountedWords, { boundWords, setPhrases }: Phrases): readonly Token[] => {
114
+ const uncounted = new Set([...boundWordParticles(tokens, numbering.particles, boundWords), ...setPhraseParticles(tokens, numbering.particles, setPhrases)]);
112
115
  const counted = countedTokens(tokens, numbering);
113
116
  return uncounted.size === 0 ? counted : counted.filter((token) => !uncounted.has(token));
114
117
  };
@@ -119,7 +122,7 @@ export const doubledParticle: Detector = (doc, options): Finding[] => {
119
122
  const breaks = (doc.lexicons[RUN_BREAK_LEXICON] ?? []).map((entry) => entry.pattern);
120
123
  const numbering = uncountedWordsOf(doc.lexicons, nesting);
121
124
  const phrases: Phrases = {
122
- groups: (doc.lexicons[HONORIFIC_GROUP_LEXICON] ?? []).map((entry) => entry.pattern),
125
+ boundWords: [HONORIFIC_GROUP_LEXICON, POSITION_LEXICON].flatMap((id) => (doc.lexicons[id] ?? []).map((entry) => entry.pattern)),
123
126
  setPhrases: (doc.lexicons[SET_PHRASE_LEXICON] ?? []).map((entry) => entry.pattern),
124
127
  };
125
128
  const prose = doc.prose ?? doc.source;
@@ -6,6 +6,7 @@ import { mergeSpans } from "../span-merge.ts";
6
6
  import { firstEndingAfter } from "../soft-break.ts";
7
7
  import { isLabelClose, isLabelInAside } from "./bracket-label.ts";
8
8
  import { isInchMark } from "./inch-mark.ts";
9
+ import { isEmoticonMouth } from "./emoticon.ts";
9
10
 
10
11
  /**
11
12
  * 括弧の組。どの言語でも同じ字の決まりなので、語彙表ではなくここに置く。family は形(丸・角)で、全角と半角は同じ形の別の幅。
@@ -95,7 +96,7 @@ export const bracketProblems = (text: string): BracketProblem[] => {
95
96
  const heads = paragraphHeads(text);
96
97
  [...text.matchAll(MARKS)].forEach((match) => {
97
98
  const quoteOpen = scan.open.some((entry) => entry.bracket.family === "quote");
98
- if (isInchMark(text, match.index, quoteOpen)) return;
99
+ if (isInchMark(text, match.index, quoteOpen) || isEmoticonMouth(text, match.index)) return;
99
100
  const opening = BY_OPEN.get(match[0]);
100
101
  const closing = BY_CLOSE.get(match[0]);
101
102
  if (opening !== undefined) openWith(scan, opening, match.index, heads.has(match.index));
@@ -19,6 +19,16 @@ const FUSED_HEADING = /^[ \t\u3000]*[0-90-9①-⑳]{1,3}【[^】\n]+】[ \t\
19
19
  /** 段落の本文が、番号付きの見出しから改行なしで始まる。段落の切れ目が失われた文書で、長さを測っても書き手の段落ではない。 */
20
20
  export const opensWithFusedHeading = (text: string): boolean => FUSED_HEADING.test(text);
21
21
 
22
+ /** A sentence end glued to the next sentence with no space ("speculate about it.Judge the claim"): a line break lost in copying. The next word ends in a space or a mark other than a period: "Cong.Rec." is an abbreviation. */
23
+ const GLUED_SENTENCES = /(?<=\p{Ll}\p{Ll})[.!?](?=\p{Lu}\p{Ll}+[\s,;:])/gu;
24
+
25
+ /** One glued pair is a typo; two or more mean the block's line breaks were lost, so its sentences were not one paragraph. */
26
+ const MIN_GLUED = 2;
27
+
28
+ /** 文の終わりと次の文の頭が空白なしでつながる所が二つ以上ある。改行が落ちた塊で、長さを測っても書き手の段落ではない。 */
29
+ export const lostLineBreaks = (sentences: readonly { readonly text: string }[]): boolean =>
30
+ sentences.reduce((count, sentence) => count + [...sentence.text.matchAll(GLUED_SENTENCES)].length, 0) >= MIN_GLUED;
31
+
22
32
  /** 【】のラベルだけの文(【0001】【技術分野】)。見出しで、文に数えない。 */
23
33
  const LABELS_ONLY = /^\s*(?:【[^】\n]+】\s*)+$/u;
24
34
 
package/src/plugin.ts CHANGED
@@ -77,6 +77,8 @@ export type LexiconEntry = {
77
77
  readonly genres?: readonly string[] | undefined;
78
78
  /** The entry counts only in a heading: a title phrase that body text uses plainly. A detector that reads headings honours it. */
79
79
  readonly heading_only?: boolean | undefined;
80
+ /** The entry counts only where it opens the sentence (近年、… but not その後、近年の…). phrase-match honours it. */
81
+ readonly opens?: boolean | undefined;
80
82
  /** pattern を adapter が語に分けたもの。品詞が読めるときだけ core が入れる。語彙表を書く側は書かない。 */
81
83
  readonly tokens?: readonly Token[] | undefined;
82
84
  };
@@ -6,6 +6,7 @@ import type { BulletList } from "./plugin.ts";
6
6
  * 箇条書きが少ないと、1 つで割合が大きく動く(4 つなら 25 ポイント)。そのときは全部が 3 項目のときだけ報告する。
7
7
  * 2 つでも測る。生成文の報告書は「要因 3 つ」「提言 3 つ」の 2 つの箇条書きで終わることが多く、人の文書で 2 つとも 3 項目は少ない。
8
8
  * 本文の最初の文より前の箇条書き(題・日付・見出しのすぐ下の要点や概要)は数えない。項目の数はサイトの型が決めている。
9
+ * どの項目も「札:数」の内訳も、ちょうど 3 項目とは数えない。
9
10
  */
10
11
  export type ThreeShare = { readonly count: number; readonly total: number; readonly share: number; readonly first: BulletList };
11
12
 
@@ -48,8 +49,33 @@ const isProseLine = (line: string): boolean => !NOT_PROSE_LINE.test(line) && SEN
48
49
  /** 本文の最初の文がある行の頭。それより前は題・日付・見出しだけ。文が無ければ文書の終わり。 */
49
50
  export const firstProseOffset = (source: string): number => [...source.matchAll(/^.*$/gmu)].find(([line]) => isProseLine(line))?.index ?? source.length;
50
51
 
52
+ const ITEM_MARKER = /^\s*(?:[-*+]|\d+[.)])\s+/u;
53
+ const LABEL_COLON = /[::]/u;
54
+ const DIGIT = /[0-90-9]/u;
55
+ const EMPHASIS = /[*_]/u;
56
+ /** 札と値の長さの上限。「執務エリアの通路沿い」「大きめを2鉢」は入り、文になった値は入らない。 */
57
+ const MAX_LABEL = 20;
58
+ const MAX_VALUE = 12;
59
+
60
+ /** 太字でない短い札とコロン、その後ろに数字を含む短い値だけがある項目(「受付:大きめを2鉢」「Rent: $1,200」)。 */
61
+ const isLabelledFigure = (item: string): boolean => {
62
+ const line = item.replace(ITEM_MARKER, "").split("\n")[0] ?? "";
63
+ const colon = line.search(LABEL_COLON);
64
+ const label = line.slice(0, colon);
65
+ const value = line.slice(colon + 1).trim();
66
+ return colon > 0 && label.length <= MAX_LABEL && !EMPHASIS.test(label) && value.length <= MAX_VALUE && DIGIT.test(value);
67
+ };
68
+
69
+ /**
70
+ * どの項目も「札:数」の箇条書き(置き場所ごとの鉢の数、費目ごとの金額)。数の内訳で、項目の数は中身が決めている。
71
+ * 札の側だけに数がある日程(「2026年12月:承認」)は内訳ではない。太字の札や、値が文になった項目(「**件数**:月平均 420 件届く」)は、
72
+ * 生成文が理由を 3 つに揃える形なので内訳と読まない。
73
+ */
74
+ export const isFigureBreakdown = (source: string, list: BulletList): boolean =>
75
+ list.itemSpans.length > 0 && list.itemSpans.every((item) => isLabelledFigure(source.slice(item.start, item.end)));
76
+
51
77
  const isExactlyThree = (source: string, list: BulletList, openWords: readonly string[]): boolean =>
52
- list.items.length === THREE && !continuesBeyond(source, list, openWords);
78
+ list.items.length === THREE && !continuesBeyond(source, list, openWords) && !isFigureBreakdown(source, list);
53
79
 
54
80
  /** 報告するときの数。報告しないときは undefined。 */
55
81
  export const threeShare = (source: string, allLists: readonly BulletList[], openWords: readonly string[], limit: number): ThreeShare | undefined => {
@@ -3,6 +3,7 @@ import { atxHeadingText, headingText } from "../heading-text.ts";
3
3
  import { addressSpans } from "../address-chain.ts";
4
4
  import { relativeMentions, substitutedDocuments } from "./relative-find.ts";
5
5
  import { resolveRelative } from "./relative-resolve.ts";
6
+ import { resolveOwnNames } from "./own-name.ts";
6
7
  import { maskSpans } from "../mask.ts";
7
8
  import type { DocumentProfile, Mention, NumberedLine, NumberingContext, Span, StructureKind, StructureNode, StructurePatterns } from "../plugin.ts";
8
9
  import { lineNumberAt, linesOf, type Line } from "./lines.ts";
@@ -398,7 +399,7 @@ export const buildTree = (input: StructureInput, patterns: StructurePatterns): S
398
399
  // コードの行は覆って読まないが、開いている節の中身ではある。節の最後にコードブロックがあっても、範囲をそこまで伸ばす。
399
400
  else if (input.source.slice(line.start, line.start + line.text.length).trim() !== "") extend(state, line.start + line.text.length);
400
401
  });
401
- const tree = freeze(doc);
402
+ const tree = resolveOwnNames(freeze(doc), input.source);
402
403
  const relative = input.profile?.relative;
403
404
  return relative === undefined ? tree : resolveRelative(tree, relative.implicitFirst);
404
405
  };
@@ -13,7 +13,7 @@ export const NEGATED = "¬";
13
13
  export const negationWords = (lexicon: Lexicon | undefined): ReadonlySet<string> =>
14
14
  new Set((lexicon ?? []).filter((entry) => entry.group === undefined).map((entry) => entry.pattern.toLowerCase()));
15
15
 
16
- const isNegation = (token: Token, words: ReadonlySet<string>): boolean =>
16
+ export const isNegation = (token: Token, words: ReadonlySet<string>): boolean =>
17
17
  words.has(token.surface.toLowerCase()) || (token.lemma !== undefined && words.has(token.lemma.toLowerCase()));
18
18
 
19
19
  export const isMarkedNegation = (token: Token): boolean => token.features?.[NEGATION_FEATURE] !== undefined;
@@ -0,0 +1,28 @@
1
+ import type { StructureNode } from "../plugin.ts";
2
+ import { foldPostOrder } from "../tree-walk.ts";
3
+
4
+ // A reference named with a longer form of the document's own name (本共同研究開発契約第6条 where 本契約 is the document's
5
+ // short own name) points into another document only when the document calls itself by the short form; otherwise the
6
+ // longer form is the document's own name (本利用規約 with no 本規約) and the reference stays in it. The language package
7
+ // marks such a reference with document and ownName; this pass decides, over the whole text. Pure.
8
+
9
+ const resolvedAttrs = (attrs: StructureNode["attrs"], ownName: string, source: string): StructureNode["attrs"] => {
10
+ const elsewhere = source.includes(ownName);
11
+ return Object.fromEntries(Object.entries(attrs).filter(([key]) => key !== "ownName" && (elsewhere || key !== "document")));
12
+ };
13
+
14
+ /** One node rebuilt over its resolved children; a node whose children did not change and that holds no marker is kept as it was. */
15
+ const resolved = (node: StructureNode, children: readonly StructureNode[], source: string): StructureNode => {
16
+ const ownName = node.attrs["ownName"];
17
+ const same = children.every((child, index) => child === node.children[index]);
18
+ if (typeof ownName !== "string") return same ? node : { ...node, children };
19
+ return { ...node, attrs: resolvedAttrs(node.attrs, ownName, source), children };
20
+ };
21
+
22
+ /** The tree with each ownName-marked reference kept in another document or brought back into this one. Read without recursion: a tree may be thousands of levels deep. */
23
+ export const resolveOwnNames = (tree: StructureNode, source: string): StructureNode =>
24
+ foldPostOrder<StructureNode, StructureNode>(
25
+ tree,
26
+ (node) => node.children,
27
+ (node, children) => resolved(node, children, source),
28
+ );
@@ -77,11 +77,22 @@ const namesRest = (source: string, sentence: Span, shares: readonly Amount[], wo
77
77
  });
78
78
  };
79
79
 
80
+ /** Whether only a joiner stands between two percentages ("from 51% to 53%", 「50%〜60%」): one share at two values. */
81
+ const joinedTo = (source: string, earlier: Amount, later: Amount, joiners: readonly string[]): boolean => {
82
+ const written = source.slice(earlier.end, later.offset);
83
+ const between = (written.startsWith(earlier.unit) ? written.slice(earlier.unit.length) : written).trim().toLowerCase();
84
+ return joiners.some((joiner) => joiner.toLowerCase() === between);
85
+ };
86
+
87
+ /** Two shares joined into a range or a change: which of the two values is the part cannot be told, so the sentence is not added. */
88
+ const holdsJoinedPair = (source: string, shares: readonly Amount[], joiners: readonly string[]): boolean =>
89
+ shares.some((share, index) => index > 0 && joinedTo(source, shares[index - 1] ?? share, share, joiners));
90
+
80
91
  const issueIn = (source: string, sentence: Span, percents: readonly Amount[], words: ShareWords): StructureIssue[] => {
81
92
  const text = source.slice(sentence.start, sentence.end);
82
93
  if (includesAny(text, words.exceptions)) return [];
83
94
  const shares = percents.filter((amount) => amount.offset >= sentence.start && amount.end <= sentence.end);
84
- if (shares.length < MIN_PARTS || shares.some((share) => isSigned(source, share))) return [];
95
+ if (shares.length < MIN_PARTS || shares.some((share) => isSigned(source, share)) || holdsJoinedPair(source, shares, words.joiners ?? [])) return [];
85
96
  if (!includesAny(text, words.labels) && !namesRest(source, sentence, shares, words)) return [];
86
97
  const sum = shares.reduce((total, share) => total + share.value, 0);
87
98
  const decimals = Math.max(0, ...shares.map((share) => decimalsOf(source, share)));
@@ -24,6 +24,8 @@ export type ShareWords = {
24
24
  readonly rests?: readonly string[];
25
25
  /** 値の動いた向きの語(伸び、grew)。その文の百分率は変化で、「その他」があっても内訳ではない。 */
26
26
  readonly changes?: readonly string[];
27
+ /** 二つの値を一つの範囲や変化につなぐ語と印(to, 〜)。つないだ二つの百分率は一つの割合の二つの値で、どちらが内訳の部分かは言えない。 */
28
+ readonly joiners?: readonly string[];
27
29
  readonly units: readonly string[];
28
30
  readonly totalLabels: readonly string[];
29
31
  };
@@ -116,9 +116,13 @@ const EN_TOPIC = /^(?:the |a |an )?([a-z][a-z-]{2,}(?: [a-z][a-z-]{2,}){0,2})/iu
116
116
  const STEM = 5;
117
117
  const LATIN_TOPIC = /^[a-z -]+$/iu;
118
118
 
119
+ /** The link starts the text as a whole word: "for" in "for pricing", not in "formulate". */
120
+ const startsWithLink = (text: string, link: string): boolean =>
121
+ text.toLowerCase().startsWith(link.toLowerCase()) && !(LATIN_TOPIC.test(link) && LETTER.test(text.charAt(link.length)));
122
+
119
123
  const topicAfter = (source: string, end: number, links: readonly string[]): string | undefined => {
120
124
  const after = source.slice(end, end + 60);
121
- const link = links.find((candidate) => after.replace(SPACE_BEFORE, "").toLowerCase().startsWith(candidate.toLowerCase()));
125
+ const link = links.find((candidate) => startsWithLink(after.replace(SPACE_BEFORE, ""), candidate));
122
126
  if (link === undefined) return undefined;
123
127
  const rest = after.replace(SPACE_BEFORE, "").slice(link.length).replace(SPACE_BEFORE, "");
124
128
  return JA_TOPIC.exec(rest)?.[0] ?? EN_TOPIC.exec(rest)?.[1];
@@ -0,0 +1,52 @@
1
+ import type { Token } from "./plugin.ts";
2
+ import { isHelperByTeFormOnly, teFormVerbOf, type InContext } from "./word-use.ts";
3
+
4
+ // orthographic-variant: a kanji verb after a て-form is the helper (書いて見る) or the next act (並んで見た), and the form alone
5
+ // cannot tell. These decide which, from the document's own spellings.
6
+
7
+ /** Where a word stands after a て-form. */
8
+ export type TeForm = {
9
+ /** A full verb read as a helper only for the て-form before it, whose verb takes no object (並んで見た). */
10
+ readonly teFormOnly?: boolean;
11
+ /** The verb whose て-form stands before it (まとめる in まとめてみる). */
12
+ readonly teVerb?: string;
13
+ };
14
+
15
+ type KeyedTeWord = TeForm & { readonly key: string; readonly spelling: string };
16
+
17
+ const OBJECT_PARTICLE = "を";
18
+
19
+ /** The て-form verb takes an object (芽を残して置く): the verb after it has none of its own, and is the helper. */
20
+ const teVerbHasObject = (word: InContext, tokens: readonly Token[], at: number): boolean => {
21
+ const teVerbAt = word.previous?.pos === "SCONJ" ? at - 2 : at - 1;
22
+ const particle = tokens[teVerbAt - 1];
23
+ return particle?.pos === "ADP" && particle.surface === OBJECT_PARTICLE;
24
+ };
25
+
26
+ export const teFormOf = (word: InContext, tokens: readonly Token[], at: number): TeForm => {
27
+ const teVerb = teFormVerbOf(word);
28
+ const doubtful = isHelperByTeFormOnly(word) && !teVerbHasObject(word, tokens, at);
29
+ return { ...(doubtful ? { teFormOnly: true } : {}), ...(teVerb === undefined ? {} : { teVerb }) };
30
+ };
31
+
32
+ const BOUND_USE = "|bound|";
33
+ const FREE_USE = "|free|";
34
+
35
+ /**
36
+ * A verb after a て-form that may be the helper or the next act (並んで見た) is read as the full verb where the document writes
37
+ * the full verb that way and its sure helpers (投資してみる) the other way: the writer keeps the helper in kana on purpose. It stays
38
+ * a helper where the same verb takes the sure helper elsewhere (まとめてみました beside まとめて見ました).
39
+ */
40
+ export const withTeFormFullVerbs = <Word extends KeyedTeWord>(words: readonly Word[]): Word[] => {
41
+ const sureOf = (key: string): Word[] => words.filter((word) => word.key === key && word.teFormOnly !== true);
42
+ const freeSpellingsOf = (key: string): Set<string> => new Set(words.filter((word) => word.key === key).map((word) => word.spelling));
43
+ return words.map((word) => {
44
+ if (word.teFormOnly !== true || !word.key.includes(BOUND_USE)) return word;
45
+ const freeKey = word.key.replace(BOUND_USE, FREE_USE);
46
+ const sure = sureOf(word.key);
47
+ const sureSpellings = new Set(sure.map((helper) => helper.spelling));
48
+ const helpsSameVerb = sure.some((helper) => helper.teVerb !== undefined && helper.teVerb === word.teVerb);
49
+ const isFullVerbSpelling = freeSpellingsOf(freeKey).has(word.spelling) && sure.length > 0 && !sureSpellings.has(word.spelling) && !helpsSameVerb;
50
+ return isFullVerbSpelling ? { ...word, key: freeKey } : word;
51
+ });
52
+ };