@hncode/hncode 0.8.0 → 0.8.2
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/README.md +18 -0
- package/README_CN.md +14 -0
- package/package.json +1 -1
- package/src/agent-task.js +354 -337
- package/src/agent.js +19 -3
- package/src/animate.js +35 -0
- package/src/clipboard.js +54 -5
- package/src/config.js +25 -7
- package/src/file-tree.js +4 -3
- package/src/highlight.js +20 -6
- package/src/i18n.js +825 -0
- package/src/image-row.js +11 -2
- package/src/index.js +730 -610
- package/src/llm.js +146 -21
- package/src/log-file.js +112 -0
- package/src/markdown.js +619 -567
- package/src/migrate-index.js +175 -0
- package/src/migrate.js +392 -0
- package/src/panels.js +9 -7
- package/src/rows-plan-bg.js +3 -2
- package/src/rows-status.js +20 -6
- package/src/rows-tool-result.js +35 -8
- package/src/screen-paint.js +153 -128
- package/src/session-recover.js +317 -0
- package/src/session.js +203 -13
- package/src/swarm-progress.js +5 -1
- package/src/tasks-browser.js +9 -8
- package/src/team-panel.js +12 -11
- package/src/text.js +192 -149
- package/src/tool-line.js +7 -2
- package/src/tool-result.js +400 -327
- package/src/tools/ask-user-question.js +1 -2
- package/src/tools/bash.js +23 -11
- package/src/tools/edit.js +640 -665
- package/src/tools/goal.js +130 -93
- package/src/tools/read.js +141 -133
- package/src/tools/shell.js +28 -2
- package/src/tools/tasks.js +214 -214
- package/src/tools/utils.js +143 -104
- package/src/tui.js +20689 -19943
package/src/markdown.js
CHANGED
|
@@ -1,567 +1,619 @@
|
|
|
1
|
-
// Markdown → ANSI rows.
|
|
2
|
-
//
|
|
3
|
-
// One block in, a list of painted rows out. Nothing here knows about a transcript, a session or a screen: a caller
|
|
4
|
-
// hands over text and a width, which is what lets the same renderer serve a chat row, a tool result and a table cell.
|
|
5
|
-
//
|
|
6
|
-
// The incremental path exists because streaming rewrites only the LAST block of a growing reply. Splitting at blank
|
|
7
|
-
// lines outside a fence makes every earlier block final, so only the tail is re-rendered — verified to produce the
|
|
8
|
-
// same rows as a whole-document render, which is the property the cache depends on.
|
|
9
|
-
|
|
10
|
-
import { C } from './colors.js';
|
|
11
|
-
import { renderLatex } from './latex.js';
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
// back the
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
const
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
//
|
|
234
|
-
//
|
|
235
|
-
//
|
|
236
|
-
|
|
237
|
-
//
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
for (
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
//
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
const
|
|
458
|
-
if (
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
*
|
|
491
|
-
*
|
|
492
|
-
*
|
|
493
|
-
*
|
|
494
|
-
*
|
|
495
|
-
*/
|
|
496
|
-
export function
|
|
497
|
-
const
|
|
498
|
-
if (!
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
const
|
|
503
|
-
if (
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
*
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
*
|
|
539
|
-
*
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
//
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
//
|
|
554
|
-
|
|
555
|
-
return
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
1
|
+
// Markdown → ANSI rows.
|
|
2
|
+
//
|
|
3
|
+
// One block in, a list of painted rows out. Nothing here knows about a transcript, a session or a screen: a caller
|
|
4
|
+
// hands over text and a width, which is what lets the same renderer serve a chat row, a tool result and a table cell.
|
|
5
|
+
//
|
|
6
|
+
// The incremental path exists because streaming rewrites only the LAST block of a growing reply. Splitting at blank
|
|
7
|
+
// lines outside a fence makes every earlier block final, so only the tail is re-rendered — verified to produce the
|
|
8
|
+
// same rows as a whole-document render, which is the property the cache depends on.
|
|
9
|
+
|
|
10
|
+
import { C } from './colors.js';
|
|
11
|
+
import { renderLatex } from './latex.js';
|
|
12
|
+
// THE TYPESETTER IS LOADED WHEN A PICTURE IS ACTUALLY NEEDED.
|
|
13
|
+
//
|
|
14
|
+
// `measureTex` / `encodeTexImage` pull in the whole TeX layout, metrics and raster pipeline: 21ms of module evaluation,
|
|
15
|
+
// which every session paid before the first frame — for a feature that (a) most replies do not use and (b) is skipped
|
|
16
|
+
// entirely when the terminal cannot show a bitmap. `placeTex` returns early in that case, so the common path never
|
|
17
|
+
// needs these at all.
|
|
18
|
+
//
|
|
19
|
+
// ESM has no synchronous require, so the first formula draws as its Unicode layout and the bitmap appears from the next
|
|
20
|
+
// frame. Asking for a picture twice to get it once is better than every startup paying for it.
|
|
21
|
+
let texMod = null;
|
|
22
|
+
let texLoading = null;
|
|
23
|
+
function loadTex() {
|
|
24
|
+
if (texMod) return texMod;
|
|
25
|
+
if (!texLoading) {
|
|
26
|
+
texLoading = import('./tex/index.js')
|
|
27
|
+
.then((m) => { texMod = m; return m; })
|
|
28
|
+
.catch(() => { texLoading = null; return null; });
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
import { encodeImageRow } from './image-row.js';
|
|
33
|
+
import { terminalCaps } from './term-caps.js';
|
|
34
|
+
import { col, visualCol, wrapWords } from './text.js';
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Mermaid is loaded on first use, not at import.
|
|
38
|
+
*
|
|
39
|
+
* It costs ~54ms of module evaluation — the largest single item behind `latex` and `tui` — and it is only needed to draw
|
|
40
|
+
* a ```mermaid fence, which most sessions never contain. On a weak machine that is a visible slice of the blank screen
|
|
41
|
+
* before the first frame, paid for a feature the session may not use at all.
|
|
42
|
+
*
|
|
43
|
+
* `require`-style sync loading is not available in ESM, so the first mermaid block renders as its SOURCE and kicks off
|
|
44
|
+
* the load; the next frame draws the diagram. A diagram appearing one frame late is not something a reader notices,
|
|
45
|
+
* and it is strictly better than every session paying for it up front.
|
|
46
|
+
*/
|
|
47
|
+
let mermaidMod = null;
|
|
48
|
+
let mermaidLoading = null;
|
|
49
|
+
function loadMermaid() {
|
|
50
|
+
if (mermaidMod) return mermaidMod;
|
|
51
|
+
if (!mermaidLoading) {
|
|
52
|
+
mermaidLoading = import('./mermaid/index.js')
|
|
53
|
+
.then((m) => { mermaidMod = m; return m; })
|
|
54
|
+
.catch(() => { mermaidLoading = null; return null; });
|
|
55
|
+
}
|
|
56
|
+
return null; // not ready yet; the caller falls back to the source this frame
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Version of the markdown renderer, part of the incremental cache key.
|
|
61
|
+
*
|
|
62
|
+
* That cache is validated on the INPUT — text, width, colours — which cannot see that the renderer itself now produces
|
|
63
|
+
* different rows for the same input. A session that cached a block before a fence type learned to draw kept showing
|
|
64
|
+
* the old output, so the change looked like it had not shipped. Bump this whenever what `renderMdText` produces for
|
|
65
|
+
* the same input changes.
|
|
66
|
+
*/
|
|
67
|
+
export const MD_RENDER_VERSION = 7; // 7: an image row carries the TeX that produced it
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Render a growing markdown text, re-rendering only the last block.
|
|
71
|
+
*
|
|
72
|
+
* @param {object} msg carries `_mdCache` between calls
|
|
73
|
+
* @param {string} text
|
|
74
|
+
* @param {number} width
|
|
75
|
+
* @param {string} fg body colour
|
|
76
|
+
* @param {string} codeFg inline-code colour
|
|
77
|
+
* @returns {{headRows: string[], tailRows: string[], headCut: number}}
|
|
78
|
+
*/
|
|
79
|
+
export function renderMdIncremental(msg, text, width, fg, codeFg) {
|
|
80
|
+
const src = text.replace(/\r\n/g, '\n');
|
|
81
|
+
let c = msg._mdCache;
|
|
82
|
+
// Layout identity: same width/colours and the same text. Comparing the text (not just its length) is required — a
|
|
83
|
+
// same-length replacement must re-render.
|
|
84
|
+
if (c && c.v === MD_RENDER_VERSION && c.width === width && c.fg === fg && c.codeFg === codeFg && c.text === src) {
|
|
85
|
+
return { headRows: c.headRows, tailRows: c.tailRows, headCut: c.headCut };
|
|
86
|
+
}
|
|
87
|
+
if (!c || c.v !== MD_RENDER_VERSION || c.width !== width || c.fg !== fg || c.codeFg !== codeFg) {
|
|
88
|
+
c = msg._mdCache = { v: MD_RENDER_VERSION, width, fg, codeFg };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const parts = splitBlocks(src);
|
|
92
|
+
// A block is final once a LATER block exists; the last one is still growing.
|
|
93
|
+
const headCount = Math.max(0, parts.length - 1);
|
|
94
|
+
// THE CACHED BLOCKS BELONG TO A VERSION OF THE RENDERER. Without that check a request for the same text, width and
|
|
95
|
+
// colours reuses rows produced by an OLDER renderer: the fast path above rejects them on `c.v`, but it leaves `c`
|
|
96
|
+
// untouched (its width and colours still match), and this reuse test then finds the block texts identical and hands
|
|
97
|
+
// back the old rows.
|
|
98
|
+
const canReuse = c.v === MD_RENDER_VERSION
|
|
99
|
+
&& Array.isArray(c.blocks)
|
|
100
|
+
&& Array.isArray(c.blockTexts)
|
|
101
|
+
&& c.blockTexts.length >= headCount
|
|
102
|
+
&& parts.length >= headCount
|
|
103
|
+
&& c.blockTexts.slice(0, headCount).every((t, i) => t === parts[i]);
|
|
104
|
+
|
|
105
|
+
const blocks = canReuse ? c.blocks.slice(0, headCount) : parts.slice(0, headCount).map((b) => renderMdText(b, width, fg, codeFg));
|
|
106
|
+
const headRows = [];
|
|
107
|
+
for (const b of blocks) for (const r of b) headRows.push(r);
|
|
108
|
+
const tailRows = renderMdText(parts.length ? parts[parts.length - 1] : '', width, fg, codeFg);
|
|
109
|
+
const headCut = parts.length > 1 ? parts.slice(0, headCount).join('\n').length : 0;
|
|
110
|
+
|
|
111
|
+
msg._mdCache = {
|
|
112
|
+
v: MD_RENDER_VERSION,
|
|
113
|
+
text: src, width, fg, codeFg,
|
|
114
|
+
blocks, blockTexts: parts.slice(0, headCount),
|
|
115
|
+
headRows, tailRows, headCut,
|
|
116
|
+
};
|
|
117
|
+
return { headRows, tailRows, headCut };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Split at blank lines OUTSIDE a fence.
|
|
122
|
+
*
|
|
123
|
+
* The blank line(s) begin the NEXT block, so every block renders the same whether or not later blocks exist — that is
|
|
124
|
+
* the property the incremental cache depends on.
|
|
125
|
+
*/
|
|
126
|
+
export function splitBlocks(src) {
|
|
127
|
+
if (src === '') return [''];
|
|
128
|
+
const lines = src.split('\n');
|
|
129
|
+
const out = [];
|
|
130
|
+
let cur = [];
|
|
131
|
+
let fence = false;
|
|
132
|
+
for (const ln of lines) {
|
|
133
|
+
const isFence = /^\s*(```+|~~~+)/.test(ln);
|
|
134
|
+
const blank = ln.trim() === '';
|
|
135
|
+
if (blank && !fence) {
|
|
136
|
+
if (cur.length) { out.push(cur); cur = []; }
|
|
137
|
+
cur.push(ln);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (isFence) fence = !fence;
|
|
141
|
+
cur.push(ln);
|
|
142
|
+
}
|
|
143
|
+
if (cur.length) out.push(cur);
|
|
144
|
+
return out.map((b) => b.join('\n'));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Render a whole markdown document to painted rows. */
|
|
148
|
+
export function renderMdText(text, width, fg, codeFg) {
|
|
149
|
+
const src = String(text).replace(/\r\n/g, '\n');
|
|
150
|
+
const para = src.split('\n');
|
|
151
|
+
const out = [];
|
|
152
|
+
let i = 0;
|
|
153
|
+
const isTableSep = (l) => /^\s*\|?\s*:?-{2,}.*\|/.test(l) || /^\s*\|[-: ]+\|/.test(l);
|
|
154
|
+
const splitCells = (l) => {
|
|
155
|
+
const s = l.trim().replace(/^\|/, '').replace(/\|$/, '');
|
|
156
|
+
return s.split('|').map((c) => c.trim());
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
while (i < para.length) {
|
|
160
|
+
const line = para[i];
|
|
161
|
+
const t = line.replace(/\s+$/, '');
|
|
162
|
+
// DISPLAY MATH: `$$ ... $$` and `\[ ... \]`.
|
|
163
|
+
//
|
|
164
|
+
// A fence is what a model writes when it wants a code block, but a formula usually arrives as `$$`. It is laid out
|
|
165
|
+
// here as the formula it describes — stacked fractions, limits above a sum — and its source is what remains when
|
|
166
|
+
// the subset cannot express it, exactly as a math fence behaves. The opener has to start the line and the closer
|
|
167
|
+
// has to end one, so `cost is $$x$$ total` stays prose and is handled as inline math by the line renderer below.
|
|
168
|
+
const mathOpen = /^\s*(\$\$|\\\[)/.exec(t);
|
|
169
|
+
if (mathOpen) {
|
|
170
|
+
const open = mathOpen[1];
|
|
171
|
+
const close = open === '$$' ? '$$' : '\\]';
|
|
172
|
+
const after = t.slice(mathOpen.index + mathOpen[0].length);
|
|
173
|
+
let body = null;
|
|
174
|
+
let used = 0;
|
|
175
|
+
let closed = true;
|
|
176
|
+
// One-line form: `$$x = 1$$` with nothing but whitespace after the closer.
|
|
177
|
+
const oneLine = after.indexOf(close);
|
|
178
|
+
if (oneLine >= 0 && after.slice(oneLine + close.length).trim() === '') {
|
|
179
|
+
body = after.slice(0, oneLine);
|
|
180
|
+
used = 1;
|
|
181
|
+
} else if (after.trim() === '') {
|
|
182
|
+
// Multi-line form: everything up to the line that ends with the closer.
|
|
183
|
+
const collected = [];
|
|
184
|
+
let k = i + 1;
|
|
185
|
+
let found = false;
|
|
186
|
+
while (k < para.length) {
|
|
187
|
+
const cl = para[k].replace(/\s+$/, '');
|
|
188
|
+
if (cl.trimEnd().endsWith(close)) {
|
|
189
|
+
collected.push(cl.slice(0, cl.lastIndexOf(close)));
|
|
190
|
+
k++;
|
|
191
|
+
found = true;
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
collected.push(para[k]);
|
|
195
|
+
k++;
|
|
196
|
+
}
|
|
197
|
+
body = collected.join('\n');
|
|
198
|
+
used = k - i;
|
|
199
|
+
// Still streaming: no closer yet, so the body is prose plus half a formula.
|
|
200
|
+
closed = found;
|
|
201
|
+
}
|
|
202
|
+
if (body !== null && closed) {
|
|
203
|
+
i += used;
|
|
204
|
+
// Same three fallbacks as a math fence: bitmap, Unicode layout, then the source.
|
|
205
|
+
const rows = mathBlockRows(body, width, true);
|
|
206
|
+
if (rows) {
|
|
207
|
+
out.push(...rows);
|
|
208
|
+
} else {
|
|
209
|
+
// Unsupported: show the TeX so the reader still gets the formula's meaning.
|
|
210
|
+
for (const l of body.split('\n')) out.push(col(' ' + l.slice(0, Math.max(1, width - 2)), C.white));
|
|
211
|
+
}
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// Fenced code block. Rendered with a rule ABOVE (labelled with the language) and a matching full-width rule BELOW,
|
|
216
|
+
// so the block is visibly delimited.
|
|
217
|
+
const fm = /^\s*(`{3,}|~{3,})\s*(\S*)/.exec(t);
|
|
218
|
+
if (fm) {
|
|
219
|
+
const lang = fm[2] || '';
|
|
220
|
+
i++;
|
|
221
|
+
const buf = [];
|
|
222
|
+
const fenceChar = fm[1][0];
|
|
223
|
+
const fenceLen = fm[1].length;
|
|
224
|
+
const isCloser = (s) => {
|
|
225
|
+
const m = /^\s*(`{3,}|~{3,})\s*$/.exec(s);
|
|
226
|
+
return !!m && m[1][0] === fenceChar && m[1].length >= fenceLen;
|
|
227
|
+
};
|
|
228
|
+
while (i < para.length && !isCloser(para[i])) { buf.push(para[i]); i++; }
|
|
229
|
+
// Whether the closing fence was actually reached: an open fence means the text is still streaming.
|
|
230
|
+
const fenceClosed = i < para.length;
|
|
231
|
+
i++; // closing fence (no-op when the fence is still open)
|
|
232
|
+
const rule = (s) => col(s, C.gray);
|
|
233
|
+
// MATH FENCES ARE TYPESET. A `latex`/`tex`/`math` fence is TeX, not code: it is drawn as the formula it
|
|
234
|
+
// describes, and when the terminal speaks an image protocol it is drawn as a TYPESET BITMAP rather than as
|
|
235
|
+
// flattened Unicode.
|
|
236
|
+
//
|
|
237
|
+
// Three fallbacks, in order, and each one keeps the formula: the bitmap; the Unicode layout when the picture
|
|
238
|
+
// cannot be placed (no protocol, no cell size, too wide, too tall); the SOURCE when the subset cannot express
|
|
239
|
+
// the TeX at all.
|
|
240
|
+
if (/^(latex|tex|math)$/i.test(lang)) {
|
|
241
|
+
const tex = buf.join('\n').trim();
|
|
242
|
+
const rendered = mathBlockRows(tex, width, fenceClosed);
|
|
243
|
+
if (rendered) {
|
|
244
|
+
out.push(...rendered);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
// Falls through to the plain code block: the source is all we have.
|
|
248
|
+
}
|
|
249
|
+
if (/^mermaid$/i.test(lang)) {
|
|
250
|
+
const diagramSrc = buf.join('\n');
|
|
251
|
+
// The module is fetched on the first mermaid block and draws from the NEXT frame; until then the source box is
|
|
252
|
+
// what the reader sees, which is the same fallback used when a diagram does not fit.
|
|
253
|
+
const mm = loadMermaid();
|
|
254
|
+
if (mm) {
|
|
255
|
+
let art = null;
|
|
256
|
+
try { art = mm.render(diagramSrc); } catch { art = null; }
|
|
257
|
+
// Wider than the panel: the frame is the honest answer, since truncating art would cut a box in half rather
|
|
258
|
+
// than say the diagram does not fit.
|
|
259
|
+
if (art && art.width <= width) {
|
|
260
|
+
// `toAnsi` keeps the role of every span, so the frame stays dim and the connectors cyan instead of the
|
|
261
|
+
// whole diagram arriving as plain white text.
|
|
262
|
+
const coloured = mm.toAnsi(art);
|
|
263
|
+
for (const l of coloured) out.push(l);
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
if (mm) {
|
|
269
|
+
for (const l of mm.sourceBox(diagramSrc, width).plain) out.push(col(l, C.white));
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
} catch { /* fall through to the plain code block */ }
|
|
273
|
+
}
|
|
274
|
+
// Opening rule: `─ <lang> ` then `─` padding out to the FULL width.
|
|
275
|
+
if (lang) {
|
|
276
|
+
const head = `\u2500 ${lang} `;
|
|
277
|
+
out.push(rule(head + '─'.repeat(Math.max(1, width - visualCol(head)))));
|
|
278
|
+
} else {
|
|
279
|
+
out.push(rule('─'.repeat(Math.max(1, width))));
|
|
280
|
+
}
|
|
281
|
+
// Fenced code block CONTENT is plain body text — the default terminal colour, not the theme's cyan. The cyan is
|
|
282
|
+
// reserved for UI chrome and the language label; a large code block in cyan reads as "everything is the theme
|
|
283
|
+
// colour".
|
|
284
|
+
for (const cl of buf) out.push(col(cl.slice(0, width), C.white));
|
|
285
|
+
// Closing rule, matching the opening one.
|
|
286
|
+
out.push(rule('─'.repeat(Math.max(1, width))));
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
// Table: a header line followed by a separator line
|
|
290
|
+
if (t.includes('|') && i + 1 < para.length && isTableSep(para[i + 1])) {
|
|
291
|
+
const header = splitCells(t);
|
|
292
|
+
const sep = splitCells(para[i + 1]);
|
|
293
|
+
const body = [];
|
|
294
|
+
i += 2;
|
|
295
|
+
while (i < para.length && para[i].trim().includes('|') && !isTableSep(para[i])) { body.push(splitCells(para[i])); i++; }
|
|
296
|
+
renderTable(out, header, body, sep.length, width, fg);
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
// Fall through to single-line renderer
|
|
300
|
+
const rows = markdownLineToRows(t, width, fg, codeFg, false);
|
|
301
|
+
out.push(...rows);
|
|
302
|
+
i++;
|
|
303
|
+
}
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Render a Markdown table as aligned columns. Header bolded, rows readable. */
|
|
308
|
+
export function renderTable(out, header, body, colCount, width, fg) {
|
|
309
|
+
const cols = Math.max(header.length, colCount, ...body.map((r) => r.length));
|
|
310
|
+
const B = C.border;
|
|
311
|
+
const val = (r, c) => (r && r[c] !== undefined ? String(r[c]) : '');
|
|
312
|
+
// Per-column natural width (visual columns), reserving 2 padding each side.
|
|
313
|
+
const natural = Array.from({ length: cols }, (_, c) => {
|
|
314
|
+
let m = 0;
|
|
315
|
+
const consider = (v) => { m = Math.max(m, visualCol(v)); };
|
|
316
|
+
consider(val(header, c));
|
|
317
|
+
for (const r of body) consider(val(r, c));
|
|
318
|
+
return m;
|
|
319
|
+
});
|
|
320
|
+
// Cap total table width to the available width (minus borders).
|
|
321
|
+
const availInner = Math.max(cols, width - (cols + 1));
|
|
322
|
+
const totalNatural = natural.reduce((a, b) => a + 2 + b, 0);
|
|
323
|
+
let widths;
|
|
324
|
+
if (totalNatural <= availInner) {
|
|
325
|
+
widths = natural;
|
|
326
|
+
} else {
|
|
327
|
+
// Scale down proportionally, but never below MIN_COL. A column squeezed to 1 is a column whose content is
|
|
328
|
+
// unreadable, so the shrink stops at a width a word can still use and the ROW grows taller instead.
|
|
329
|
+
const MIN_COL = 4;
|
|
330
|
+
const over = totalNatural - availInner;
|
|
331
|
+
const surplus = natural.reduce((a, b) => a + (b > MIN_COL ? b - MIN_COL : 0), 0);
|
|
332
|
+
widths = natural.map((n) => {
|
|
333
|
+
const shrink = over > 0 && surplus > 0 ? Math.round((Math.max(0, n - MIN_COL)) * (over / surplus)) : 0;
|
|
334
|
+
return Math.max(Math.min(MIN_COL, n), n - shrink);
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
// WRAP, DO NOT TRUNCATE. A cell whose text does not fit its column used to be emitted at full length, which pushed
|
|
338
|
+
// every border after it to the right and broke the table's alignment for the rest of the row. The row now grows
|
|
339
|
+
// taller: each cell is wrapped to its column, and every line is padded to the same width.
|
|
340
|
+
const wrapCell = (text, w) => {
|
|
341
|
+
if (!text) return [''];
|
|
342
|
+
return wrapWords(text, Math.max(1, w));
|
|
343
|
+
};
|
|
344
|
+
// A cell renders its INLINE MARKDOWN (bold, code, links) — a table of `**name**` and `` `value` `` used to show the
|
|
345
|
+
// asterisks and backticks verbatim, which is not what the author wrote.
|
|
346
|
+
const styled = (text, w, bold) => {
|
|
347
|
+
const plain = wrapCell(text, w);
|
|
348
|
+
const paint = bold ? C.white + C.bold : C.gray;
|
|
349
|
+
return plain.map((lineText) => {
|
|
350
|
+
// Render the markdown FIRST, then pad the RESULT.
|
|
351
|
+
//
|
|
352
|
+
// The pad has to be measured on what the cell will actually PRINT, not on the source: `` `--verbose` `` is 11
|
|
353
|
+
// characters of source but 9 on screen once the backticks become a colour, so padding by the source width left
|
|
354
|
+
// the column short by two and every border after it moved left.
|
|
355
|
+
const md = inlineMarkdown(lineText, C.gray, bold ? C.white : C.gray);
|
|
356
|
+
const printed = visualCol(String(md).replace(/\x1b\[[0-9;]*m/g, ''));
|
|
357
|
+
const pad = Math.max(0, w - printed);
|
|
358
|
+
return col(' ', paint) + col(md, paint) + col(' '.repeat(pad) + ' ', paint);
|
|
359
|
+
});
|
|
360
|
+
};
|
|
361
|
+
const rule = (left, mid, right) => col(left + widths.map((w) => '─'.repeat(w + 2)).join(mid) + right, B);
|
|
362
|
+
// One logical row, as several physical lines when any cell wraps.
|
|
363
|
+
const oneRow = (cells, bold) => {
|
|
364
|
+
const rendered = [];
|
|
365
|
+
for (let c = 0; c < cols; c++) rendered.push(styled(val(cells, c), widths[c], bold));
|
|
366
|
+
const height = Math.max(1, ...rendered.map((r) => r.length));
|
|
367
|
+
for (let lineIdx = 0; lineIdx < height; lineIdx++) {
|
|
368
|
+
const parts = rendered.map((r, c) => (r[lineIdx] !== undefined
|
|
369
|
+
? r[lineIdx]
|
|
370
|
+
: col(' ' + ' '.repeat(widths[c]) + ' ', bold ? C.white + C.bold : C.gray)));
|
|
371
|
+
out.push(col('│', B) + parts.join(col('│', B)) + col('│', B));
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
out.push(rule('╭', '┬', '╮'));
|
|
375
|
+
oneRow(header, true);
|
|
376
|
+
out.push(rule('├', '┼', '┤'));
|
|
377
|
+
for (const r of body) oneRow(r, false);
|
|
378
|
+
out.push(rule('╰', '┴', '╯'));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** One line of markdown to rows: headings, rules, quotes, lists, then inline styles. */
|
|
382
|
+
export function markdownLineToRows(line, width, fg, codeFg, isContinuation) {
|
|
383
|
+
const out = [];
|
|
384
|
+
const t = line.replace(/\s+$/, '');
|
|
385
|
+
|
|
386
|
+
// Headings: `# Title`
|
|
387
|
+
let m = /^(\s*)(#{1,6})\s+(.*)$/.exec(t);
|
|
388
|
+
if (m && !isContinuation) {
|
|
389
|
+
const hashCount = m[2].length;
|
|
390
|
+
// h1 is bold white, h2 is plain white, h3+ is gray. Only h1 carries BOLD.
|
|
391
|
+
const size = hashCount === 1 ? C.white + C.bold : hashCount === 2 ? C.white : C.gray;
|
|
392
|
+
for (const w of wrapWords(m[3], width)) {
|
|
393
|
+
out.push(col(w, size));
|
|
394
|
+
}
|
|
395
|
+
return out;
|
|
396
|
+
}
|
|
397
|
+
// Thematic break
|
|
398
|
+
if (/^\s*(-{3,}|\*{3,}|_{3,})$/.test(t)) {
|
|
399
|
+
out.push(col('─'.repeat(Math.min(width, Math.max(8, width))), C.gray));
|
|
400
|
+
return out;
|
|
401
|
+
}
|
|
402
|
+
// Blockquote
|
|
403
|
+
//
|
|
404
|
+
// THE RULE AND THE TEXT ARE DIFFERENT COLOURS. The rule takes the theme colour, so a quote reads as a distinct block
|
|
405
|
+
// in the transcript; the text takes the comment grey, so quoted material is visibly not the reply's own voice.
|
|
406
|
+
// Colouring both the same made a quote indistinguishable from an indented paragraph.
|
|
407
|
+
if (/^\s*>\s?/.test(t)) {
|
|
408
|
+
const content = t.replace(/^\s*>\s?/, '');
|
|
409
|
+
for (const w of wrapWords(content, Math.max(1, width - 2))) {
|
|
410
|
+
out.push(col('▍ ', C.cyan) + col(w, C.comment));
|
|
411
|
+
}
|
|
412
|
+
return out;
|
|
413
|
+
}
|
|
414
|
+
// Unordered/ordered list — bold the bullet, keep content plain. Also handles task checkboxes.
|
|
415
|
+
{
|
|
416
|
+
const task = /^(\s*)([-*+]\s+)?\[( |x|X)\]\s+(.*)$/.exec(t);
|
|
417
|
+
if (task && !isContinuation) {
|
|
418
|
+
const checked = task[3] !== ' ';
|
|
419
|
+
const box = checked ? col('✓', C.green) : col('○', C.gray);
|
|
420
|
+
const content = col(' ' + inlineMarkdown(task[4], codeFg, fg), fg);
|
|
421
|
+
for (const w of wrapWords(task[4], Math.max(1, width - 4))) {
|
|
422
|
+
out.push(col(' ', C.gray) + box + (w === task[4] ? content : col(' ' + w, fg)));
|
|
423
|
+
}
|
|
424
|
+
return out;
|
|
425
|
+
}
|
|
426
|
+
const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(t);
|
|
427
|
+
if (li && !isContinuation) {
|
|
428
|
+
const isOrdered = /^\d/.test(li[2]);
|
|
429
|
+
const bullet = isOrdered ? col(li[2], C.cyan) : col('•', C.cyan);
|
|
430
|
+
const pad = isOrdered ? ' '.repeat(visualCol(li[2])) + ' ' : ' ';
|
|
431
|
+
let first = true;
|
|
432
|
+
for (const w of wrapWords(inlineMarkdown(li[3], codeFg, fg), Math.max(1, width - 2))) {
|
|
433
|
+
out.push((first ? col('', C.gray) + bullet + ' ' : col(pad, C.gray)) + col(w, fg));
|
|
434
|
+
first = false;
|
|
435
|
+
}
|
|
436
|
+
return out;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
// Inline styles: **bold**, *italic*, `code`, [text](url), $math$
|
|
440
|
+
if (/[*`\[$]|\\\(/.test(t)) {
|
|
441
|
+
for (const w of wrapWords(t, width)) out.push(col(inlineMarkdown(w, codeFg, fg), fg));
|
|
442
|
+
return out;
|
|
443
|
+
}
|
|
444
|
+
// Plain - apply default foreground color
|
|
445
|
+
for (const w of wrapWords(t, width)) out.push(col(w, fg));
|
|
446
|
+
return out;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Whether the terminal can receive a formula as a picture.
|
|
451
|
+
*
|
|
452
|
+
* Both halves are required: a protocol the terminal reported (Sixel today) and a cell size it reported (XTWINOPS 16).
|
|
453
|
+
* Without the cell size the picture would be measured in guessed cells, which is what put a formula on the wrong rows
|
|
454
|
+
* before — so a missing cell size falls back to text rather than guess.
|
|
455
|
+
*/
|
|
456
|
+
export function mathImageCapable() {
|
|
457
|
+
const caps = terminalCaps();
|
|
458
|
+
if (!caps) return null;
|
|
459
|
+
// KITTY FIRST. A terminal that speaks both (Kitty can be built with Sixel support) handles Kitty far better: the
|
|
460
|
+
// pixels are uploaded once and every later frame is a placement, while a Sixel has to be retransmitted and moves the
|
|
461
|
+
// cursor when it is drawn.
|
|
462
|
+
const protocol = caps.kittyGraphics
|
|
463
|
+
? 'kitty'
|
|
464
|
+
: (Array.isArray(caps.extensions) && caps.extensions.includes('sixel') ? 'sixel' : null);
|
|
465
|
+
if (!protocol) return null;
|
|
466
|
+
const cell = caps.cell && caps.cell.w > 0 && caps.cell.h > 0 ? caps.cell : null;
|
|
467
|
+
return cell ? { protocol, cell } : null;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Ink colour for a typeset formula: the body text colour, so a picture sits in the text rather than beside it. */
|
|
471
|
+
export const MATH_INK = { r: 220, g: 220, b: 220 };
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* The terminal's cell height in pixels, for cropping a picture that straddles the top of the window.
|
|
475
|
+
*
|
|
476
|
+
* A crop has to convert CELL ROWS to six-pixel BANDS; without the cell height the two units get confused and the image
|
|
477
|
+
* is drawn from the wrong point in its own payload. 20 is the conventional monospace cell height and matches the
|
|
478
|
+
* fallback `src/tex/` uses when the terminal never answers XTWINOPS 16.
|
|
479
|
+
*/
|
|
480
|
+
export function mathCellHeight() {
|
|
481
|
+
const caps = terminalCaps();
|
|
482
|
+
const cell = caps && caps.cell;
|
|
483
|
+
return cell && cell.h > 0 ? cell.h : 20;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* Rows for one display formula: a typeset bitmap when the terminal can show one, the Unicode layout when it cannot,
|
|
488
|
+
* and nothing when the TeX is outside the subset (the caller then shows the source).
|
|
489
|
+
*
|
|
490
|
+
* @param {string} tex TeX without delimiters.
|
|
491
|
+
* @param {number} width Columns available.
|
|
492
|
+
* @param {boolean} closed The closing delimiter arrived. A formula still streaming keeps to the text form: a picture of
|
|
493
|
+
* half a formula is worse than the TeX of half a formula.
|
|
494
|
+
* @returns {string[]|null}
|
|
495
|
+
*/
|
|
496
|
+
export function mathBlockRows(tex, width, closed) {
|
|
497
|
+
const src = stripMathDelimiters(tex);
|
|
498
|
+
if (!src) return null;
|
|
499
|
+
// A picture sits where the text form does: one column of indent, and no wider than the panel.
|
|
500
|
+
const room = Math.max(8, width - 2);
|
|
501
|
+
if (closed) {
|
|
502
|
+
const placed = placeTex(src, room);
|
|
503
|
+
if (placed) return placed;
|
|
504
|
+
}
|
|
505
|
+
const rendered = renderLatex(src, { display: true });
|
|
506
|
+
if (rendered === undefined) return null;
|
|
507
|
+
return rendered
|
|
508
|
+
.split('\n')
|
|
509
|
+
.map((l) => col(l.slice(0, width), C.white));
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Remove the delimiters a formula may still be wrapped in.
|
|
514
|
+
*
|
|
515
|
+
* A `$$…$$` block and a ```latex fence both reach the typesetter, and the fence's content may carry the delimiters too
|
|
516
|
+
* — a model writes the fence around `$$…$$` often enough that it is the common case, not the odd one. Typesetting the
|
|
517
|
+
* delimiters along with the formula draws them as glyphs inside the picture.
|
|
518
|
+
*
|
|
519
|
+
* Only a delimiter that spans the WHOLE body is removed: a `$$` in the middle is TeX the author meant, and stripping it
|
|
520
|
+
* would change the formula. The loop runs because a doubled wrapper leaves one pair behind after the first pass.
|
|
521
|
+
*/
|
|
522
|
+
export function stripMathDelimiters(tex) {
|
|
523
|
+
let s = String(tex || '').trim();
|
|
524
|
+
for (;;) {
|
|
525
|
+
const before = s;
|
|
526
|
+
if (s.startsWith('$$') && s.endsWith('$$') && s.length > 4) {
|
|
527
|
+
s = s.slice(2, -2).trim();
|
|
528
|
+
} else if (s.startsWith('\\[') && s.endsWith('\\]') && s.length > 4) {
|
|
529
|
+
s = s.slice(2, -2).trim();
|
|
530
|
+
} else if (s.startsWith('\\(') && s.endsWith('\\)') && s.length > 4) {
|
|
531
|
+
s = s.slice(2, -2).trim();
|
|
532
|
+
}
|
|
533
|
+
if (s === before) return s;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Typeset a formula into a frame row, or null when it cannot be placed as a picture here.
|
|
539
|
+
*
|
|
540
|
+
* The picture is one row of TEXT plus a payload: the row is the sentinel `image-row.js` understands, the rows below it
|
|
541
|
+
* are blank, and the frame writer turns them into a cursor move and a graphics sequence. Every reason to decline is a
|
|
542
|
+
* reason the caller already has a text fallback for, so this never throws.
|
|
543
|
+
*/
|
|
544
|
+
export function placeTex(tex, room) {
|
|
545
|
+
const capable = mathImageCapable();
|
|
546
|
+
if (!capable) return null;
|
|
547
|
+
// Loaded on first use — see loadTex. Until it lands the caller draws the Unicode layout, which is the same fallback
|
|
548
|
+
// used when a formula cannot be placed as a picture.
|
|
549
|
+
const T = loadTex();
|
|
550
|
+
if (!T) return null;
|
|
551
|
+
try {
|
|
552
|
+
// Measured first, because laying out is what rejects TeX outside the subset: a raster would be paid for and then
|
|
553
|
+
// thrown away.
|
|
554
|
+
const measured = T.measureTex(tex, { cell: capable.cell });
|
|
555
|
+
if (!measured || measured.columns > room || measured.rows > T.TEX_MAX_ROWS) return null;
|
|
556
|
+
const image = T.encodeTexImage(tex, { protocol: capable.protocol, cell: capable.cell, colour: MATH_INK });
|
|
557
|
+
if (!image) return null;
|
|
558
|
+
// THE SOURCE TRAVELS WITH THE ROW. A picture that straddles the top of the window has to be redrawn from its first
|
|
559
|
+
// VISIBLE row, and only the TeX can produce that raster: cropping the encoded payload can only land on a six-pixel
|
|
560
|
+
// band boundary, which leaves up to a quarter of a cell of the formula above the window and makes it slide as the
|
|
561
|
+
// view scrolls. The frame writer reads this back and re-renders with `skipTop` when a picture needs cropping.
|
|
562
|
+
const rows = [encodeImageRow(image.sequence, image.rows, image.columns, tex)];
|
|
563
|
+
for (let r = 1; r < image.rows; r++) rows.push('');
|
|
564
|
+
return rows;
|
|
565
|
+
} catch {
|
|
566
|
+
// A bitmap that cannot be drawn is a reason to show text, never a reason to lose the frame.
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Whether a `$...$` body is a formula rather than prose.
|
|
573
|
+
*
|
|
574
|
+
* Prices, shell variables and identifiers all use `$`: `costs $5 and $10`, `$HOME`, `${VAR}`. A body that starts or
|
|
575
|
+
* ends with a space, is a bare number or an all-caps word is prose, and so is one with no TeX command and no operator
|
|
576
|
+
* in it — `vitamin $C$` stays text while `$x^2$` becomes a formula.
|
|
577
|
+
*/
|
|
578
|
+
export function looksLikeInlineMath(body) {
|
|
579
|
+
if (/^\s/.test(body) || /\s$/.test(body)) return false;
|
|
580
|
+
if (body.startsWith('{') || body.includes('`')) return false;
|
|
581
|
+
if (/^\d+([.,]\d+)?$/.test(body)) return false;
|
|
582
|
+
if (/^[A-Z][A-Z0-9_]*$/.test(body)) return false;
|
|
583
|
+
return /\\[A-Za-z]+|[=+\-*/<>^_]/.test(body) || (/^[A-Za-z]$/.test(body));
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Apply inline markdown to a single line: `code`, **bold**, *italic*, ~~strike~~, [text](url).
|
|
588
|
+
*
|
|
589
|
+
* Order matters so inner tokens are handled safely. `base` is the surrounding foreground colour; every inline style
|
|
590
|
+
* re-asserts it after its own reset, otherwise the bare `\e[0m` would cancel the base colour for the REST of the line
|
|
591
|
+
* — plain text after a **bold** run used to lose its colour and fall back to the terminal default.
|
|
592
|
+
*/
|
|
593
|
+
export function inlineMarkdown(s, codeFg, base) {
|
|
594
|
+
const fb = base || '';
|
|
595
|
+
let r = s;
|
|
596
|
+
// Inline code first so it is not mangled by * [] ~.
|
|
597
|
+
r = r.replace(/`([^`]+)`/g, (_, c) => col(c, codeFg) + fb);
|
|
598
|
+
// INLINE MATH. After the code spans, so a formula inside backticks stays code, and before emphasis, so `*` and `_`
|
|
599
|
+
// inside TeX cannot turn into italics. `\(...\)` is the other inline form models use.
|
|
600
|
+
r = r.replace(/\$([^$\n]+?)\$|\\\(([^\n]+?)\\\)/g, (m, dollar, paren) => {
|
|
601
|
+
const tex = dollar !== undefined ? dollar : paren;
|
|
602
|
+
// A price or a shell variable is not math: `$5 and $10`, `$HOME`, `${VAR}`.
|
|
603
|
+
if (dollar !== undefined && !looksLikeInlineMath(tex)) return m;
|
|
604
|
+
const out = renderLatex(tex, { display: false });
|
|
605
|
+
// Unsupported or multi-line: the source stands, because inline math sits inside wrapped prose.
|
|
606
|
+
if (out === undefined || out.includes('\n')) return m;
|
|
607
|
+
return out;
|
|
608
|
+
});
|
|
609
|
+
// Bold
|
|
610
|
+
r = r.replace(/\*\*([^*]+)\*\*/g, (_, c) => C.bold + c + C.reset + fb);
|
|
611
|
+
// Strikethrough
|
|
612
|
+
r = r.replace(/~~([^~]+)~~/g, (_, c) => '\x1b[9m' + c + '\x1b[29m');
|
|
613
|
+
// Italic
|
|
614
|
+
r = r.replace(/(^|[^*])\*([^*\s][^*]*?)\*(?!\*)/g, (_, pre, c) => pre + '\x1b[3m' + c + '\x1b[23m');
|
|
615
|
+
// Links: [text](url) -> text (cyan); autolink bare http(s) urls
|
|
616
|
+
r = r.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, txt) => col(txt, C.cyan) + fb);
|
|
617
|
+
r = r.replace(/(^|\s)(https?:\/\/[^\s]+)/g, (_, pre, url) => pre + col(url, C.cyan));
|
|
618
|
+
return r;
|
|
619
|
+
}
|