pi-reply-reader 0.1.0 → 0.2.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.
- package/CHANGELOG.md +143 -0
- package/README.md +402 -39
- package/dist/src/cli.js +137 -10
- package/dist/src/listener.js +532 -0
- package/dist/src/music.js +452 -0
- package/dist/src/outputs.js +29 -4
- package/dist/src/playback.js +170 -46
- package/dist/src/player.js +265 -0
- package/dist/src/project.js +50 -0
- package/dist/src/reading-lock.js +296 -68
- package/dist/src/settings.js +32 -3
- package/dist/src/speech-text.js +581 -64
- package/examples/reply-reader-desktop-audio.service +23 -10
- package/examples/reply-reader-vps-audio.service +57 -0
- package/extensions/reply-reader.ts +920 -106
- package/package.json +3 -2
- package/src/auto-queue.ts +123 -0
- package/src/cli.ts +131 -10
- package/src/listener.ts +522 -0
- package/src/music.ts +474 -0
- package/src/outputs.ts +37 -5
- package/src/pause-key.ts +105 -0
- package/src/playback.ts +179 -48
- package/src/player.ts +255 -0
- package/src/project.ts +46 -0
- package/src/prompts.ts +142 -0
- package/src/reading-lock.ts +364 -66
- package/src/settings.ts +34 -3
- package/src/speech-text.ts +692 -56
package/src/speech-text.ts
CHANGED
|
@@ -14,13 +14,74 @@ export type Language = "es" | "en";
|
|
|
14
14
|
* of a larger text (a section, the closing questions), so the part follows the language of the whole.
|
|
15
15
|
*/
|
|
16
16
|
export function speechReading(markdown: string, language: Language = detectLanguage(markdown)): { text: string; language: Language } {
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
17
|
+
const { text } = speechNarration(markdown, language);
|
|
18
|
+
return { text, language };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** (S12) What a block of the reply is, which a listener hears as its shape. */
|
|
22
|
+
export type Role = "heading" | "paragraph" | "item" | "row" | "codeBlock";
|
|
23
|
+
|
|
24
|
+
/** (S12) What follows a fragment: a sentence on the same line, a line, or a blank line (also after a heading). */
|
|
25
|
+
export type Boundary = "sentence" | "line" | "paragraph";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* (S12) One block of the Markdown, in order, with its 1-based source line and still in Markdown: the plan adds no
|
|
29
|
+
* word of any language. A `break` is a blank line, a thematic break or a reference definition.
|
|
30
|
+
*/
|
|
31
|
+
export type PlanBlock =
|
|
32
|
+
| { role: "heading"; source: string; line: number }
|
|
33
|
+
| { role: "paragraph"; source: string; line: number }
|
|
34
|
+
| { role: "item"; number?: string; source: string; line: number }
|
|
35
|
+
| { role: "row"; cells: string[]; line: number }
|
|
36
|
+
| { role: "codeBlock"; line: number }
|
|
37
|
+
| { role: "break"; line: number };
|
|
38
|
+
|
|
39
|
+
export interface NarrationPlan {
|
|
40
|
+
blocks: PlanBlock[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** (S12) One piece of speech, synthesized at once, with the boundary (and so the pause) after it. */
|
|
44
|
+
export interface Fragment {
|
|
45
|
+
text: string;
|
|
46
|
+
role: Role;
|
|
47
|
+
after: Boundary;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* (S12) A technical token no reading class claimed, read as written: one holding `/ \ = < > | * { } $ ^ @ # +`
|
|
52
|
+
* or `..`, other than a plain number. Listed by source line; within a line,
|
|
53
|
+
* tokens in code spans come before those in prose. Never changes what is spoken.
|
|
54
|
+
*/
|
|
55
|
+
export interface Diagnostic {
|
|
56
|
+
line: number;
|
|
57
|
+
token: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface Narration {
|
|
61
|
+
/** The same text `speechText` returns. */
|
|
62
|
+
text: string;
|
|
63
|
+
language: Language;
|
|
64
|
+
fragments: Fragment[];
|
|
65
|
+
diagnostics: Diagnostic[];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** (S12) `speechReading`, plus the fragments playback speaks and the tokens the cleanup could not classify. */
|
|
69
|
+
export function speechNarration(markdown: string, language: Language = detectLanguage(markdown)): Narration {
|
|
70
|
+
return renderNarration(narrationPlan(markdown), language);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* (S18, T48) Several documents read one after another, each cleaned on its own, so no Markdown block of one (an
|
|
75
|
+
* unclosed code fence, a list) runs into the next. Empty parts say nothing.
|
|
76
|
+
*/
|
|
77
|
+
export function speechNarrationOfParts(parts: readonly string[], language: Language): Narration {
|
|
78
|
+
const narrations = parts.map((part) => speechNarration(part, language)).filter((narration) => narration.text);
|
|
79
|
+
return {
|
|
80
|
+
text: narrations.map((narration) => narration.text).join("\n\n"),
|
|
81
|
+
language,
|
|
82
|
+
fragments: narrations.flatMap((narration) => narration.fragments),
|
|
83
|
+
diagnostics: narrations.flatMap((narration) => narration.diagnostics),
|
|
84
|
+
};
|
|
24
85
|
}
|
|
25
86
|
|
|
26
87
|
/**
|
|
@@ -28,6 +89,11 @@ export function speechReading(markdown: string, language: Language = detectLangu
|
|
|
28
89
|
* Spanish wins ties, so a reply with no clear English majority reads as it always did.
|
|
29
90
|
*/
|
|
30
91
|
export function detectLanguage(markdown: string): Language {
|
|
92
|
+
return languageOfWords(markdown) ?? "es";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** (S7, S18) `detectLanguage`, or undefined when the text has no function word of either language ("git", "OK?"). */
|
|
96
|
+
export function languageOfWords(markdown: string): Language | undefined {
|
|
31
97
|
const prose = markdown
|
|
32
98
|
.replace(/^\s{0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\s{0,3}\1[^\n]*$|(?![\s\S]))/gm, " ")
|
|
33
99
|
// The closing heading every reply here uses is English even in a Spanish reply.
|
|
@@ -41,6 +107,7 @@ export function detectLanguage(markdown: string): Language {
|
|
|
41
107
|
if (ENGLISH_WORDS.has(word)) english++;
|
|
42
108
|
else if (SPANISH_WORDS.has(word)) spanish++;
|
|
43
109
|
}
|
|
110
|
+
if (english === 0 && spanish === 0) return undefined;
|
|
44
111
|
return english > spanish ? "en" : "es";
|
|
45
112
|
}
|
|
46
113
|
|
|
@@ -52,11 +119,19 @@ const SPANISH_WORDS = new Set(
|
|
|
52
119
|
"el la los las de del al que y en un una unos unas es son era fue ser está están estar por para con sin se lo le les su sus este esta esto estos estas ese esa eso como más pero si sí ya hay cuando también porque sobre muy entre hasta desde todo todos cada qué cómo donde dónde o ni".split(" "),
|
|
53
120
|
);
|
|
54
121
|
|
|
55
|
-
/** The phrasebook of the text being cleaned; `
|
|
122
|
+
/** The phrasebook of the text being cleaned; `renderNarration` sets it around one synchronous run. */
|
|
56
123
|
let words: Phrasebook;
|
|
124
|
+
/** Where `renderNarration` collects diagnostics during its run, and the source line of the block being rendered. */
|
|
125
|
+
let diagnosis: { diagnostics: Diagnostic[]; line: number } | undefined;
|
|
126
|
+
/**
|
|
127
|
+
* (k5) The tags of the text being rendered, in the order the renderer meets them: a first run records them, and
|
|
128
|
+
* `paired` then says which opening and closing tags match, for the run that is kept.
|
|
129
|
+
*/
|
|
130
|
+
let tagging: { seen: { name: string; closing: boolean }[]; paired?: boolean[]; next: number } | undefined;
|
|
57
131
|
|
|
58
|
-
|
|
59
|
-
|
|
132
|
+
/** (S12) The blocks of `markdown`, language-free: fences, table rows and one block per other line. */
|
|
133
|
+
export function narrationPlan(markdown: string): NarrationPlan {
|
|
134
|
+
const blocks: PlanBlock[] = [];
|
|
60
135
|
const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
|
|
61
136
|
let fence: { char: string; length: number } | undefined;
|
|
62
137
|
|
|
@@ -71,35 +146,155 @@ function cleaned(markdown: string, language: Language): string {
|
|
|
71
146
|
const open = /^\s{0,3}(`{3,}|~{3,})/.exec(raw);
|
|
72
147
|
if (open) {
|
|
73
148
|
fence = { char: open[1][0], length: open[1].length };
|
|
74
|
-
|
|
149
|
+
blocks.push({ role: "codeBlock", line: i + 1 });
|
|
75
150
|
continue;
|
|
76
151
|
}
|
|
77
152
|
|
|
78
153
|
if (raw.includes("|") && TABLE_SEPARATOR.test(lines[i + 1] ?? "")) {
|
|
79
|
-
|
|
154
|
+
blocks.push({ role: "row", cells: tableCells(raw), line: i + 1 });
|
|
80
155
|
i++;
|
|
81
156
|
while (i + 1 < lines.length && lines[i + 1].includes("|") && lines[i + 1].trim() !== "") {
|
|
82
|
-
|
|
157
|
+
i++;
|
|
158
|
+
blocks.push({ role: "row", cells: tableCells(lines[i]), line: i + 1 });
|
|
83
159
|
}
|
|
84
160
|
continue;
|
|
85
161
|
}
|
|
86
162
|
|
|
87
|
-
|
|
88
|
-
|
|
163
|
+
blocks.push(lineBlock(raw, i + 1));
|
|
164
|
+
}
|
|
165
|
+
return { blocks };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* (S12) The words of `plan` in `language`: one line per block (and a blank one after a heading, so playback pauses
|
|
170
|
+
* as at a blank line), split into fragments, with the tokens no reading class claimed.
|
|
171
|
+
*/
|
|
172
|
+
export function renderNarration(plan: NarrationPlan, language: Language): Narration {
|
|
173
|
+
const previous = { words, diagnosis, tagging };
|
|
174
|
+
words = PHRASEBOOKS[language];
|
|
175
|
+
try {
|
|
176
|
+
tagging = undefined;
|
|
177
|
+
// (k5) A closing tag anywhere means a pair may span blocks: a first run finds which tags match.
|
|
178
|
+
if (plan.blocks.some((block) => CLOSING_TAG.test("source" in block ? block.source : "cells" in block ? block.cells.join(" ") : ""))) {
|
|
179
|
+
tagging = { seen: [], next: 0 };
|
|
180
|
+
rendered(plan, language);
|
|
181
|
+
tagging = { seen: [], paired: pairedTags(tagging.seen), next: 0 };
|
|
182
|
+
}
|
|
183
|
+
return rendered(plan, language);
|
|
184
|
+
} finally {
|
|
185
|
+
({ words, diagnosis, tagging } = previous);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const CLOSING_TAG = /<\/\p{L}[\p{L}\p{N}-]*>/u;
|
|
190
|
+
|
|
191
|
+
/** (k5) Which of `seen` belong to a pair: each closing tag matches the nearest open tag of the same name before it. */
|
|
192
|
+
function pairedTags(seen: readonly { name: string; closing: boolean }[]): boolean[] {
|
|
193
|
+
const paired = seen.map(() => false);
|
|
194
|
+
const open = new Map<string, number[]>();
|
|
195
|
+
seen.forEach(({ name, closing }, index) => {
|
|
196
|
+
const key = name.toLowerCase();
|
|
197
|
+
const stack = open.get(key) ?? [];
|
|
198
|
+
open.set(key, stack);
|
|
199
|
+
if (!closing) stack.push(index);
|
|
200
|
+
else {
|
|
201
|
+
const start = stack.pop();
|
|
202
|
+
if (start !== undefined) paired[start] = paired[index] = true;
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
return paired;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** One run of the renderer over `plan`, with the current phrasebook. */
|
|
209
|
+
function rendered(plan: NarrationPlan, language: Language): Narration {
|
|
210
|
+
diagnosis = { diagnostics: [], line: 0 };
|
|
211
|
+
const lines: SpokenLine[] = [];
|
|
212
|
+
for (const block of plan.blocks) {
|
|
213
|
+
diagnosis.line = block.line;
|
|
214
|
+
const role = block.role === "break" ? "paragraph" : block.role;
|
|
215
|
+
lines.push({ text: numbersInWords(finished(blockText(block))), role });
|
|
89
216
|
// A heading or bold-only line ends its section, so playback pauses as at a blank line; trim drops a last one.
|
|
90
|
-
if (
|
|
217
|
+
if (block.role === "heading") lines.push({ text: "", role });
|
|
218
|
+
}
|
|
219
|
+
const text = lines
|
|
220
|
+
.map((line) => line.text)
|
|
221
|
+
.join("\n")
|
|
222
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
223
|
+
.trim();
|
|
224
|
+
return { text, language, fragments: fragmentsOf(lines), diagnostics: diagnosis.diagnostics };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* (S14) What a reading that waited in the line says first: "Respuesta P12.R2." / "Reply P12.R2." for a reply,
|
|
229
|
+
* "Archivo notas.md." / "File notes.md." for a file, cleaned like any text in `language`, with a section break after it.
|
|
230
|
+
*/
|
|
231
|
+
export function announcement(kind: "reply" | "file", name: string, language: Language): Fragment[] {
|
|
232
|
+
// As inline code, so a name's own `_` or `*` is not read as emphasis.
|
|
233
|
+
const named = name.includes("`") ? name : `\`${name}\``;
|
|
234
|
+
const fragments = speechNarration(`${PHRASEBOOKS[language][kind]} ${named}.`, language).fragments;
|
|
235
|
+
const last = fragments.at(-1);
|
|
236
|
+
if (last) last.after = "paragraph";
|
|
237
|
+
return fragments;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* (S19) What a reading of another project than the last one says first: the project's name, read like any text in
|
|
242
|
+
* `language` ("pi-reply-reader.", "p uno."), with a section break after it.
|
|
243
|
+
*/
|
|
244
|
+
export function projectAnnouncement(project: string, language: Language): Fragment[] {
|
|
245
|
+
// As inline code, so a name's own `_` or `*` is not read as emphasis.
|
|
246
|
+
const named = project.includes("`") ? project : `\`${project}\``;
|
|
247
|
+
const fragments = speechNarration(`${named}.`, language).fragments;
|
|
248
|
+
const last = fragments.at(-1);
|
|
249
|
+
if (last) last.after = "paragraph";
|
|
250
|
+
return fragments;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** (S12) Text already meant for speech, split as playback speaks it: every fragment a paragraph's. */
|
|
254
|
+
export function spokenFragments(text: string): Fragment[] {
|
|
255
|
+
return fragmentsOf(text.split("\n").map((line) => ({ text: line, role: "paragraph" })));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
interface SpokenLine {
|
|
259
|
+
text: string;
|
|
260
|
+
role: Role;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Sentences and lines, in order, each with the boundary after it; Supertonic only calls back once per
|
|
265
|
+
* 300 characters, so we split first. Never at ":" or ";", where a pause would sound like a full stop.
|
|
266
|
+
* A line with no sentence (blank, or emoji only) ends a paragraph.
|
|
267
|
+
*/
|
|
268
|
+
function fragmentsOf(lines: readonly SpokenLine[]): Fragment[] {
|
|
269
|
+
const result: Fragment[] = [];
|
|
270
|
+
let blank = false;
|
|
271
|
+
for (const { text, role } of lines) {
|
|
272
|
+
const sentences = text
|
|
273
|
+
.split(/(?<=[.!?…])\s+/)
|
|
274
|
+
.map((sentence) => sentence.trim())
|
|
275
|
+
.filter((sentence) => sentence !== "");
|
|
276
|
+
if (sentences.length === 0) {
|
|
277
|
+
blank = true;
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
const previous = result.at(-1);
|
|
281
|
+
if (previous) previous.after = blank ? "paragraph" : "line";
|
|
282
|
+
blank = false;
|
|
283
|
+
for (const sentence of sentences) result.push({ text: sentence, role, after: "sentence" });
|
|
91
284
|
}
|
|
285
|
+
return result;
|
|
286
|
+
}
|
|
92
287
|
|
|
93
|
-
|
|
94
|
-
|
|
288
|
+
/** The passes that once ran over the whole text; none of them crosses a line break, so they run per line. */
|
|
289
|
+
function finished(line: string): string {
|
|
290
|
+
const spaced = line.replace(/[ \t]{2,}|\t/g, " ");
|
|
291
|
+
return (words.contracts ? contracted(spaced) : spaced)
|
|
95
292
|
// A numbered heading or bold line ("## 1. Estado", "## 5.2. Título") starts with "1." too; "1:" keeps playback
|
|
96
293
|
// from cutting there.
|
|
97
|
-
.replace(new RegExp(`^(\\d+(?: ${words.point} \\d+)*)\\.
|
|
98
|
-
.replace(/\n{3,}/g, "\n\n")
|
|
99
|
-
.trim();
|
|
294
|
+
.replace(new RegExp(`^(\\d+(?: ${words.point} \\d+)*)\\. `), "$1: ");
|
|
100
295
|
}
|
|
101
296
|
|
|
102
|
-
/** Spanish
|
|
297
|
+
/** Spanish: the readings add "el comando", "la rama", "un commit" next to "de" and "a". */
|
|
103
298
|
function contracted(text: string): string {
|
|
104
299
|
return (
|
|
105
300
|
text
|
|
@@ -108,7 +303,7 @@ function contracted(text: string): string {
|
|
|
108
303
|
// The reverse for a contraction already written before the token: "del el comando" → "del comando",
|
|
109
304
|
// "del la rama" → "de la rama", "al un commit" → "a un commit".
|
|
110
305
|
.replace(
|
|
111
|
-
/(?<![\p{L}\p{N}])([dD]e|[aA])l (el|la|un) (comando|carpeta|rama|commit)(?![\p{L}\p{N}])/gu,
|
|
306
|
+
/(?<![\p{L}\p{N}])([dD]e|[aA])l (el|la|un) (comando|carpeta|rama|commit|etiqueta)(?![\p{L}\p{N}])/gu,
|
|
112
307
|
(_m, word: string, article: string, noun: string) => (article === "el" ? `${word}l ${noun}` : `${word} ${article} ${noun}`),
|
|
113
308
|
)
|
|
114
309
|
);
|
|
@@ -118,6 +313,14 @@ function contracted(text: string): string {
|
|
|
118
313
|
interface Phrasebook {
|
|
119
314
|
/** Said in place of a fenced block, so a sentence like "run this:" does not hang. */
|
|
120
315
|
codeBlock: string;
|
|
316
|
+
/** (S14) Before the ID of a reply that waited in the line: "Respuesta P12.R2." */
|
|
317
|
+
reply: string;
|
|
318
|
+
/** (S14) Before the name of a file that waited in the line: "Archivo notas.md." */
|
|
319
|
+
file: string;
|
|
320
|
+
/** Said for the English closing heading "Needs your decision", which this language's voice would mangle. */
|
|
321
|
+
needsYourDecision?: string;
|
|
322
|
+
/** "de el" and "a el" contract, as in Spanish. */
|
|
323
|
+
contracts: boolean;
|
|
121
324
|
command: string;
|
|
122
325
|
folder: string;
|
|
123
326
|
branch: string;
|
|
@@ -130,6 +333,14 @@ interface Phrasebook {
|
|
|
130
333
|
/** Between the digit groups of a dotted number (h1). */
|
|
131
334
|
point: string;
|
|
132
335
|
or: string;
|
|
336
|
+
/** (i2) Before an issue or PR number: `#43`. */
|
|
337
|
+
number: string;
|
|
338
|
+
/** (i3) Between the keys of a combination: `Alt+R`. */
|
|
339
|
+
plus: string;
|
|
340
|
+
/** (i4) After a minimum version: `v1+`. */
|
|
341
|
+
orLater: string;
|
|
342
|
+
/** (i4) After a count: `100+`. */
|
|
343
|
+
orMore: string;
|
|
133
344
|
approximately: string;
|
|
134
345
|
/** × between numbers. */
|
|
135
346
|
times: string;
|
|
@@ -140,10 +351,95 @@ interface Phrasebook {
|
|
|
140
351
|
symbols: [RegExp, string][];
|
|
141
352
|
/** "2.750" is a Spanish thousand; in English it is a decimal. */
|
|
142
353
|
thousands: boolean;
|
|
354
|
+
/** (j1) "1,234" is an English thousand; any other comma between digits is read as `comma`. */
|
|
355
|
+
commaThousands: boolean;
|
|
356
|
+
/** (j1) Between the digit groups of a decimal written with a comma: "1,2". */
|
|
357
|
+
comma: string;
|
|
358
|
+
/** (j1) A leading minus: "-16". */
|
|
359
|
+
minus: string;
|
|
360
|
+
/** (j1) A whole number from 0 to 999.999.999.999 in words. */
|
|
361
|
+
cardinal: (n: number) => string;
|
|
362
|
+
/** (j1) Spanish only: "un"/"una" by the word after a number ending in 1; (k1) feminine hundreds. */
|
|
363
|
+
agreement?: { feminine: Set<string>; keepsUno: Set<string> };
|
|
364
|
+
/** (k2) A time with minutes 00, after its hour: "siete en punto". */
|
|
365
|
+
oClock: string;
|
|
366
|
+
/** (k3) Month names, January first. */
|
|
367
|
+
months: readonly string[];
|
|
368
|
+
/** (k3) A date from its parts, already in words. */
|
|
369
|
+
date: (day: string, month: string, year: string) => string;
|
|
370
|
+
/** (k4) A glob's leading `*`: "cualquier hs punto lan". */
|
|
371
|
+
any: string;
|
|
372
|
+
/** (k4) A glob's trailing `/*`: "todo lo de bin". */
|
|
373
|
+
everythingIn: string;
|
|
374
|
+
/** (k4) Any other `*` in a glob: "lab algo". */
|
|
375
|
+
something: string;
|
|
376
|
+
/** (k5) A lone closing or self-closing tag by its name: "la etiqueta iframe". */
|
|
377
|
+
tag: (name: string) => string;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const SPANISH_UNITS = "cero uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciséis diecisiete dieciocho diecinueve veinte veintiuno veintidós veintitrés veinticuatro veinticinco veintiséis veintisiete veintiocho veintinueve".split(" ");
|
|
381
|
+
const SPANISH_TENS = " veinte treinta cuarenta cincuenta sesenta setenta ochenta noventa".split(" ");
|
|
382
|
+
const SPANISH_HUNDREDS = " ciento doscientos trescientos cuatrocientos quinientos seiscientos setecientos ochocientos novecientos".split(" ");
|
|
383
|
+
|
|
384
|
+
/** "veintiuno" → "veintiún", "treinta y uno" → "treinta y un": before "mil", "millones" or a noun. */
|
|
385
|
+
function apocope(text: string): string {
|
|
386
|
+
return text.replace(/(veinti)?uno$/, (_m, twenty?: string) => (twenty ? "veintiún" : "un"));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function spanishBelowThousand(n: number): string {
|
|
390
|
+
if (n === 100) return "cien";
|
|
391
|
+
const hundreds = SPANISH_HUNDREDS[Math.floor(n / 100)];
|
|
392
|
+
const rest = n % 100;
|
|
393
|
+
const tens = rest < 30 ? SPANISH_UNITS[rest] : `${SPANISH_TENS[Math.floor(rest / 10)]}${rest % 10 ? ` y ${SPANISH_UNITS[rest % 10]}` : ""}`;
|
|
394
|
+
return [hundreds, rest || !hundreds ? tens : ""].filter((part) => part !== "").join(" ");
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function spanishCardinal(n: number): string {
|
|
398
|
+
if (n >= 1_000_000) {
|
|
399
|
+
const millions = Math.floor(n / 1_000_000);
|
|
400
|
+
const rest = n % 1_000_000;
|
|
401
|
+
const head = millions === 1 ? "un millón" : `${apocope(spanishCardinal(millions))} millones`;
|
|
402
|
+
return rest ? `${head} ${spanishCardinal(rest)}` : head;
|
|
403
|
+
}
|
|
404
|
+
if (n >= 1000) {
|
|
405
|
+
const thousands = Math.floor(n / 1000);
|
|
406
|
+
const rest = n % 1000;
|
|
407
|
+
const head = thousands === 1 ? "mil" : `${apocope(spanishBelowThousand(thousands))} mil`;
|
|
408
|
+
return rest ? `${head} ${spanishBelowThousand(rest)}` : head;
|
|
409
|
+
}
|
|
410
|
+
return spanishBelowThousand(n);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const ENGLISH_UNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split(" ");
|
|
414
|
+
const ENGLISH_TENS = " twenty thirty forty fifty sixty seventy eighty ninety".split(" ");
|
|
415
|
+
|
|
416
|
+
function englishCardinal(n: number): string {
|
|
417
|
+
for (const [size, name] of [[1e9, "billion"], [1e6, "million"], [1e3, "thousand"], [100, "hundred"]] as const) {
|
|
418
|
+
if (n >= size) {
|
|
419
|
+
const rest = n % size;
|
|
420
|
+
const head = `${englishCardinal(Math.floor(n / size))} ${name}`;
|
|
421
|
+
return rest ? `${head} ${englishCardinal(rest)}` : head;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return n < 20 ? ENGLISH_UNITS[n] : `${ENGLISH_TENS[Math.floor(n / 10)]}${n % 10 ? ` ${ENGLISH_UNITS[n % 10]}` : ""}`;
|
|
143
425
|
}
|
|
144
426
|
|
|
427
|
+
/** (j1) Frequent feminine nouns, singular and plural: "una respuesta", "veintiuna líneas". Tunable. */
|
|
428
|
+
const FEMININE = new Set(
|
|
429
|
+
(
|
|
430
|
+
"línea respuesta pregunta sesión tarea vez hora semana página carpeta rama prueba versión lectura voz opción regla palabra cosa parte persona máquina salida entrada imagen corrida fila " +
|
|
431
|
+
"líneas respuestas preguntas sesiones tareas veces horas semanas páginas carpetas ramas pruebas versiones lecturas voces opciones reglas palabras cosas partes personas máquinas salidas entradas imágenes corridas filas"
|
|
432
|
+
).split(" "),
|
|
433
|
+
);
|
|
434
|
+
/** (j1) Function words a number ending in 1 keeps "uno" before: "de 1 a 5", "1 de 3". */
|
|
435
|
+
const KEEPS_UNO = new Set("a de del al y e o u ni en por para con sin entre hasta desde sobre contra según que es son más menos coma punto no ya se lo la el los las le está era queda sigue fue".split(" "));
|
|
436
|
+
|
|
145
437
|
const SPANISH: Phrasebook = {
|
|
146
438
|
codeBlock: "Bloque de código.",
|
|
439
|
+
reply: "Respuesta",
|
|
440
|
+
file: "Archivo",
|
|
441
|
+
needsYourDecision: "Decisiones pendientes",
|
|
442
|
+
contracts: true,
|
|
147
443
|
command: "el comando",
|
|
148
444
|
folder: "la carpeta",
|
|
149
445
|
branch: "la rama",
|
|
@@ -153,6 +449,10 @@ const SPANISH: Phrasebook = {
|
|
|
153
449
|
dot: "punto",
|
|
154
450
|
point: "punto",
|
|
155
451
|
or: "o",
|
|
452
|
+
number: "número",
|
|
453
|
+
plus: "más",
|
|
454
|
+
orLater: "o superior",
|
|
455
|
+
orMore: "o más",
|
|
156
456
|
approximately: "aproximadamente",
|
|
157
457
|
times: "por",
|
|
158
458
|
units: {
|
|
@@ -203,10 +503,25 @@ const SPANISH: Phrasebook = {
|
|
|
203
503
|
[/&+/, "y"],
|
|
204
504
|
],
|
|
205
505
|
thousands: true,
|
|
506
|
+
commaThousands: false,
|
|
507
|
+
comma: "coma",
|
|
508
|
+
minus: "menos",
|
|
509
|
+
cardinal: spanishCardinal,
|
|
510
|
+
agreement: { feminine: FEMININE, keepsUno: KEEPS_UNO },
|
|
511
|
+
oClock: "en punto",
|
|
512
|
+
months: "enero febrero marzo abril mayo junio julio agosto septiembre octubre noviembre diciembre".split(" "),
|
|
513
|
+
date: (day, month, year) => `${day} de ${month} de ${year}`,
|
|
514
|
+
any: "cualquier",
|
|
515
|
+
everythingIn: "todo lo de",
|
|
516
|
+
something: "algo",
|
|
517
|
+
tag: (name) => `la etiqueta ${name}`,
|
|
206
518
|
};
|
|
207
519
|
|
|
208
520
|
const ENGLISH: Phrasebook = {
|
|
209
521
|
codeBlock: "Code block.",
|
|
522
|
+
reply: "Reply",
|
|
523
|
+
file: "File",
|
|
524
|
+
contracts: false,
|
|
210
525
|
command: "the command",
|
|
211
526
|
folder: "the folder",
|
|
212
527
|
branch: "the branch",
|
|
@@ -216,6 +531,10 @@ const ENGLISH: Phrasebook = {
|
|
|
216
531
|
dot: "dot",
|
|
217
532
|
point: "point",
|
|
218
533
|
or: "or",
|
|
534
|
+
number: "number",
|
|
535
|
+
plus: "plus",
|
|
536
|
+
orLater: "or later",
|
|
537
|
+
orMore: "or more",
|
|
219
538
|
approximately: "approximately",
|
|
220
539
|
times: "times",
|
|
221
540
|
units: {
|
|
@@ -266,6 +585,17 @@ const ENGLISH: Phrasebook = {
|
|
|
266
585
|
[/&+/, "and"],
|
|
267
586
|
],
|
|
268
587
|
thousands: false,
|
|
588
|
+
commaThousands: true,
|
|
589
|
+
comma: "comma",
|
|
590
|
+
minus: "minus",
|
|
591
|
+
cardinal: englishCardinal,
|
|
592
|
+
oClock: "o'clock",
|
|
593
|
+
months: "January February March April May June July August September October November December".split(" "),
|
|
594
|
+
date: (day, month, year) => `${month} ${day}, ${year}`,
|
|
595
|
+
any: "any",
|
|
596
|
+
everythingIn: "everything in",
|
|
597
|
+
something: "something",
|
|
598
|
+
tag: (name) => `the ${name} tag`,
|
|
269
599
|
};
|
|
270
600
|
|
|
271
601
|
const PHRASEBOOKS: Record<Language, Phrasebook> = { es: SPANISH, en: ENGLISH };
|
|
@@ -276,49 +606,169 @@ const WORD = String.raw`\p{L}\p{N}_`;
|
|
|
276
606
|
/** A line wrapped whole in one emphasis (`**Qué cambió**`, `*Nota*`, `__X__`), read like a heading. */
|
|
277
607
|
const EMPHASIS_LINE = /^(?:\*\*(?=\S)(?:(?!\*\*).)+(?<=\S)\*\*|__(?=\S)(?:(?!__).)+(?<=\S)__|\*(?=\S)[^*]+(?<=\S)\*|_(?=\S)[^_]+(?<=\S)_)$/;
|
|
278
608
|
|
|
279
|
-
/** One line
|
|
280
|
-
function
|
|
281
|
-
let
|
|
282
|
-
while (/^>\s?/.test(
|
|
609
|
+
/** One line outside fences and tables, as a block; `line` is its 1-based source line. */
|
|
610
|
+
function lineBlock(raw: string, line: number): PlanBlock {
|
|
611
|
+
let text = raw.trim();
|
|
612
|
+
while (/^>\s?/.test(text)) text = text.replace(/^>\s?/, "").trim();
|
|
283
613
|
|
|
284
|
-
if (/^([-*_])(\s*\1){2,}$/.test(
|
|
285
|
-
if (/^\[[^\]]+\]:\s*\S+/.test(line)) return { text: "" };
|
|
614
|
+
if (text === "" || /^([-*_])(\s*\1){2,}$/.test(text) || /^\[[^\]]+\]:\s*\S+/.test(text)) return { role: "break", line };
|
|
286
615
|
|
|
287
|
-
const heading = /^#{1,6}\s+(.*?)(\s+#+)?$/.exec(
|
|
288
|
-
if (heading) {
|
|
289
|
-
|
|
290
|
-
return { text: closeSentence(spokenHeading(text)), section: true };
|
|
291
|
-
}
|
|
292
|
-
if (EMPHASIS_LINE.test(line)) return { text: closeSentence(spokenHeading(inline(line))), section: true };
|
|
616
|
+
const heading = /^#{1,6}\s+(.*?)(\s+#+)?$/.exec(text);
|
|
617
|
+
if (heading) return { role: "heading", source: heading[1], line };
|
|
618
|
+
if (EMPHASIS_LINE.test(text)) return { role: "heading", source: text, line };
|
|
293
619
|
|
|
294
|
-
const bullet = /^[-*+]\s+(?:\[[ xX]\]\s+)?(.*)$/.exec(
|
|
295
|
-
if (bullet) return {
|
|
620
|
+
const bullet = /^[-*+]\s+(?:\[[ xX]\]\s+)?(.*)$/.exec(text);
|
|
621
|
+
if (bullet) return { role: "item", source: bullet[1], line };
|
|
296
622
|
|
|
297
|
-
const numbered = /^(\d+)[.)]\s+(.*)$/.exec(
|
|
298
|
-
|
|
299
|
-
if (numbered) return { text: closeSentence(`${numbered[1]}: ${inline(numbered[2])}`) };
|
|
623
|
+
const numbered = /^(\d+)[.)]\s+(.*)$/.exec(text);
|
|
624
|
+
if (numbered) return { role: "item", number: numbered[1], source: numbered[2], line };
|
|
300
625
|
|
|
301
|
-
return {
|
|
626
|
+
return { role: "paragraph", source: text, line };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** One block in the words of the current phrasebook, before the per-line passes. */
|
|
630
|
+
function blockText(block: PlanBlock): string {
|
|
631
|
+
switch (block.role) {
|
|
632
|
+
case "break":
|
|
633
|
+
return "";
|
|
634
|
+
case "codeBlock":
|
|
635
|
+
return words.codeBlock;
|
|
636
|
+
case "heading":
|
|
637
|
+
return closeSentence(spokenHeading(inline(block.source)));
|
|
638
|
+
case "item":
|
|
639
|
+
// "1:" rather than "1.", which playback would cut at, reading the number alone.
|
|
640
|
+
return closeSentence(block.number === undefined ? inline(block.source) : `${block.number}: ${inline(block.source)}`);
|
|
641
|
+
case "row":
|
|
642
|
+
return closeSentence(
|
|
643
|
+
block.cells
|
|
644
|
+
.map((cell) => inline(cell))
|
|
645
|
+
.filter((cell) => cell !== "")
|
|
646
|
+
.join(", "),
|
|
647
|
+
);
|
|
648
|
+
case "paragraph":
|
|
649
|
+
return inline(block.source);
|
|
650
|
+
}
|
|
302
651
|
}
|
|
303
652
|
|
|
304
653
|
/** Every reply here closes with the English heading "Needs your decision"; a Spanish voice would mangle it. */
|
|
305
654
|
function spokenHeading(text: string): string {
|
|
306
|
-
return words
|
|
655
|
+
return words.needsYourDecision !== undefined && /^needs your decision:?$/i.test(text) ? words.needsYourDecision : text;
|
|
307
656
|
}
|
|
308
657
|
|
|
309
|
-
|
|
310
|
-
|
|
658
|
+
/** A table row's cells, trimmed and still in Markdown; escaped pipes stay inside their cell. */
|
|
659
|
+
function tableCells(raw: string): string[] {
|
|
660
|
+
return raw
|
|
311
661
|
.trim()
|
|
312
662
|
.replace(/^\|/, "")
|
|
313
663
|
.replace(/(?<!\\)\|$/, "")
|
|
314
664
|
.split(/(?<!\\)\|/)
|
|
315
|
-
.map((cell) =>
|
|
316
|
-
.filter((cell) => cell !== "");
|
|
317
|
-
return closeSentence(cells.join(", "));
|
|
665
|
+
.map((cell) => cell.trim());
|
|
318
666
|
}
|
|
319
667
|
|
|
320
668
|
function closeSentence(text: string): string {
|
|
321
|
-
|
|
669
|
+
const bare = text.replace(KEPT_MARKS, "");
|
|
670
|
+
return bare === "" || /[.!?:;…,]$/.test(bare) ? text : `${text}.`;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* (j1) Text whose digits stay as written (URL hosts, technical tokens no class claimed) is held between \uE00A and
|
|
675
|
+
* \uE00B from `speakable` until `numbersInWords` drops the marks.
|
|
676
|
+
*/
|
|
677
|
+
const KEPT_MARKS = /[\uE00A\uE00B]/g;
|
|
678
|
+
|
|
679
|
+
/** (j1) Kept text, or a run of digits, its groups joined by single dots or commas, with an optional leading minus. */
|
|
680
|
+
const DIGITS = /\uE00A[^\uE00B]*\uE00B|[-−]?\d+(?:[.,]\d+)*/gu;
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* (j1) The last pass of a line: every run of digits left becomes words in the current language, except in kept text.
|
|
684
|
+
* The text around it does not change, so units, numbering, IDs and the (h1) and (i4) readings keep their shape.
|
|
685
|
+
*/
|
|
686
|
+
function numbersInWords(line: string): string {
|
|
687
|
+
return line.replace(DIGITS, (match: string, offset: number, whole: string) => {
|
|
688
|
+
if (match.startsWith("\uE00A")) {
|
|
689
|
+
// A later rule may have split a kept token into words (">=1 punto 2 punto 0"): only its technical parts stay.
|
|
690
|
+
const kept = match.slice(1, -1);
|
|
691
|
+
return /\s/.test(kept) ? kept.replace(/\S+/g, (part) => (UNCLASSIFIED.test(part) && !NUMERIC.test(part) ? part : numbersInWords(part))) : kept;
|
|
692
|
+
}
|
|
693
|
+
const before = whole.slice(0, offset);
|
|
694
|
+
const after = whole.slice(offset + match.length);
|
|
695
|
+
let sign = "";
|
|
696
|
+
let run = match;
|
|
697
|
+
if (/^[-−]/.test(run)) {
|
|
698
|
+
// A hyphen right after a word or a number ("2026-10-27", "a-1") is not a minus.
|
|
699
|
+
sign = /[\p{L}\p{N}_.,\-−]$/u.test(before) ? run[0] : `${words.minus} `;
|
|
700
|
+
run = run.slice(1);
|
|
701
|
+
}
|
|
702
|
+
// Digits glued to letters are spoken apart from them: "Q5" reads "Q cinco".
|
|
703
|
+
const space = (char: string) => (/\p{L}/u.test(char) ? " " : "");
|
|
704
|
+
// A decimal part ("2 punto 1 segundos") keeps "uno", as a decimal run does, and so does a name such as "T1".
|
|
705
|
+
const decimalPart = new RegExp(`(?:^|\\s)(?:${words.point}|${words.comma}) $`).test(before);
|
|
706
|
+
const glued = sign === "" && space(before.at(-1) ?? "") !== "";
|
|
707
|
+
const following = /^[ \t]+(\p{L}+)(?:[ \t]+(\p{L}+))?/u.exec(after);
|
|
708
|
+
const next = following?.[1];
|
|
709
|
+
// (k1) "200 mil líneas": the hundreds agree with the noun after "mil".
|
|
710
|
+
const noun = next?.toLowerCase() === "mil" ? following?.[2] : next;
|
|
711
|
+
const reading = digitRun(run, decimalPart || glued ? undefined : { next: next ?? "", noun });
|
|
712
|
+
return `${sign === "" ? space(before.at(-1) ?? "") : ""}${sign}${reading}${space(after[0] ?? "")}`;
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** The word right after a number, and the noun it counts (the word after "mil" when that word is "mil"). */
|
|
717
|
+
interface Following {
|
|
718
|
+
next: string;
|
|
719
|
+
noun: string | undefined;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** One run of digit groups; `following` holds the words after it, which a whole number agrees with (Spanish). */
|
|
723
|
+
function digitRun(run: string, following: Following | undefined): string {
|
|
724
|
+
const thousands = words.thousands
|
|
725
|
+
? /^([1-9]\d{0,2}(?:\.\d{3})+)(?:,(\d+))?$/.exec(run)
|
|
726
|
+
: words.commaThousands
|
|
727
|
+
? /^([1-9]\d{0,2}(?:,\d{3})+)$/.exec(run)
|
|
728
|
+
: null;
|
|
729
|
+
if (thousands && !IP_ADDRESS.test(run)) {
|
|
730
|
+
const whole = words.cardinal(Number(thousands[1].replace(/[.,]/g, "")));
|
|
731
|
+
return thousands[2] === undefined ? agreed(whole, following) : `${whole} ${words.comma} ${digitGroup(thousands[2])}`;
|
|
732
|
+
}
|
|
733
|
+
if (/^\d+$/.test(run)) {
|
|
734
|
+
const reading = digitGroup(run);
|
|
735
|
+
return run.length > 1 && (run.startsWith("0") || run.length > 9) ? reading : agreed(reading, following);
|
|
736
|
+
}
|
|
737
|
+
return run
|
|
738
|
+
.split(/([.,])/)
|
|
739
|
+
.map((part) => (part === "." ? ` ${words.point} ` : part === "," ? ` ${words.comma} ` : digitGroup(part)))
|
|
740
|
+
.join("");
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** Four groups of 0-255: an IP address, read group by group even when it looks like a Spanish thousand. */
|
|
744
|
+
const IP_ADDRESS = /^(?:(?:25[0-5]|2[0-4]\d|1?\d{1,2})\.){3}(?:25[0-5]|2[0-4]\d|1?\d{1,2})$/;
|
|
745
|
+
|
|
746
|
+
/** A group of digits: a whole number, or digit by digit when it is longer than 9 digits or starts with 0. */
|
|
747
|
+
function digitGroup(digits: string): string {
|
|
748
|
+
if (digits.length > 9 || (digits.length > 1 && digits.startsWith("0"))) return [...digits].map((digit) => words.cardinal(Number(digit))).join(" ");
|
|
749
|
+
return words.cardinal(Number(digits));
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* "uno" becomes "un" before a word, "una" before a listed feminine noun; it stays before a function word. (k1) Before
|
|
754
|
+
* a listed feminine noun, right after the number or after "mil", the hundreds below the millions are feminine too.
|
|
755
|
+
*/
|
|
756
|
+
function agreed(reading: string, following: Following | undefined): string {
|
|
757
|
+
const agreement = words.agreement;
|
|
758
|
+
if (!agreement || following === undefined || following.next === "") return reading;
|
|
759
|
+
const feminine = following.noun !== undefined && agreement.feminine.has(following.noun.toLowerCase());
|
|
760
|
+
const agreeing = feminine ? feminineHundreds(reading) : reading;
|
|
761
|
+
if (!/uno$/.test(agreeing)) return agreeing;
|
|
762
|
+
const word = following.next.toLowerCase();
|
|
763
|
+
if (agreement.feminine.has(word)) return agreeing.replace(/uno$/, "una");
|
|
764
|
+
return agreement.keepsUno.has(word) ? agreeing : apocope(agreeing);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** (k1) "doscientos mil" → "doscientas mil"; "millón" and "millones" are masculine, so hundreds before them stay. */
|
|
768
|
+
function feminineHundreds(reading: string): string {
|
|
769
|
+
const parts = reading.split(/(?<=millón |millones )/);
|
|
770
|
+
const last = parts.pop() ?? "";
|
|
771
|
+
return `${parts.join("")}${last.replace(/ientos(?![\p{L}])/gu, "ientas")}`;
|
|
322
772
|
}
|
|
323
773
|
|
|
324
774
|
/**
|
|
@@ -338,7 +788,21 @@ function inline(text: string): string {
|
|
|
338
788
|
return prose(parked)
|
|
339
789
|
.replace(/\uE000(\d+)\uE001/g, (_m, code: string) => String.fromCodePoint(Number(code)))
|
|
340
790
|
.replace(/\uE002(\d+)\uE003/g, (_m, index: string) => spans[Number(index)])
|
|
341
|
-
.replace(/[ \t]*\uE008
|
|
791
|
+
.replace(/[ \t]*\uE008/g, "")
|
|
792
|
+
// (k5) The pauses around `<< text >>`, now that code spans are back in the line.
|
|
793
|
+
.replace(QUOTE_OPENING, (_m, offset: number, whole: string) => {
|
|
794
|
+
const before = whole.slice(0, offset).replace(KEPT_MARKS, "");
|
|
795
|
+
if (before === "" || /[([{"'“«¿¡]$/u.test(before)) return "";
|
|
796
|
+
return /[\p{L}\p{N}]$/u.test(before) ? ", " : " ";
|
|
797
|
+
})
|
|
798
|
+
.replace(QUOTE_CLOSING, (match: string, offset: number, whole: string) => {
|
|
799
|
+
const after = whole.slice(offset + match.length).replace(KEPT_MARKS, "");
|
|
800
|
+
if (after === "" || /^[)\]}.,;:!?…"'”»]/u.test(after)) return "";
|
|
801
|
+
return /[.,;:!?…]$/u.test(whole.slice(0, offset)) ? " " : ", ";
|
|
802
|
+
})
|
|
803
|
+
// (j1) A host keeps its digits: its marks become the kept-text marks `numbersInWords` drops.
|
|
804
|
+
.replace(/\uE006/g, "\uE00A")
|
|
805
|
+
.replace(/\uE007/g, "\uE00B");
|
|
342
806
|
}
|
|
343
807
|
|
|
344
808
|
/**
|
|
@@ -354,6 +818,7 @@ function codeSpan(code: string, before: string, after: string): string {
|
|
|
354
818
|
function speakable(text: string, before = "", after = ""): string {
|
|
355
819
|
const urls: string[] = [];
|
|
356
820
|
let out = text.replace(/\S*:\/\/\S*/g, (url) => `\uE004${urls.push(url) - 1}\uE005`);
|
|
821
|
+
out = tags(angleQuotes(out), before, after);
|
|
357
822
|
out = identifierSpaces(
|
|
358
823
|
out.replace(/\S+/g, (token: string, offset: number, whole: string) =>
|
|
359
824
|
tokenReading(token, previousWord(before + whole.slice(0, offset)), nextWord(whole.slice(offset + token.length) + after)),
|
|
@@ -372,7 +837,7 @@ function speakable(text: string, before = "", after = ""): string {
|
|
|
372
837
|
out = out.replace(/(\d)[ \t]*×[ \t]*(?=\d)/g, `$1 ${words.times} `);
|
|
373
838
|
for (const [symbol, word] of words.symbols) out = spokenAs(out, symbol, word);
|
|
374
839
|
return spokenAs(out, EMOJI, "")
|
|
375
|
-
.replace(/\uE004(\d+)\uE005/g, (_m, index: string) => identifierSpaces(urls[Number(index)]))
|
|
840
|
+
.replace(/\uE004(\d+)\uE005/g, (_m, index: string) => `\uE00A${identifierSpaces(urls[Number(index)])}\uE00B`)
|
|
376
841
|
.replace(/\uE009/g, ".");
|
|
377
842
|
}
|
|
378
843
|
|
|
@@ -421,15 +886,26 @@ function tokenReading(token: string, previous: string, next: string): string {
|
|
|
421
886
|
// English puts the noun after the token ("the `/read` command"); punctuation in between ends the phrase.
|
|
422
887
|
const noun = words === ENGLISH && trail === "" ? next.toLowerCase() : "";
|
|
423
888
|
const reading = classified(core, previous.toLowerCase(), noun);
|
|
424
|
-
if (reading === undefined)
|
|
889
|
+
if (reading === undefined) {
|
|
890
|
+
if (!UNCLASSIFIED.test(core) || NUMERIC.test(core)) return token;
|
|
891
|
+
if (diagnosis) diagnosis.diagnostics.push({ line: diagnosis.line, token: core });
|
|
892
|
+
// (j1) Read as written, digits included.
|
|
893
|
+
return `${lead}\uE00A${core}\uE00B${trail}`;
|
|
894
|
+
}
|
|
425
895
|
if (reading === "") return `\uE008${trail}`;
|
|
426
896
|
// A dot between digits in a reading ("a punto ts, en 1.2") is the token's own; (h1) leaves it.
|
|
427
897
|
return `${lead}${reading.replace(/(?<=\d)\.(?=\d)/g, "\uE009")}${trail}`;
|
|
428
898
|
}
|
|
429
899
|
|
|
900
|
+
/** (S12) Characters a voice reads oddly in a token no class claimed; numbers such as `1/2` or `10:30` are fine. */
|
|
901
|
+
const UNCLASSIFIED = /[/\\=<>|*{}$^@#+]|\.\./;
|
|
902
|
+
const NUMERIC = /^~?[\d.,:/]+$/;
|
|
903
|
+
|
|
430
904
|
/** `noun` is the English noun right after the token, which the reading then leaves out ("the read command"). */
|
|
431
905
|
function classified(core: string, previous: string, noun: string): string | undefined {
|
|
432
906
|
if (previous === "rama" || previous === "branch") return nameWords(core);
|
|
907
|
+
const moment = clockTime(core) ?? calendarDate(core);
|
|
908
|
+
if (moment !== undefined) return moment;
|
|
433
909
|
const line = /^(.+):(\d+)$/.exec(core);
|
|
434
910
|
const file = line && (pathReading(line[1], previous) ?? fileName(line[1]));
|
|
435
911
|
if (line && file) return `${file}, ${words.line} ${line[2]}`;
|
|
@@ -439,20 +915,170 @@ function classified(core: string, previous: string, noun: string): string | unde
|
|
|
439
915
|
if (folder !== undefined) return folder;
|
|
440
916
|
}
|
|
441
917
|
return (
|
|
918
|
+
issueNumber(core) ??
|
|
919
|
+
keyCombination(core) ??
|
|
920
|
+
minimumVersion(core) ??
|
|
442
921
|
alternatives(core) ??
|
|
443
922
|
pathReading(core, previous) ??
|
|
444
923
|
command(core, previous, noun) ??
|
|
445
924
|
fileName(core) ??
|
|
446
925
|
commitHash(core, previous) ??
|
|
926
|
+
emphasis(core) ??
|
|
927
|
+
glob(core) ??
|
|
447
928
|
slashWords(core)
|
|
448
929
|
);
|
|
449
930
|
}
|
|
450
931
|
|
|
932
|
+
/**
|
|
933
|
+
* (k2) A standalone `H:MM` or `HH:MM`, optionally `:SS`, reads like a digital clock, already in words: `21:02`
|
|
934
|
+
* "veintiuno cero dos", `07:30` "siete treinta", `07:00` "siete en punto". With seconds, minutes 00 read "cero cero".
|
|
935
|
+
*/
|
|
936
|
+
function clockTime(core: string): string | undefined {
|
|
937
|
+
const time = /^([01]?\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/.exec(core);
|
|
938
|
+
if (!time) return undefined;
|
|
939
|
+
const [, hour, minutes, seconds] = time;
|
|
940
|
+
const said = words.cardinal(Number(hour));
|
|
941
|
+
if (seconds === undefined && minutes === "00") return `${said} ${words.oClock}`;
|
|
942
|
+
return [said, digitGroup(minutes), ...(seconds === undefined ? [] : [digitGroup(seconds)])].join(" ");
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** (k3) `2026-10-27` and day-first `27/10/2026`, valid only: "veintisiete de octubre de dos mil veintiséis". */
|
|
946
|
+
function calendarDate(core: string): string | undefined {
|
|
947
|
+
const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(core);
|
|
948
|
+
const dayFirst = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(core);
|
|
949
|
+
const [year, month, day] = iso ? [iso[1], iso[2], iso[3]] : dayFirst ? [dayFirst[3], dayFirst[2], dayFirst[1]] : [];
|
|
950
|
+
if (year === undefined || month === undefined || day === undefined) return undefined;
|
|
951
|
+
const [y, m, d] = [Number(year), Number(month), Number(day)];
|
|
952
|
+
// Day 0 of the next month is the last day of this one.
|
|
953
|
+
if (m < 1 || m > 12 || d < 1 || d > new Date(Date.UTC(y, m, 0)).getUTCDate()) return undefined;
|
|
954
|
+
return words.date(words.cardinal(d), words.months[m - 1], words.cardinal(y));
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/** (k5) Where the pauses around `<< text >>` go, placed by `inline` once code spans are back in the line. */
|
|
958
|
+
const QUOTE_OPEN = String.fromCharCode(0xe00c);
|
|
959
|
+
const QUOTE_CLOSE = String.fromCharCode(0xe00d);
|
|
960
|
+
const QUOTE_OPENING = new RegExp(`[ \\t]*${QUOTE_OPEN}[ \\t]*`, "g");
|
|
961
|
+
const QUOTE_CLOSING = new RegExp(`[ \\t]*${QUOTE_CLOSE}[ \\t]*`, "g");
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* (k5) `<< text >>`, a format models use, reads like quotes: the marks are silent and the text has a short pause
|
|
965
|
+
* around it. It needs a letter inside and a `>>` on the same line, so a shift such as `a << b` or `x << 2 >> 1`
|
|
966
|
+
* keeps its reading and swallows nothing.
|
|
967
|
+
*/
|
|
968
|
+
function angleQuotes(text: string): string {
|
|
969
|
+
return text.replace(
|
|
970
|
+
/(?<![^\s([{"'“«])<<(?!<)[ \t]*([^<>\n]*?\p{L}[^<>\n]*?)[ \t]*>>(?![>\p{L}\p{N}_])/gu,
|
|
971
|
+
(_m, inside: string) => ` ${QUOTE_OPEN} ${inside} ${QUOTE_CLOSE} `,
|
|
972
|
+
);
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/** (k5) A tag name: letters, digits and `-`, starting with a letter. */
|
|
976
|
+
const TAG = /<(\/?)(\p{L}[\p{L}\p{N}-]*)(\/?)>/gu;
|
|
977
|
+
/**
|
|
978
|
+
* A tag glued to a letter, digit or `_` (`a<b>c`, `List<String>`) is not one: markup or a generic type. So is one
|
|
979
|
+
* glued to a code span, URL or escape parked behind a private-use mark (`` `x`<br>`y` ``).
|
|
980
|
+
*/
|
|
981
|
+
const TAG_GLUE = /[\p{L}\p{N}_\uE000-\uE00F]/u;
|
|
982
|
+
|
|
983
|
+
/**
|
|
984
|
+
* (k5) Tags, HTML or not. A pair `<name>…</name>` of the same text reads "name: " and then the content, the closing
|
|
985
|
+
* tag silent; the opening tag may be glued to the content, the closing one to the content before it. A lone
|
|
986
|
+
* `<name>` reads its name (`<archivo>` "archivo"); a lone `</name>` or `<name/>` reads "la etiqueta name" ("the
|
|
987
|
+
* name tag"), only the name right after "etiqueta"/"tag". Lone tags glued to other text (`a<b>c`) are not tags.
|
|
988
|
+
*/
|
|
989
|
+
function tags(text: string, before: string, after: string): string {
|
|
990
|
+
return text.replace(TAG, (match: string, closing: string, rawName: string, selfClosing: string, offset: number, whole: string) => {
|
|
991
|
+
if (closing !== "" && selfClosing !== "") return match;
|
|
992
|
+
const prior = offset === 0 ? "" : whole[offset - 1];
|
|
993
|
+
const next = whole[offset + match.length] ?? "";
|
|
994
|
+
const apartBefore = prior === "" || !TAG_GLUE.test(prior);
|
|
995
|
+
const apartAfter = next === "" || !TAG_GLUE.test(next);
|
|
996
|
+
const name = rawName.replace(/-+/g, " ");
|
|
997
|
+
let paired = false;
|
|
998
|
+
// An opening tag may start a pair only where a word could start, a closing one end it only where a word could end.
|
|
999
|
+
if (selfClosing === "" && tagging && (closing === "" ? apartBefore : apartAfter)) {
|
|
1000
|
+
const index = tagging.next++;
|
|
1001
|
+
tagging.seen.push({ name: rawName, closing: closing !== "" });
|
|
1002
|
+
paired = tagging.paired?.[index] ?? false;
|
|
1003
|
+
}
|
|
1004
|
+
if (paired) return closing === "" ? `${name}:${next === "" || /\s/.test(next) ? "" : " "}` : "";
|
|
1005
|
+
// Alone, a tag right after another tag's `>` (`height="450"></iframe>`) is still markup, and one between `/`
|
|
1006
|
+
// (`/catalog/<id>`) is part of a path, whose reading gives the name.
|
|
1007
|
+
if (!apartBefore || !apartAfter || prior === ">" || next === "<" || prior === "/" || next === "/") return match;
|
|
1008
|
+
if (closing === "" && selfClosing === "") return name;
|
|
1009
|
+
const said = previousWord(before + whole.slice(0, offset)).toLowerCase();
|
|
1010
|
+
const noun = words === ENGLISH && /^\s/.test(next) ? nextWord(whole.slice(offset + match.length) + after).toLowerCase() : "";
|
|
1011
|
+
return said === "etiqueta" || said === "tag" || noun === "tag" ? name : words.tag(name);
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/** (k4, L128) Markdown emphasis written as code, `**negrita**` or `*nota*`, reads only its letters: "negrita". */
|
|
1016
|
+
function emphasis(core: string): string | undefined {
|
|
1017
|
+
return /^(\*{1,2})(\p{L}+)\1$/u.exec(core)?.[2];
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* (k4) A glob with a letter: a leading `*` reads "cualquier" (`*.hs.lan` "cualquier hs punto lan"), a trailing `/*`
|
|
1022
|
+
* "todo lo de" plus the folder (`bin/*` "todo lo de bin"), any other `*` "algo" (`lab-*` "lab algo").
|
|
1023
|
+
*/
|
|
1024
|
+
function glob(core: string): string | undefined {
|
|
1025
|
+
if (!core.includes("*") || !/^[\p{L}\p{N}._~/*-]+$/u.test(core) || !/\p{L}/u.test(core)) return undefined;
|
|
1026
|
+
const folder = /^(.*[^/*])\/\*+$/.exec(core)?.[1];
|
|
1027
|
+
if (folder !== undefined && !folder.includes("*")) return `${words.everythingIn} ${pathReading(`${folder}/`, "carpeta") ?? nameWords(folder)}`;
|
|
1028
|
+
if (!core.startsWith("*")) return globWords(core);
|
|
1029
|
+
const rest = globWords(core.replace(/^\*+/, ""));
|
|
1030
|
+
return rest === "" ? undefined : `${words.any} ${rest}`;
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
/** A glob's parts as words, each `*` (or `**`) as "algo": `TEST_CKAN_*` "TEST CKAN algo". */
|
|
1034
|
+
function globWords(text: string): string {
|
|
1035
|
+
return text
|
|
1036
|
+
.split(/\*+/)
|
|
1037
|
+
.map((part) =>
|
|
1038
|
+
part
|
|
1039
|
+
.replace(/^[._~/-]+|[._~/-]+$/g, "")
|
|
1040
|
+
.replace(/(?<=[\p{L}\p{N}])\.(?=[\p{L}\p{N}])/gu, ` ${words.dot} `)
|
|
1041
|
+
.replace(/[._~/-]+/g, " "),
|
|
1042
|
+
)
|
|
1043
|
+
.join(` ${words.something} `)
|
|
1044
|
+
.replace(/\s+/g, " ")
|
|
1045
|
+
.trim();
|
|
1046
|
+
}
|
|
1047
|
+
|
|
451
1048
|
const BRANCH = /^(?:feat|fix|docs|chore|refactor|test|release|origin|upstream)\/[\p{L}\p{N}][\p{L}\p{N}._/-]*$/u;
|
|
452
1049
|
const PATH = /^[\p{L}\p{N}._~/+-]+$/u;
|
|
453
1050
|
/** A bare `name.<tld>` is a host, not a file. */
|
|
454
1051
|
const HOST_ENDINGS = new Set(["com", "org", "net", "io", "dev", "lan", "app", "ai", "co"]);
|
|
455
1052
|
|
|
1053
|
+
/** (i2) `#43` reads as "número 43"; a heading's own `#` never gets here. */
|
|
1054
|
+
function issueNumber(core: string): string | undefined {
|
|
1055
|
+
const digits = /^#(\d+)$/.exec(core)?.[1];
|
|
1056
|
+
return digits === undefined ? undefined : `${words.number} ${digits}`;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
const MODIFIER = /^(?:ctrl|control|alt|shift|cmd|command|super|meta|win|option|fn)$/i;
|
|
1060
|
+
const KEY = /^(?:[\p{L}\p{N}]|enter|tab|esc|space|delete|backspace|up|down|left|right|home|end|f(?:[1-9]|1[0-2]))$/iu;
|
|
1061
|
+
|
|
1062
|
+
/** (i3) `Ctrl+Shift+P` reads as "Control más Shift más P": modifiers joined by `+` to one key. */
|
|
1063
|
+
function keyCombination(core: string): string | undefined {
|
|
1064
|
+
const keys = core.split("+");
|
|
1065
|
+
const key = keys.pop() ?? "";
|
|
1066
|
+
if (keys.length === 0 || !keys.every((name) => MODIFIER.test(name)) || !KEY.test(key)) return undefined;
|
|
1067
|
+
return [...keys.map((name) => (/^ctrl$/i.test(name) ? "Control" : name)), key].join(` ${words.plus} `);
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/**
|
|
1071
|
+
* (i4) `v2.0+` reads as "v2 punto 0 o superior". Without a `v`, a whole number (`100+`, or a Spanish thousand such
|
|
1072
|
+
* as `6.000+`) is a count: "100 o más".
|
|
1073
|
+
*/
|
|
1074
|
+
function minimumVersion(core: string): string | undefined {
|
|
1075
|
+
const version = /^(v?)(\d+(?:\.\d+)*)\+$/.exec(core);
|
|
1076
|
+
if (!version) return undefined;
|
|
1077
|
+
const [, v, number] = version;
|
|
1078
|
+
if (v === "" && (!number.includes(".") || (words.thousands && THOUSANDS.test(number)))) return `${number} ${words.orMore}`;
|
|
1079
|
+
return `${v}${dottedNumber(number)} ${words.orLater}`;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
456
1082
|
/** `feat/pending-central` reads as "feat pending central". */
|
|
457
1083
|
function nameWords(core: string): string {
|
|
458
1084
|
return core.replace(/(?<=[\p{L}\p{N}])[-_/]+(?=[\p{L}\p{N}])/gu, " ");
|
|
@@ -468,19 +1094,25 @@ function alternatives(core: string): string | undefined {
|
|
|
468
1094
|
/**
|
|
469
1095
|
* The last part plus its folder: `~/.gentle-shell/agent/AGENTS.md` reads as "AGENTS punto md, en agent"
|
|
470
1096
|
* and `/tmp/x/wav/hs/` as "la carpeta hs, en wav" ("hs, en wav" right after "carpeta"). A single `/word` is
|
|
471
|
-
* left to `command`, `1/2` to the numbers.
|
|
1097
|
+
* left to `command`, `1/2` to the numbers. (i1) A relative `src/` is a folder too, and a last part starting with
|
|
1098
|
+
* a dot (`ckan-docker/.prettierrc.json`) reads like any other; with no extension and a folder before it
|
|
1099
|
+
* (`ckan-docker/.gitignore`) it is a file named without the dot: "gitignore, en ckan docker".
|
|
472
1100
|
*/
|
|
473
1101
|
function pathReading(core: string, previous: string): string | undefined {
|
|
474
1102
|
if (!PATH.test(core)) return undefined;
|
|
475
1103
|
const root = /^(?:~|\.{1,2})?\//.exec(core)?.[0] ?? "";
|
|
476
1104
|
const parts = core.slice(root.length).split("/").filter((part) => part !== "");
|
|
477
1105
|
const isFolder = core.endsWith("/");
|
|
1106
|
+
const bareFolder = root === "" && parts.length === 1 && isFolder && /\p{L}/u.test(parts[0]);
|
|
1107
|
+
if (bareFolder) return previous === "carpeta" || previous === "folder" ? partName(parts[0]) : `${words.folder} ${partName(parts[0])}`;
|
|
478
1108
|
if (root === "/" ? parts.length < 2 && !isFolder : root === "" && parts.length < 2) return undefined;
|
|
479
|
-
if (root === "" && !/\p{L}
|
|
1109
|
+
if (root === "" && !/\p{L}\/\.?[\p{L}\p{N}]|[\p{L}\p{N}]\/\.?\p{L}/u.test(core)) return undefined;
|
|
480
1110
|
const name = partName(parts.at(-1) ?? "");
|
|
481
1111
|
if (name === "") return undefined;
|
|
482
1112
|
const said = previous === "carpeta" || previous === "folder";
|
|
483
|
-
const
|
|
1113
|
+
const last = parts.at(-1) ?? "";
|
|
1114
|
+
const dotFile = !isFolder && parts.length > 1 && last.startsWith(".") ? name : undefined;
|
|
1115
|
+
const reading = (!isFolder && fileReading(last)) || dotFile || (said ? name : `${words.folder} ${name}`);
|
|
484
1116
|
const folder = parts.length > 1 ? partName(parts[parts.length - 2]) : "";
|
|
485
1117
|
return folder === "" ? reading : `${reading}, ${words.in} ${folder}`;
|
|
486
1118
|
}
|
|
@@ -531,11 +1163,15 @@ function commitHash(core: string, previous: string): string | undefined {
|
|
|
531
1163
|
return previous === "commit" || previous === "commits" ? "" : words.aCommit;
|
|
532
1164
|
}
|
|
533
1165
|
|
|
534
|
-
/** Other paths, such as `@scope/pkg
|
|
1166
|
+
/** Other paths, such as `@scope/pkg` or `/a/<id>/b`, keep (d)'s reading: their parts as words. */
|
|
535
1167
|
function slashWords(core: string): string | undefined {
|
|
536
1168
|
if (!/^(?:~|\.{1,2})?\//.test(core) && !/\p{L}\/[\p{L}\p{N}]|[\p{L}\p{N}]\/\p{L}/u.test(core)) return undefined;
|
|
537
1169
|
const parts = core.split("/").map((part) => part.replace(/^[~.]+/, "")).filter((part) => part !== "");
|
|
538
|
-
|
|
1170
|
+
// (k5) A placeholder in a path reads by its name: `/catalog/download/<id>` "catalog download id".
|
|
1171
|
+
return parts
|
|
1172
|
+
.join(" ")
|
|
1173
|
+
.replace(/<(\p{L}[\p{L}\p{N}-]*)>/gu, "$1")
|
|
1174
|
+
.replace(/(?<=[\p{L}\p{N}])[-_]+(?=[\p{L}\p{N}])/gu, " ");
|
|
539
1175
|
}
|
|
540
1176
|
|
|
541
1177
|
/** The word right before a token, across spaces, opening quotes and emphasis markers. */
|