@joelincc/mailroom 0.3.0 → 0.3.1

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.
@@ -23,7 +23,7 @@ export type Block =
23
23
  | { t: 'h'; level: number; c: Inline[] }
24
24
  | { t: 'hr' }
25
25
  | { t: 'quote'; c: Block[] }
26
- | { t: 'list'; ordered: boolean; items: Block[][] }
26
+ | { t: 'list'; ordered: boolean; /** 有序清單的起始編號(1 以外才有)。 */ start?: number; items: Block[][] }
27
27
  | { t: 'code'; v: string }
28
28
  | { t: 'table'; head: Inline[][]; align: (string | null)[]; rows: Inline[][][] }
29
29
  | { t: 'image'; src: string; alt: string; link?: Inline & { t: 'link' } }
@@ -41,7 +41,6 @@ const clip = (s: string, n = 60) => (s.length > n ? `${s.slice(0, n)}…` : s).r
41
41
  /** 嵌入類 HTML(互動圖表、影片):信裡放不了,換成「到網站看」的連結卡。 */
42
42
  const EMBED_TAG = /^\s*<\s*(iframe|video|audio|embed|object|canvas)\b/i;
43
43
  const ANY_TAG = /<\/?[a-zA-Z][^>]*>/;
44
- const BLOCK_HTML = /^\s*<\/?[a-zA-Z!]/;
45
44
  /** 行內標籤開頭的行不是 HTML 區塊,當一般段落(a、b、strong、i、em、br)。 */
46
45
  const INLINE_START = /^\s*<\s*(a|b|strong|i|em|br)\b|^\s*<https?:\/\//i;
47
46
  /** 原稿裡寫的 \{ 先換成這個私用字元,輸出時才變成真的「{」,避免被當成佔位。 */
@@ -69,7 +68,19 @@ function tagProblem(tag: string, inline: boolean): { message: string; where: str
69
68
  return { message: '原稿有看起來像 HTML 標籤的文字(角括號包著的字),引擎會當成標籤而排不出來;如果它不是標籤,請改寫(拿掉角括號,或用反引號包起來)', where };
70
69
  }
71
70
 
72
- const URL_RE = /https?:\/\/[A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]+/g;
71
+ // 非 ASCII 的字(中日韓文、全形標點)也算網址的一部分,跟網站一樣:維基條目、商品頁的中文路徑要整串連過去;
72
+ // 只有空白(含全形空白、不換行空白)和 < 會讓網址結束。私用區字元是引擎自己的記號(例:跳脫的大括號),不算。
73
+ const URL_RE = /https?:\/\/(?:[A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]|[^\x00-\x7F\s\uE000-\uF8FF])+/g;
74
+ /** 網址裡的非 ASCII 字照網站的寫法轉成 %XX(UTF-8),連結目的地才跟網站一樣、也能安全放進轉址標頭。 */
75
+ function encodeNonAscii(u: string): string {
76
+ return u.replace(/[^\x00-\x7F]+/g, (m) => {
77
+ try {
78
+ return encodeURIComponent(m);
79
+ } catch {
80
+ return encodeURIComponent(m.replace(/[\uD800-\uDFFF]/g, '\uFFFD'));
81
+ }
82
+ });
83
+ }
73
84
 
74
85
  function splitFrontmatter(src: string): { body: string; fm: Record<string, string> } {
75
86
  const text = src.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
@@ -91,7 +102,141 @@ function splitFrontmatter(src: string): { body: string; fm: Record<string, strin
91
102
  return { body: text.slice(m[0].length), fm };
92
103
  }
93
104
 
94
- // ───────────── 行內 ─────────────
105
+ // ───────────── 註解與程式碼:只在解析器裡、隨著解析掃一次就決定 ─────────────
106
+ // 沒有「先剝註解再解析」的前置步驟:區塊切好之後,行內的程式碼與註解在同一個迴圈裡由左到右認,誰先開頭誰贏
107
+ // (與 CommonMark 一樣)。所以「哪裡是程式碼、哪裡是註解」全檔只有一份判定,不會有兩套看法對不上。
108
+
109
+ /** 解析時記的帳:遇到的問題、當成註解藏起來的 <!-- 個數、落在程式碼裡的 <!-- 個數(最後拿來跟原文對帳)。 */
110
+ interface Ctx {
111
+ problems: Problem[];
112
+ hidden: number;
113
+ inCode: number;
114
+ /** 行首結構(縮排、> 後、清單記號後)用了 tab 的第一行(判不準,最後記 error)。 */
115
+ tab: string;
116
+ /** 合格的腳註定義標籤(小寫,依出現順序,重複的也留著)。 */
117
+ defs: string[];
118
+ /** 正文裡真正的腳註引用標籤(小寫;不含定義那幾行裡的)。 */
119
+ refs: Set<string>;
120
+ inDef: boolean;
121
+ inLink: number;
122
+ /** 正在轉 [文字](網址) 的連結文字(網站在這裡面不做自動連結)。 */
123
+ mdLink: number;
124
+ /** 正在轉的強調緊接在裸網址後面(網站會把整串吞進網址,裡面的腳註引用不算)。 */
125
+ urlCtx: number;
126
+ /** 這段行內內容裡,信裡真的收成連結目的地的範圍(在最外層原稿裡的位置):裡面的網址不是裸網址。 */
127
+ dest: [number, number][];
128
+ /** 最近一段合格腳註定義結束在哪一行(只在最外層用):之後空行+縮排的行=網站上可能屬於腳註的續段,判不準。 */
129
+ lastDefEnd: number;
130
+ }
131
+ const newCtx = (): Ctx => ({ problems: [], hidden: 0, inCode: 0, tab: '', defs: [], refs: new Set(), inDef: false, inLink: 0, mdLink: 0, urlCtx: 0, dest: [], lastDefEnd: -1 });
132
+ const scratch = newCtx;
133
+ /** 行首空白裡有 tab。 */
134
+ const tabLead = (l: string) => /^[ \t]*\t/.test(l.startsWith(LAZY) ? l.slice(1) : l);
135
+ const noteTab = (ctx: Ctx, l: string) => {
136
+ if (!ctx.tab) ctx.tab = l;
137
+ };
138
+ const marks = (s: string) => s.split('<!--').length - 1;
139
+
140
+ /** CommonMark 可用反斜線跳脫的字元(ASCII 標點)。 */
141
+ const ESCAPABLE = /[!-/:-@[-`{-~]/;
142
+
143
+ /** s[i] 起是 <!--:回傳註解結束後的位置(第一個 -->;<!--> 與 <!---> 是空註解)。沒收尾回 -1。區塊與行內共用。 */
144
+ function commentEnd(s: string, i: number): number {
145
+ const e = s.indexOf('-->', i + 2);
146
+ return e < 0 ? -1 : e + 3;
147
+ }
148
+
149
+ /** 一段要藏起來的註解:記帳;裡面有「--!>」時瀏覽器會提早結束註解(網站藏的範圍和這裡不同),記 error。 */
150
+ function hideComment(text: string, ctx: Ctx): void {
151
+ ctx.hidden += marks(text);
152
+ if (text.includes('--!>')) {
153
+ ctx.problems.push({ code: 'comment_ambiguous', severity: 'error', message: 'HTML 註解裡有「--!>」:瀏覽器會在那裡就結束註解,後面的字會被讀者看到;請拿掉這三個字元', where: clip(text) });
154
+ }
155
+ }
156
+
157
+ const unclosedComment = (where: string): Problem => ({ code: 'unclosed_comment', severity: 'error', message: 'HTML 註解(<!--)沒有收尾:網站上它會把後面的內容藏起來,信裡則會露出來;請補上 -->', where: clip(where) });
158
+
159
+ /**
160
+ * 行內程式碼:s[i] 是一串反引號的開頭,找下一串「剛好一樣長」的反引號當收尾。找不到=不是程式碼(回 null,整串反引號當一般字元)。
161
+ * s 是已經切好的一個區塊的內容(段落、標題、表格的一格),所以不會跨區塊配對。
162
+ */
163
+ function codeSpanAt(s: string, i: number): { open: number; close: number; end: number } | null {
164
+ let n = 0;
165
+ while (s[i + n] === '`') n++;
166
+ let j = i + n;
167
+ while (j < s.length) {
168
+ if (s[j] === '`') {
169
+ let m = 0;
170
+ while (s[j + m] === '`') m++;
171
+ if (m === n) return { open: n, close: j, end: j + m };
172
+ j += m;
173
+ continue;
174
+ }
175
+ j++;
176
+ }
177
+ return null;
178
+ }
179
+
180
+ const RAW_TAG = /^<\/?[a-zA-Z][^>]*>/;
181
+ const AUTOLINK = /^<(https?:\/\/[^\s<>]+)>/i;
182
+
183
+ /**
184
+ * s[i] 起若是一個「不可切開」的行內單位(反斜線跳脫、行內程式碼或一串沒配對的反引號、註解、自動連結、HTML 標籤),回傳它結束的位置;不是回 -1。
185
+ * 找連結的 ]、強調的收尾記號、</a> 時都跳過這些單位,所以強調或連結不會把程式碼或註解切成兩半(CommonMark 的優先順序)。
186
+ */
187
+ function atomEnd(s: string, i: number): number {
188
+ const ch = s[i];
189
+ if (ch === '\\' && i + 1 < s.length && ESCAPABLE.test(s[i + 1])) return i + 2;
190
+ if (ch === '`') {
191
+ const span = codeSpanAt(s, i);
192
+ if (span) return span.end;
193
+ let n = 0;
194
+ while (s[i + n] === '`') n++;
195
+ return i + n;
196
+ }
197
+ if (ch === '<') {
198
+ if (s.startsWith('<!--', i)) return commentEnd(s, i);
199
+ // 偽註解(<?…?>、<!X…>、<![CDATA[…]]>)在網站上也是一整塊原始 HTML,不能從中間切開(例如吞掉連結的 ](網址))
200
+ const close = s.startsWith('<![CDATA[', i) ? ']]>' : s.startsWith('<?', i) ? '?>' : /^<![A-Za-z]/.test(s.slice(i, i + 3)) ? '>' : '';
201
+ if (close) {
202
+ const e = s.indexOf(close, i + 2);
203
+ if (e >= 0) return e + close.length;
204
+ }
205
+ const m = s.slice(i).match(AUTOLINK) ?? s.slice(i).match(RAW_TAG);
206
+ if (m) return i + m[0].length;
207
+ }
208
+ return -1;
209
+ }
210
+
211
+ /** 從 from 起找 mark(大小寫不分),跳過不可切開的單位;找不到回 -1。 */
212
+ function findMark(s: string, from: number, mark: string): number {
213
+ const lower = mark.toLowerCase();
214
+ for (let i = from; i < s.length; ) {
215
+ if (s.slice(i, i + mark.length).toLowerCase() === lower) return i;
216
+ const a = atomEnd(s, i);
217
+ i = a > i ? a : i + 1;
218
+ }
219
+ return -1;
220
+ }
221
+
222
+ /** 從 s[start](必須是 '[')找對應的 ']'(可巢狀,跳過程式碼、註解、跳脫),回傳位置。 */
223
+ function matchBracket(s: string, start: number): number {
224
+ let depth = 0;
225
+ for (let i = start; i < s.length; ) {
226
+ const a = i === start ? -1 : atomEnd(s, i);
227
+ if (a > i) {
228
+ i = a;
229
+ continue;
230
+ }
231
+ if (s[i] === '[') depth++;
232
+ else if (s[i] === ']') {
233
+ depth--;
234
+ if (depth === 0) return i;
235
+ }
236
+ i++;
237
+ }
238
+ return -1;
239
+ }
95
240
 
96
241
  /** 從 s[start](必須是 '(')讀一個括號平衡的網址,回傳 [網址, 下一個位置];讀不到回 null。 */
97
242
  function readParenUrl(s: string, start: number): [string, number] | null {
@@ -117,27 +262,10 @@ function readParenUrl(s: string, start: number): [string, number] | null {
117
262
  return [url, i + 1];
118
263
  }
119
264
 
120
- /** 從 s[start](必須是 '[')找對應的 ']'(可巢狀),回傳位置。 */
121
- function matchBracket(s: string, start: number): number {
122
- let depth = 0;
123
- for (let i = start; i < s.length; i++) {
124
- if (s[i] === '\\') {
125
- i++;
126
- continue;
127
- }
128
- if (s[i] === '[') depth++;
129
- else if (s[i] === ']') {
130
- depth--;
131
- if (depth === 0) return i;
132
- }
133
- }
134
- return -1;
135
- }
136
-
137
265
  function trimUrlTail(u: string): string {
138
266
  // 網址尾巴的標點不算網址
139
267
  let end = u.length;
140
- while (end > 0 && /[.,;:!?'*]/.test(u[end - 1])) end--;
268
+ while (end > 0 && /[.,;:!?'*_~\]]/.test(u[end - 1])) end--;
141
269
  // 不成對的右括號也不算
142
270
  while (end > 0 && u[end - 1] === ')') {
143
271
  const sub = u.slice(0, end);
@@ -147,7 +275,9 @@ function trimUrlTail(u: string): string {
147
275
  return u.slice(0, end);
148
276
  }
149
277
 
150
- function autolink(text: string): Inline[] {
278
+ /** 網址最後一個字是中日韓文的句讀或右括號(詳見https://….、(https://…)):多半是作者沒在網址後面空格。 */
279
+ const CJK_PUNCT_END = /[,。、;:!?)」』】》〉]$/;
280
+ function autolink(text: string, ctx?: Ctx): Inline[] {
151
281
  const out: Inline[] = [];
152
282
  let last = 0;
153
283
  for (const m of text.matchAll(URL_RE)) {
@@ -155,50 +285,132 @@ function autolink(text: string): Inline[] {
155
285
  const url = trimUrlTail(raw);
156
286
  const at = m.index ?? 0;
157
287
  if (url.length < 9) continue;
288
+ // 網址前面緊接英文字母或數字(例:abchttps://…):網站不做成連結,照字面留著
289
+ if (at > 0 && /[A-Za-z0-9]/.test(text[at - 1])) continue;
158
290
  if (at > last) out.push({ t: 'text', v: text.slice(last, at) });
159
- out.push({ t: 'link', href: url, c: [{ t: 'text', v: url }], bare: true });
291
+ // 網址緊貼全形標點(詳見https://…。、(https://…)):網站把標點算進網址(連結多半會壞),信裡照網站做,提醒作者
292
+ if (ctx && CJK_PUNCT_END.test(url)) ctx.problems.push({ code: 'url_glued_text', severity: 'warn', message: '網址後面緊貼著全形標點或文字,網站會把它們都算進網址(連結多半會壞);信裡照網站的樣子做。請在網址和後面的字之間加空格', where: clip(url) });
293
+ out.push({ t: 'link', href: encodeNonAscii(url), c: [{ t: 'text', v: url }], bare: true });
160
294
  last = at + url.length;
161
295
  }
162
296
  if (last < text.length) out.push({ t: 'text', v: text.slice(last) });
163
297
  return out.map((n) => (n.t === 'text' ? { t: 'text', v: decodeEntities(n.v) } : n));
164
298
  }
165
299
 
300
+ /** 網站會自動連結的網址(http、https、www.、email)出現在一串不含空白的字裡。 */
301
+ const URL_TAIL = /(?:https?:\/\/|www\.|[\w.+-]+@[\w-]+\.)/i;
302
+ /** 腳註標籤比對:不分大小寫,照 Unicode 的大小寫折疊(ß=ss、ς=σ)。 */
303
+ const EMAIL_TAIL = /[\w.+-]+@[\w-]+\./;
304
+ /** 一串字裡每一個網址的開頭(https://www. 只算一次)。 */
305
+ const URL_STARTS = /https?:\/\/(?:www\.)?|www\./gi;
166
306
  /**
167
- * 行內程式碼的唯一判定(解析器與註解剝除共用,兩邊不會對「哪裡是程式碼」有不同看法)。
168
- * s[i] 是一串反引號的開頭:找下一串「剛好一樣長」的反引號當收尾;空白行(段落分隔)擋住,不能跨段。
169
- * 找不到=不是程式碼(回 null,反引號當一般字元)。
307
+ * 原稿這一串(不含空白)裡有裸網址:網站的自動連結會從網址一路吞到下一個空白(中間的 [..](..)、**、反引號都吞)。
308
+ * 每一個網址都要看(不只第一個);只有信裡真的收成連結目的地的才不算——[文字](網址)、![圖](網址)、<網址>、<a href>,
309
+ * 而且那個連結在網站上也得是連結(連結文字裡又有連結時,網站不把外層當連結,外層的 ](網址) 就變成裸網址)。
310
+ * at=這一串在最外層原稿裡從哪裡開始;ctx.dest 記著這些連結目的地在最外層原稿裡的範圍。
170
311
  */
171
- export function codeSpanAt(s: string, i: number): { open: number; close: number; end: number } | null {
172
- let n = 0;
173
- while (s[i + n] === '`') n++;
174
- let j = i + n;
175
- while (j < s.length) {
176
- if (s[j] === '\n' && /^[ \t]*\n/.test(s.slice(j + 1))) return null; // 空白行=段落結束
177
- if (s[j] === '`') {
178
- let m = 0;
179
- while (s[j + m] === '`') m++;
180
- if (m === n) return { open: n, close: j, end: j + m };
181
- j += m;
182
- continue;
312
+ function bareUrlBefore(srcTail: string, at: number, ctx: Ctx): boolean {
313
+ for (const m of srcTail.matchAll(URL_STARTS)) {
314
+ const p = at + (m.index ?? 0);
315
+ if (!ctx.dest.some(([a, b]) => p >= a && p < b)) return true;
316
+ }
317
+ return false;
318
+ }
319
+ const hasLink = (ns: Inline[]): boolean => ns.some((n) => n.t === 'link' || ('c' in n && Array.isArray(n.c) && hasLink(n.c as Inline[])));
320
+ const fnLabel = (l: string) => l.toLowerCase().toUpperCase().toLowerCase();
321
+
322
+ /**
323
+ * 緊貼寫法的總檢查(判不準就擋):一串不含空白的字裡,
324
+ * ① 裸網址(http(s)://、www.)後面還緊貼著 [ * ` 這類記號(或前面緊貼實體字):網站會把它們全吞進網址,信裡卻當成語法;
325
+ * ② 出現 ![^:網站不當腳註引用;
326
+ * ③ 腳註引用前面有巢狀中括號:網站的切法判不準。
327
+ * 程式碼片段的內容先遮掉不看。
328
+ */
329
+ function gluedProblem(s: string): string | null {
330
+ let masked = '';
331
+ for (let i = 0; i < s.length; ) {
332
+ if (s[i] === '`') {
333
+ const span = codeSpanAt(s, i);
334
+ if (span) {
335
+ masked += '`' + ' '.repeat(Math.max(0, span.end - i - 2)).replace(/ /g, '\u0001') + '`';
336
+ i = span.end;
337
+ continue;
338
+ }
339
+ }
340
+ masked += s[i++];
341
+ }
342
+ for (const tok of masked.split(/\s+/)) {
343
+ if (!tok) continue;
344
+ if (tok.includes('![^')) return tok;
345
+ // 一串裡的每一個網址都要看(例:<網址>_網址**…、![圖](網址)(www.…**…),不只第一個
346
+ for (let from = 0; ; ) {
347
+ URL_STARTS.lastIndex = from;
348
+ const m = URL_STARTS.exec(tok);
349
+ if (!m) break;
350
+ const u = m.index;
351
+ // 實體字(&amp; 等)緊接網址:網站解碼後的切法跟信裡不同
352
+ if (u > 0 && /&[A-Za-z0-9#]+;$/.test(tok.slice(0, u))) return tok;
353
+ // ](網址)、<網址>、[網址](…)(網址當連結文字)、href="網址"(HTML 屬性)裡的網址不是裸網址;
354
+ // 跳過整個網址再找下一個(存檔網址 https://web.archive.org/web/…/https://… 、app.www.… 裡面的不另算)
355
+ const wrap = tok.slice(0, u).match(/(?:\]\(|<|\[|=(["']))$/);
356
+ if (wrap) {
357
+ const close = wrap[0] === '](' ? ')' : wrap[0] === '<' ? '>' : wrap[0] === '[' ? ']' : wrap[1];
358
+ const end = tok.indexOf(close, u);
359
+ if (end < 0) break;
360
+ from = end + 1;
361
+ continue;
362
+ }
363
+ // 裸網址:網站一路吞到這一串結束,後面緊貼的 [ * ` 都會被吞進去;後面的網址也在它裡面,不必再看
364
+ if (GLUE_AFTER_URL.test(tok.slice(u))) return tok;
365
+ break;
366
+ }
367
+ const f = tok.search(/\[\^[^\]\s]+\]/);
368
+ if (f > 0) {
369
+ let d = 0;
370
+ for (const ch of tok.slice(0, f)) {
371
+ if (ch === '[') d++;
372
+ else if (ch === ']') d = Math.max(0, d - 1);
373
+ if (d >= 2) return tok;
374
+ }
183
375
  }
184
- j++;
185
376
  }
186
377
  return null;
187
378
  }
379
+ // 網址本身常有 _ & ~ !(查詢字串、維基檔名),不算;只看會被信裡當成語法的 [ * `
380
+ const GLUE_AFTER_URL = /[[*`]/;
188
381
 
189
- export function parseInline(s: string, problems: Problem[], depth = 0): Inline[] {
382
+ function parseInline(s: string, ctx: Ctx, depth = 0, off = 0): Inline[] {
383
+ // off=s 在最外層原稿裡從哪裡開始(腳註、強調前面有沒有裸網址,要對照 ctx.dest 的範圍)
384
+ if (depth === 0) ctx.dest = [];
385
+ if (depth === 0 && !ctx.inLink) {
386
+ const g = gluedProblem(s);
387
+ if (g) ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '網址、腳註引用、強調記號沒有空格緊貼在一起,網站上的切法判不準;請在網址前後加空格', where: clip(g) });
388
+ }
190
389
  const out: Inline[] = [];
191
390
  let buf = '';
192
391
  const flush = () => {
193
392
  if (buf) {
194
- out.push(...autolink(buf));
393
+ // [文字](網址) 的連結文字裡,網站不再自動連結(連結裡不能有連結);<a href> 裡的網站會自動連結,照做
394
+ out.push(...(ctx.mdLink ? [{ t: 'text', v: decodeEntities(buf) } as Inline] : autolink(buf, ctx)));
195
395
  buf = '';
196
396
  }
197
397
  };
198
398
  let i = 0;
399
+ // 強調的內層:前面緊接裸網址時,網站把整串吞進網址,內層的腳註引用不算
400
+ const tailAt = () => {
401
+ const t = s.slice(0, i).match(/\S*$/)![0];
402
+ return [t, off + i - t.length] as const;
403
+ };
404
+ const inner = (from: number, to: number): Inline[] => {
405
+ const u = bareUrlBefore(...tailAt(), ctx) || URL_TAIL.test(buf.match(/\S*$/)![0]);
406
+ if (u) ctx.urlCtx++;
407
+ const r = parseInline(s.slice(from, to), ctx, depth + 1, off + from);
408
+ if (u) ctx.urlCtx--;
409
+ return r;
410
+ };
199
411
  while (i < s.length) {
200
412
  const ch = s[i];
201
- if (ch === '\\' && i + 1 < s.length && /[\\`*_{}[\]()#+\-.!|<>~]/.test(s[i + 1])) {
413
+ if (ch === '\\' && i + 1 < s.length && ESCAPABLE.test(s[i + 1])) {
202
414
  buf += s[i + 1] === '{' ? LBRACE : s[i + 1];
203
415
  i += 2;
204
416
  continue;
@@ -212,10 +424,17 @@ export function parseInline(s: string, problems: Problem[], depth = 0): Inline[]
212
424
  continue;
213
425
  }
214
426
  if (ch === '`') {
427
+ // 網址後面緊接反引號:網站會把反引號收進自動連結,程式碼的切法就跟信裡不同,判不準
428
+ if (URL_TAIL.test(buf.match(/\S*$/)![0]) || bareUrlBefore(...tailAt(), ctx)) ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '網址後面緊接反引號,網站會把反引號當成網址的一部分;請在網址和反引號之間加空格', where: clip(buf.match(/\S*$/)![0] + s.slice(i, i + 20)) });
215
429
  const span = codeSpanAt(s, i);
216
430
  if (span) {
217
431
  flush();
218
- out.push({ t: 'code', v: protectBraces(s.slice(i + span.open, span.close)) });
432
+ const raw = s.slice(i + span.open, span.close);
433
+ ctx.inCode += marks(raw);
434
+ // CommonMark:換行當空白;頭尾各有一個空白(且不全是空白)就各去掉一個
435
+ let v = raw.replace(/\n/g, ' ');
436
+ if (v.length > 2 && v.startsWith(' ') && v.endsWith(' ') && v.trim() !== '') v = v.slice(1, -1);
437
+ out.push({ t: 'code', v: protectBraces(v) });
219
438
  i = span.end;
220
439
  continue;
221
440
  }
@@ -226,25 +445,76 @@ export function parseInline(s: string, problems: Problem[], depth = 0): Inline[]
226
445
  i += n;
227
446
  continue;
228
447
  }
448
+ if (ch === '<' && s.startsWith('<!--', i)) {
449
+ const e = commentEnd(s, i);
450
+ if (e < 0) {
451
+ // 網站上這是字面文字;信裡也照原樣留著,但記 error 擋下(作者多半是忘了收尾)
452
+ ctx.problems.push(unclosedComment(s.slice(i)));
453
+ buf += '<!--';
454
+ i += 4;
455
+ continue;
456
+ }
457
+ flush(); // 註解把前後的字隔開:網址到這裡就結束,不能跟註解後面的字黏成一個網址
458
+ hideComment(s.slice(i, e), ctx);
459
+ i = e;
460
+ continue;
461
+ }
462
+ if (ch === '<' && PSEUDO_COMMENT.test(s.slice(i, i + 9))) {
463
+ flush();
464
+ ctx.problems.push({ code: 'unsupported_html', severity: 'error', message: '原稿有 <? 、<!X 或 <![CDATA[ 開頭的寫法,網站上會被當成註解藏起來,信裡做不到;請拿掉', where: clip(s.slice(i)) });
465
+ const close = s.indexOf('>', i);
466
+ const end = close < 0 ? s.length : close + 1;
467
+ ctx.hidden += marks(s.slice(i, end));
468
+ i = end;
469
+ continue;
470
+ }
229
471
  if (ch === '!' && s[i + 1] === '[') {
230
472
  const close = matchBracket(s, i + 1);
231
473
  if (close > 0 && s[close + 1] === '(') {
232
474
  const u = readParenUrl(s, close + 1);
233
475
  if (u) {
234
476
  flush();
477
+ ctx.dest.push([off + close + 1, off + u[1]]);
235
478
  out.push({ t: 'image', src: u[0], alt: s.slice(i + 2, close).replace(/\\(.)/g, '$1') });
236
479
  i = u[1];
237
480
  continue;
238
481
  }
239
482
  }
240
483
  }
484
+ // 腳註引用 [^名稱]:記下來(判斷定義有沒有被引用);字面照留。連結文字裡的引用網站不做連結,判不準,記 error
485
+ if (ch === '[') {
486
+ const fn = s.slice(i).match(/^\[\^([^\]\s\\]+)\]/);
487
+ // 接在網址後面(https://…[^1]、(www.…)[^1])的不算:網站會把整串變成自動連結(只看還沒處理的字,連結的 ](網址) 不算)
488
+ // 原稿這一串(例:*www.e.com*[^1])裡有網址、又不是 [文字](網址) 或 <網址> 收好的,也不算
489
+ const [srcTail, tailStart] = tailAt();
490
+ const inUrl = URL_TAIL.test(buf.match(/\S*$/)![0]) || bareUrlBefore(srcTail, tailStart, ctx) || (EMAIL_TAIL.test(srcTail) && !srcTail.includes('](') && !srcTail.endsWith('>'));
491
+ const isRef = fn && s[i + fn[0].length] !== '(' && s[i + fn[0].length] !== ':';
492
+ if (isRef && !inUrl && !ctx.urlCtx) {
493
+ if (!ctx.inDef) ctx.refs.add(fnLabel(fn[1]));
494
+ if (ctx.inLink) ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '連結文字裡有腳註引用,網站上不會做成連結;請把腳註移到連結外面', where: clip(fn[0]) });
495
+ } else if (isRef) {
496
+ // 網站把這個腳註引用吞進前面的網址(例:(www.…**[^1]**)、**https://…**[^1]),不顯示腳註;信裡分不出來,擋下
497
+ ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '腳註引用緊貼在網址(或包著網址的括號、強調記號)後面,網站會把它當成網址的一部分、不顯示腳註;請在網址和腳註引用之間加空格', where: clip(srcTail + fn[0]) });
498
+ }
499
+ }
241
500
  if (ch === '[' && depth < 3) {
242
501
  const close = matchBracket(s, i);
243
502
  if (close > 0 && s[close + 1] === '(') {
244
503
  const u = readParenUrl(s, close + 1);
245
504
  if (u) {
246
505
  flush();
247
- out.push({ t: 'link', href: u[0], c: parseInline(s.slice(i + 1, close), problems, depth + 1) });
506
+ ctx.inLink++;
507
+ ctx.mdLink++;
508
+ const c = parseInline(s.slice(i + 1, close), ctx, depth + 1, off + i + 1);
509
+ ctx.mdLink--;
510
+ ctx.inLink--;
511
+ // 連結文字裡又有連結:網站不把外層當連結,外層的 (網址) 是裸網址,不記成收好的目的地
512
+ if (!hasLink(c)) ctx.dest.push([off + close + 1, off + u[1]]);
513
+ else {
514
+ // 網站不把外層當連結:外層的 [、](網址) 都照字面顯示。信裡做不到一模一樣(會變成巢狀連結、少掉那幾個字),擋下。
515
+ ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '連結文字裡又有一個連結:網站不會把外層當成連結(外層的方括號與網址會照字面顯示),信裡會少字;請把裡面那個連結拿出來', where: clip(s.slice(i, u[1])) });
516
+ }
517
+ out.push({ t: 'link', href: u[0], c });
248
518
  i = u[1];
249
519
  continue;
250
520
  }
@@ -258,9 +528,10 @@ export function parseInline(s: string, problems: Problem[], depth = 0): Inline[]
258
528
  i += br[0].length;
259
529
  continue;
260
530
  }
261
- const auto = s.slice(i).match(/^<(https?:\/\/[^\s<>]+)>/i);
531
+ const auto = s.slice(i).match(AUTOLINK);
262
532
  if (auto) {
263
533
  flush();
534
+ ctx.dest.push([off + i, off + i + auto[0].length]);
264
535
  out.push({ t: 'link', href: auto[1], c: [{ t: 'text', v: auto[1] }], bare: true });
265
536
  i += auto[0].length;
266
537
  continue;
@@ -269,10 +540,14 @@ export function parseInline(s: string, problems: Problem[], depth = 0): Inline[]
269
540
  const a = s.slice(i).match(/^<a\s+([^>]*)>/i);
270
541
  if (a) {
271
542
  const href = a[1].match(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
272
- const closeAt = s.toLowerCase().indexOf('</a>', i + a[0].length);
543
+ const closeAt = findMark(s, i + a[0].length, '</a>');
273
544
  if (href && closeAt > 0) {
274
545
  flush();
275
- out.push({ t: 'link', href: decodeEntities(href[1] ?? href[2] ?? ''), c: parseInline(s.slice(i + a[0].length, closeAt), problems, depth + 1) });
546
+ ctx.dest.push([off + i, off + i + a[0].length]);
547
+ ctx.inLink++;
548
+ const c = parseInline(s.slice(i + a[0].length, closeAt), ctx, depth + 1, off + i + a[0].length);
549
+ ctx.inLink--;
550
+ out.push({ t: 'link', href: decodeEntities(href[1] ?? href[2] ?? ''), c });
276
551
  i = closeAt + 4;
277
552
  continue;
278
553
  }
@@ -281,18 +556,19 @@ export function parseInline(s: string, problems: Problem[], depth = 0): Inline[]
281
556
  const fmt = s.slice(i).match(/^<(b|strong|i|em)>/i);
282
557
  if (fmt) {
283
558
  const name = fmt[1].toLowerCase();
284
- const closeAt = s.toLowerCase().indexOf(`</${name}>`, i + fmt[0].length);
559
+ const closeAt = findMark(s, i + fmt[0].length, `</${name}>`);
285
560
  if (closeAt > 0) {
286
561
  flush();
287
- out.push({ t: name === 'b' || name === 'strong' ? 'strong' : 'em', c: parseInline(s.slice(i + fmt[0].length, closeAt), problems, depth + 1) });
562
+ out.push({ t: name === 'b' || name === 'strong' ? 'strong' : 'em', c: inner(i + fmt[0].length, closeAt) });
288
563
  i = closeAt + name.length + 3;
289
564
  continue;
290
565
  }
291
566
  }
292
- const tag = s.slice(i).match(/^<\/?[a-zA-Z][^>]*>/);
567
+ const tag = s.slice(i).match(RAW_TAG);
293
568
  if (tag) {
294
569
  flush();
295
- problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(tag[0], true) });
570
+ ctx.problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(tag[0], true) });
571
+ ctx.hidden += marks(tag[0]);
296
572
  i += tag[0].length;
297
573
  continue;
298
574
  }
@@ -300,20 +576,20 @@ export function parseInline(s: string, problems: Problem[], depth = 0): Inline[]
300
576
  if (ch === '*' && depth < 4) {
301
577
  const strong = s[i + 1] === '*';
302
578
  const mark = strong ? '**' : '*';
303
- const end = s.indexOf(mark, i + mark.length);
579
+ const end = findMark(s, i + mark.length, mark);
304
580
  if (end > i + mark.length && !/^\s/.test(s[i + mark.length]) && !/\s$/.test(s.slice(i + mark.length, end))) {
305
581
  flush();
306
- out.push({ t: strong ? 'strong' : 'em', c: parseInline(s.slice(i + mark.length, end), problems, depth + 1) });
582
+ out.push({ t: strong ? 'strong' : 'em', c: inner(i + mark.length, end) });
307
583
  i = end + mark.length;
308
584
  continue;
309
585
  }
310
586
  }
311
587
  if (ch === '_' && depth < 4) {
312
588
  const prev = s[i - 1] ?? ' ';
313
- const end = s.indexOf('_', i + 1);
589
+ const end = findMark(s, i + 1, '_');
314
590
  if (end > i + 1 && !/[A-Za-z0-9]/.test(prev) && !/\s/.test(s[i + 1]) && !/[A-Za-z0-9]/.test(s[end + 1] ?? ' ') && !/\s/.test(s[end - 1])) {
315
591
  flush();
316
- out.push({ t: 'em', c: parseInline(s.slice(i + 1, end), problems, depth + 1) });
592
+ out.push({ t: 'em', c: inner(i + 1, end) });
317
593
  i = end + 1;
318
594
  continue;
319
595
  }
@@ -326,14 +602,158 @@ export function parseInline(s: string, problems: Problem[], depth = 0): Inline[]
326
602
  }
327
603
 
328
604
  // ───────────── 區塊 ─────────────
605
+ // 照 CommonMark 的區塊規則切:先決定每一行屬於哪個區塊(程式碼框、註解區塊、段落…),區塊內容才交給行內解析。
606
+
607
+ const HR = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
608
+ const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
609
+ const SETEXT = /^ {0,3}(=+|-+)[ \t]*$/;
610
+ const QUOTE = /^ {0,3}>/;
611
+ /** HTML 註解區塊(CommonMark HTML 區塊第 2 型):行首(最多縮 3 格)是 <!--,到含 --> 的那一行結束;可以打斷段落。 */
612
+ const COMMENT_START = /^ {0,3}<!--/;
613
+ /** 會打斷段落的其他 HTML 區塊開頭(CommonMark 第 1、3~6 型)。 */
614
+ const HTML_INTERRUPT = /^ {0,3}(?:<(?:script|pre|style|textarea)(?:[\s>]|$)|<\?|<![A-Za-z]|<!\[CDATA\[|<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:[\s>]|\/>|$))/i;
615
+ const BLOCK_HTML = /^ {0,3}<\/?[a-zA-Z!]/;
616
+ /** 一行只有一個完整標籤(CommonMark HTML 區塊第 7 型):網站原樣輸出到空行為止,不轉 markdown;不能打斷段落,但會切斷懶惰續行。 */
617
+ const LONE_TAG = /^ {0,3}(?:<[A-Za-z][A-Za-z0-9-]*(?:\s+[^<>]*?)?\s*\/?>|<\/[A-Za-z][A-Za-z0-9-]*\s*>)\s*$/;
618
+ /** 瀏覽器當成註解藏起來的另外三種寫法(<?…>、<!X…>、<![CDATA[…]]>):信裡沒法照做,一律記 error。 */
619
+ const PSEUDO_COMMENT = /<(?:\?|![A-Za-z]|!\[CDATA\[)/;
620
+ /** 參照式連結定義([名稱]: 網址):網站上不顯示,信裡不支援,記 error(不然網站看不到的字會寄出去)。 */
621
+ const LINK_REF_DEF = /^ {0,3}\[(?!\^[^\]\s]+\]:)[^\]]+\]:/;
622
+ const DIV_WRAPPER = /^ {0,3}(?:<div(?:\s+lang\s*=\s*(?:"[A-Za-z-]*"|'[A-Za-z-]*'))?\s*>|<\/div\s*>)\s*$/i;
623
+ const TABLE_SEP = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
624
+ /** 懶惰續行的記號:引言或清單收進來的「沒縮排、接在段落後面」的行,在內層一律當段落續行(不能變成表頭或標題底線)。 */
625
+ const LAZY = '\uE002';
626
+
627
+ /*
628
+ * tab 的欄位:CommonMark 的 tab 是跳到「絕對欄位」4 的倍數。引言、清單裡的行拿掉外層記號後,行首不再是第 0 欄,
629
+ * 所以下面幾個函式都帶 col=這一行在原稿裡從第幾欄開始。只在判斷「縮了幾格、是什麼區塊」時換算;
630
+ * 程式碼內容一律從原行切出來,裡面的 tab 原樣保留(不然 Go、Makefile 的 tab 會被悄悄換成空白)。
631
+ */
632
+ /** 行首縮排的欄數。 */
633
+ function indentCols(line: string, col = 0): number {
634
+ let c = col;
635
+ for (const ch of line) {
636
+ if (ch === ' ') c++;
637
+ else if (ch === '\t') c += 4 - (c % 4);
638
+ else break;
639
+ }
640
+ return c - col;
641
+ }
642
+
643
+ /** 去掉行首最多 n 欄的空白(tab 跨過界線時,剩下的欄數補成空白)。 */
644
+ function stripCols(line: string, n: number, col = 0): string {
645
+ let c = col;
646
+ let i = 0;
647
+ while (i < line.length && c < col + n) {
648
+ if (line[i] === ' ') {
649
+ c++;
650
+ i++;
651
+ } else if (line[i] === '\t') {
652
+ const w = 4 - (c % 4);
653
+ if (c + w > col + n) return ' '.repeat(c + w - col - n) + line.slice(i + 1);
654
+ c += w;
655
+ i++;
656
+ } else break;
657
+ }
658
+ return line.slice(i);
659
+ }
660
+
661
+ /** 拿掉行首 n 欄時,拿掉的部分有沒有碰到 tab(剩下的 tab 屬於內容,不算)。 */
662
+ function consumedHasTab(line: string, n: number, col = 0): boolean {
663
+ if (line.startsWith(LAZY)) line = line.slice(1);
664
+ let c = col;
665
+ for (let i = 0; i < line.length && c < col + n; i++) {
666
+ if (line[i] === ' ') c++;
667
+ else if (line[i] === '\t') return true;
668
+ else break;
669
+ }
670
+ return false;
671
+ }
672
+
673
+ /** 縮排不到 4 欄(不是程式碼)的行:行首空白換成等寬的空格,給只認空格的區塊判斷用。 */
674
+ function normLead(line: string, col: number): string {
675
+ if (line.startsWith(LAZY)) return line;
676
+ const lead = line.match(/^[ \t]*/)![0];
677
+ if (!lead.includes('\t')) return line;
678
+ const k = indentCols(line, col);
679
+ return k >= 4 ? line : ' '.repeat(k) + line.slice(lead.length);
680
+ }
681
+
682
+ /** 拿掉一行引言記號 >(和它後面可省略的一格;後面是 tab 時只吃掉一欄)。qcol=引言內層的起始欄(第一行的);p=這一行自己的。 */
683
+ function stripQuote(line: string, col: number, qcol: number): { rest: string; p: number; ambiguous: boolean } {
684
+ const m = line.match(/^( {0,3})>/)!;
685
+ let rest = line.slice(m[0].length);
686
+ let p = col + m[1].length + 1;
687
+ if (rest[0] === ' ') {
688
+ rest = rest.slice(1);
689
+ p++;
690
+ } else if (rest[0] === '\t') {
691
+ rest = ' '.repeat(3 - (p % 4)) + rest.slice(1);
692
+ p++;
693
+ }
694
+ // 這一行內層起點跟其他行不同(> 前面縮排不一樣)而行首還有 tab:照它自己的欄位換成空格,免得對不齊
695
+ if (p !== qcol && /^[ ]*\t/.test(rest)) {
696
+ const lead = rest.match(/^[ \t]*/)![0];
697
+ rest = ' '.repeat(indentCols(rest, p)) + rest.slice(lead.length);
698
+ }
699
+ // 起點不同、而結構前綴(清單記號、> 之後)裡還有 tab:欄位換算判不準,交給呼叫端記 error
700
+ // > 後面是 tab、換算後縮到 4 欄以上又像表格分隔列:網站的引擎會把 tab 整個吃掉照樣排表格,也判不準
701
+ const tabSep = line.slice(m[0].length).startsWith('\t') && indentCols(rest, p) >= 4 && TABLE_SEP.test(rest.trim()) && rest.includes('|');
702
+ const ambiguous = tabSep || (p !== qcol && /^(?:[ \t]*(?:>|[-*+]|\d{1,9}[.)])(?=[ \t]|$))*[ \t]*/.exec(rest)![0].includes('\t'));
703
+ return { rest, p, ambiguous };
704
+ }
705
+
706
+ /** 表格分隔列前面是 tab、換算後剛好縮到 4 欄以上:網站的引擎在引言裡會把 tab 吃掉照樣排表格,排法判不準,記 error。 */
707
+ function tabTableAmbiguous(line: string, next: string | undefined, col: number): boolean {
708
+ if (next === undefined || line.trim() === '' || next.startsWith(LAZY) || line.startsWith(LAZY)) return false;
709
+ const lead = next.match(/^[ \t]*/)![0];
710
+ if (!lead.includes('\t') || indentCols(next, col) < 4) return false;
711
+ const t = next.trim();
712
+ return TABLE_SEP.test(t) && t.includes('|') && splitRow(line).length === splitRow(t).length;
713
+ }
714
+
715
+ interface Fence {
716
+ indent: number;
717
+ ch: string;
718
+ len: number;
719
+ info: string;
720
+ }
721
+ /** 程式碼框開頭:最多縮 3 格、3 個以上 ` 或 ~;反引號框的說明文字裡不能有反引號(不然那是行內程式碼)。 */
722
+ function fenceOpen(line: string): Fence | null {
723
+ const m = line.match(/^( {0,3})(`{3,}|~{3,})(.*)$/);
724
+ if (!m || (m[2][0] === '`' && m[3].includes('`'))) return null;
725
+ return { indent: m[1].length, ch: m[2][0], len: m[2].length, info: m[3].trim() };
726
+ }
727
+ /** 程式碼框收尾:同一種記號、至少一樣長、最多縮 3 格、後面只能有空白。 */
728
+ function fenceCloses(line: string, f: Fence): boolean {
729
+ const m = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);
730
+ return !!m && m[1][0] === f.ch && m[1].length >= f.len;
731
+ }
329
732
 
330
- const FENCE = /^\s{0,3}(```|~~~)/;
331
- const LOOSE_FENCE = /^[\s>]*(```|~~~)/;
332
- const HR = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
333
- const HEADING = /^\s{0,3}(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/;
334
- const QUOTE = /^\s{0,3}>/;
335
- const LIST_ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
336
- const TABLE_SEP = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/;
733
+ interface Marker {
734
+ ordered: boolean;
735
+ kind: string;
736
+ start: number;
737
+ /** 項目內容的縮排欄數(後續行要縮到這裡才屬於本項)。 */
738
+ content: number;
739
+ first: string;
740
+ empty: boolean;
741
+ }
742
+ function listMarker(line: string, col = 0): Marker | null {
743
+ if (HR.test(line)) return null;
744
+ const m = line.match(/^( {0,3})([-*+]|(\d{1,9})([.)]))(?=[ \t]|$)([ \t]*)(.*)$/);
745
+ if (!m) return null;
746
+ const ordered = m[3] !== undefined;
747
+ const at = m[1].length + m[2].length;
748
+ let spaces = 0;
749
+ for (const ch of m[5]) spaces += ch === '\t' ? 4 - ((col + at + spaces) % 4) : 1;
750
+ const empty = m[6].trim() === '';
751
+ const base = { ordered, kind: ordered ? m[4] : m[2], start: ordered ? Number(m[3]) : 0, empty };
752
+ if (empty) return { ...base, content: at + 1, first: '' };
753
+ // 記號後空 5 欄以上=內容是縮排程式碼:只拿掉一欄,剩下的空白(含 tab)原樣留給程式碼
754
+ if (spaces >= 5) return { ...base, content: at + 1, first: stripCols(m[5] + m[6], 1, col + at) };
755
+ return { ...base, content: at + spaces, first: m[6] };
756
+ }
337
757
 
338
758
  function splitRow(line: string): string[] {
339
759
  let t = line.trim();
@@ -354,36 +774,192 @@ function splitRow(line: string): string[] {
354
774
  return cells;
355
775
  }
356
776
 
357
- function isBlockStart(line: string, next: string | undefined): boolean {
358
- return FENCE.test(line) || HR.test(line) || HEADING.test(line) || QUOTE.test(line) || LIST_ITEM.test(line) || (line.includes('|') && next !== undefined && TABLE_SEP.test(next) && line.trim() !== '');
777
+ /** 表格開頭:這一行+下一行是分隔列(要有 |、格數相同)。兩行都不能縮 4 欄以上,也不能本身是清單項目、標題、引言(那些先成立)。 */
778
+ function isTableStart(line: string, next: string | undefined, col = 0): boolean {
779
+ if (next === undefined || line.trim() === '' || next.startsWith(LAZY)) return false;
780
+ line = normLead(line, col);
781
+ next = normLead(next, col);
782
+ if (indentCols(line) >= 4 || indentCols(next) >= 4) return false;
783
+ if (listMarker(line, col) || listMarker(next, col) || ATX.test(line) || QUOTE.test(line) || QUOTE.test(next) || fenceOpen(line)) return false;
784
+ return TABLE_SEP.test(next) && next.includes('|') && splitRow(line).length === splitRow(next).length;
785
+ }
786
+
787
+ /** 這一行能不能打斷同一層正在進行的段落(CommonMark 的規則:有序清單要從 1 開始、空項目不行、縮 4 格以上不行)。 */
788
+ function interrupts(line: string, next: string | undefined, tables = true, col = 0): boolean {
789
+ if (indentCols(line, col) >= 4) return false;
790
+ line = normLead(line, col);
791
+ if (fenceOpen(line) || HR.test(line) || ATX.test(line) || QUOTE.test(line) || COMMENT_START.test(line) || HTML_INTERRUPT.test(line)) return true;
792
+ const lm = listMarker(line, col);
793
+ if (lm && !lm.empty && (!lm.ordered || lm.start === 1)) return true;
794
+ return tables && isTableStart(line, next, col);
795
+ }
796
+
797
+ /** 懶惰續行(引言、清單裡沒縮排的下一行):只有「內層最後是一個還開著的段落」才接得上;任何清單項目、區塊開頭都會斷開(表格不會:那時表頭只是段落續行)。 */
798
+ function lazyBreaks(line: string, col = 0): boolean {
799
+ if (indentCols(line, col) >= 4) return false;
800
+ line = normLead(line, col);
801
+ return !!fenceOpen(line) || HR.test(line) || ATX.test(line) || QUOTE.test(line) || COMMENT_START.test(line) || HTML_INTERRUPT.test(line) || LONE_TAG.test(line) || listMarker(line, col) !== null;
802
+ }
803
+
804
+ /** 註解區塊收尾那一行,--> 後面剩下的字(網站上原樣當 HTML 顯示):再藏掉裡面的註解,其他照字面留著。 */
805
+ function rawTail(rest: string, ctx: Ctx): Block | null {
806
+ let out = '';
807
+ let pos = 0;
808
+ while (pos < rest.length) {
809
+ const c = rest.indexOf('<!--', pos);
810
+ if (c < 0) {
811
+ out += rest.slice(pos);
812
+ break;
813
+ }
814
+ out += rest.slice(pos, c);
815
+ const e = commentEnd(rest, c);
816
+ if (e < 0) {
817
+ ctx.problems.push(unclosedComment(rest.slice(c)));
818
+ out += rest.slice(c);
819
+ break;
820
+ }
821
+ hideComment(rest.slice(c, e), ctx);
822
+ pos = e;
823
+ }
824
+ if (PSEUDO_COMMENT.test(out)) ctx.problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(out.match(PSEUDO_COMMENT)![0], false) });
825
+ const tag = out.match(/<\/?[a-zA-Z][^>]*>/) ?? out.match(/<[A-Za-z/!?][^\s>]*/); // 沒收尾的 <字母 也算:瀏覽器會把後面整段吞成標籤
826
+ if (tag) ctx.problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(tag[0], false) });
827
+ const v = decodeEntities(out.trim());
828
+ return v ? { t: 'p', c: [{ t: 'text', v }] } : null;
829
+ }
830
+
831
+ /** 腳註定義(合格的單行寫法、任何寫法、內容是區塊寫法)。 */
832
+ const FN_DEF = /^\[\^([^\]\s\\]+)\]:/;
833
+ const FN_DEF_ANY = /^ {0,3}\[\^[^\]]*\]:/;
834
+ const FN_DEF_BLOCK = /^(?:\s{4,}\S|\s*<|\s*\[[^\]]*\]:|\s*(?:>|[-*+](?:\s|$)|\d{1,9}[.)](?:\s|$)|`{3,}|~{3,}|#{1,6}(?:\s|$)|\|))/;
835
+
836
+ /** 段落:從 lines[start] 收到空行或能打斷段落的行為止;下一行是 === 或 --- =標題(setext)。回傳下一個要看的行。 */
837
+ function paragraph(lines: string[], start: number, ctx: Ctx, blocks: Block[], col: number): number {
838
+ const n = lines.length;
839
+ const unlazy = (l: string) => (l.startsWith(LAZY) ? l.slice(1) : l);
840
+ const para: string[] = [unlazy(lines[start])];
841
+ const raw: string[] = [lines[start]];
842
+ let i = start + 1;
843
+ let setext = 0;
844
+ let tabTable = false;
845
+ while (i < n) {
846
+ const l = lines[i];
847
+ if (l.trim() === '') break;
848
+ if (tabLead(l)) noteTab(ctx, l);
849
+ if (tabTableAmbiguous(lines[i - 1], l, col)) tabTable = true;
850
+ if (!l.startsWith(LAZY)) {
851
+ const sx = indentCols(l, col) < 4 ? normLead(l, col).match(SETEXT) : null;
852
+ if (sx) {
853
+ setext = sx[1][0] === '=' ? 1 : 2;
854
+ i++;
855
+ break;
856
+ }
857
+ if (interrupts(l, lines[i + 1], true, col) || (BLOCK_HTML.test(normLead(l, col)) && EMBED_TAG.test(l))) break;
858
+ }
859
+ para.push(unlazy(l));
860
+ raw.push(l);
861
+ i++;
862
+ }
863
+ if (tabTable) ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '表格分隔列前面用 tab 縮排,網站上的排法判不準;請改用空格或不縮排', where: clip(para[0]) });
864
+ // 腳註定義:只有「最外層、從第 0 欄寫起、整段每一行都是單行定義、內容不是區塊寫法、不是標題」判得準
865
+ const isDef = (l: string) => FN_DEF.test(l) && !FN_DEF_BLOCK.test(l.replace(FN_DEF, ''));
866
+ const defLike = para.some((l) => FN_DEF_ANY.test(l));
867
+ let def = false;
868
+ if (defLike) {
869
+ // 後面要接空行或文末:被別的區塊(表格、清單…)打斷時,網站會把那個區塊也收進腳註
870
+ if (col === 0 && !setext && (i >= n || lines[i].trim() === '') && raw.every((l) => !l.startsWith(LAZY) && isDef(l))) {
871
+ def = true;
872
+ for (const l of raw) ctx.defs.push(fnLabel(l.match(FN_DEF)![1]));
873
+ } else ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '腳註定義要從行首寫起、前面空一行、一則一行(不能縮排、不能放在引言或清單裡、不能接在段落後面或變成標題,內容不能是清單、引言、程式碼);不然網站上的顯示判不準', where: clip(para.find((l) => FN_DEF_ANY.test(l))!) });
874
+ }
875
+ ctx.inDef = def;
876
+ // 連續的腳註定義在網站上是各自獨立的一則:一行一行分開轉(行內程式碼不能跨到下一則)
877
+ const inline: Inline[] = def ? para.flatMap((l, k) => [...(k ? [{ t: 'br' } as Inline] : []), ...parseInline(l.trim(), ctx)]) : parseInline(para.join('\n').trim(), ctx);
878
+ ctx.inDef = false;
879
+ if (def) ctx.lastDefEnd = i;
880
+ if (setext) blocks.push({ t: 'h', level: setext, c: inline });
881
+ // 整段只有一張圖(或一個包著圖的連結)=圖片區塊
882
+ else if (inline.length === 1 && inline[0].t === 'image') blocks.push({ t: 'image', src: inline[0].src, alt: inline[0].alt });
883
+ else if (inline.length === 1 && inline[0].t === 'link' && inline[0].c.length === 1 && inline[0].c[0].t === 'image') {
884
+ const img = inline[0].c[0];
885
+ blocks.push({ t: 'image', src: img.src, alt: img.alt, link: inline[0] });
886
+ } else blocks.push({ t: 'p', c: inline });
887
+ return i;
359
888
  }
360
889
 
361
- function parseBlocks(lines: string[], problems: Problem[]): Block[] {
890
+ /** 把一個容器(整份原稿、引言內層、清單項目)的行切成區塊。open=最後一個區塊是還開著的段落(給懶惰續行判斷)。 */
891
+ /**
892
+ * restrictFirst=第一行是「打斷段落的那一行」開出來的內層(例:段落下一行的「- 2. …」):
893
+ * 網站的規則是打斷段落時,不是從 1 開始的有序清單、空的清單項目都不成立,這個限制要一路帶進同一行開的內層容器。
894
+ */
895
+ function parseBlocks(lines: string[], ctx: Ctx, col = 0, restrictFirst = false): { blocks: Block[]; open: boolean } {
362
896
  const blocks: Block[] = [];
897
+ const n = lines.length;
898
+ let open = false;
899
+ // 沒收尾的註解區塊:CommonMark 裡它一路延伸到容器結尾,所以容器最後不是「開著的段落」,懶惰續行接不上
900
+ let unclosedHtml = false;
901
+ // 上一個區塊是縮排程式碼:網站的引擎在它後面不認「不是從 1 開始的有序清單」,當成段落(照網站做)
902
+ let afterIndentedCode = false;
903
+ // 上一個段落結束在哪一行(那一行若開了清單或引言=打斷段落)
904
+ let paraEnd = -1;
363
905
  let i = 0;
364
- while (i < lines.length) {
365
- const line = lines[i];
906
+ while (i < n) {
907
+ const line = normLead(lines[i], col);
908
+ open = false;
366
909
  if (line.trim() === '') {
367
910
  i++;
368
911
  continue;
369
912
  }
913
+ const prevIndentedCode = afterIndentedCode;
914
+ afterIndentedCode = false;
915
+ // 行首結構用 tab:縮排程式碼只看拿掉的那 4 欄,其他行看整段行首空白
916
+ if (indentCols(lines[i], col) >= 4 ? consumedHasTab(lines[i], 4, col) : tabLead(lines[i])) noteTab(ctx, lines[i]);
917
+ // 腳註定義後面空行、再接縮 4 欄的行:網站上那是腳註的續段(多段腳註),判不準
918
+ if (col === 0 && ctx.lastDefEnd >= 0 && i > ctx.lastDefEnd && lines.slice(ctx.lastDefEnd, i).every((l) => l.trim() === '') && indentCols(lines[i]) >= 1) {
919
+ ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '腳註定義後面接了縮排的行(可能是多段腳註),網站上的顯示判不準;請把腳註寫成一則一行、後面的段落不要縮排', where: clip(lines[i]) });
920
+ }
921
+ if (line.startsWith(LAZY)) {
922
+ i = paragraph(lines, i, ctx, blocks, col);
923
+ if (blocks[blocks.length - 1]?.t === 'p') paraEnd = i;
924
+ open = i >= n;
925
+ continue;
926
+ }
927
+ const interrupting = i === paraEnd || (restrictFirst && i === 0);
928
+ // 縮排 4 格以上=程式碼(段落中間的縮排行不算,那是段落續行)
929
+ if (indentCols(lines[i], col) >= 4) {
930
+ const body: string[] = [];
931
+ while (i < n && (lines[i].trim() === '' || indentCols(lines[i], col) >= 4)) {
932
+ if (consumedHasTab(lines[i], 4, col)) noteTab(ctx, lines[i]);
933
+ body.push(stripCols(lines[i++], 4, col));
934
+ }
935
+ while (body.length && body[body.length - 1].trim() === '') body.pop();
936
+ const v = body.join('\n');
937
+ ctx.inCode += marks(v);
938
+ blocks.push({ t: 'code', v: protectBraces(v) });
939
+ afterIndentedCode = true;
940
+ continue;
941
+ }
370
942
  // 圍欄程式碼
371
- const fence = line.match(FENCE);
943
+ const fence = fenceOpen(line);
372
944
  if (fence) {
373
- const mark = fence[1];
374
- const lang = line.trim().slice(mark.length).trim().toLowerCase();
375
945
  const body: string[] = [];
376
- const start = line;
377
946
  i++;
378
- while (i < lines.length && !lines[i].trim().startsWith(mark)) body.push(lines[i++]);
379
- if (i >= lines.length) {
380
- // 沒收尾的程式碼框:不猜,後面的內容會被整段吃掉,所以直接記 error
381
- problems.push({ code: 'unclosed_fence', severity: 'error', message: '程式碼框(```)沒有收尾,後面的內容會被吃掉', where: clip(start) });
947
+ let closed = false;
948
+ while (i < n) {
949
+ if (fenceCloses(normLead(lines[i], col), fence)) {
950
+ closed = true;
951
+ i++;
952
+ break;
953
+ }
954
+ body.push(stripCols(lines[i++], fence.indent, col));
382
955
  }
383
- i++;
956
+ // 沒收尾的程式碼框:網站上它會把後面整段都變成程式碼,所以記 error
957
+ if (!closed) ctx.problems.push({ code: 'unclosed_fence', severity: 'error', message: '程式碼框(```)沒有收尾,後面的內容會被吃掉', where: clip(line) });
958
+ const v = body.join('\n');
959
+ ctx.inCode += marks(v);
384
960
  // 圖表(mermaid)信裡畫不出來:換成「到網站看」連結卡
385
- if (lang === 'mermaid') blocks.push({ t: 'embed' });
386
- else blocks.push({ t: 'code', v: protectBraces(body.join('\n')) });
961
+ if (fence.info.split(/\s+/)[0].toLowerCase() === 'mermaid') blocks.push({ t: 'embed' });
962
+ else blocks.push({ t: 'code', v: protectBraces(v) });
387
963
  continue;
388
964
  }
389
965
  if (HR.test(line)) {
@@ -391,234 +967,207 @@ function parseBlocks(lines: string[], problems: Problem[]): Block[] {
391
967
  i++;
392
968
  continue;
393
969
  }
394
- const h = line.match(HEADING);
970
+ const h = line.match(ATX);
395
971
  if (h) {
396
- blocks.push({ t: 'h', level: h[1].length, c: parseInline(h[2], problems) });
972
+ blocks.push({ t: 'h', level: h[1].length, c: parseInline(h[2] ?? '', ctx) });
397
973
  i++;
398
974
  continue;
399
975
  }
400
- // 只有 <div> 、<div lang="…"> 或 </div> 的行(語言標記的外框;帶 hidden/style 等其他屬性的 div 不收):外框丟掉,裡面的內容照常轉
401
- if (/^\s*(?:<div(?:\s+lang\s*=\s*(?:"[A-Za-z-]*"|'[A-Za-z-]*'))?\s*>|<\/div\s*>)\s*$/i.test(line)) {
976
+ // HTML 註解區塊:到含 --> 的那一行為止整段藏起來(中間的空行也算在內)
977
+ if (COMMENT_START.test(line)) {
978
+ const col = line.indexOf('<!--');
979
+ let j = i;
980
+ let close = line.indexOf('-->', col + 2);
981
+ while (close < 0 && j + 1 < n) close = lines[++j].indexOf('-->');
982
+ if (close < 0) {
983
+ // 沒收尾:只拿掉開頭這一行,後面照常轉(內容不能被吃掉),並記 error 擋下
984
+ ctx.problems.push(unclosedComment(line));
985
+ unclosedHtml = true;
986
+ i++;
987
+ continue;
988
+ }
989
+ const text = j === i ? line.slice(col, close + 3) : [line.slice(col), ...lines.slice(i + 1, j), lines[j].slice(0, close + 3)].join('\n');
990
+ hideComment(text, ctx);
991
+ const tail = rawTail((j === i ? line : lines[j]).slice(close + 3), ctx); // 同一行收尾時用換算過 tab 的那一行,位置才對得上
992
+ if (tail) blocks.push(tail);
993
+ i = j + 1;
994
+ continue;
995
+ }
996
+ // 只有 <div> 、<div lang="…"> 或 </div> 的行(語言標記的外框;帶 hidden/style 等其他屬性的 div 不收),而且下一行是空行:
997
+ // 外框丟掉,裡面的內容照常轉。下一行不是空行時,網站會把接著的幾行當原始 HTML(不轉 markdown),所以走下面的 HTML 區塊。
998
+ if (DIV_WRAPPER.test(line) && (i + 1 >= n || lines[i + 1].trim() === '')) {
402
999
  i++;
403
1000
  continue;
404
1001
  }
1002
+ if (LINK_REF_DEF.test(line)) {
1003
+ const start = line;
1004
+ while (i < n && lines[i].trim() !== '') ctx.hidden += marks(lines[i++]);
1005
+ ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '原稿有參照式連結定義([名稱]: 網址),網站上不顯示、信裡不支援;請改成一般的 [文字](網址)', where: clip(start) });
1006
+ continue;
1007
+ }
405
1008
  // 自訂區塊語法(:::note 之類)
406
1009
  if (line.trim().startsWith(':::')) {
407
1010
  const start = line;
408
- while (i < lines.length && lines[i].trim() !== '') i++;
409
- problems.push({ code: 'unsupported_syntax', severity: 'error', message: '原稿有信件轉不了的區塊語法', where: clip(start) });
1011
+ while (i < n && lines[i].trim() !== '') ctx.hidden += marks(lines[i++]);
1012
+ ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '原稿有信件轉不了的區塊語法', where: clip(start) });
410
1013
  continue;
411
1014
  }
412
1015
  // 區塊 HTML
413
- if (BLOCK_HTML.test(line) && ANY_TAG.test(line) && !INLINE_START.test(line)) {
1016
+ if ((BLOCK_HTML.test(line) && ANY_TAG.test(line) && !INLINE_START.test(line)) || LONE_TAG.test(line) || /^ {0,3}<(?:\?|![A-Za-z]|!\[CDATA\[)/.test(line)) {
414
1017
  const start = line;
415
- const chunk: string[] = [];
416
- while (i < lines.length && lines[i].trim() !== '') chunk.push(lines[i++]);
1018
+ while (i < n && lines[i].trim() !== '') ctx.hidden += marks(lines[i++]);
417
1019
  if (EMBED_TAG.test(start)) {
418
1020
  blocks.push({ t: 'embed' });
419
1021
  } else {
420
- problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(start.trim().match(/^<\/?[a-zA-Z!][^>]*>?/)?.[0] ?? start, false) });
1022
+ ctx.problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(start.trim().match(/^<\/?[a-zA-Z!][^>]*>?/)?.[0] ?? start, false) });
421
1023
  }
422
1024
  continue;
423
1025
  }
424
1026
  if (QUOTE.test(line)) {
425
1027
  const inner: string[] = [];
426
- while (i < lines.length && (QUOTE.test(lines[i]) || (lines[i].trim() !== '' && inner.length > 0 && !isBlockStart(lines[i], lines[i + 1])))) {
427
- inner.push(lines[i].replace(/^\s{0,3}> ?/, ''));
428
- i++;
1028
+ const qcol = stripQuote(line, col, -1).p;
1029
+ let ambiguous = false;
1030
+ while (i < n) {
1031
+ const l = normLead(lines[i], col);
1032
+ if (QUOTE.test(l)) {
1033
+ if (tabLead(lines[i]) || /^ {0,3}>\t/.test(l)) noteTab(ctx, lines[i]);
1034
+ const q = stripQuote(l, col, qcol);
1035
+ if (q.rest.trim() === '' && l.includes('\t')) noteTab(ctx, lines[i]); // 只有空白的引言行裡有 tab
1036
+ if (q.ambiguous) ambiguous = true;
1037
+ inner.push(q.rest);
1038
+ i++;
1039
+ continue;
1040
+ }
1041
+ if (l.trim() !== '' && inner.length > 0 && !lazyBreaks(l, col) && parseBlocks(inner, scratch(), qcol, interrupting).open) {
1042
+ if (tabLead(lines[i])) noteTab(ctx, lines[i]);
1043
+ inner.push(l.startsWith(LAZY) ? l : LAZY + l);
1044
+ i++;
1045
+ continue;
1046
+ }
1047
+ break;
429
1048
  }
430
- blocks.push({ t: 'quote', c: parseBlocks(inner, problems) });
1049
+ if (ambiguous) ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '引言裡 > 後面用 tab 縮排(或有的接空格、有的沒有),網站上的排法判不準;請統一寫成「> 」並改用空格', where: clip(line) });
1050
+ const r = parseBlocks(inner, ctx, qcol, interrupting);
1051
+ blocks.push({ t: 'quote', c: r.blocks });
1052
+ open = r.open && i >= n;
431
1053
  continue;
432
1054
  }
433
- if (line.includes('|') && i + 1 < lines.length && TABLE_SEP.test(lines[i + 1])) {
1055
+ if (isTableStart(line, lines[i + 1], col)) {
434
1056
  const head = splitRow(line);
435
1057
  const align = splitRow(lines[i + 1]).map((c) => (/^:-+:$/.test(c) ? 'center' : /^-+:$/.test(c) ? 'right' : /^:-+$/.test(c) ? 'left' : null));
436
1058
  i += 2;
437
1059
  const rows: Inline[][][] = [];
438
- while (i < lines.length && lines[i].trim() !== '' && lines[i].includes('|')) {
1060
+ // 表格不是段落:任何清單項目(不從 1 開始、空項目也算)都會結束表格
1061
+ while (i < n && lines[i].trim() !== '' && indentCols(lines[i], col) < 4 && !lines[i].startsWith(LAZY) && !interrupts(lines[i], lines[i + 1], false, col) && !listMarker(normLead(lines[i], col), col)) {
1062
+ if (tabLead(lines[i])) noteTab(ctx, lines[i]);
1063
+ if (FN_DEF_ANY.test(normLead(lines[i], col))) ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '表格裡有腳註定義,網站上的顯示判不準', where: clip(lines[i]) });
439
1064
  const cells = splitRow(lines[i++]);
440
1065
  while (cells.length < head.length) cells.push('');
441
- rows.push(cells.slice(0, head.length).map((c) => parseInline(c, problems)));
1066
+ for (const extra of cells.slice(head.length)) ctx.hidden += marks(extra); // 多出來的格子網站上也不顯示(表格裡再出現像表頭的兩行,也只是一般的列)
1067
+ rows.push(cells.slice(0, head.length).map((c) => parseInline(c, ctx)));
442
1068
  }
443
- blocks.push({ t: 'table', head: head.map((c) => parseInline(c, problems)), align, rows });
1069
+ blocks.push({ t: 'table', head: head.map((c) => parseInline(c, ctx)), align, rows });
444
1070
  continue;
445
1071
  }
446
- const li = line.match(LIST_ITEM);
447
- if (li) {
448
- const base = li[1].length;
449
- const ordered = /\d/.test(li[2][0]);
1072
+ const lm = listMarker(line, col);
1073
+ const restricted = prevIndentedCode || interrupting;
1074
+ const first = lm && !(restricted && ((lm.ordered && lm.start !== 1) || lm.empty)) ? lm : null;
1075
+ if (first) {
450
1076
  const items: Block[][] = [];
451
- while (i < lines.length) {
452
- const m = lines[i].match(LIST_ITEM);
453
- if (!m || m[1].length !== base || /\d/.test(m[2][0]) !== ordered) break;
454
- const itemLines: string[] = [m[3]];
1077
+ let cur = first;
1078
+ while (true) {
1079
+ // 清單記號後面用 tab
1080
+ if (/^ {0,3}(?:[-*+]|\d{1,9}[.)])[ ]*\t/.test(normLead(lines[i], col))) noteTab(ctx, lines[i]);
1081
+ const itemLines: string[] = [cur.first];
455
1082
  i++;
456
- const contentIndent = base + m[2].length + 1;
457
- while (i < lines.length) {
1083
+ while (i < n) {
458
1084
  const l = lines[i];
459
1085
  if (l.trim() === '') {
460
- // 空行後若仍是縮排內容,屬於本項
1086
+ // 空行之後若還有縮排到項目內容的行,屬於本項(項目最多只能以一個空行開頭)
461
1087
  let j = i;
462
- while (j < lines.length && lines[j].trim() === '') j++;
463
- if (j < lines.length && /^\s+\S/.test(lines[j]) && lines[j].search(/\S/) > base) {
1088
+ while (j < n && lines[j].trim() === '') j++;
1089
+ const startsBlank = itemLines.length === 1 && itemLines[0] === '';
1090
+ if (j < n && indentCols(lines[j], col) >= cur.content && !startsBlank) {
464
1091
  for (; i < j; i++) itemLines.push('');
465
1092
  continue;
466
1093
  }
467
1094
  break;
468
1095
  }
469
- const sub = l.match(LIST_ITEM);
470
- if (sub && sub[1].length <= base) break;
471
- if (sub || /^\s+\S/.test(l)) {
472
- itemLines.push(l.slice(Math.min(contentIndent, l.search(/\S/))));
1096
+ if (indentCols(l, col) >= cur.content) {
1097
+ if (consumedHasTab(l, cur.content, col)) noteTab(ctx, l);
1098
+ itemLines.push(stripCols(l, cur.content, col));
473
1099
  i++;
474
- } else if (!isBlockStart(l, lines[i + 1])) {
475
- itemLines.push(l); // 懶惰續行
1100
+ continue;
1101
+ }
1102
+ if (!lazyBreaks(l, col) && parseBlocks(itemLines, scratch(), col + cur.content, interrupting && items.length === 0).open) {
1103
+ if (tabLead(l)) noteTab(ctx, l);
1104
+ itemLines.push(l.startsWith(LAZY) ? l : LAZY + l); // 懶惰續行
476
1105
  i++;
477
- } else break;
1106
+ continue;
1107
+ }
1108
+ break;
478
1109
  }
479
- items.push(parseBlocks(itemLines, problems));
480
- // 項目之間的空行
1110
+ const r = parseBlocks(itemLines, ctx, col + cur.content, interrupting && items.length === 0);
1111
+ items.push(r.blocks);
1112
+ open = r.open && i >= n;
1113
+ // 下一個同類的清單記號=同一張清單的下一項(中間可以有空行)
481
1114
  let j = i;
482
- while (j < lines.length && lines[j].trim() === '') j++;
483
- if (j < lines.length && lines[j].match(LIST_ITEM)?.[1].length === base) i = j;
484
- else break;
1115
+ while (j < n && lines[j].trim() === '') j++;
1116
+ const next = j < n ? listMarker(normLead(lines[j], col), col) : null;
1117
+ if (next && next.ordered === first.ordered && next.kind === first.kind) {
1118
+ i = j;
1119
+ cur = next;
1120
+ open = false;
1121
+ continue;
1122
+ }
1123
+ break;
485
1124
  }
486
- blocks.push({ t: 'list', ordered, items });
1125
+ blocks.push(first.ordered && first.start !== 1 ? { t: 'list', ordered: true, start: first.start, items } : { t: 'list', ordered: first.ordered, items });
487
1126
  continue;
488
1127
  }
489
1128
  // 段落
490
- const para: string[] = [];
491
- while (i < lines.length && lines[i].trim() !== '' && (para.length === 0 || !isBlockStart(lines[i], lines[i + 1])) && !(para.length > 0 && BLOCK_HTML.test(lines[i]) && EMBED_TAG.test(lines[i]))) {
492
- para.push(lines[i++]);
493
- }
494
- const inline = parseInline(para.join('\n').trim(), problems);
495
- // 整段只有一張圖(或一個包著圖的連結)=圖片區塊
496
- if (inline.length === 1 && inline[0].t === 'image') blocks.push({ t: 'image', src: inline[0].src, alt: inline[0].alt });
497
- else if (inline.length === 1 && inline[0].t === 'link' && inline[0].c.length === 1 && inline[0].c[0].t === 'image') {
498
- const img = inline[0].c[0];
499
- blocks.push({ t: 'image', src: img.src, alt: img.alt, link: inline[0] });
500
- } else blocks.push({ t: 'p', c: inline });
1129
+ i = paragraph(lines, i, ctx, blocks, col);
1130
+ if (blocks[blocks.length - 1]?.t === 'p') paraEnd = i;
1131
+ open = i >= n && blocks[blocks.length - 1]?.t !== 'h';
501
1132
  }
502
- return blocks;
1133
+ return { blocks, open: open && !unclosedHtml };
503
1134
  }
504
1135
 
505
- /**
506
- * 拿掉 HTML 註解(<!-- … -->):行首、段落下一行、清單項目裡、行內、跨行,位置都一樣處理(CommonMark 的註解可以打斷段落)。
507
- * 程式碼框(``` 或 ~~~)裡的不動。找不到結尾的註解=記 error,且保留原文(不能把後面整段吃掉)。
508
- */
509
- const MARK = '\uE001';
510
-
511
- /**
512
- * 拿掉 HTML 註解(<!-- … -->):行首、段落下一行、清單項目裡、行內、跨行,位置都一樣處理(CommonMark 的註解可以打斷段落)。
513
- * 「程式碼」的判定:程式碼框(``` 或 ~~~,頂格、清單內、引言內都算;開頭與收尾用同一套前綴規則)與行內程式碼(共用 codeSpanAt,
514
- * 含跨行、不同長度的反引號;反斜線跳脫的反引號不開頭)。程式碼裡的 <!-- 不動。
515
- * 找不到結尾的註解=記 error,且保留原文(不能把後面整段吃掉)。
516
- */
517
- export function stripComments(lines: string[], problems: Problem[]): string[] {
518
- const fenceLead = (l: string) => l.replace(/^[\s>]*/, '');
519
- // 切成「程式碼框」與「文字」兩種區段
520
- const segs: { code: boolean; lines: string[] }[] = [];
521
- let i = 0;
522
- while (i < lines.length) {
523
- const f = lines[i].match(LOOSE_FENCE);
524
- if (f) {
525
- const mark = f[1];
526
- const seg = [lines[i++]];
527
- while (i < lines.length) {
528
- const l = lines[i++];
529
- seg.push(l);
530
- if (fenceLead(l).startsWith(mark)) break;
531
- }
532
- segs.push({ code: true, lines: seg });
533
- } else {
534
- const seg: string[] = [];
535
- while (i < lines.length && !LOOSE_FENCE.test(lines[i])) seg.push(lines[i++]);
536
- segs.push({ code: false, lines: seg });
537
- }
538
- }
539
- const out: string[] = [];
540
- for (const seg of segs) {
541
- if (seg.code) {
542
- out.push(...seg.lines);
543
- continue;
544
- }
545
- const text = seg.lines.join('\n');
546
- let res = '';
547
- let pos = 0;
548
- let unclosedAt = -1;
549
- while (pos < text.length) {
550
- const ch = text[pos];
551
- if (ch === '\\' && (text[pos + 1] === '`' || text[pos + 1] === '<')) {
552
- res += ch + text[pos + 1]; // 反斜線跳脫的反引號不開程式碼、跳脫的 < 不開註解(與解析器一致)
553
- pos += 2;
554
- continue;
555
- }
556
- if (ch === '`') {
557
- const span = codeSpanAt(text, pos);
558
- if (span) {
559
- res += text.slice(pos, span.end);
560
- pos = span.end;
561
- } else {
562
- let n = 0;
563
- while (text[pos + n] === '`') n++;
564
- res += text.slice(pos, pos + n);
565
- pos += n;
566
- }
567
- continue;
568
- }
569
- if (text.startsWith('<!--', pos)) {
570
- const e = text.indexOf('-->', pos + 4);
571
- if (e < 0) {
572
- unclosedAt = pos;
573
- res += text.slice(pos);
574
- pos = text.length;
575
- break;
576
- }
577
- res += MARK;
578
- pos = e + 3;
579
- continue;
580
- }
581
- res += ch;
582
- pos++;
583
- }
584
- if (unclosedAt >= 0) {
585
- const startLine = text.slice(0, unclosedAt).split('\n').length - 1;
586
- problems.push({ code: 'unclosed_comment', severity: 'error', message: 'HTML 註解(<!--)沒有收尾,後面的內容會被吃掉', where: clip(seg.lines[startLine] ?? '') });
587
- }
588
- // 整行只剩註解=空行;行內註解=直接拿掉
589
- for (const l of res.split('\n')) out.push(l.includes(MARK) && l.split(MARK).join('').trim() === '' ? '' : l.split(MARK).join(''));
590
- }
591
- return out;
592
- }
593
-
594
- /** 保險:解析完之後,程式碼以外的文字節點若還有 <!--,代表註解剝除與解析器對「程式碼在哪」的看法不一致 → 記 error,不放行。 */
595
- function leakedComments(blocks: Block[], problems: Problem[]): void {
596
- const inl = (ns: Inline[]) => {
597
- for (const n of ns) {
598
- if (n.t === 'text' && n.v.includes('<!--')) {
599
- problems.push({ code: 'comment_leaked', severity: 'error', message: '有 HTML 註解沒被剝掉,會原樣出現在信裡(疑似程式碼寫法被誤判);請檢查附近的反引號與程式碼框', where: clip(n.v.slice(Math.max(0, n.v.indexOf('<!--') - 10))) });
600
- } else if (n.t === 'strong' || n.t === 'em' || n.t === 'link') inl(n.c);
601
- else if (n.t === 'image' && n.alt.includes('<!--')) problems.push({ code: 'comment_leaked', severity: 'error', message: '圖片替代文字裡有未剝掉的 HTML 註解', where: clip(n.alt) });
602
- }
603
- };
604
- const walk = (bs: Block[]) => {
605
- for (const b of bs) {
606
- if (b.t === 'p' || b.t === 'h') inl(b.c);
607
- else if (b.t === 'quote') walk(b.c);
608
- else if (b.t === 'list') for (const it of b.items) walk(it);
609
- else if (b.t === 'table') {
610
- for (const c of b.head) inl(c);
611
- for (const r of b.rows) for (const c of r) inl(c);
612
- } else if (b.t === 'image' && b.alt.includes('<!--')) problems.push({ code: 'comment_leaked', severity: 'error', message: '圖片替代文字裡有未剝掉的 HTML 註解', where: clip(b.alt) });
1136
+ /** 最後的總檢查:行首結構用 tab、腳註定義有沒有被引用與重複。 */
1137
+ function finalChecks(ctx: Ctx, blocks: Block[]): void {
1138
+ const fail = (message: string, where: string) => ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message, where: clip(where) });
1139
+ // 連結被拆壞的跡象:「](」後面直接接一個裸網址(例:*[**c**](https://…)字*,強調先切開了連結)。網站上那是連結,信裡變成吞掉後面字的裸網址
1140
+ let broken = '';
1141
+ const walk = (x: unknown): void => {
1142
+ if (broken || !x || typeof x !== 'object') return;
1143
+ if (Array.isArray(x)) {
1144
+ x.forEach((n, k) => {
1145
+ const prev = x[k - 1] as Inline | undefined;
1146
+ if (n && (n as Inline).t === 'link' && (n as { bare?: boolean }).bare && prev?.t === 'text' && prev.v.endsWith('](')) broken = (n as { href: string }).href;
1147
+ });
613
1148
  }
1149
+ for (const v of Object.values(x)) if (v && typeof v === 'object') walk(v);
614
1150
  };
615
1151
  walk(blocks);
1152
+ if (broken) fail('強調和連結的組合(例:*[**文字**](網址)字*)信裡排不出來,連結會被拆開;請把強調移到連結文字裡面或外面加空格', broken);
1153
+ if (ctx.tab) fail('行首的縮排、引言 > 或清單記號後面用了 tab,網站上的排法判不準;請改用空格(程式碼框裡的 tab 不受影響)', ctx.tab);
1154
+ const seen = new Set<string>();
1155
+ for (const label of ctx.defs) {
1156
+ if (seen.has(label)) fail(`腳註 [^${label}] 定義了兩次,網站只顯示第一個;請刪掉重複的`, `[^${label}]:`);
1157
+ seen.add(label);
1158
+ if (!ctx.refs.has(label)) fail(`腳註 [^${label}] 有定義但正文沒引用,網站上不顯示;請刪掉或在正文引用它`, `[^${label}]:`);
1159
+ }
616
1160
  }
617
1161
 
618
1162
  export function parseMarkdown(source: string): Parsed {
619
1163
  const { body, fm } = splitFrontmatter(source);
620
- const problems: Problem[] = [];
621
- const blocks = parseBlocks(stripComments(body.split('\n'), problems), problems);
622
- if (!problems.some((p) => p.code === 'unclosed_comment')) leakedComments(blocks, problems);
623
- return { blocks, problems, frontmatter: fm };
1164
+ const ctx = newCtx();
1165
+ const { blocks } = parseBlocks(body.split('\n'), ctx);
1166
+ finalChecks(ctx, blocks);
1167
+ // 對帳:原文每一個 <!--,不是被當成註解藏起來,就是落在程式碼裡;對不上=有一個註解符號跑進了正文(或內容不見了),擋下。
1168
+ const total = marks(body);
1169
+ if (total !== ctx.hidden + ctx.inCode && !ctx.problems.some((p) => p.code === 'unclosed_comment')) {
1170
+ ctx.problems.push({ code: 'comment_leaked', severity: 'error', message: `原稿有 ${total} 個 <!--,其中 ${ctx.hidden} 個當註解藏起來、${ctx.inCode} 個在程式碼裡,剩下的會以文字出現在信裡(例如反斜線跳脫的 \\<!--、圖片替代文字或網址裡的 <!--);請改寫或用反引號包起來`, where: clip(body.slice(Math.max(0, body.indexOf('<!--') - 10))) });
1171
+ }
1172
+ return { blocks, problems: ctx.problems, frontmatter: fm };
624
1173
  }