dsh-zju-lecture-note 2.2.4 → 2.2.6

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.
@@ -291,6 +291,32 @@ _PSEUDO_HEADING_RE = re.compile(
291
291
  r"^\*\*[^*\n]{1,40}\*\*(?:\s*`?\[\d{1,2}:\d{2}(?::\d{2})?\]`?)?\s*$"
292
292
  )
293
293
 
294
+ #: 行内粗体小标题:`**矛盾从哪里来** \`[00:05]\`–\`[00:06]\`:…`。
295
+ #: 它和整行粗体的伪标题是同一个意思(下一个话题的抬头),只是后面直接接了正文。
296
+ #: 例题四段式的标签(`**题目**:` 等)必须排除,否则 `[例]` 会被拆散。
297
+ _BOLD_LEAD_RE = re.compile(
298
+ r"^\*\*([^*\n]{1,40})\*\*\s*"
299
+ r"(?:`?\[\d{1,2}:\d{2}(?::\d{2})?\]`?\s*"
300
+ r"(?:[–—~-]\s*`?\[\d{1,2}:\d{2}(?::\d{2})?\]`?)?\s*)?"
301
+ r"[::]"
302
+ )
303
+ _REVIEW_HEAD_LABELS = frozenset({"题目", "切入点", "关键步骤", "易错点", "易错"})
304
+
305
+ #: 短引导词 + 时间码 + 冒号:`推导要点 \`[00:43]\`–\`[00:45]\`:…`。
306
+ #: 与粗体小标题同一个意思,只是作者没加粗;框在这一行收尾。证明块例外 ——
307
+ #: 证明的 qed 必须落在整段推导的末尾,不能因为一个「第一步 [00:12]:」就截断。
308
+ _PLAIN_LEAD_RE = re.compile(
309
+ r"^([\u4e00-\u9fff][^\s::,。;、()()]{0,11})\s*"
310
+ r"`?\[\d{1,2}:\d{2}(?::\d{2})?\]`?\s*"
311
+ r"(?:[–—~-]\s*`?\[\d{1,2}:\d{2}(?::\d{2})?\]`?\s*)?"
312
+ r"[::]"
313
+ )
314
+
315
+ #: 未知的中文块标记:`[推导] …`。只认中文标签 —— 行首的 `[1]` 引用、公式里
316
+ #: 的 `[S]` 都不是标记。跨段收集在这里收尾,渲染时按加粗小标题排,
317
+ #: 不再把方括号原样印进 PDF。
318
+ _UNKNOWN_MARKER_RE = re.compile(r"^\[([\u4e00-\u9fff][^\]\n]{0,7})\]\s*(.*)$")
319
+
294
320
  #: 斜杠分式:`\partial D/\partial t`、`\mathrm{d}i/\mathrm{d}t`、
295
321
  #: `\sqrt{\mu_0/\varepsilon_0}`。这些写法在行内会与上下标挤在一起,
296
322
  #: 渲染层统一改成 `\frac{…}{…}`;只处理**明确的微分/根式**,不碰一般 `a/b`。
@@ -361,10 +387,21 @@ _LATEX_SYMBOLS: Dict[str, str] = {
361
387
  "sup": '"sup"', "inf": '"inf"', "Pr": '"Pr"',
362
388
  # 省略号 / 竖排省略号(Typst 的符号名与 LaTeX 不同,这里直接给字符)
363
389
  "cdots": "dots", "vdots": "⋮", "ddots": "⋱",
364
- # 绝对值 / 范数 / 集合分隔
390
+ # 绝对值 / 范数 / 集合分隔。amsmath 的 `\lVert` / `\rVert` 与 `\|` 是范数
391
+ # 竖线,早先漏映射:`\lVert x \rVert` 直接印成 `lVert x rVert`,
392
+ # `\left\lVert … \right\rVert` 更惨,被 `\left` 分支整段吞掉(竖线消失)。
365
393
  "lvert": "|", "rvert": "|", "vert": "|", "mid": "|", "Vert": "‖",
394
+ "lVert": "‖", "rVert": "‖", "|": "‖",
366
395
  # 花括号本身在 Typst 数学里就是字面量,直接放行
367
396
  "{": "{", "}": "}",
397
+ # 定界符尺寸命令只是排版开关,后面的括号由正常流程输出;
398
+ # 不映射的话 `\big(` 会印出单词 `big`。
399
+ "big": "", "Big": "", "bigg": "", "Bigg": "",
400
+ "bigl": "", "bigr": "", "Bigl": "", "Bigr": "",
401
+ "biggl": "", "biggr": "", "Biggl": "", "Biggr": "",
402
+ "middle": "",
403
+ # 百分号:Typst 数学里 `%` 是合法符号,映射一下免得 note_lint 误报「未映射」
404
+ "%": "%",
368
405
  # 反斜杠 + 空格:LaTeX 的显式空格(`0,\ 1,\ 2`)
369
406
  " ": " ",
370
407
  # 长箭头
@@ -444,7 +481,7 @@ _TYPST_BARE_NAMES = (
444
481
  "mat", "cases", "quad", "wide", "thin", "med", "slash",
445
482
  "product", "integral", "sum", "dots",
446
483
  "overbrace", "underbrace", "overline", "underline",
447
- "hat", "tilde", "bar", "vec", "dot", "ddot", "compose",
484
+ "hat", "tilde", "bar", "vec", "dot", "ddot", "compose", "degree",
448
485
  })
449
486
  )
450
487
 
@@ -521,18 +558,41 @@ def _typst_script(content: str) -> str:
521
558
 
522
559
  内容先递归转换一遍:``a_{n=-\\infty}`` 里的 ``\\infty`` 不转换的话,
523
560
  到 Typst 那里就是一个不认识的变量名。
561
+
562
+ **逐字母拆词只针对「还没转换过的裸字母串」。** 转换器自己会产出
563
+ ``alpha`` / ``theta`` / ``compose`` 这类 Typst 名字,它们本身就是**一个**
564
+ 记号;早先不加区分地按 ``[A-Za-z]{2,}`` 拆,于是 ``29^{\\circ}`` 排成
565
+ ``(c o m p o s e)``、``x^{\\alpha}`` 排成 ``(a l p h a)`` —— PDF 的右上角
566
+ 直接印出单词(实地会话 session-42baa52c 的 ``sin 29^{compose}``)。
567
+ 判据就是 :data:`_TYPST_BARE_NAMES`:能裸写的名字不拆,其余照旧拆。
524
568
  """
525
569
  text, _ = latex_to_typst(content)
526
570
  text = text.strip()
527
571
  if not text:
528
572
  return "()"
529
- if re.fullmatch(r"[A-Za-z]{2,}", text):
573
+ if text == "compose":
574
+ # LaTeX 把 ``29^{\\circ}`` 当角度写,``\\circ`` 在上下标里就是度数符号。
575
+ # Typst 的 ``compose`` 是数学轴上的 ∘,``degree`` 才是 °。
576
+ text = "degree"
577
+ if re.fullmatch(r"[A-Za-z]{2,}", text) and text not in _TYPST_BARE_NAMES:
530
578
  return "(" + " ".join(text) + ")"
531
579
  # `=` 在上下标里补空格:Typst 对关系符号更宽容,但补上更稳。
532
580
  text = re.sub(r"\s*=\s*", " = ", text)
533
581
  return "(" + text + ")"
534
582
 
535
583
 
584
+ def _read_script_command(text: str, index: int) -> Tuple[Optional[str], int]:
585
+ """从 ``index`` 处读一个**不带花括号**的上下标记号(只认反斜杠命令)。
586
+
587
+ ``29^\\circ`` / ``\\sum_{n=1}^\\infty`` 里的记号没有花括号,Typst 侧要补一层
588
+ ``(...)`` 才不会被后面紧跟的字母粘住。返回 ``(记号的原文, 结束后的下标)``。
589
+ """
590
+ match = _LATEX_COMMAND_RE.match(text, index)
591
+ if not match:
592
+ return None, index
593
+ return text[index:match.end()], match.end()
594
+
595
+
536
596
  def _read_environment(
537
597
  text: str, index: int, name: str
538
598
  ) -> Tuple[Optional[str], int]:
@@ -779,17 +839,28 @@ def latex_to_typst(expression: str, inline: bool = False) -> Tuple[str, List[str
779
839
  continue
780
840
 
781
841
  if command in ("left", "right"):
782
- # `\left\{` / `\right\}` 是花括号字面量,必须保留转义。
842
+ # `\left⟨分隔符⟩ … \right⟨分隔符⟩` 里**分隔符本身要留下来**。
843
+ # 早先只认 `\{` / `\}`,其余分两种坏法:`\left\lvert`、
844
+ # `\left\|`、`\left\lVert` 被整段吞掉(绝对值 / 范数竖线消失),
845
+ # `\left.` 又把那个点的字面量印进 PDF。这里按符号表落字符,
846
+ # `\left.` / `\right.` 是不可见分隔符,直接跳过。
783
847
  if index < length and expression[index] == "\\":
784
848
  nxt = _LATEX_COMMAND_RE.match(expression, index)
785
849
  if nxt:
786
- if nxt.group(1) == "{":
787
- out.append("\\{")
788
- elif nxt.group(1) == "}":
789
- out.append("\\}")
850
+ name = nxt.group(1)
790
851
  index = nxt.end()
791
- else:
792
- index += 1
852
+ if name == ".":
853
+ continue
854
+ if name in ("{", "}"):
855
+ out.append("\\" + name)
856
+ continue
857
+ _emit(_LATEX_SYMBOLS.get(name, name), index)
858
+ continue
859
+ index += 1
860
+ continue
861
+ if index < length and expression[index] == ".":
862
+ index += 1
863
+ continue
793
864
  continue
794
865
 
795
866
  if command in _LATEX_FRACTIONS:
@@ -1048,6 +1119,19 @@ def latex_to_typst(expression: str, inline: bool = False) -> Tuple[str, List[str
1048
1119
  out.append(char + _typst_script(content))
1049
1120
  index = next_index
1050
1121
  continue
1122
+ # 不带花括号的命令:`29^\circ`、`x^\alpha`、`\sum_{n=1}^\infty`。
1123
+ # 只有反斜杠命令需要补括号;裸字母/数字(`x_1`、`a_n`)在 Typst 里
1124
+ # 本来就是一个记号,动了反而破坏既有输出、也会破坏幂等。
1125
+ if index + 1 < length and expression[index + 1] == "\\":
1126
+ token, after = _read_script_command(expression, index + 1)
1127
+ if token is not None:
1128
+ converted = latex_to_typst(token)[0].strip()
1129
+ if converted:
1130
+ if converted == "compose":
1131
+ converted = "degree"
1132
+ out.append(char + "(" + converted + ")")
1133
+ index = after
1134
+ continue
1051
1135
  out.append(char)
1052
1136
  index += 1
1053
1137
  continue
@@ -1393,21 +1477,60 @@ def _is_marker_line(text: str) -> bool:
1393
1477
  )
1394
1478
 
1395
1479
 
1480
+ def block_boundary(text: str, proof: bool = False) -> bool:
1481
+ """跨段装置是否应该在这一行**收尾**(两条 PDF 链路共用)。
1482
+
1483
+ 框与证明本来就该跨段(v2.2.4:公式与段落不能掉出框外),但「跨段」不能
1484
+ 等于「吞到下一个标题」:一份讲义里 `[定理]` 后面紧跟的普通段落往往是
1485
+ 下一段讲解,`[定义]` 后面常跟着推导与结论。旧规则只认标题、已知标记与
1486
+ 整行粗体,实地讲义里出现过一个定义框吞掉推导、提示块甚至列表的情况。
1487
+
1488
+ 这里补四条**结构性**边界,都是「作者显然在开一个新块」的信号:
1489
+
1490
+ * 引用 / 提示块(``>``)—— 独立块,不属于上一个装置;
1491
+ * 以 ``⚠`` 开头的提醒段 —— 同样是独立提示,不应该被 qed 或方框包住;
1492
+ * 粗体小标题 + 冒号(可带时间码)—— 例题四段式标签例外;
1493
+ * 短引导词 + 时间码 + 冒号 —— 与上一条同义,只是没加粗;
1494
+ ``proof=True`` 时跳过,避免把证明从中间截断(qed 会停在半路);
1495
+ * 未知的中文标记(``[推导]``)—— 作者想开新块,只是名字不在表里。
1496
+
1497
+ 普通段落、块级公式、列表、表格仍然留在装置里,证明与例题的多段正文不受影响。
1498
+ """
1499
+ stripped = text.strip()
1500
+ if not stripped:
1501
+ return False
1502
+ if re.match(r"^#{1,6}\s+", stripped):
1503
+ return True
1504
+ if _is_marker_line(stripped) or _PSEUDO_HEADING_RE.match(stripped):
1505
+ return True
1506
+ if stripped.startswith(">") or stripped.startswith("\u26a0"):
1507
+ return True
1508
+ bold = _BOLD_LEAD_RE.match(stripped)
1509
+ if bold and bold.group(1).strip() not in _REVIEW_HEAD_LABELS:
1510
+ return True
1511
+ if not proof:
1512
+ lead = _PLAIN_LEAD_RE.match(stripped)
1513
+ if lead and lead.group(1).strip() not in _REVIEW_HEAD_LABELS:
1514
+ return True
1515
+ unknown = _UNKNOWN_MARKER_RE.match(stripped)
1516
+ if unknown and unknown.group(1) not in MARKERS:
1517
+ return True
1518
+ return False
1519
+
1520
+
1396
1521
  def _collect_block_lines(
1397
1522
  lines: Sequence[str],
1398
1523
  cursor: int,
1524
+ name: str = "",
1399
1525
  ) -> Tuple[List[str], int]:
1400
- """收集标记行之后、到下一个标题/标记为止的底稿行(空行保留)。"""
1526
+ """收集标记行之后、到下一个标题/标记/新话题为止的底稿行(空行保留)。"""
1401
1527
  body: List[str] = []
1402
1528
  total = len(lines)
1529
+ proof = name == "证明"
1403
1530
  while cursor < total:
1404
1531
  raw = lines[cursor]
1405
1532
  stripped = raw.strip()
1406
- if stripped and (
1407
- re.match(r"^#{1,6}\s+", stripped)
1408
- or _is_marker_line(stripped)
1409
- or _PSEUDO_HEADING_RE.match(stripped)
1410
- ):
1533
+ if stripped and block_boundary(stripped, proof=proof):
1411
1534
  break
1412
1535
  body.append(raw)
1413
1536
  cursor += 1
@@ -1580,7 +1703,7 @@ _TYPST_SAFE_WORDS = (
1580
1703
  "frac", "sqrt", "root", "mat", "cases", "cal", "frak", "bold",
1581
1704
  "upright", "op", "compose", "norm", "abs", "floor", "ceil", "round",
1582
1705
  "diag", "rank", "Res", "tr", "det", "lim", "max", "min", "sup", "inf",
1583
- "wide", "thin", "med", "slash",
1706
+ "wide", "thin", "med", "slash", "degree",
1584
1707
  })
1585
1708
  )
1586
1709
 
@@ -1869,7 +1992,7 @@ def render_typst(
1869
1992
  continue
1870
1993
  if _marker_absorbs_blocks(name):
1871
1994
  # 框与证明跨段:同一装置的公式、段落、列表都留在块内。
1872
- extra, cursor = _collect_block_lines(input_lines, cursor)
1995
+ extra, cursor = _collect_block_lines(input_lines, cursor, name)
1873
1996
  fragment, label, body_paragraphs = _render_block_marker(
1874
1997
  name, body, extra, known_labels, warnings
1875
1998
  )
@@ -1885,20 +2008,71 @@ def render_typst(
1885
2008
  knots.append({"call": call, "section": section})
1886
2009
  continue
1887
2010
 
2011
+ # 未知的中文标记(`[推导] …`):作者想开一个新块,但名字不在 MARKERS 表里。
2012
+ # 推导按旧规范的 Proof 排(斜体 Proof. + 块末 qed,跨段、不套框);
2013
+ # 其余未知标记按「加粗小标题 + 正文」兜底。note_lint 仍会提示改成已支持的标记。
2014
+ unknown = _UNKNOWN_MARKER_RE.match(stripped)
2015
+ if unknown:
2016
+ if unknown.group(1) == "推导":
2017
+ extra, cursor = _collect_block_lines(input_lines, cursor, "证明")
2018
+ fragment, label, body_paragraphs = _render_block_marker(
2019
+ "证明", unknown.group(2), extra, known_labels, warnings
2020
+ )
2021
+ lines_out.append(fragment)
2022
+ paragraphs += body_paragraphs
2023
+ if label:
2024
+ labels.append(label)
2025
+ _count("proof")
2026
+ continue
2027
+ lead = "**" + unknown.group(1) + "**"
2028
+ if unknown.group(2):
2029
+ lead += " " + unknown.group(2)
2030
+ lines_out.append(BODY_INDENT + escape_typst(lead, known_labels))
2031
+ paragraph_raw[len(lines_out) - 1] = lead
2032
+ paragraphs += 1
2033
+ _count("paragraph")
2034
+ continue
2035
+
1888
2036
  # Markdown 引用块。Typst **没有** `>` 引用语法(0.15 实测:`>` 会被
1889
2037
  # 当成字面量印出来,整段抬头变成「> 来源:… > 上课时间:…」),
1890
2038
  # 所以走 prelude 里的 `#quoted` 内容块;字段之间用行间断行。
2039
+ # `> [!IMPORTANT]` 这类 GitHub alert 先摘掉标记行:重点走 `#keypoint`
2040
+ # (规范蓝色的文字段落,不是方框),其余 alert 退化成带标签的灰色引用。
1891
2041
  if stripped.startswith(">"):
1892
2042
  quote_lines = [raw_line]
1893
2043
  while cursor < len(input_lines) and input_lines[cursor].strip().startswith(">"):
1894
2044
  quote_lines.append(input_lines[cursor])
1895
2045
  cursor += 1
1896
- items = split_quote_items(quote_lines)
2046
+ kind = ""
2047
+ cleaned: List[str] = []
2048
+ for line in quote_lines:
2049
+ text_line = line.strip()
2050
+ if text_line.startswith(">"):
2051
+ text_line = text_line[1:].lstrip()
2052
+ alert = re.match(
2053
+ r"^\[!(IMPORTANT|WARNING|CAUTION|NOTE|TIP)\]$", text_line, re.I
2054
+ )
2055
+ if alert and not cleaned:
2056
+ kind = alert.group(1).upper()
2057
+ continue
2058
+ cleaned.append(line)
2059
+ items = split_quote_items(cleaned)
1897
2060
  body = " \\\n".join(
1898
2061
  escape_typst(join_cjk_lines(item), known_labels) for item in items
1899
2062
  )
1900
- lines_out.append("#quoted[\n" + body + "\n]")
1901
- _count("quote")
2063
+ if kind == "IMPORTANT":
2064
+ lines_out.append("#keypoint[*重点* " + body + "]")
2065
+ _count("keypoint")
2066
+ elif kind:
2067
+ label = {
2068
+ "WARNING": "注意", "CAUTION": "注意",
2069
+ "NOTE": "说明", "TIP": "提示",
2070
+ }.get(kind, "提示")
2071
+ lines_out.append("#quoted[*" + label + "* " + body + "]")
2072
+ _count("quote")
2073
+ else:
2074
+ lines_out.append("#quoted[\n" + body + "\n]")
2075
+ _count("quote")
1902
2076
  continue
1903
2077
 
1904
2078
  # Markdown 水平分隔线 → Typst 的细分隔线。不处理的话 `---` 会被