An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve pasting Microsoft Word comments https://github.com/siyuan-note/siyuan/issues/18748
Daniel7b10fb5d2c8e
diff --git a/kernel/api/lute.go b/kernel/api/lute.goindex 7b909e3d33..46a98f7e10 100644--- a/kernel/api/lute.go+++ b/kernel/api/lute.go@@ -17,6 +17,7 @@package apiimport (+ "html""net/http""os""path/filepath"@@ -27,6 +28,7 @@ import ("github.com/88250/lute/ast""github.com/88250/lute/parse""github.com/88250/lute/render"+ "github.com/PuerkitoBio/goquery""github.com/gin-gonic/gin""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/model"@@ -106,6 +108,8 @@ func html2BlockDOM(c *gin.Context) {luteEngine := util.NewLute()luteEngine.SetHTMLTag2TextMark(true)luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})+ // 将 Word 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748+ dom = normalizeMSWordComments(dom)tree, _ := model.HTML2Tree(dom, luteEngine, boxID)if nil == tree {ret.Data = "Failed to convert"@@ -234,6 +238,83 @@ func html2BlockDOM(c *gin.Context) {ret.Data = gulu.Str.FromBytes(output)}+func normalizeMSWordComments(dom string) string {+ if !strings.Contains(dom, "mso-comment") && !strings.Contains(dom, "MsoComment") && !strings.Contains(dom, "msocom") {+ return dom+ }++ doc, err := goquery.NewDocumentFromReader(strings.NewReader(dom))+ if err != nil {+ return dom+ }++ comments := map[string]string{}+ doc.Find(`[id^="_com_"]`).Each(func(_ int, comment *goquery.Selection) {+ id, _ := comment.Attr("id")+ var paragraphs []string+ comment.Find(".MsoCommentText").Each(func(_ int, paragraph *goquery.Selection) {+ paragraph = paragraph.Clone()+ paragraph.Find(".MsoCommentReference, .msocomoff").Remove()+ if text := strings.TrimSpace(paragraph.Text()); text != "" {+ paragraphs = append(paragraphs, text)+ }+ })+ if 0 < len(paragraphs) {+ comments[strings.TrimPrefix(id, "_com_")] = strings.Join(paragraphs, "\n")+ }+ })++ doc.Find("a[style]").Each(func(_ int, anchor *goquery.Selection) {+ style, _ := anchor.Attr("style")+ if !strings.Contains(strings.ToLower(style), "mso-comment-reference:") {+ return+ }+ if href, exists := anchor.Attr("href"); exists && href != "" {+ return+ }++ content, err := anchor.Html()+ if err != nil {+ return+ }+ comment := comments[msWordCommentID(anchor, style)]+ if comment == "" {+ anchor.ReplaceWithHtml(content)+ return+ }+ anchor.ReplaceWithHtml(`<span title="` + html.EscapeString(comment) + `">` + content + `</span>`)+ })++ doc.Find(".MsoCommentReference, .msocomanchor, .msocomoff").Remove()+ doc.Find("[style]").Each(func(_ int, selection *goquery.Selection) {+ style, _ := selection.Attr("style")+ if strings.Contains(strings.ToLower(style), "mso-element:comment-list") {+ selection.Remove()+ }+ })++ ret, err := doc.Find("body").Html()+ if err != nil {+ return dom+ }+ return ret+}++func msWordCommentID(anchor *goquery.Selection, style string) string {+ if href, exists := anchor.Next().Find(`a[href^="#_msocom_"]`).First().Attr("href"); exists {+ return strings.TrimPrefix(href, "#_msocom_")+ }++ style = style[strings.Index(strings.ToLower(style), "mso-comment-reference:")+len("mso-comment-reference:"):]+ if semicolon := strings.IndexByte(style, ';'); 0 <= semicolon {+ style = style[:semicolon]+ }+ if underscore := strings.LastIndexByte(style, '_'); 0 <= underscore {+ return strings.TrimSpace(style[underscore+1:])+ }+ return ""+}+func spinBlockDOM(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/lute_word_comment_test.go b/kernel/api/lute_word_comment_test.gonew file mode 100644index 0000000000..efddb3c6c1--- /dev/null+++ b/kernel/api/lute_word_comment_test.go@@ -0,0 +1,84 @@+// 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 (+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/PuerkitoBio/goquery"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestNormalizeMSWordComments(t *testing.T) {+ dom := `<p>before<a style="mso-comment-reference:TA_1">annotated</a>` ++ `<span class="MsoCommentReference"><a class="msocomanchor" href="#_msocom_1">[TA1]</a></span>after</p>` ++ `<div style="mso-element:comment-list"><hr class="msocomoff"><div id="_com_1" class="msocomtxt">` ++ `<p class="MsoCommentText"><span class="MsoCommentReference">[TA1]</span>memo</p></div></div>`++ normalized := normalizeMSWordComments(dom)+ doc, err := goquery.NewDocumentFromReader(strings.NewReader(normalized))+ if err != nil {+ t.Fatal(err)+ }+ memo := doc.Find(`span[title="memo"]`)+ if memo.Length() != 1 || memo.Text() != "annotated" {+ t.Fatalf("unexpected normalized memo: %s", normalized)+ }+ if doc.Find("a, hr, .MsoCommentReference, .msocomtxt").Length() != 0 {+ t.Fatalf("Word comment artifacts were not removed: %s", normalized)+ }+ if doc.Find("body").Text() != "beforeannotatedafter" {+ t.Fatalf("unexpected normalized text: %s", doc.Find("body").Text())+ }++ luteEngine := util.NewLute()+ luteEngine.SetHTMLTag2TextMark(true)+ tree := luteEngine.HTML2Tree(normalized)+ var inlineMemo *ast.Node+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == node.Type && node.IsTextMarkType("inline-memo") {+ inlineMemo = node+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if inlineMemo == nil || inlineMemo.TextMarkTextContent != "annotated" || inlineMemo.TextMarkInlineMemoContent != "memo" {+ t.Fatalf("Word comment was not converted to an inline memo")+ }+}++func TestNormalizeMSWordCommentsFallsBackToText(t *testing.T) {+ dom := `<p>before<a style="mso-comment-reference:TA_2">annotated</a>after</p>`+ normalized := normalizeMSWordComments(dom)++ doc, err := goquery.NewDocumentFromReader(strings.NewReader(normalized))+ if err != nil {+ t.Fatal(err)+ }+ if doc.Find("a").Length() != 0 || doc.Find("body").Text() != "beforeannotatedafter" {+ t.Fatalf("unmatched Word comment did not fall back to text: %s", normalized)+ }+}++func TestNormalizeMSWordCommentsLeavesRegularHTMLUnchanged(t *testing.T) {+ dom := `<p><a href="#target">link</a></p><hr>`+ if normalized := normalizeMSWordComments(dom); normalized != dom {+ t.Fatalf("regular HTML was modified: %s", normalized)+ }+}