An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support pasting editable Microsoft Word and WPS formulas https://github.com/siyuan-note/siyuan/issues/18747
Daniel0e46e030bfd6
diff --git a/app/electron/main.js b/app/electron/main.jsindex a8e9980be3..c1f1950eaa 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -1645,6 +1645,43 @@ app.whenReady().then(() => {if (data.cmd === "clipboardRead") {return clipboard.read(data.format);}+ if (data.cmd === "clipboardReadMathML") {+ if (typeof data.text !== "string" ||+ normalizeClipboardText(clipboard.readText()) !== normalizeClipboardText(data.text)) {+ return "";+ }+ const formats = clipboard.availableFormats().filter((format) =>+ /^mathml(?: presentation)?$/i.test(format));+ formats.push("MathML", "MathML Presentation");+ // availableFormats 可能不包含 Office 原生 MathML 格式,需要直接尝试标准格式名+ for (const format of new Set(formats)) {+ const buffer = clipboard.readBuffer(format);+ if (buffer.length === 0 || buffer.length > 1024 * 1024 || buffer.length % 2 !== 0) {+ continue;+ }+ const mathML = buffer.toString("utf16le")+ .replace(/^\uFEFF/, "")+ .replace(/\0+$/, "")+ .trim();+ if (/<(?:[A-Za-z_][\w.-]*:)?math(?:\s|>)/i.test(mathML)) {+ return mathML;+ }+ }+ return "";+ }+ if (data.cmd === "clipboardReadOffice") {+ if (typeof data.text !== "string" ||+ normalizeClipboardText(clipboard.readText()) !== normalizeClipboardText(data.text)) {+ return "";+ }+ const buffer = clipboard.readBuffer("Embed Source");+ const compoundFileSignature = Buffer.from([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]);+ if (buffer.length === 0 || buffer.length > 8 * 1024 * 1024 ||+ !buffer.subarray(0, compoundFileSignature.length).equals(compoundFileSignature)) {+ return "";+ }+ return buffer.toString("base64");+ }if (data.cmd === "clipboardReadWPS") {if (typeof data.text !== "string" ||normalizeClipboardText(clipboard.readText()) !== normalizeClipboardText(data.text)) {diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex f5b6541862..6270081d27 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -501,6 +501,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenlet siyuanHTML: string;let files: FileList | DataTransferItemList | File[];let vscodeEditorData = "";+ let mathML = "";+ let office = "";let wps = "";if ("clipboardData" in event) {textHTML = event.clipboardData.getData("text/html");@@ -532,10 +534,20 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven/// #if !BROWSERif (!("dataTransfer" in event) && !siyuanHTML && textHTML && textPlain) {- wps = await ipcRenderer.invoke(Constants.SIYUAN_GET, {- cmd: "clipboardReadWPS",- text: textPlain,- });+ [mathML, office, wps] = await Promise.all([+ ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "clipboardReadMathML",+ text: textPlain,+ }),+ ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "clipboardReadOffice",+ text: textPlain,+ }),+ ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "clipboardReadWPS",+ text: textPlain,+ }),+ ]);}if (!siyuanHTML && !textHTML && !textPlain && ("clipboardData" in event)) {const localFiles: ILocalFiles[] = await getLocalFiles();@@ -611,6 +623,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvensiyuanHTML = normalizedResponse.siyuanHTML;files = normalizedResponse.files;originalTextHTML = textHTML;+ mathML = "";+ office = "";wps = "";}}@@ -916,6 +930,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenfetchPost("/api/lute/html2BlockDOM", {dom: tempElement.innerHTML,text: textPlain,+ mathML,+ office,wps,}, (response) => {insertHTML(response.data, protyle, false, false, true);diff --git a/kernel/api/lute.go b/kernel/api/lute.goindex ec3a7cb722..d1bb1621ab 100644--- a/kernel/api/lute.go+++ b/kernel/api/lute.go@@ -106,10 +106,18 @@ func html2BlockDOM(c *gin.Context) {return}text, _ := arg["text"].(string)+ mathML, _ := arg["mathML"].(string)+ office, _ := arg["office"].(string)wps, _ := arg["wps"].(string)luteEngine := util.NewLute()luteEngine.SetHTMLTag2TextMark(true)luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})+ // 将 Word 和 WPS 公式转换为可编辑公式 https://github.com/siyuan-note/siyuan/issues/18747+ if markdown, converted := convertClipboardMath(mathML, office, wps); converted {+ luteEngine.SetInlineMath(true)+ ret.Data = luteEngine.Md2BlockDOM(markdown, false)+ return+ }// 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748dom = normalizeWPSComments(dom, text, wps)dom = normalizeMSWordComments(dom)diff --git a/kernel/api/lute_clipboard_math.go b/kernel/api/lute_clipboard_math.gonew file mode 100644index 0000000000..42f92f9fe0--- /dev/null+++ b/kernel/api/lute_clipboard_math.go@@ -0,0 +1,357 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ archivezip "archive/zip"+ "bytes"+ "context"+ "encoding/base64"+ "encoding/json"+ "encoding/xml"+ "fmt"+ "io"+ "os/exec"+ "strings"+ "time"+ "unicode"++ "github.com/88250/gulu"+ "github.com/richardlehane/mscfb"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const (+ maxClipboardMathMLBytes = 1024 * 1024+ maxClipboardMathPandocOutput = 2 * 1024 * 1024+ clipboardMathPandocTimeout = 5 * time.Second+ officeCompoundFileSignature = "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"+)++type clipboardMath struct {+ tex string+ display bool+}++type pandocNode struct {+ typeName string+ content json.RawMessage+}++func (node *pandocNode) UnmarshalJSON(data []byte) error {+ var value struct {+ TypeName string `json:"t"`+ Content json.RawMessage `json:"c"`+ }+ if err := json.Unmarshal(data, &value); err != nil {+ return err+ }+ node.typeName = value.TypeName+ node.content = value.Content+ return nil+}++type clipboardMathPandocRunner func(from, to string, input []byte) ([]byte, error)++func convertClipboardMath(mathML, office, wps string) (markdown string, converted bool) {+ markdown, converted, err := convertClipboardMathWithRunner(mathML, office, wps, runClipboardMathPandoc)+ if err != nil {+ logging.LogWarnf("convert clipboard math with pandoc failed: %s", err)+ }+ return+}++func convertClipboardMathWithRunner(mathML, office, wps string, runner clipboardMathPandocRunner) (markdown string, converted bool, err error) {+ from, input, ok := clipboardMathPandocInput(mathML, office, wps)+ if !ok {+ return+ }+ output, err := runner(from, "json", input)+ if err != nil {+ return "", false, err+ }+ if len(output) > maxClipboardMathPandocOutput {+ return "", false, fmt.Errorf("pandoc output is too large")+ }+ math, ok := parsePandocSingleMath(output)+ if !ok {+ if from != "docx" || !isSimplePandocMathDocument(output) {+ return "", false, nil+ }+ markdownOutput, writeErr := runner("json", "markdown-raw_attribute", output)+ if writeErr != nil {+ return "", false, writeErr+ }+ if len(markdownOutput) > maxClipboardMathPandocOutput {+ return "", false, fmt.Errorf("pandoc output is too large")+ }+ markdown = strings.TrimSpace(strings.ReplaceAll(string(markdownOutput), "<!-- -->", ""))+ return markdown, markdown != "", nil+ }+ if math.display {+ return "$$\n" + math.tex + "\n$$", true, nil+ }+ return "$" + math.tex + "$", true, nil+}++func clipboardMathPandocInput(mathML, office, wps string) (from string, input []byte, ok bool) {+ if from, input, ok = wpsClipboardMathInput(wps); ok {+ return+ }+ if from, input, ok = officeClipboardMathInput(office); ok {+ return+ }+ if normalized, valid := normalizeClipboardMathML(mathML); valid {+ return "html", []byte(normalized), true+ }+ return+}++func normalizeClipboardMathML(mathML string) (normalized string, ok bool) {+ if len(mathML) == 0 || len(mathML) > maxClipboardMathMLBytes {+ return+ }+ normalized = strings.TrimFunc(mathML, func(r rune) bool {+ return unicode.IsSpace(r) || r == '\u0000' || r == '\uFEFF'+ })+ decoder := xml.NewDecoder(strings.NewReader(normalized))+ for {+ token, err := decoder.Token()+ if err != nil {+ return "", false+ }+ if start, isStart := token.(xml.StartElement); isStart {+ return normalized, start.Name.Local == "math"+ }+ }+}++func wpsClipboardMathInput(encoded string) (from string, input []byte, ok bool) {+ if encoded == "" || len(encoded) > base64.StdEncoding.EncodedLen(maxWPSClipboardBytes) {+ return+ }+ data, err := base64.StdEncoding.DecodeString(encoded)+ if err != nil || len(data) > maxWPSClipboardBytes {+ return+ }+ if !isClipboardMathDOCX(data) {+ return+ }+ return "docx", data, true+}++func officeClipboardMathInput(encoded string) (from string, input []byte, ok bool) {+ if encoded == "" || len(encoded) > base64.StdEncoding.EncodedLen(maxWPSClipboardBytes) {+ return+ }+ data, err := base64.StdEncoding.DecodeString(encoded)+ if err != nil || len(data) > maxWPSClipboardBytes ||+ !bytes.HasPrefix(data, []byte(officeCompoundFileSignature)) {+ return+ }+ compoundFile, err := mscfb.New(bytes.NewReader(data))+ if err != nil {+ return+ }+ for entry, nextErr := compoundFile.Next(); nextErr == nil; entry, nextErr = compoundFile.Next() {+ if !strings.EqualFold(entry.Name, "Package") || entry.Size <= 0 || entry.Size > maxWPSClipboardBytes {+ continue+ }+ packageData, readErr := io.ReadAll(io.LimitReader(entry, maxWPSClipboardBytes+1))+ if readErr != nil || len(packageData) > maxWPSClipboardBytes || !isClipboardMathDOCX(packageData) {+ return+ }+ return "docx", packageData, true+ }+ return+}++func isClipboardMathDOCX(data []byte) bool {+ archive, err := archivezip.NewReader(bytes.NewReader(data), int64(len(data)))+ if err != nil {+ return false+ }+ var totalUncompressed uint64+ for _, file := range archive.File {+ if file.UncompressedSize64 > maxWPSClipboardBytes ||+ totalUncompressed > maxWPSClipboardBytes-file.UncompressedSize64 {+ return false+ }+ totalUncompressed += file.UncompressedSize64+ }+ documentXML, err := readWPSClipboardFile(archive, "word/document.xml")+ if err != nil || !bytes.Contains(documentXML, []byte("<m:oMath")) {+ return false+ }+ return true+}++func runClipboardMathPandoc(from, to string, input []byte) ([]byte, error) {+ pandocBinPath := util.GetPandocRuntime().BinPath+ if pandocBinPath == "" {+ return nil, util.ErrPandocNotFound+ }+ ctx, cancel := context.WithTimeout(context.Background(), clipboardMathPandocTimeout)+ defer cancel()+ command := exec.CommandContext(ctx, pandocBinPath, "--from="+from, "--to="+to, "--wrap=none")+ gulu.CmdAttr(command)+ command.Stdin = bytes.NewReader(input)+ output, err := command.Output()+ if ctx.Err() != nil {+ return nil, ctx.Err()+ }+ if err != nil {+ return nil, err+ }+ return output, nil+}++func isSimplePandocMathDocument(data []byte) bool {+ var document struct {+ Blocks []pandocNode `json:"blocks"`+ }+ if err := json.Unmarshal(data, &document); err != nil {+ return false+ }+ hasMath := false+ for _, block := range document.Blocks {+ switch block.typeName {+ case "Null":+ continue+ case "Para", "Plain":+ var inlines []pandocNode+ if len(block.content) == 0 || bytes.Equal(bytes.TrimSpace(block.content), []byte("null")) {+ continue+ }+ if err := json.Unmarshal(block.content, &inlines); err != nil {+ return false+ }+ meaningfulCount := 0+ displayMath := false+ for _, inline := range inlines {+ switch inline.typeName {+ case "Math":+ math, valid := parsePandocMath(inline.content)+ if !valid {+ return false+ }+ hasMath = true+ displayMath = displayMath || math.display+ meaningfulCount+++ case "Str":+ if !isIgnorablePandocInline(inline) {+ meaningfulCount+++ }+ case "Space", "SoftBreak", "LineBreak":+ default:+ return false+ }+ }+ if displayMath && meaningfulCount != 1 {+ return false+ }+ default:+ return false+ }+ }+ return hasMath+}++func parsePandocSingleMath(data []byte) (ret clipboardMath, ok bool) {+ var document struct {+ Blocks []pandocNode `json:"blocks"`+ }+ if err := json.Unmarshal(data, &document); err != nil {+ return+ }+ found := false+ for _, block := range document.Blocks {+ switch block.typeName {+ case "Null":+ continue+ case "Para", "Plain":+ var inlines []pandocNode+ if len(block.content) == 0 || bytes.Equal(bytes.TrimSpace(block.content), []byte("null")) {+ continue+ }+ if err := json.Unmarshal(block.content, &inlines); err != nil {+ return clipboardMath{}, false+ }+ for _, inline := range inlines {+ if inline.typeName == "Math" {+ if found {+ return clipboardMath{}, false+ }+ math, valid := parsePandocMath(inline.content)+ if !valid {+ return clipboardMath{}, false+ }+ ret = math+ found = true+ continue+ }+ if !isIgnorablePandocInline(inline) {+ return clipboardMath{}, false+ }+ }+ default:+ return clipboardMath{}, false+ }+ }+ return ret, found+}++func parsePandocMath(content json.RawMessage) (ret clipboardMath, ok bool) {+ var parts []json.RawMessage+ if err := json.Unmarshal(content, &parts); err != nil || len(parts) != 2 {+ return+ }+ var mathType pandocNode+ if err := json.Unmarshal(parts[0], &mathType); err != nil {+ return+ }+ if mathType.typeName != "InlineMath" && mathType.typeName != "DisplayMath" {+ return+ }+ if err := json.Unmarshal(parts[1], &ret.tex); err != nil {+ return clipboardMath{}, false+ }+ ret.tex = strings.TrimSpace(ret.tex)+ if ret.tex == "" {+ return clipboardMath{}, false+ }+ ret.display = mathType.typeName == "DisplayMath"+ return ret, true+}++func isIgnorablePandocInline(inline pandocNode) bool {+ switch inline.typeName {+ case "Space", "SoftBreak", "LineBreak":+ return true+ case "Str":+ var text string+ if err := json.Unmarshal(inline.content, &text); err != nil {+ return false+ }+ return strings.TrimFunc(text, func(r rune) bool {+ return unicode.IsSpace(r) || r == '\u200B' || r == '\uFEFF'+ }) == ""+ default:+ return false+ }+}diff --git a/kernel/api/lute_clipboard_math_test.go b/kernel/api/lute_clipboard_math_test.gonew file mode 100644index 0000000000..9ca46bbac5--- /dev/null+++ b/kernel/api/lute_clipboard_math_test.go@@ -0,0 +1,234 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "bytes"+ "encoding/base64"+ "errors"+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++const (+ inlineMathPandocJSON = `{"pandoc-api-version":[1,23,1,2],"meta":{},"blocks":[{"t":"Para","c":[{"t":"Math","c":[{"t":"InlineMath"},"x+y"]},{"t":"Str","c":"\u200b"}]}]}`+ displayMathPandocJSON = `{"pandoc-api-version":[1,23,1,2],"meta":{},"blocks":[{"t":"Plain","c":[{"t":"Math","c":[{"t":"DisplayMath"},"\\frac{S}{N}"]}]}]}`+)++func TestConvertClipboardMathWithRunner(t *testing.T) {+ mathML := `<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math>`+ markdown, converted, err := convertClipboardMathWithRunner(mathML, "", "", func(from, to string, input []byte) ([]byte, error) {+ if from != "html" || to != "json" || string(input) != mathML {+ t.Fatalf("unexpected MathML input: from=%q to=%q input=%q", from, to, input)+ }+ return []byte(inlineMathPandocJSON), nil+ })+ if err != nil || !converted || markdown != "$x+y$" {+ t.Fatalf("unexpected MathML conversion: markdown=%q converted=%v err=%v", markdown, converted, err)+ }++ wps := buildWPSClipboard(t, `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><w:body><m:oMathPara><m:oMath><m:f><m:num><m:r><m:t>S</m:t></m:r></m:num><m:den><m:r><m:t>N</m:t></m:r></m:den></m:f></m:oMath></m:oMathPara></w:body></w:document>`, "")+ markdown, converted, err = convertClipboardMathWithRunner("", "", wps, func(from, to string, input []byte) ([]byte, error) {+ if from != "docx" || to != "json" || len(input) < 2 || !bytes.Equal(input[:2], []byte{'P', 'K'}) {+ t.Fatalf("unexpected WPS input: from=%q to=%q input=%v", from, to, input)+ }+ return []byte(displayMathPandocJSON), nil+ })+ if err != nil || !converted || markdown != "$$\n\\frac{S}{N}\n$$" {+ t.Fatalf("unexpected WPS conversion: markdown=%q converted=%v err=%v", markdown, converted, err)+ }+}++func TestConvertClipboardMathMixedWPS(t *testing.T) {+ wps := buildWPSClipboard(t, `<w:document xmlns:w="urn:w" xmlns:m="urn:m"><w:body><m:oMath/></w:body></w:document>`, "")+ pandocJSON := `{"pandoc-api-version":[1,23,1,2],"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"123"}]},{"t":"Para","c":[{"t":"Math","c":[{"t":"DisplayMath"},"\\frac{S}{N}"]}]},{"t":"Para","c":[{"t":"Str","c":"456"}]}]}`+ markdownOutput := "123\n\n$$\\frac{S}{N}$$\n\n456\n"+ calls := 0+ markdown, converted, err := convertClipboardMathWithRunner("", "", wps, func(from, to string, input []byte) ([]byte, error) {+ calls+++ switch calls {+ case 1:+ if from != "docx" || to != "json" {+ t.Fatalf("unexpected reader call: from=%q to=%q", from, to)+ }+ return []byte(pandocJSON), nil+ case 2:+ if from != "json" || to != "markdown-raw_attribute" || string(input) != pandocJSON {+ t.Fatalf("unexpected writer call: from=%q to=%q input=%q", from, to, input)+ }+ return []byte(markdownOutput), nil+ default:+ t.Fatalf("unexpected runner call: %d", calls)+ return nil, nil+ }+ })+ if err != nil || !converted || markdown != strings.TrimSpace(markdownOutput) || calls != 2 {+ t.Fatalf("unexpected mixed conversion: markdown=%q converted=%v calls=%d err=%v", markdown, converted, calls, err)+ }++ adjacentJSON := `{"pandoc-api-version":[1,23,1,2],"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"Foo"},{"t":"Space"},{"t":"Math","c":[{"t":"InlineMath"},"x"]},{"t":"Str","c":"111"}]}]}`+ calls = 0+ markdown, converted, err = convertClipboardMathWithRunner("", "", wps, func(from, to string, input []byte) ([]byte, error) {+ calls+++ if calls == 1 {+ return []byte(adjacentJSON), nil+ }+ if from != "json" || to != "markdown-raw_attribute" || string(input) != adjacentJSON {+ t.Fatalf("unexpected adjacent writer call: from=%q to=%q input=%q", from, to, input)+ }+ return []byte("Foo $x$<!-- -->111\n"), nil+ })+ if err != nil || !converted || markdown != "Foo $x$111" || calls != 2 {+ t.Fatalf("unexpected adjacent conversion: markdown=%q converted=%v calls=%d err=%v", markdown, converted, calls, err)+ }+}++func TestNormalizeClipboardMathML(t *testing.T) {+ input := "\uFEFF \r\n<?xml version=\"1.0\"?><m:math xmlns:m=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><m:mi>x</m:mi></m:math>\u0000"+ normalized, ok := normalizeClipboardMathML(input)+ if !ok || !strings.HasPrefix(normalized, `<?xml version="1.0"?><m:math`) || !strings.HasSuffix(normalized, `</m:math>`) {+ t.Fatalf("unexpected normalized MathML: normalized=%q ok=%v", normalized, ok)+ }+ if _, ok = normalizeClipboardMathML(`<html><math/></html>`); ok {+ t.Fatal("non-MathML root was accepted")+ }+}++func TestClipboardMathPandocInputPriority(t *testing.T) {+ mathML := `<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math>`+ wps := buildWPSClipboard(t, `<w:document xmlns:w="urn:w" xmlns:m="urn:m"><w:body><m:oMath/></w:body></w:document>`, "")+ from, input, ok := clipboardMathPandocInput(mathML, "", wps)+ if !ok || from != "docx" || len(input) < 2 || !bytes.Equal(input[:2], []byte{'P', 'K'}) {+ t.Fatalf("WPS DOCX was not preferred: from=%q input=%v ok=%v", from, input, ok)+ }+ invalidOffice := base64.StdEncoding.EncodeToString([]byte("not a compound file"))+ from, input, ok = clipboardMathPandocInput(mathML, invalidOffice, "")+ if !ok || from != "html" || string(input) != mathML {+ t.Fatalf("MathML fallback failed: from=%q input=%q ok=%v", from, input, ok)+ }+}++func TestConvertClipboardMathFallback(t *testing.T) {+ runnerCalled := false+ wps := buildWPSClipboard(t, `<w:document xmlns:w="urn:w"><w:body><w:p/></w:body></w:document>`, "")+ _, converted, err := convertClipboardMathWithRunner("not MathML", "", wps, func(string, string, []byte) ([]byte, error) {+ runnerCalled = true+ return nil, nil+ })+ if err != nil || converted || runnerCalled {+ t.Fatalf("unexpected fallback: converted=%v called=%v err=%v", converted, runnerCalled, err)+ }++ expectedErr := errors.New("pandoc failed")+ _, converted, err = convertClipboardMathWithRunner(`<math/>`, "", "", func(string, string, []byte) ([]byte, error) {+ return nil, expectedErr+ })+ if converted || !errors.Is(err, expectedErr) {+ t.Fatalf("unexpected runner error: converted=%v err=%v", converted, err)+ }++ mixedJSON := `{"blocks":[{"t":"Para","c":[{"t":"Str","c":"before"}]},{"t":"Para","c":[{"t":"Math","c":[{"t":"DisplayMath"},"x"]}]}]}`+ calls := 0+ _, converted, err = convertClipboardMathWithRunner("", "", buildWPSClipboard(t,+ `<w:document xmlns:w="urn:w" xmlns:m="urn:m"><w:body><m:oMath/></w:body></w:document>`, ""),+ func(string, string, []byte) ([]byte, error) {+ calls+++ if calls == 1 {+ return []byte(mixedJSON), nil+ }+ return nil, expectedErr+ })+ if converted || !errors.Is(err, expectedErr) || calls != 2 {+ t.Fatalf("unexpected writer error: converted=%v calls=%d err=%v", converted, calls, err)+ }+}++func TestSimplePandocMathDocument(t *testing.T) {+ tests := []struct {+ name string+ input string+ ok bool+ }{+ {name: "display with paragraphs", input: `{"blocks":[{"t":"Para","c":[{"t":"Str","c":"123"}]},{"t":"Para","c":[{"t":"Math","c":[{"t":"DisplayMath"},"x"]}]},{"t":"Para","c":[{"t":"Str","c":"456"}]}]}`, ok: true},+ {name: "inline with text", input: `{"blocks":[{"t":"Para","c":[{"t":"Str","c":"before"},{"t":"Space"},{"t":"Math","c":[{"t":"InlineMath"},"x"]},{"t":"Space"},{"t":"Str","c":"after"}]}]}`, ok: true},+ {name: "multiple math", input: `{"blocks":[{"t":"Para","c":[{"t":"Math","c":[{"t":"InlineMath"},"x"]}]},{"t":"Para","c":[{"t":"Math","c":[{"t":"DisplayMath"},"y"]}]}]}`, ok: true},+ {name: "display with text", input: `{"blocks":[{"t":"Para","c":[{"t":"Str","c":"before"},{"t":"Math","c":[{"t":"DisplayMath"},"x"]}]}]}`},+ {name: "strong", input: `{"blocks":[{"t":"Para","c":[{"t":"Strong","c":[{"t":"Str","c":"text"}]},{"t":"Math","c":[{"t":"InlineMath"},"x"]}]}]}`},+ {name: "image", input: `{"blocks":[{"t":"Para","c":[{"t":"Image","c":[["",[],[]],[],["image.png",""]]},{"t":"Math","c":[{"t":"InlineMath"},"x"]}]}]}`},+ {name: "other block", input: `{"blocks":[{"t":"CodeBlock","c":[["",[],[]],"x"]},{"t":"Para","c":[{"t":"Math","c":[{"t":"InlineMath"},"x"]}]}]}`},+ {name: "no math", input: `{"blocks":[{"t":"Para","c":[{"t":"Str","c":"text"}]}]}`},+ {name: "invalid", input: `{`},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if actual := isSimplePandocMathDocument([]byte(test.input)); actual != test.ok {+ t.Fatalf("unexpected result: %v", actual)+ }+ })+ }+}++func TestParsePandocSingleMath(t *testing.T) {+ tests := []struct {+ name string+ input string+ tex string+ display bool+ ok bool+ }{+ {name: "inline", input: inlineMathPandocJSON, tex: "x+y", ok: true},+ {name: "display", input: displayMathPandocJSON, tex: `\frac{S}{N}`, display: true, ok: true},+ {name: "empty paragraphs", input: `{"blocks":[{"t":"Para","c":[]},{"t":"Para","c":[{"t":"Math","c":[{"t":"InlineMath"},"x"]}]},{"t":"Plain","c":[]}]}`, tex: "x", ok: true},+ {name: "text", input: `{"blocks":[{"t":"Plain","c":[{"t":"Math","c":[{"t":"InlineMath"},"x"]},{"t":"Str","c":"text"}]}]}`},+ {name: "multiple", input: `{"blocks":[{"t":"Plain","c":[{"t":"Math","c":[{"t":"InlineMath"},"x"]},{"t":"Math","c":[{"t":"InlineMath"},"y"]}]}]}`},+ {name: "other block", input: `{"blocks":[{"t":"CodeBlock","c":[["",[],[]],"x"]}]}`},+ {name: "invalid", input: `{`},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ math, ok := parsePandocSingleMath([]byte(test.input))+ if ok != test.ok || math.tex != test.tex || math.display != test.display {+ t.Fatalf("unexpected result: math=%+v ok=%v", math, ok)+ }+ })+ }+}++func TestClipboardMathMarkdownBlockDOM(t *testing.T) {+ luteEngine := util.NewLute()+ luteEngine.SetInlineMath(true)+ inline := luteEngine.Md2BlockDOM("$x+y$", false)+ if !strings.Contains(inline, `data-type="inline-math"`) {+ t.Fatalf("inline math was not generated: %s", inline)+ }+ display := luteEngine.Md2BlockDOM("$$\n\\frac{S}{N}\n$$", false)+ if !strings.Contains(display, `data-type="NodeMathBlock"`) {+ t.Fatalf("display math was not generated: %s", display)+ }+ mixed := luteEngine.Md2BlockDOM("123\n\n$$\\frac{S}{N}$$\n\n456", false)+ formulaIndex := strings.Index(mixed, `data-type="NodeMathBlock"`)+ if textBefore, textAfter := strings.Index(mixed, "123"), strings.Index(mixed, "456"); textBefore < 0 || formulaIndex < textBefore || textAfter < formulaIndex {+ t.Fatalf("mixed content order was not preserved: %s", mixed)+ }+ adjacent := luteEngine.Md2BlockDOM("Foo $x$111", false)+ if !strings.Contains(adjacent, `data-type="inline-math"`) || !strings.Contains(adjacent, "Foo") ||+ !strings.Contains(adjacent, "111") || strings.Contains(adjacent, "{=html}") || strings.Contains(adjacent, "<!--") {+ t.Fatalf("adjacent inline content was not preserved: %s", adjacent)+ }+}diff --git a/kernel/go.mod b/kernel/go.modindex d075f99256..400e558de5 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -64,6 +64,7 @@ require (github.com/pkoukk/tiktoken-go-loader v0.0.2github.com/r3labs/sse/v2 v2.10.0github.com/radovskyb/watcher v1.0.7+ github.com/richardlehane/mscfb v1.0.7github.com/rqlite/sql v0.0.0-20260224021119-1b2524a41372github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06github.com/samber/lo v1.53.0@@ -204,7 +205,6 @@ require (github.com/quic-go/quic-go v0.61.0 // indirectgithub.com/refraction-networking/utls v1.8.2 // indirectgithub.com/restic/chunker v0.5.0 // indirect- github.com/richardlehane/mscfb v1.0.7 // indirectgithub.com/richardlehane/msoleps v1.0.6 // indirectgithub.com/segmentio/asm v1.2.1 // indirectgithub.com/segmentio/encoding v0.5.4 // indirect