Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support pasting editable PowerPoint equations (#18795)

Achuan-2fcca9066fd6a
diff --git a/app/src/protyle/util/officeMath.test.ts b/app/src/protyle/util/officeMath.test.ts
new file mode 100644
index 0000000000..845972ed64
--- /dev/null
+++ b/app/src/protyle/util/officeMath.test.ts
@@ -0,0 +1,14 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {extractOfficeMathHTML} from "./officeMath";
+
+describe("extractOfficeMathHTML", () => {
+ it("extracts PowerPoint OMML before HTML sanitization", () => {
+ const html = "<p><!--[if gte msEquation 12]><m:oMathPara><m:oMath><m:r><span>SNR</span></m:r></m:oMath></m:oMathPara><![endif]--><![if !msEquation]><span>SNR</span><![endif]></p>";
+ assert.equal(extractOfficeMathHTML(html), "<m:oMathPara><m:oMath><m:r><span>SNR</span></m:r></m:oMath></m:oMathPara>");
+ });
+
+ it("ignores ordinary HTML", () => {
+ assert.equal(extractOfficeMathHTML("<p>SNR</p>"), "");
+ });
+});
diff --git a/app/src/protyle/util/officeMath.ts b/app/src/protyle/util/officeMath.ts
new file mode 100644
index 0000000000..9ccb7aa6f6
--- /dev/null
+++ b/app/src/protyle/util/officeMath.ts
@@ -0,0 +1,10 @@
+const OFFICE_MATH_CONDITIONAL_COMMENT = /<!--\s*\[if\s+gte\s+msEquation\s+\d+\]\s*>([\s\S]*?)<!\s*\[endif\]\s*-->/gi;
+
+export const extractOfficeMathHTML = (html: string) => {
+ if (!html) {
+ return "";
+ }
+ return Array.from(html.matchAll(OFFICE_MATH_CONDITIONAL_COMMENT), match => match[1].trim())
+ .filter(Boolean)
+ .join("");
+};
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index ba76f978a8..19eea58944 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -27,6 +27,7 @@ import {extractCrossBlockPasteContext, shouldPreservePastedBlockStructure} from
import {normalizePasteResponse} from "./pasteResponse";
import {applyLuteMarkdownSyntax} from "../render/luteMarkdownSyntax";
import {convertOfficeLists} from "./officeList";
+import {extractOfficeMathHTML} from "./officeMath";
import {
extractWPSPresentationClipboard,
getWPSPresentationFallback,
@@ -526,6 +527,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
let vscodeEditorData = "";
let mathML = "";
let office = "";
+ let officeMathHTML = "";
let wps = "";
let wpsPresentation: IWPSPresentationClipboard | undefined;
let officeListConverted = false;
@@ -563,6 +565,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
// Improve the pasting of selected text in PDF rectangular annotation https://github.com/siyuan-note/siyuan/issues/11629
textPlain = textPlain.replace(/\r\n|\r|\u2028|\u2029/g, "\n");
+ // PowerPoint 将可编辑公式放在条件注释中,必须在 DOM 解析和清理前读取
+ officeMathHTML = extractOfficeMathHTML(textHTML);
/// #if !BROWSER
if (!("dataTransfer" in event) && !siyuanHTML && textHTML && textPlain) {
@@ -657,6 +661,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
originalTextHTML = textHTML;
mathML = "";
office = "";
+ officeMathHTML = extractOfficeMathHTML(textHTML);
wps = "";
wpsPresentation = undefined;
}
@@ -997,6 +1002,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
text: textPlain,
mathML,
office,
+ officeMathHTML,
wps,
}, (response) => {
insertConvertedBlockDOM(protyle, response.data);
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index d1bb1621ab..57726d8aef 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -108,6 +108,7 @@ func html2BlockDOM(c *gin.Context) {
text, _ := arg["text"].(string)
mathML, _ := arg["mathML"].(string)
office, _ := arg["office"].(string)
+ officeMathHTML, _ := arg["officeMathHTML"].(string)
wps, _ := arg["wps"].(string)
luteEngine := util.NewLute()
luteEngine.SetHTMLTag2TextMark(true)
@@ -118,6 +119,11 @@ func html2BlockDOM(c *gin.Context) {
ret.Data = luteEngine.Md2BlockDOM(markdown, false)
return
}
+ if markdown, converted := convertOfficeHTMLClipboardMath(officeMathHTML); converted {
+ luteEngine.SetInlineMath(true)
+ ret.Data = luteEngine.Md2BlockDOM(markdown, false)
+ return
+ }
// 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748
dom = normalizeWPSComments(dom, text, wps)
dom = normalizeMSWordComments(dom)
diff --git a/kernel/api/lute_clipboard_math.go b/kernel/api/lute_clipboard_math.go
index 42f92f9fe0..3e41856599 100644
--- a/kernel/api/lute_clipboard_math.go
+++ b/kernel/api/lute_clipboard_math.go
@@ -24,6 +24,7 @@ import (
"encoding/json"
"encoding/xml"
"fmt"
+ "html"
"io"
"os/exec"
"strings"
@@ -43,6 +44,11 @@ const (
officeCompoundFileSignature = "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
)
+const (
+ officeHTMLOMMLNamespace = "http://schemas.microsoft.com/office/2004/12/omml"
+ docxOMMLNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+)
+
type clipboardMath struct {
tex string
display bool
@@ -76,6 +82,18 @@ func convertClipboardMath(mathML, office, wps string) (markdown string, converte
return
}
+func convertOfficeHTMLClipboardMath(officeMathHTML string) (markdown string, converted bool) {
+ input, ok := officeHTMLClipboardMathInput(officeMathHTML)
+ if !ok {
+ return
+ }
+ markdown, converted, err := convertClipboardMathWithRunner("", "", base64.StdEncoding.EncodeToString(input), runClipboardMathPandoc)
+ if err != nil {
+ logging.LogWarnf("convert Office HTML clipboard math with pandoc failed: %s", err)
+ }
+ return markdown, converted
+}
+
func convertClipboardMathWithRunner(mathML, office, wps string, runner clipboardMathPandocRunner) (markdown string, converted bool, err error) {
from, input, ok := clipboardMathPandocInput(mathML, office, wps)
if !ok {
@@ -181,6 +199,109 @@ func officeClipboardMathInput(encoded string) (from string, input []byte, ok boo
return
}
+func officeHTMLClipboardMathInput(fragment string) (input []byte, ok bool) {
+ if fragment == "" || len(fragment) > maxClipboardMathMLBytes {
+ return
+ }
+ documentBody, ok := normalizeOfficeHTMLOMML(fragment)
+ if !ok {
+ return nil, false
+ }
+ documentXML := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="` + docxOMMLNamespace + `"><w:body>` +
+ documentBody + `<w:sectPr/></w:body></w:document>`
+ return buildClipboardMathDOCX(documentXML)
+}
+
+func normalizeOfficeHTMLOMML(fragment string) (normalized string, ok bool) {
+ decoder := xml.NewDecoder(strings.NewReader(`<root xmlns:m="` + officeHTMLOMMLNamespace + `">` + fragment + `</root>`))
+ decoder.Entity = map[string]string{"nbsp": "\u00a0"}
+ var builder strings.Builder
+ var mathStack []string
+ rootCount := 0
+ for {
+ token, err := decoder.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return "", false
+ }
+ switch value := token.(type) {
+ case xml.StartElement:
+ if value.Name.Space != officeHTMLOMMLNamespace && value.Name.Space != docxOMMLNamespace {
+ continue
+ }
+ if len(mathStack) == 0 {
+ if value.Name.Local != "oMathPara" && value.Name.Local != "oMath" {
+ continue
+ }
+ rootCount++
+ builder.WriteString("<w:p>")
+ }
+ mathStack = append(mathStack, value.Name.Local)
+ builder.WriteString("<m:" + value.Name.Local)
+ for _, attr := range value.Attr {
+ if attr.Name.Space == officeHTMLOMMLNamespace || attr.Name.Space == docxOMMLNamespace {
+ builder.WriteString(` m:` + attr.Name.Local + `="` + html.EscapeString(attr.Value) + `"`)
+ } else if attr.Name.Space == "http://www.w3.org/XML/1998/namespace" {
+ builder.WriteString(` xml:` + attr.Name.Local + `="` + html.EscapeString(attr.Value) + `"`)
+ }
+ }
+ builder.WriteByte('>')
+ case xml.EndElement:
+ if value.Name.Space != officeHTMLOMMLNamespace && value.Name.Space != docxOMMLNamespace || len(mathStack) == 0 {
+ continue
+ }
+ localName := mathStack[len(mathStack)-1]
+ if localName != value.Name.Local {
+ return "", false
+ }
+ builder.WriteString("</m:" + localName + ">")
+ mathStack = mathStack[:len(mathStack)-1]
+ if len(mathStack) == 0 {
+ builder.WriteString("</w:p>")
+ }
+ case xml.CharData:
+ if len(mathStack) == 0 {
+ continue
+ }
+ content := strings.ReplaceAll(string(value), "\u00a0", " ")
+ if mathStack[len(mathStack)-1] == "t" {
+ builder.WriteString(html.EscapeString(content))
+ } else if mathStack[len(mathStack)-1] == "r" && strings.TrimSpace(content) != "" {
+ builder.WriteString(`<m:t xml:space="preserve">` + html.EscapeString(content) + `</m:t>`)
+ }
+ }
+ }
+ return builder.String(), rootCount > 0 && len(mathStack) == 0
+}
+
+func buildClipboardMathDOCX(documentXML string) (data []byte, ok bool) {
+ var buffer bytes.Buffer
+ writer := archivezip.NewWriter(&buffer)
+ files := map[string]string{
+ "[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?>` +
+ `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>`,
+ "_rels/.rels": `<?xml version="1.0" encoding="UTF-8"?>` +
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>`,
+ "word/document.xml": documentXML,
+ }
+ for name, content := range files {
+ file, err := writer.Create(name)
+ if err != nil {
+ return nil, false
+ }
+ if _, err = file.Write([]byte(content)); err != nil {
+ return nil, false
+ }
+ }
+ if err := writer.Close(); err != nil {
+ return nil, false
+ }
+ return buffer.Bytes(), true
+}
+
func isClipboardMathDOCX(data []byte) bool {
archive, err := archivezip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
diff --git a/kernel/api/lute_clipboard_math_test.go b/kernel/api/lute_clipboard_math_test.go
index 9ca46bbac5..d49da8ed02 100644
--- a/kernel/api/lute_clipboard_math_test.go
+++ b/kernel/api/lute_clipboard_math_test.go
@@ -17,6 +17,7 @@
package api
import (
+ archivezip "archive/zip"
"bytes"
"encoding/base64"
"errors"
@@ -110,6 +111,29 @@ func TestNormalizeClipboardMathML(t *testing.T) {
}
}
+func TestOfficeHTMLClipboardMathInput(t *testing.T) {
+ fragment := `<m:oMathPara xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"><m:oMath><m:r><span>SNR&nbsp;(dB)=20×</span></m:r><m:sSub><m:e><m:r><span>log</span></m:r></m:e><m:sub><m:r><span>10</span></m:r></m:sub></m:sSub><m:d><m:e><m:f><m:num><m:r><span>&#119878;</span></m:r></m:num><m:den><m:r><span>&#119873;</span></m:r></m:den></m:f></m:e></m:d></m:oMath></m:oMathPara>`
+ normalized, ok := normalizeOfficeHTMLOMML(fragment)
+ if !ok || !strings.Contains(normalized, `<m:t xml:space="preserve">SNR (dB)=20×</m:t>`) ||
+ !strings.Contains(normalized, `<m:sSub>`) || !strings.Contains(normalized, `<m:f>`) ||
+ strings.Contains(normalized, "<span") || !strings.Contains(normalized, "<m:oMathPara>") {
+ t.Fatalf("unexpected normalized Office HTML math: normalized=%q ok=%v", normalized, ok)
+ }
+ docx, ok := officeHTMLClipboardMathInput(fragment)
+ if !ok || !isClipboardMathDOCX(docx) {
+ t.Fatal("Office HTML math was not converted to a valid DOCX payload")
+ }
+ archive, err := archivezip.NewReader(bytes.NewReader(docx), int64(len(docx)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ documentXML, err := readWPSClipboardFile(archive, "word/document.xml")
+ if err != nil || !bytes.Contains(documentXML, []byte(`<m:oMath>`)) ||
+ !bytes.Contains(documentXML, []byte(docxOMMLNamespace)) {
+ t.Fatalf("unexpected generated document.xml: xml=%q err=%v", documentXML, err)
+ }
+}
+
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>`, "")