Luogu Markdown Better

Luogu Markdown Better 是一款用于洛谷 Markdown 编辑器的用户脚本。

更新于 2026年9月26日约 27 分钟阅读

Luogu Markdown Better 是一款用于洛谷 Markdown 编辑器的用户脚本,为题解、文章和讨论等内容的编写提供符号配对、洛谷 Markdown 补全、LaTeX 补全、公式快捷输入与题解格式整理功能。

安装

安装用户脚本管理器

请先在浏览器中安装 Tampermonkey 或 Violentmonkey。

如果使用新版 Chrome 或基于 Chromium 的浏览器,还需要在扩展管理页面打开用户脚本管理器的“允许用户脚本”权限。若脚本安装后完全没有效果,请优先检查此项。

安装脚本

  1. 打开 luogu-markdown-better.user.js 的发布地址或源代码页面。
  2. 选择“安装”,或将脚本内容复制到用户脚本管理器的新脚本中。
  3. 保存脚本并刷新洛谷页面。
  4. 打开任意洛谷 Markdown 编辑器。编辑器原有工具栏右侧出现“题解格式整理”和“设置”图标,即表示脚本已成功启用。

脚本适用于:

  • https://www.luogu.com.cn/*
  • https://www.luogu.com/*

功能与用法

成对符号

输入左侧符号时,脚本会自动补上右侧符号,并将光标放在中间。已选中文字时,输入左侧符号可以包裹选中内容。

支持的符号包括:

  • ()、[]、{}
  • ()、【】
  • “”、‘’、""、''
  • $...$
  • **...**、~~...~~
  • 行内代码反引号

在一对空符号中按退格键,可以同时删除左右符号。光标位于自动生成的右侧符号前时,再次输入该符号会直接越过它。

连续输入三个反引号会生成开合代码围栏:

```|
```

光标会停在开头三个反引号后,可继续输入 cpp、python 等语言名称,然后换行编写代码。

代码围栏首行支持语言名称补全。输入三个反引号后会显示候选列表,常用选项包括 cpp、c、python、javascript、typescript、java、rust、go、bash、text 等。

语言名称后输入空格,还可以补全洛谷代码块参数:

  • line-numbers:显示代码行号,例如 ```cpp line-numbers(实际输入时不含两侧空格)。
  • lines=<start>-<end>:高亮指定范围,候选会插入示例 lines=6-9,可以继续修改成所需范围。
  • 两个参数可以同时使用,例如 ```cpp line-numbers lines=6-9。

洛谷 Markdown 容器补全

输入 ::: 后会出现候选列表,可以使用方向键选择,按 Enter 或 Tab 确认,按 Esc 关闭。

支持的模板包括:

  • :::align{center}:居中排版
  • :::align{right}:居右排版
  • :::epigraph[署名]:引言
  • ::::info[标题]:信息折叠框
  • ::::success[标题]:成功折叠框
  • ::::warning[标题]:警告折叠框
  • ::::error[标题]:错误折叠框
  • ::::info[标题]{open}:默认展开的折叠框

LaTeX 补全

LaTeX 补全仅在 $...$ 或 $$...$$ 公式内生效。输入反斜杠和命令前缀后,会出现与 IDE 类似的候选列表。

例如:

  • 输入 \sqr,选择后得到 \sqrt{}。
  • 输入 \colo,选择后得到 \color{}{}。
  • 输入 \disp,选择后得到 \displaystyle。
  • 输入 \begin{p,可以选择圆括号矩阵模板。

完整输入以下命令时会直接展开参数模板:

输入展开结果
\frac\frac{}{}
\dfrac\dfrac{}{}
\sum\sum_{}^{}
\prod\prod_{}^{}

候选列表还包含:

  • 分式、根式、积分、极限、二项式和矩阵
  • 希腊字母、集合符号、逻辑符号和箭头
  • \displaystyle 与 \textstyle
  • \tiny、\small、\large、\Large、\LARGE、\huge、\Huge 等字号
  • \color{}{} 与 \textcolor{}{}

公式快捷输入

以下快捷输入仅在公式中生效:

输入转换结果
xor\oplus
*\times
<=\le
>=\ge
!=\ne
<-\gets
->\to
=>\Rightarrow
<=>\Leftrightarrow
.\cdot
...\dots

输入 ^ 或 _ 时会自动补充花括号。

如果本次转换并非你的本意,可以立即按 Ctrl+Z 恢复原始输入。例如,输入 <= 自动转换成 \le 后,按 Ctrl+Z 会恢复为 <=。

题解格式整理

点击洛谷编辑器工具栏右侧的“题解格式整理”图标,或按 Ctrl+Alt+F,可以整理当前 Markdown 文本。

整理内容包括:

  • 在中文与西文字符或数字之间双向补充半角空格。
  • 将中文语境中的半角标点转换为全角标点。
  • 为中文正文段落补充句末标点。
  • 在行内代码、行内公式与相邻的中文、英文或数字之间补充半角空格,例如将 中文`code`English 整理为 中文 `code` English。紧邻中文标点时不添加空格。

整理时不会修改以下内容:

  • 反引号或波浪号围栏代码块,以及四空格或 Tab 缩进代码
  • 行内代码内部文本
  • 行内公式和行间公式
  • 链接地址
  • 洛谷 ::: 容器定界符

整理后可以立即按撤销快捷键恢复整理前的全文。

设置

点击洛谷编辑器工具栏右侧的齿轮图标,可以单独开关:

  • 括号与引号配对
  • Markdown 与公式定界符配对
  • LaTeX 参数模板
  • 公式快捷替换
  • 上下标花括号
  • 语法补全候选列表
  • 即时空格和标点规范

设置面板还可以修改:

  • 撤销自动展开或上一步操作的快捷键,默认是 Ctrl+Z
  • 题解格式整理快捷键,默认是 Ctrl+Alt+F

点击快捷键输入框后直接按下新的组合键即可保存;按 Backspace 或 Delete 可以清除快捷键。所有设置会保存在当前浏览器中。

常见问题

安装后完全没有效果

请依次检查:

  1. 用户脚本管理器是否已经启用。
  2. 浏览器扩展设置中的“允许用户脚本”是否已经打开。
  3. Luogu Markdown Better 是否处于启用状态。
  4. 当前网址是否属于 www.luogu.com.cn 或 www.luogu.com。
  5. 刷新洛谷页面后,编辑器工具栏中是否出现脚本的两个图标。

不希望自动转换某种公式写法

可以立即按撤销快捷键恢复原始输入,也可以在设置中关闭“公式快捷替换”或“LaTeX 参数模板”。

补全列表如何操作

  • ↑ / ↓:切换候选
  • Enter / Tab:插入当前候选
  • Esc:关闭候选列表

隐私说明

脚本只在浏览器本地处理编辑器内容,不会上传、收集或发送正在编辑的文本。功能设置保存在浏览器本地存储中。

许可证

本项目采用 MIT License 发布。

源代码

// ==UserScript==
// @name         Luogu Markdown Better
// @namespace    https://www.luogu.com.cn/
// @version      1.4.2
// @description  为洛谷 Markdown 编辑器提供成对符号、LaTeX/容器补全和题解规范整理。
// @author       csxx601cjy and gpt-5.6-sol
// @match        https://www.luogu.com.cn/*
// @match        https://www.luogu.com/*
// @grant        GM_registerMenuCommand
// @run-at       document-idle
// @license      MIT
// ==/UserScript==

(function () {
  'use strict';

  const VERSION = '1.4.2';
  const EDITOR_SELECTOR = '.cm-content[contenteditable="true"][data-language="markdown"]';
  const CJK = '\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uF900-\\uFAFF';
  const DEFAULT_SETTINGS = {
    pairs: true,
    markdownPairs: true,
    completion: true,
    latexTemplates: true,
    latexAliases: true,
    latexScripts: true,
    liveFormat: true,
    undoExpansionHotkey: 'Ctrl+Z',
    formatHotkey: 'Ctrl+Alt+F',
  };
  const PAIRS = new Map([
    ['(', ')'], ['[', ']'], ['{', '}'], ['(', ')'], ['【', '】'],
    ['“', '”'], ['‘', '’'], ['"', '"'], ["'", "'"], ['`', '`'], ['$' , '$'],
  ]);
  const CLOSERS = new Set([...PAIRS.values()]);

  const CONTAINER_COMPLETIONS = [
    { label: 'align{center}', detail: '居中排版', text: ':::align{center}\n\n:::', back: 4 },
    { label: 'align{right}', detail: '居右排版', text: ':::align{right}\n\n:::', back: 4 },
    { label: 'epigraph[署名]', detail: '引言', text: ':::epigraph[]\n\n:::', back: 6 },
    { label: 'info[标题]', detail: '信息折叠框', text: '::::info[]\n\n::::', back: 7 },
    { label: 'success[标题]', detail: '成功折叠框', text: '::::success[]\n\n::::', back: 7 },
    { label: 'warning[标题]', detail: '警告折叠框', text: '::::warning[]\n\n::::', back: 7 },
    { label: 'error[标题]', detail: '错误折叠框', text: '::::error[]\n\n::::', back: 7 },
    { label: 'info[标题]{open}', detail: '默认展开的信息框', text: '::::info[]{open}\n\n::::', back: 13 },
  ];

  const CODE_LANGUAGE_COMPLETIONS = [
    ['cpp', 'C++'], ['c', 'C'], ['python', 'Python'], ['javascript', 'JavaScript'],
    ['typescript', 'TypeScript'], ['java', 'Java'], ['kotlin', 'Kotlin'], ['rust', 'Rust'],
    ['go', 'Go'], ['csharp', 'C#'], ['php', 'PHP'], ['ruby', 'Ruby'], ['swift', 'Swift'],
    ['scala', 'Scala'], ['bash', 'Bash'], ['powershell', 'PowerShell'], ['html', 'HTML'],
    ['css', 'CSS'], ['json', 'JSON'], ['yaml', 'YAML'], ['xml', 'XML'], ['sql', 'SQL'],
    ['markdown', 'Markdown'], ['latex', 'LaTeX'], ['text', '纯文本'], ['plaintext', '纯文本'],
  ].map(([label, detail]) => ({ label, detail, text: label, back: 0 }));

  const CODE_OPTION_COMPLETIONS = [
    { label: 'line-numbers', detail: '显示代码行号', text: 'line-numbers', back: 0 },
    { label: 'lines=<start>-<end>', detail: '高亮指定行范围,例如 6-9', text: 'lines=6-9', back: 0 },
  ];

  const LATEX_COMPLETIONS = [
    ['frac', '分式', '\\frac{}{}', 3], ['dfrac', '行间分式', '\\dfrac{}{}', 3],
    ['sqrt', '根式', '\\sqrt{}', 1], ['sqrt[n]', 'n 次根', '\\sqrt[]{}', 3],
    ['sum', '求和', '\\sum_{}^{}', 4], ['prod', '连乘', '\\prod_{}^{}', 4],
    ['int', '积分', '\\int_{}^{}', 4], ['lim', '极限', '\\lim_{}', 1],
    ['binom', '二项式', '\\binom{}{}', 3], ['text', '公式文本', '\\text{}', 1],
    ['mathrm', '正体', '\\mathrm{}', 1], ['mathbf', '粗体', '\\mathbf{}', 1],
    ['mathit', '斜体', '\\mathit{}', 1], ['mathbb', '黑板粗体', '\\mathbb{}', 1],
    ['mathcal', '花体', '\\mathcal{}', 1], ['operatorname', '自定义算子', '\\operatorname{}', 1],
    ['overline', '上划线', '\\overline{}', 1], ['underline', '下划线', '\\underline{}', 1],
    ['overbrace', '上花括号', '\\overbrace{}^{}', 4], ['underbrace', '下花括号', '\\underbrace{}_{}', 4],
    ['vec', '向量', '\\vec{}', 1], ['hat', '帽子', '\\hat{}', 1],
    ['displaystyle', '行内公式使用行间样式'], ['textstyle', '行间公式使用行内样式'],
    ['tiny', '极小字号', '\\tiny{}', 1], ['scriptsize', '脚本字号', '\\scriptsize{}', 1],
    ['footnotesize', '脚注字号', '\\footnotesize{}', 1], ['small', '小字号', '\\small{}', 1],
    ['normalsize', '正常字号', '\\normalsize{}', 1], ['large', '大字号', '\\large{}', 1],
    ['Large', '较大字号', '\\Large{}', 1], ['LARGE', '更大字号', '\\LARGE{}', 1],
    ['huge', '特大字号', '\\huge{}', 1], ['Huge', '最大字号', '\\Huge{}', 1],
    ['color', '颜色', '\\color{}{}', 3], ['textcolor', '文本颜色', '\\textcolor{}{}', 3],
    ['left', '自适应左括号', '\\left', 0], ['right', '自适应右括号', '\\right', 0],
    ['begin{cases}', '分段函数', '\\begin{cases}\n  & \\\\\n  &\n\\end{cases}', 16],
    ['begin{matrix}', '矩阵', '\\begin{matrix}\n  & \\\\\n  &\n\\end{matrix}', 17],
    ['begin{pmatrix}', '圆括号矩阵', '\\begin{pmatrix}\n  & \\\\\n  &\n\\end{pmatrix}', 18],
    ['begin{bmatrix}', '方括号矩阵', '\\begin{bmatrix}\n  & \\\\\n  &\n\\end{bmatrix}', 18],
    ['alpha', '希腊字母 α'], ['beta', '希腊字母 β'], ['gamma', '希腊字母 γ'],
    ['delta', '希腊字母 δ'], ['epsilon', '希腊字母 ε'], ['varepsilon', '希腊字母 ε(变体)'],
    ['zeta', '希腊字母 ζ'], ['eta', '希腊字母 η'], ['theta', '希腊字母 θ'],
    ['vartheta', '希腊字母 θ(变体)'], ['iota', '希腊字母 ι'], ['kappa', '希腊字母 κ'],
    ['lambda', '希腊字母 λ'], ['mu', '希腊字母 μ'], ['nu', '希腊字母 ν'],
    ['xi', '希腊字母 ξ'], ['pi', '希腊字母 π'], ['varpi', '希腊字母 π(变体)'],
    ['rho', '希腊字母 ρ'], ['sigma', '希腊字母 σ'], ['tau', '希腊字母 τ'],
    ['upsilon', '希腊字母 υ'], ['phi', '希腊字母 φ'], ['varphi', '希腊字母 φ(变体)'],
    ['chi', '希腊字母 χ'], ['psi', '希腊字母 ψ'], ['omega', '希腊字母 ω'],
    ['Gamma', '希腊字母 Γ'], ['Delta', '希腊字母 Δ'], ['Theta', '希腊字母 Θ'],
    ['Lambda', '希腊字母 Λ'], ['Xi', '希腊字母 Ξ'], ['Pi', '希腊字母 Π'],
    ['Sigma', '希腊字母 Σ'], ['Phi', '希腊字母 Φ'], ['Psi', '希腊字母 Ψ'], ['Omega', '希腊字母 Ω'],
    ['times', '乘号 ×'], ['cdot', '点乘 ·'], ['div', '除号 ÷'], ['pm', '正负号 ±'],
    ['mp', '负正号 ∓'], ['oplus', '异或/直和 ⊕'], ['otimes', '张量积 ⊗'],
    ['le', '小于等于 ≤'], ['ge', '大于等于 ≥'], ['ne', '不等于 ≠'],
    ['approx', '约等于 ≈'], ['equiv', '恒等于 ≡'], ['propto', '正比于 ∝'],
    ['in', '属于 ∈'], ['notin', '不属于 ∉'], ['subset', '子集 ⊂'], ['subseteq', '子集或等于 ⊆'],
    ['supset', '超集 ⊃'], ['cup', '并集 ∪'], ['cap', '交集 ∩'], ['setminus', '差集'],
    ['forall', '任意 ∀'], ['exists', '存在 ∃'], ['nexists', '不存在 ∄'],
    ['land', '逻辑与 ∧'], ['lor', '逻辑或 ∨'], ['neg', '逻辑非 ¬'],
    ['gets', '左赋值箭头 ←'], ['to', '右箭头 →'], ['leftarrow', '左箭头 ←'],
    ['rightarrow', '右箭头 →'], ['leftrightarrow', '双向箭头 ↔'],
    ['Rightarrow', '推出 ⇒'], ['Leftrightarrow', '等价 ⇔'],
    ['infty', '无穷 ∞'], ['partial', '偏微分 ∂'], ['nabla', '梯度 ∇'],
    ['dots', '智能省略号 …'], ['ldots', '低省略号 …'], ['cdots', '居中省略号 ⋯'], ['vdots', '竖省略号 ⋮'], ['ddots', '斜省略号 ⋱'],
    ['sin', '正弦'], ['cos', '余弦'], ['tan', '正切'], ['cot', '余切'],
    ['log', '对数'], ['ln', '自然对数'], ['gcd', '最大公因数'], ['min', '最小值'], ['max', '最大值'],
  ].map(([label, detail, text, back]) => ({
    label: `\\${label}`,
    detail,
    text: text || `\\${label}`,
    back: back || 0,
  }));

  const LATEX_SHORTCUTS = [
    ['<=>', '\\Leftrightarrow'], ['=>', '\\Rightarrow'], ['<=', '\\le'], ['>=', '\\ge'],
    ['!=', '\\ne'], ['<-', '\\gets'], ['->', '\\to'], ['xor', '\\oplus'],
  ];
  const LATEX_AUTO_TEMPLATES = new Map(
    LATEX_COMPLETIONS
      .filter(item => ['\\frac', '\\dfrac', '\\sum', '\\prod'].includes(item.label))
      .map(item => [item.label, item]),
  );

  function loadSettings() {
    try {
      const stored = JSON.parse(localStorage.getItem('lmb-settings') || '{}');
      const migrated = { ...DEFAULT_SETTINGS, ...stored };
      if (typeof stored.shortcuts === 'boolean') {
        for (const key of ['latexTemplates', 'latexAliases', 'latexScripts']) {
          if (!(key in stored)) migrated[key] = stored.shortcuts;
        }
      }
      return migrated;
    } catch (_) {
      return { ...DEFAULT_SETTINGS };
    }
  }

  let settings = loadSettings();
  let activeEditor = null;
  let popup = null;
  let popupItems = [];
  let popupIndex = 0;
  let popupReplaceLength = 0;
  let composing = false;
  let programmaticInputDepth = 0;
  let dispatchingUndo = false;
  const expansionHistory = new WeakMap();
  const formatHistory = new WeakMap();
  const toolbarEditors = new WeakMap();

  function addStyles() {
    if (document.getElementById('lmb-styles')) return;
    const style = document.createElement('style');
    style.id = 'lmb-styles';
    style.textContent = `
      .lmb-toolbar-group { white-space: nowrap; }
      .lmb-tool { position: relative; }
      .lmb-tool svg { width: 1em; height: 1em; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
      .lmb-popup { position: fixed; z-index: 2147483646; width: min(360px, calc(100vw - 20px)); max-height: 280px; overflow-y: auto; padding: 4px; border: 1px solid #c8d0d8; border-radius: 6px; background: #fff; box-shadow: 0 8px 24px rgba(0,0,0,.16); color: #24292f; font: 13px/1.35 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
      .lmb-item { display: grid; grid-template-columns: minmax(0,1fr) auto; gap: 12px; width: 100%; padding: 7px 9px; border: 0; border-radius: 4px; background: transparent; color: inherit; text-align: left; cursor: pointer; }
      .lmb-item[aria-selected="true"] { background: #e9f3fb; color: #0875bd; }
      .lmb-label { overflow: hidden; font: 600 13px/1.35 ui-monospace, SFMono-Regular, Consolas, monospace; text-overflow: ellipsis; white-space: nowrap; }
      .lmb-detail { color: #687079; font-size: 12px; white-space: nowrap; }
      .lmb-toast { position: fixed; z-index: 2147483647; left: 50%; bottom: 28px; transform: translateX(-50%); padding: 8px 12px; border-radius: 5px; background: rgba(30,35,40,.92); color: #fff; font: 13px/1.4 sans-serif; pointer-events: none; }
      .lmb-menu { position: absolute; z-index: 2147483645; top: calc(100% + 6px); right: 4px; width: 300px; max-height: min(520px, calc(100vh - 70px)); overflow-y: auto; padding: 8px; border: 1px solid #c8d0d8; border-radius: 6px; background: #fff; box-shadow: 0 8px 24px rgba(0,0,0,.16); color: #24292f; font: 13px/1.4 sans-serif; }
      .lmb-menu-title { padding: 5px 7px 3px; color: #687079; font-size: 11px; font-weight: 700; letter-spacing: .06em; }
      .lmb-menu label { display: flex; align-items: center; gap: 8px; padding: 6px 7px; border-radius: 4px; cursor: pointer; }
      .lmb-menu label:hover { background: #f2f5f7; }
      .lmb-menu input { margin: 0; accent-color: #1683d8; }
      .lmb-hotkey-row { display: grid; grid-template-columns: 1fr 112px; align-items: center; gap: 8px; padding: 5px 7px; }
      .lmb-hotkey { width: 112px; padding: 5px 7px; border: 1px solid #c8d0d8; border-radius: 4px; background: #fff; color: inherit; font: 12px/1.3 ui-monospace, SFMono-Regular, Consolas, monospace; text-align: center; cursor: pointer; }
      .lmb-menu-note { padding: 2px 7px 7px; color: #7a848e; font-size: 11px; }
      .lmb-reset { width: calc(100% - 14px); margin: 5px 7px 2px; padding: 6px; border: 1px solid #c8d0d8; border-radius: 4px; background: transparent; color: inherit; cursor: pointer; }
      .lmb-reset:hover { background: #f2f5f7; }
      @media (prefers-color-scheme: dark) {
        .lmb-popup, .lmb-menu { border-color: #4c535b; background: #252a30; color: #e6edf3; }
        .lmb-menu label:hover { background: #343b43; }
        .lmb-item[aria-selected="true"] { background: #173b54; color: #62b5ed; } .lmb-detail { color: #9aa4ae; }
        .lmb-hotkey { border-color: #4c535b; background: #1f2429; } .lmb-reset { border-color: #4c535b; }
      }
    `;
    document.head.appendChild(style);
  }

  function selectionIn(editor) {
    const selection = window.getSelection();
    return selection && selection.rangeCount && editor.contains(selection.anchorNode) ? selection : null;
  }

  function currentLine(editor) {
    const selection = selectionIn(editor);
    if (!selection) return null;
    const element = selection.anchorNode.nodeType === Node.ELEMENT_NODE
      ? selection.anchorNode
      : selection.anchorNode.parentElement;
    return element && element.closest('.cm-line');
  }

  function textBeforeCaret(editor, wholeEditor = false) {
    const selection = selectionIn(editor);
    if (!selection) return '';
    const line = currentLine(editor);
    if (!line) return '';
    const range = document.createRange();
    range.selectNodeContents(line);
    try { range.setEnd(selection.anchorNode, selection.anchorOffset); } catch (_) { return ''; }
    const linePrefix = range.toString();
    if (!wholeEditor) return linePrefix;
    const lines = [...editor.children].filter(child => child.classList?.contains('cm-line'));
    const lineIndex = lines.indexOf(line);
    if (lineIndex < 0) return linePrefix;
    return [...lines.slice(0, lineIndex).map(item => item.textContent || ''), linePrefix].join('\n');
  }

  function charAfterCaret(editor) {
    const selection = selectionIn(editor);
    if (!selection) return '';
    const line = currentLine(editor);
    if (!line) return '';
    const range = document.createRange();
    range.selectNodeContents(line);
    try { range.setStart(selection.focusNode, selection.focusOffset); } catch (_) { return ''; }
    return range.toString().charAt(0);
  }

  function moveCaretBack(editor, count) {
    if (!count) return;
    const selection = selectionIn(editor);
    if (!selection || !selection.isCollapsed) return;
    let node = selection.focusNode;
    let offset = selection.focusOffset;
    while (count > 0 && node) {
      if (node.nodeType === Node.TEXT_NODE && offset > 0) {
        const step = Math.min(count, offset);
        offset -= step;
        count -= step;
      } else {
        const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT);
        let previous = null;
        while (walker.nextNode()) {
          if (walker.currentNode === node || (node.nodeType === Node.ELEMENT_NODE && node.contains(walker.currentNode))) break;
          previous = walker.currentNode;
        }
        if (!previous) break;
        node = previous;
        offset = node.data.length;
      }
    }
    const range = document.createRange();
    range.setStart(node, offset);
    range.collapse(true);
    selection.removeAllRanges();
    selection.addRange(range);
  }

  function selectBackward(editor, count) {
    const selection = selectionIn(editor);
    if (!selection || !selection.isCollapsed || count <= 0) return;
    const endNode = selection.focusNode;
    const endOffset = selection.focusOffset;
    let node = endNode;
    let offset = endOffset;
    while (count > 0 && node) {
      if (node.nodeType === Node.TEXT_NODE && offset > 0) {
        const step = Math.min(count, offset);
        offset -= step;
        count -= step;
      } else {
        const line = currentLine(editor);
        const texts = [];
        const walker = line && document.createTreeWalker(line, NodeFilter.SHOW_TEXT);
        while (walker?.nextNode()) texts.push(walker.currentNode);
        const index = texts.indexOf(node);
        if (index <= 0) break;
        node = texts[index - 1];
        offset = node.data.length;
      }
    }
    const range = document.createRange();
    range.setStart(node, offset);
    range.setEnd(endNode, endOffset);
    selection.removeAllRanges();
    selection.addRange(range);
  }

  function pointAtTextOffset(line, target) {
    const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT);
    let consumed = 0;
    while (walker.nextNode()) {
      const length = walker.currentNode.data.length;
      if (target <= consumed + length) return { node: walker.currentNode, offset: target - consumed };
      consumed += length;
    }
    return { node: line, offset: line.childNodes.length };
  }

  function moveCaretToTextOffset(line, offset) {
    if (!line?.isConnected) return false;
    const point = pointAtTextOffset(line, offset);
    const range = document.createRange();
    range.setStart(point.node, point.offset);
    range.collapse(true);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    return true;
  }

  function selectAroundCaret(editor, before, after, expected) {
    const selection = selectionIn(editor);
    const line = currentLine(editor);
    if (!selection || !selection.isCollapsed || !line) return false;
    const prefixRange = document.createRange();
    prefixRange.selectNodeContents(line);
    try { prefixRange.setEnd(selection.focusNode, selection.focusOffset); } catch (_) { return false; }
    const caretOffset = prefixRange.toString().length;
    const lineText = line.textContent || '';
    const startOffset = caretOffset - before;
    const endOffset = caretOffset + after;
    if (startOffset < 0 || endOffset > lineText.length) return false;
    if (expected != null && lineText.slice(startOffset, endOffset) !== expected) return false;
    const start = pointAtTextOffset(line, startOffset);
    const end = pointAtTextOffset(line, endOffset);
    const range = document.createRange();
    range.setStart(start.node, start.offset);
    range.setEnd(end.node, end.offset);
    selection.removeAllRanges();
    selection.addRange(range);
    return true;
  }

  function insertText(editor, text, back = 0, replaceLength = 0) {
    editor.focus();
    if (replaceLength) selectBackward(editor, replaceLength);
    let inserted = false;
    try { inserted = document.execCommand('insertText', false, text); } catch (_) { /* ignored */ }
    if (!inserted) return false;
    moveCaretBack(editor, back);
    return true;
  }

  function editorText(editor) {
    const lines = [...editor.children].filter(child => child.classList?.contains('cm-line'));
    if (lines.length) return lines.map(line => line.textContent || '').join('\n');
    return editor.innerText.replace(/\n$/, '');
  }

  function replaceEditorText(editor, source, target) {
    const sourceLines = source.replace(/\r\n/g, '\n').split('\n');
    const targetLines = target.replace(/\r\n/g, '\n').split('\n');
    if (sourceLines.length !== targetLines.length) return false;
    editor.focus();
    programmaticInputDepth += 1;
    let replaced = true;
    try {
      for (let index = targetLines.length - 1; index >= 0; index -= 1) {
        if (sourceLines[index] === targetLines[index]) continue;
        const lines = [...editor.children].filter(child => child.classList?.contains('cm-line'));
        const line = lines[index];
        if (!line) { replaced = false; break; }
        const selection = window.getSelection();
        const range = document.createRange();
        range.selectNodeContents(line);
        selection.removeAllRanges();
        selection.addRange(range);
        let lineReplaced = false;
        try { lineReplaced = document.execCommand('insertText', false, targetLines[index]); } catch (_) { /* ignored */ }
        if (!lineReplaced) { replaced = false; break; }
      }
    }
    finally { programmaticInputDepth -= 1; }
    return replaced && editorText(editor) === target.replace(/\r\n/g, '\n');
  }

  function applyExpansion(editor, original, text, back = 0, replaceLength = original.length) {
    programmaticInputDepth += 1;
    let inserted = false;
    try { inserted = insertText(editor, text, back, replaceLength); }
    finally { programmaticInputDepth -= 1; }
    if (inserted) {
      expansionHistory.set(editor, {
        original,
        expanded: text,
        before: text.length - back,
        after: back,
      });
    }
    return inserted;
  }

  function replaceProgrammatically(editor, text, back, replaceLength) {
    programmaticInputDepth += 1;
    try { return insertText(editor, text, back, replaceLength); }
    finally { programmaticInputDepth -= 1; }
  }

  function undoLastExpansion(editor) {
    const record = expansionHistory.get(editor);
    if (!record || !selectAroundCaret(editor, record.before, record.after, record.expanded)) return false;
    programmaticInputDepth += 1;
    let restored = false;
    try { restored = insertText(editor, record.original); }
    finally { programmaticInputDepth -= 1; }
    if (!restored) return false;
    expansionHistory.delete(editor);
    toast('已撤销自动展开');
    return true;
  }

  function undoLastFormat(editor) {
    const record = formatHistory.get(editor);
    if (!record || editorText(editor) !== record.after) return false;
    if (!replaceEditorText(editor, record.after, record.before)) return false;
    formatHistory.delete(editor);
    toast('已撤销题解格式整理');
    return true;
  }

  function isEscaped(text, index) {
    let slashes = 0;
    for (let i = index - 1; i >= 0 && text[i] === '\\'; i -= 1) slashes += 1;
    return slashes % 2 === 1;
  }

  function contextAtCaret(editor) {
    const before = textBeforeCaret(editor, true);
    const lines = before.split('\n');
    let fence = null;
    let inlineCode = false;
    let math = false;
    for (let row = 0; row < lines.length; row += 1) {
      const line = lines[row];
      const fenceMatch = line.match(/^\s*(?:>\s*)*(`{3,}|~{3,})(.*)$/);
      if (fence) {
        if (fenceMatch && fenceMatch[1][0] === fence.character
          && fenceMatch[1].length >= fence.length && !fenceMatch[2].trim()) {
          fence = null;
        }
        continue;
      }
      if (fenceMatch) {
        fence = { character: fenceMatch[1][0], length: fenceMatch[1].length };
        continue;
      }
      for (let i = 0; i < line.length; i += 1) {
        if (line[i] === '`' && !isEscaped(line, i)) inlineCode = !inlineCode;
        if (line[i] === '$' && !inlineCode && !isEscaped(line, i)) {
          if (line[i + 1] === '$') i += 1;
          math = !math;
        }
      }
      if (row < lines.length - 1) inlineCode = false;
    }
    return { before, line: lines.at(-1) || '', fenced: Boolean(fence), inlineCode, math };
  }

  function caretRect(editor) {
    const selection = selectionIn(editor);
    if (!selection || !selection.rangeCount) return editor.getBoundingClientRect();
    const range = selection.getRangeAt(0).cloneRange();
    let rect = range.getBoundingClientRect();
    if (!rect.width && !rect.height) rect = currentLine(editor)?.getBoundingClientRect() || editor.getBoundingClientRect();
    return rect;
  }

  function closePopup() {
    popup?.remove();
    popup = null;
    popupItems = [];
  }

  function renderPopup() {
    if (!popup) return;
    popup.innerHTML = '';
    popupItems.forEach((item, index) => {
      const button = document.createElement('button');
      button.type = 'button';
      button.className = 'lmb-item';
      button.setAttribute('aria-selected', String(index === popupIndex));
      const label = document.createElement('span');
      label.className = 'lmb-label';
      label.textContent = item.label;
      const detail = document.createElement('span');
      detail.className = 'lmb-detail';
      detail.textContent = item.detail;
      button.append(label, detail);
      button.addEventListener('mouseenter', () => { popupIndex = index; renderPopup(); });
      button.addEventListener('mousedown', event => {
        event.preventDefault();
        acceptCompletion(index);
      });
      popup.appendChild(button);
    });
    popup.children[popupIndex]?.scrollIntoView({ block: 'nearest' });
  }

  function showPopup(editor, items, replaceLength) {
    popupItems = items.slice(0, 40);
    popupReplaceLength = replaceLength;
    popupIndex = 0;
    if (!popup) {
      popup = document.createElement('div');
      popup.className = 'lmb-popup';
      popup.setAttribute('role', 'listbox');
      document.body.appendChild(popup);
    }
    const rect = caretRect(editor);
    const top = Math.min(rect.bottom + 5, window.innerHeight - 290);
    popup.style.left = `${Math.max(8, Math.min(rect.left, window.innerWidth - 370))}px`;
    popup.style.top = `${Math.max(8, top)}px`;
    renderPopup();
  }

  function acceptCompletion(index = popupIndex) {
    const item = popupItems[index];
    if (!item || !activeEditor) return;
    const original = textBeforeCaret(activeEditor).slice(-popupReplaceLength);
    closePopup();
    applyExpansion(activeEditor, original, item.text, item.back, popupReplaceLength);
  }

  function updateCompletions(editor) {
    if (!settings.completion || composing) return closePopup();
    const context = contextAtCaret(editor);
    const fenceMatch = context.line.match(/^\s*(`{3,}|~{3,})([^\s`]*)?(?:\s+(.*))?$/);
    if (fenceMatch) {
      const language = fenceMatch[2] || '';
      const optionText = fenceMatch[3];
      if (optionText === undefined) {
        const exact = CODE_LANGUAGE_COMPLETIONS.some(item => item.label.toLowerCase() === language.toLowerCase());
        const items = exact ? [] : CODE_LANGUAGE_COMPLETIONS.filter(item => item.label.toLowerCase().startsWith(language.toLowerCase()));
        if (items.length) return showPopup(editor, items, language.length);
      } else {
        const tokens = optionText.trim().split(/\s+/).filter(Boolean);
        const query = /\s$/.test(optionText) ? '' : tokens.at(-1) || '';
        const completedTokens = query ? tokens.slice(0, -1) : tokens;
        const completed = new Set(completedTokens.map(token => token.split('=')[0]));
        const items = CODE_OPTION_COMPLETIONS.filter(item => {
          const name = item.label.split('=')[0];
          return !completed.has(name) && item.label.toLowerCase().startsWith(query.toLowerCase());
        });
        if (items.length) return showPopup(editor, items, query.length);
      }
    }
    const containerMatch = context.line.match(/(:{3,})([a-z-]*)$/i);
    if (!context.fenced && !context.math && containerMatch) {
      const query = containerMatch[2].toLowerCase();
      const items = CONTAINER_COMPLETIONS.filter(item => item.label.toLowerCase().includes(query));
      if (items.length) return showPopup(editor, items, containerMatch[0].length);
    }
    if (context.math && !context.inlineCode) {
      const commandMatch = context.line.match(/\\([a-zA-Z]*|begin\{[a-zA-Z]*)$/);
      if (commandMatch) {
        const query = commandMatch[0].toLowerCase();
        const items = LATEX_COMPLETIONS
          .filter(item => item.label.toLowerCase().startsWith(query))
          .sort((a, b) => a.label.length - b.label.length);
        if (items.length) return showPopup(editor, items, commandMatch[0].length);
      }
    }
    closePopup();
  }

  function tryLatexShortcut(editor) {
    if (!settings.latexAliases) return false;
    const context = contextAtCaret(editor);
    if (!context.math || context.fenced || context.inlineCode) return false;
    for (const [typed, replacement] of LATEX_SHORTCUTS) {
      if (context.line.endsWith(typed)) {
        applyExpansion(editor, typed, replacement);
        return true;
      }
    }
    return false;
  }

  function tryLatexTemplate(editor) {
    if (!settings.latexTemplates) return false;
    const context = contextAtCaret(editor);
    if (!context.math || context.fenced || context.inlineCode) return false;
    for (const [command, item] of LATEX_AUTO_TEMPLATES) {
      if (context.line.endsWith(command)) {
        applyExpansion(editor, command, item.text, item.back);
        return true;
      }
    }
    return false;
  }

  function tryDotShortcut(editor) {
    if (!settings.latexAliases) return false;
    const context = contextAtCaret(editor);
    if (!context.math || context.fenced || context.inlineCode) return false;
    if (context.line.endsWith('\\cdot.')) {
      expansionHistory.delete(editor);
      replaceProgrammatically(editor, '..', 0, 6);
      return true;
    }
    if (context.line.endsWith('...')) {
      applyExpansion(editor, '...', '\\dots');
      return true;
    }
    if (context.line.endsWith('.')) {
      applyExpansion(editor, '.', '\\cdot');
      return true;
    }
    return false;
  }

  function isProseLine(line) {
    const trimmed = line.trim();
    if (!trimmed || /^(#{1,6}\s|>|[-+*]\s|\d+[.)]\s|\||:{3,}|```|~~~|<[^>]+>|!\[|\[.+\]:)/.test(trimmed)) return false;
    if (/^(https?:\/\/|\\begin|\\end)/.test(trimmed)) return false;
    const prose = trimmed
      .replace(/`+[^`]*`+/g, '')
      .replace(/\${1,2}[^$]*\${1,2}/g, '')
      .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
      .replace(/https?:\/\/\S+/g, '');
    return new RegExp(`[${CJK}]`).test(prose);
  }

  function transformPlainText(text) {
    const punctuation = { ',': ',', ';': ';', ':': ':', '!': '!', '?': '?', '.': '。' };
    let formatted = text
      .replace(new RegExp(`([${CJK}])([A-Za-z0-9])`, 'g'), '$1 $2')
      .replace(new RegExp(`([A-Za-z0-9])([${CJK}])`, 'g'), '$1 $2')
      .replace(new RegExp(`([${CJK}])[ \\t]*,`, 'g'), '$1,')
      .replace(new RegExp(`([${CJK}])[ \\t]*;`, 'g'), '$1;')
      .replace(new RegExp(`([${CJK}])[ \\t]*:`, 'g'), '$1:')
      .replace(new RegExp(`([${CJK}])[ \\t]*!`, 'g'), '$1!')
      .replace(new RegExp(`([${CJK}])[ \\t]*\\?`, 'g'), '$1?')
      .replace(new RegExp(`([${CJK}])[ \\t]*\\.`, 'g'), '$1。');
    formatted = formatted.replace(new RegExp(`([A-Za-z0-9)\\]}>])([,;:!?])(?=\\s*[${CJK}])`, 'g'),
      (_, lead, mark) => lead + punctuation[mark]);
    if (new RegExp(`[${CJK}]`).test(formatted)) {
      formatted = formatted.replace(/([,;:!?.])(?=\s*$)/, mark => punctuation[mark]);
    }
    return formatted;
  }

  function needsInlineTokenSpace(character) {
    return Boolean(character && new RegExp(`[${CJK}A-Za-z0-9]`).test(character));
  }

  function transformUnprotected(line) {
    let output = '';
    let plain = '';
    let i = 0;
    const flush = () => { output += transformPlainText(plain); plain = ''; };
    while (i < line.length) {
      const containerFence = line.slice(i).match(/^:{3,}/);
      if (containerFence) {
        flush();
        output += containerFence[0];
        i += containerFence[0].length;
        continue;
      }
      if (line[i] === '`') {
        const ticks = line.slice(i).match(/^`+/)[0];
        const end = line.indexOf(ticks, i + ticks.length);
        if (end !== -1) {
          flush();
          if (needsInlineTokenSpace(output.at(-1))) output += ' ';
          output += line.slice(i, end + ticks.length);
          i = end + ticks.length;
          if (needsInlineTokenSpace(line[i])) output += ' ';
          continue;
        }
      }
      if (line[i] === '$' && !isEscaped(line, i)) {
        const delimiter = line[i + 1] === '$' ? '$$' : '$';
        const end = line.indexOf(delimiter, i + delimiter.length);
        if (end !== -1) {
          flush();
          if (needsInlineTokenSpace(output.at(-1))) output += ' ';
          output += line.slice(i, end + delimiter.length);
          i = end + delimiter.length;
          if (needsInlineTokenSpace(line[i])) output += ' ';
          continue;
        }
      }
      const link = line.slice(i).match(/^(!?\[[^\]]*\]\([^)]*\)|https?:\/\/[^\s<]+)/);
      if (link) {
        flush(); output += link[0]; i += link[0].length; continue;
      }
      plain += line[i];
      i += 1;
    }
    flush();
    return output;
  }

  function formatMarkdown(source) {
    const newline = source.includes('\r\n') ? '\r\n' : '\n';
    const lines = source.replace(/\r\n/g, '\n').split('\n');
    let fence = null;
    let displayMath = false;
    const result = lines.map(line => {
      const fenceMatch = line.match(/^\s*(?:>\s*)*(`{3,}|~{3,})(.*)$/);
      if (fence) {
        if (fenceMatch && fenceMatch[1][0] === fence.character
          && fenceMatch[1].length >= fence.length && !fenceMatch[2].trim()) {
          fence = null;
        }
        return line;
      }
      if (fenceMatch) {
        fence = { character: fenceMatch[1][0], length: fenceMatch[1].length };
        return line;
      }
      if (/^(?: {4}|\t)/.test(line)) return line;
      if (/^\s*\$\$\s*$/.test(line)) {
        displayMath = !displayMath;
        return line;
      }
      if (displayMath) return line;
      return transformUnprotected(line);
    });
    for (let i = 0; i < result.length; i += 1) {
      const line = result[i];
      const next = result[i + 1] ?? '';
      if (!isProseLine(line) || next.trim()) continue;
      const trimmed = line.trimEnd();
      if (!/[。!?;:,,.!?;:)》】”’\])}]$/.test(trimmed)) result[i] = `${trimmed}。${line.slice(trimmed.length)}`;
    }
    return result.join(newline);
  }

  function formatEditor(editor) {
    const original = editorText(editor);
    const formatted = formatMarkdown(original);
    if (formatted === original) return toast('未发现需要整理的内容');
    if (!replaceEditorText(editor, original, formatted)) {
      const partial = editorText(editor);
      if (partial !== original) replaceEditorText(editor, partial, original);
      toast('整理失败,原文已保留');
      return false;
    }
    expansionHistory.delete(editor);
    formatHistory.set(editor, { before: original, after: formatted });
    toast(`已按题解规范整理,可按 ${settings.undoExpansionHotkey || '浏览器撤销键'} 撤销`);
    return true;
  }

  function toast(message) {
    document.querySelector('.lmb-toast')?.remove();
    const element = document.createElement('div');
    element.className = 'lmb-toast';
    element.textContent = message;
    document.body.appendChild(element);
    setTimeout(() => element.remove(), 1600);
  }

  function normalizeRecentInput(editor) {
    if (!settings.liveFormat) return;
    const context = contextAtCaret(editor);
    if (context.fenced || context.inlineCode || context.math) return;
    const before = textBeforeCaret(editor);
    const inlineAfter = before.match(new RegExp(`((?:` + '`[^`\\n]+`' + `|\\$[^$\\n]+\\$))([${CJK}A-Za-z0-9])$`));
    if (inlineAfter) {
      replaceProgrammatically(editor, `${inlineAfter[1]} ${inlineAfter[2]}`, 0, inlineAfter[0].length);
      return;
    }
    const inlineBefore = before.match(new RegExp(`([${CJK}A-Za-z0-9])((?:` + '`[^`\\n]+`' + `|\\$[^$\\n]+\\$))$`));
    if (inlineBefore) {
      replaceProgrammatically(editor, `${inlineBefore[1]} ${inlineBefore[2]}`, 0, inlineBefore[0].length);
      return;
    }
    const match = before.match(new RegExp(`([${CJK}][A-Za-z0-9]+|[A-Za-z0-9]+[${CJK}]|[${CJK}][,;:!?.]|[A-Za-z0-9][,;:!?][${CJK}])$`));
    if (!match) return;
    const formatted = transformPlainText(match[0]);
    if (formatted !== match[0]) replaceProgrammatically(editor, formatted, 0, match[0].length);
  }

  function hotkeyFromEvent(event) {
    if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
    const parts = [];
    if (event.ctrlKey) parts.push('Ctrl');
    if (event.altKey) parts.push('Alt');
    if (event.shiftKey) parts.push('Shift');
    if (event.metaKey) parts.push('Meta');
    let key = event.key === ' ' ? 'Space' : event.key;
    if (key.length === 1) key = key.toUpperCase();
    parts.push(key);
    return parts.join('+');
  }

  function matchesHotkey(event, hotkey) {
    if (!hotkey) return false;
    return hotkeyFromEvent(event).toLowerCase() === hotkey.toLowerCase();
  }

  function requestEditorUndo(editor) {
    const undoEvent = new KeyboardEvent('keydown', {
      key: 'z', code: 'KeyZ', ctrlKey: true, bubbles: true, cancelable: true,
    });
    dispatchingUndo = true;
    try { editor.dispatchEvent(undoEvent); }
    finally { dispatchingUndo = false; }
    if (!undoEvent.defaultPrevented) {
      try { document.execCommand('undo'); } catch (_) { /* ignored */ }
    }
  }

  function handleKeydown(event, editor) {
    activeEditor = editor;
    if (dispatchingUndo) return;
    if (!dispatchingUndo && matchesHotkey(event, settings.undoExpansionHotkey)) {
      event.preventDefault();
      event.stopImmediatePropagation();
      if (!undoLastExpansion(editor) && !undoLastFormat(editor)) requestEditorUndo(editor);
      return;
    }
    if (matchesHotkey(event, settings.formatHotkey)) {
      event.preventDefault();
      event.stopImmediatePropagation();
      formatEditor(editor);
      return;
    }
    if (popup) {
      if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
        event.preventDefault();
        const delta = event.key === 'ArrowDown' ? 1 : -1;
        popupIndex = (popupIndex + delta + popupItems.length) % popupItems.length;
        renderPopup();
        return;
      }
      if (event.key === 'Enter' || event.key === 'Tab') {
        event.preventDefault();
        acceptCompletion();
        return;
      }
      if (event.key === 'Escape') {
        event.preventDefault();
        closePopup();
        return;
      }
    }
    if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || composing) return;

    const selection = selectionIn(editor);
    const context = contextAtCaret(editor);
    if (settings.latexScripts && context.math && (event.key === '^' || event.key === '_')) {
      event.preventDefault();
      insertText(editor, `${event.key}{}`, 1);
      return;
    }
    if (settings.latexAliases && context.math && event.key === '*') {
      event.preventDefault();
      applyExpansion(editor, '*', '\\times', 0, 0);
      return;
    }
    if (settings.liveFormat && event.key === 'Enter' && !event.shiftKey) {
      const line = context.line;
      const isFenceLine = /^\s*(`{3,}|~{3,})/.test(line);
      if (!context.fenced && !context.inlineCode && !context.math && !isFenceLine
        && isProseLine(line) && !/[。!?;:,,.!?;:)》】”’\])}]\s*$/.test(line)) {
        insertText(editor, '。');
      }
      return;
    }
    if (!selection) return;

    if (settings.markdownPairs && event.key === '`' && selection.isCollapsed) {
      const before = context.line;
      const after = charAfterCaret(editor);
      if (before.endsWith('``') && after === '`') {
        event.preventDefault();
        const openingLine = currentLine(editor);
        const lineIndex = [...editor.children].filter(child => child.classList?.contains('cm-line')).indexOf(openingLine);
        const openingOffset = before.length - 2;
        if (selectAroundCaret(editor, 2, 1, '```') && insertText(editor, '```\n```')) {
          const updatedLines = [...editor.children].filter(child => child.classList?.contains('cm-line'));
          moveCaretToTextOffset(updatedLines[lineIndex] || openingLine, openingOffset + 3);
          updateCompletions(editor);
        }
        return;
      }
      if (before.endsWith('`') && after === '`') {
        event.preventDefault();
        insertText(editor, '`');
        return;
      }
    }

    if ((settings.pairs || settings.markdownPairs) && event.key === 'Backspace' && selection.isCollapsed) {
      const before = context.line.at(-1);
      const after = charAfterCaret(editor);
      const pairEnabled = before === '$' || before === '`' ? settings.markdownPairs : settings.pairs;
      if (pairEnabled && before && PAIRS.get(before) === after) {
        event.preventDefault();
        selectBackward(editor, 1);
        selection.modify('extend', 'forward', 'character');
        insertText(editor, '');
      }
      return;
    }

    if (settings.markdownPairs && (event.key === '*' || event.key === '~') && selection.isCollapsed && context.line.endsWith(event.key)) {
      event.preventDefault();
      insertText(editor, `${event.key}${event.key}${event.key}`, 2);
      return;
    }

    if (settings.markdownPairs && event.key === '$' && selection.isCollapsed && context.line.endsWith('$') && charAfterCaret(editor) === '$') {
      event.preventDefault();
      selection.modify('extend', 'forward', 'character');
      insertText(editor, '$\n\n$$', 2);
      return;
    }

    const pairEnabled = event.key === '$' || event.key === '`' ? settings.markdownPairs : settings.pairs;
    if (!pairEnabled) return;
    if (CLOSERS.has(event.key) && selection.isCollapsed && charAfterCaret(editor) === event.key) {
      event.preventDefault();
      selection.modify('move', 'forward', 'character');
      return;
    }

    const close = PAIRS.get(event.key);
    if (!close) return;
    event.preventDefault();
    const selected = selection.toString();
    const inlinePrefix = selection.isCollapsed && (event.key === '$' || event.key === '`')
      && needsInlineTokenSpace(context.line.at(-1)) ? ' ' : '';
    insertText(editor, `${inlinePrefix}${event.key}${selected}${close}`, close.length, selected.length);
  }

  function handleInput(event, editor) {
    activeEditor = editor;
    if (!composing && programmaticInputDepth === 0) {
      const isInsertion = event.inputType?.startsWith('insert') || event.data != null;
      if (isInsertion && !tryDotShortcut(editor) && !tryLatexShortcut(editor) && !tryLatexTemplate(editor)) normalizeRecentInput(editor);
      if (settings.pairs && PAIRS.has(event.data) && /[(【“‘]/.test(event.data || '') && charAfterCaret(editor) !== PAIRS.get(event.data)) {
        insertText(editor, PAIRS.get(event.data), 1);
      }
      updateCompletions(editor);
      if (event.inputType?.startsWith('delete')) {
        requestAnimationFrame(() => {
          if (editor.isConnected && !composing) updateCompletions(editor);
        });
      }
    }
  }

  function saveSettings() {
    try { localStorage.setItem('lmb-settings', JSON.stringify(settings)); } catch (_) { /* ignored */ }
    document.querySelectorAll('.lmb-tool[data-action="format"]').forEach(button => {
      const title = `按题解规范整理${settings.formatHotkey ? ` (${settings.formatHotkey})` : ''}`;
      button.setAttribute('aria-label', title);
      const tooltip = button.querySelector('.cs-tooltip');
      if (tooltip) tooltip.textContent = title;
    });
  }

  function buildSettingsMenu(host) {
    host.querySelector('.lmb-menu')?.remove();
    const menu = document.createElement('div');
    menu.className = 'lmb-menu';
    const addTitle = text => {
      const title = document.createElement('div');
      title.className = 'lmb-menu-title';
      title.textContent = text;
      menu.appendChild(title);
    };
    addTitle('自动展开');
    const labels = {
      pairs: '括号与引号配对',
      markdownPairs: 'Markdown 与公式定界符配对',
      latexTemplates: 'LaTeX 参数模板(\\sum、\\frac 等)',
      latexAliases: '公式快捷替换(<=、.、xor 等)',
      latexScripts: '上下标花括号(^、_)',
      completion: '显示语法补全列表',
      liveFormat: '即时规范空格和标点',
    };
    Object.entries(labels).forEach(([key, labelText]) => {
      const label = document.createElement('label');
      const input = document.createElement('input');
      input.type = 'checkbox';
      input.checked = settings[key];
      input.addEventListener('change', () => {
        settings[key] = input.checked;
        saveSettings();
      });
      label.append(input, document.createTextNode(labelText));
      menu.appendChild(label);
    });
    addTitle('快捷键');
    const hotkeys = {
      undoExpansionHotkey: '撤销展开/上一步',
      formatHotkey: '题解格式整理',
    };
    Object.entries(hotkeys).forEach(([key, labelText]) => {
      const row = document.createElement('div');
      row.className = 'lmb-hotkey-row';
      const text = document.createElement('span');
      text.textContent = labelText;
      const input = document.createElement('input');
      input.className = 'lmb-hotkey';
      input.readOnly = true;
      input.value = settings[key];
      input.title = '点击后直接按下新的组合键;按 Backspace 清除';
      input.addEventListener('keydown', event => {
        event.preventDefault();
        event.stopPropagation();
        if (event.key === 'Escape') return input.blur();
        if ((event.key === 'Backspace' || event.key === 'Delete') && !event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
          settings[key] = '';
          input.value = '';
          saveSettings();
          return;
        }
        const hotkey = hotkeyFromEvent(event);
        if (!hotkey) return;
        settings[key] = hotkey;
        input.value = hotkey;
        saveSettings();
      });
      row.append(text, input);
      menu.appendChild(row);
    });
    const note = document.createElement('div');
    note.className = 'lmb-menu-note';
    note.textContent = '点击快捷键框后按新组合键;Backspace 可清除。';
    menu.appendChild(note);
    const reset = document.createElement('button');
    reset.type = 'button';
    reset.className = 'lmb-reset';
    reset.textContent = '恢复默认设置';
    reset.addEventListener('click', () => {
      settings = { ...DEFAULT_SETTINGS };
      saveSettings();
      buildSettingsMenu(host);
    });
    menu.appendChild(reset);
    host.appendChild(menu);
    const dismiss = event => {
      if (!host.contains(event.target)) { menu.remove(); document.removeEventListener('mousedown', dismiss, true); }
    };
    setTimeout(() => document.addEventListener('mousedown', dismiss, true));
  }

  function iconButton(title, svgPath, handler) {
    const tool = document.createElement('span');
    tool.className = 'cs-toolbar-tool lmb-tool';
    tool.tabIndex = 0;
    tool.setAttribute('role', 'button');
    tool.setAttribute('aria-label', title);
    tool.innerHTML = `<svg class="cs-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${svgPath}</svg><span class="cs-tooltip"></span>`;
    tool.querySelector('.cs-tooltip').textContent = title;
    tool.addEventListener('mousedown', event => event.preventDefault());
    tool.addEventListener('click', handler);
    tool.addEventListener('keydown', event => {
      if (event.key !== 'Enter' && event.key !== ' ') return;
      event.preventDefault();
      handler(event);
    });
    return tool;
  }

  function findNativeToolbar(editor) {
    for (let ancestor = editor.parentElement; ancestor && ancestor !== document.body; ancestor = ancestor.parentElement) {
      const toolbars = ancestor.querySelectorAll('.cs-toolbar');
      if (toolbars.length) return toolbars[0];
    }
    const toolbars = document.querySelectorAll('.cs-toolbar');
    return toolbars.length === 1 ? toolbars[0] : null;
  }

  function toolbarEditor(toolbar) {
    const editor = toolbarEditors.get(toolbar);
    if (editor?.isConnected) return editor;
    return activeEditor?.isConnected ? activeEditor : null;
  }

  function mountToolbar(editor) {
    const toolbar = findNativeToolbar(editor);
    if (!toolbar) return false;
    toolbarEditors.set(toolbar, editor);
    if (getComputedStyle(toolbar).position === 'static') toolbar.style.position = 'relative';
    if (toolbar.querySelector('.lmb-toolbar-group')) return true;

    const group = document.createElement('span');
    group.className = 'cs-toolbar-group lmb-toolbar-group';
    const formatTitle = `按题解规范整理${settings.formatHotkey ? ` (${settings.formatHotkey})` : ''}`;
    const formatButton = iconButton(formatTitle, '<path d="M4 7h10M4 12h16M4 17h10"/><path d="m17 15 3 3-3 3"/>', () => {
      const current = toolbarEditor(toolbar);
      if (current) formatEditor(current);
      else toast('请先点入 Markdown 编辑器');
    });
    formatButton.dataset.action = 'format';
    const settingsButton = iconButton('Luogu Markdown Better 设置', '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1-2.8 2.8-.1-.1a1.7 1.7 0 0 0-1.9-.3 1.7 1.7 0 0 0-1 1.6v.2h-4V21a1.7 1.7 0 0 0-1-1.6 1.7 1.7 0 0 0-1.9.3l-.1.1L4.2 17l.1-.1a1.7 1.7 0 0 0 .3-1.9A1.7 1.7 0 0 0 3 14H2.8v-4H3a1.7 1.7 0 0 0 1.6-1 1.7 1.7 0 0 0-.3-1.9L4.2 7 7 4.2l.1.1a1.7 1.7 0 0 0 1.9.3A1.7 1.7 0 0 0 10 3V2.8h4V3a1.7 1.7 0 0 0 1 1.6 1.7 1.7 0 0 0 1.9-.3l.1-.1L19.8 7l-.1.1a1.7 1.7 0 0 0-.3 1.9 1.7 1.7 0 0 0 1.6 1h.2v4H21a1.7 1.7 0 0 0-1.6 1Z"/>', () => buildSettingsMenu(settingsButton));
    group.append(formatButton, settingsButton);

    const areas = [...toolbar.children].filter(child => child.tagName === 'DIV');
    (areas.at(-1) || toolbar).appendChild(group);
    return true;
  }

  function attach(editor) {
    mountToolbar(editor);
    if (editor.dataset.lmbAttached) return;
    editor.dataset.lmbAttached = VERSION;
    editor.addEventListener('focus', () => { activeEditor = editor; });
    editor.addEventListener('keydown', event => handleKeydown(event, editor), true);
    editor.addEventListener('input', event => handleInput(event, editor));
    editor.addEventListener('compositionstart', () => { composing = true; closePopup(); });
    editor.addEventListener('compositionend', () => {
      composing = false;
      normalizeRecentInput(editor);
      setTimeout(() => normalizeRecentInput(editor));
      updateCompletions(editor);
    });
    editor.addEventListener('blur', () => setTimeout(() => { if (!popup?.matches(':hover')) closePopup(); }, 100));
  }

  function scan(root = document) {
    if (root.matches?.(EDITOR_SELECTOR)) attach(root);
    root.querySelectorAll?.(EDITOR_SELECTOR).forEach(attach);
    if (root.matches?.('.cs-toolbar') || root.querySelector?.('.cs-toolbar')) {
      document.querySelectorAll(EDITOR_SELECTOR).forEach(attach);
    }
  }

  function init() {
    addStyles();
    scan();
    new MutationObserver(records => records.forEach(record => record.addedNodes.forEach(node => {
      if (node.nodeType === Node.ELEMENT_NODE) scan(node);
    }))).observe(document.documentElement, { childList: true, subtree: true });
    if (typeof GM_registerMenuCommand === 'function') {
      GM_registerMenuCommand('整理当前 Markdown', () => activeEditor ? formatEditor(activeEditor) : toast('请先点入 Markdown 编辑器'));
    }
  }

  window.LuoguMarkdownBetter = Object.freeze({ version: VERSION, formatMarkdown, scan });
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init, { once: true });
  else init();
})();

Vector Log · 算法竞赛学习笔记

Built with Nuxt UI & Nuxt MDC