An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Index callout title references https://github.com/siyuan-note/siyuan/issues/20573
Danielb4efb4381472
diff --git a/kernel/model/asset_download_read.go b/kernel/model/asset_download_read.goindex 8a318b61b7..45cf9ee38a 100644--- a/kernel/model/asset_download_read.go+++ b/kernel/model/asset_download_read.go@@ -214,7 +214,7 @@ func prepareExportAssetsInScope(boxID string, docPaths []string, includeFootnoteif err := treenode.MaterializeTableCellRichExport(tree.Root); err != nil {return err}- defer treenode.MaterializeTabTitles(tree.Root)()+ defer treenode.MaterializeInlineTitles(tree.Root)()}if includeFootnotes && confExportSnapshot.BlockRefMode == 4 && tree.Root.Type == ast.NodeDocument {// 按单文件导出的脚注展开规则收集资源,不受是否另行导出关联文档影响@@ -234,7 +234,7 @@ func prepareExportAssetsInScope(boxID string, docPaths []string, includeFootnotetrees[footnoteTree.ID] = &footnoteTree}}- treenode.WalkWithTabTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {confSearchSnapshot := Conf.LoadSearch()if !entering || node.Type != ast.NodeBlockQueryEmbedScript {@@ -274,7 +274,7 @@ func prepareExportAssetsInScope(boxID string, docPaths []string, includeFootnoteavBoxID = tree.Box}avIDs := hashset.New()- treenode.WalkWithTabTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {if entering && node.Type == ast.NodeAttributeView && node.AttributeViewID != "" {walkRelationAvs(node.AttributeViewID, avBoxID, avIDs)}diff --git a/kernel/model/asset_reference.go b/kernel/model/asset_reference.goindex 7769936945..ccb67cc85d 100644--- a/kernel/model/asset_reference.go+++ b/kernel/model/asset_reference.go@@ -166,7 +166,7 @@ func rewriteTreeAssetReferences(tree *parse.Tree, options assetReferenceRewriteOtree.Root.SetIALAttr("title-img", strings.Replace(titleImg, titleImgPath, rewritten, 1))}- treenode.WalkWithTabTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}diff --git a/kernel/model/asset_relink_references.go b/kernel/model/asset_relink_references.goindex 170875ea2f..4bbae35aa8 100644--- a/kernel/model/asset_relink_references.go+++ b/kernel/model/asset_relink_references.go@@ -185,7 +185,7 @@ func (r *assetRelinker) html(raw []byte, location apicontract.AssetReference) []}func (r *assetRelinker) tree(tree *parse.Tree, location apicontract.AssetReference) {- treenode.WalkWithTabTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 044b519590..c8ed1d45ee 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -669,8 +669,8 @@ func NetAssets2LocalAssets(rootID string, onlyImg bool, originalURL string) (err}func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string, assetsDirPath string, needWriteTree bool) (err error) {- finishTabTitles := treenode.MaterializeTabTitles(tree.Root)- defer finishTabTitles()+ finishInlineTitles := treenode.MaterializeInlineTitles(tree.Root)+ defer finishInlineTitles()var files intvar size int64msgId := gulu.Rand.String(7)@@ -880,7 +880,7 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,util.PushClearMsg(msgId)- finishTabTitles()+ finishInlineTitles()if needWriteTree {if 0 < files {msgId = util.PushMsg(Conf.Language(113), 7000)@@ -2555,7 +2555,7 @@ func emojisInTree(tree *parse.Tree) (ret []string) {}}- treenode.WalkWithTabTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}@@ -2620,7 +2620,7 @@ func getAssetsLinkDestsWithAttributeViewItemFilter(normalize ...func(string) string,) (ret []string) {ret = []string{}- treenode.WalkWithTabTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {if n.IsBlock() {// 以 custom-data-assets 开头的块属性值可能是多个资源文件链接,需要计入// Ignore assets associated with the `custom-data-assets` block attribute when cleaning unreferenced assets https://github.com/siyuan-note/siyuan/issues/12574diff --git a/kernel/model/backlink_sort.go b/kernel/model/backlink_sort.goindex 9077d76245..48fc803bfa 100644--- a/kernel/model/backlink_sort.go+++ b/kernel/model/backlink_sort.go@@ -59,7 +59,7 @@ func backlinkAnchorSortKeys(blocks []*Block, tree *parse.Tree, refs []*sql.Ref,nodes, _ := getBacklinkRenderNodes(node, originalRefBlockIDs)found := falsefor _, root := range nodes {- ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering || !treenode.IsBlockRef(n) {return ast.WalkContinue}diff --git a/kernel/model/backlink_sort_test.go b/kernel/model/backlink_sort_test.goindex 0b2954613c..0106934628 100644--- a/kernel/model/backlink_sort_test.go+++ b/kernel/model/backlink_sort_test.go@@ -7,6 +7,7 @@ import ("github.com/88250/lute/ast""github.com/88250/lute/parse""github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode")func TestBacklinkAnchorSort(t *testing.T) {@@ -29,6 +30,44 @@ func TestBacklinkAnchorSort(t *testing.T) {}}+func TestBacklinkAnchorSortInlineTitles(t *testing.T) {+ const defID = "20261015120000-ref0001"+ for _, typ := range []ast.NodeType{ast.NodeCallout, ast.NodeTabItem} {+ t.Run(typ.String(), func(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument, ID: ast.NewNodeID()}+ tree := &parse.Tree{Root: root, ID: root.ID}+ var blocks []*Block+ var refs []*sql.Ref+ for _, text := range []string{"A10", "A2"} {+ title := `<span data-type="block-ref" data-id="` + defID + `" data-subtype="s">` + text + `</span>`+ node := &ast.Node{Type: typ, ID: ast.NewNodeID(), CalloutTitle: title, TabItemTitle: title}+ body := treenode.NewParagraph("")+ body.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: defID,+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: "Body"})+ node.AppendChild(body)+ root.AppendChild(node)+ blocks = append(blocks, &Block{ID: node.ID})+ refs = append(refs, &sql.Ref{BlockID: node.ID, DefBlockID: defID}, &sql.Ref{BlockID: body.ID, DefBlockID: defID})+ }+ for _, mode := range []int{1, 2} {+ keys := backlinkAnchorSortKeys(blocks, tree, refs, nil, mode)+ if keys[blocks[0].ID] != "A10" || keys[blocks[1].ID] != "A2" {+ t.Fatalf("title must supply the first matching anchor: %v", keys)+ }+ items := []*Backlink{{ID: blocks[0].ID}, {ID: blocks[1].ID}}+ sortBacklinksByAnchor(items, keys, mode)+ wantFirst := blocks[0].ID+ if mode == 1 {+ wantFirst = blocks[1].ID+ }+ if items[0].ID != wantFirst {+ t.Fatalf("mode %d did not sort title anchors naturally", mode)+ }+ }+ })+ }+}+func TestBacklinkAnchorSortKeys(t *testing.T) {root := &ast.Node{Type: ast.NodeDocument, ID: "root"}tree := &parse.Tree{Root: root, ID: root.ID}diff --git a/kernel/model/callout_reference_fts5_test.go b/kernel/model/callout_reference_fts5_test.gonew file mode 100644index 0000000000..0bafbdbadb--- /dev/null+++ b/kernel/model/callout_reference_fts5_test.go@@ -0,0 +1,139 @@+//go:build fts5++package model++import (+ "context"+ "os"+ "os/exec"+ "strings"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func calloutReferenceTestProcess(t *testing.T) bool {+ t.Helper()+ const helper = "SIYUAN_TEST_CALLOUT_REFERENCE"+ if os.Getenv(helper) == t.Name() {+ return true+ }+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+t.Name()+"$", "-test.v")+ command.Env = append(os.Environ(), helper+"="+t.Name())+ if output, err := command.CombinedOutput(); err != nil {+ t.Fatalf("callout reference subprocess: %v\n%s", err, output)+ }+ return false+}++func TestCalloutTitleReferenceLifecycle(t *testing.T) {+ if !calloutReferenceTestProcess(t) {+ return+ }+ prepareHPathRefreshTest(t)+ box := &Box{ID: ast.NewNodeID()}+ boxConf := conf.NewBoxConf()+ boxConf.Closed = false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ testCalloutTitleReferenceLifecycle(t, box.ID)+}++func testCalloutTitleReferenceLifecycle(t *testing.T, boxID string) {+ definition := newHPathTestDoc(t, boxID, "/", "Definition", 1)+ reference := newHPathTestDoc(t, boxID, "/", "Reference", 1)+ l := util.NewLute()+ save := func(tree *parse.Tree) {+ t.Helper()+ if err := writeTreeUpsertQueue(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.FlushQueue()+ }+ save(definition)+ save(reference)+ callout := &ast.Node{Type: ast.NodeCallout, ID: ast.NewNodeID(), CalloutType: "NOTE", CalloutTitleExplicit: true,+ CalloutTitle: `<span data-type="block-ref" data-id="` + definition.ID + `" data-subtype="d">Definition</span> ((` + definition.ID + ` "Static"))`}+ callout.SetIALAttr("id", callout.ID)+ callout.AppendChild(treenode.NewParagraph(""))+ perform := func(op *Operation) {+ t.Helper()+ if err := PerformTxSync(&Transaction{DoOperations: []*Operation{op}}); err != nil {+ t.Fatal(err)+ }+ sql.FlushQueue()+ }+ assertRefs := func(want int) {+ t.Helper()+ refs := sql.QueryRefsByDefIDInBox(definition.ID, false, boxID)+ if len(refs) != want {+ t.Fatalf("reference count: got %d, want %d", len(refs), want)+ }+ if want == 1 && (refs[0].BlockID != callout.ID || refs[0].RootID != reference.ID) {+ t.Fatalf("incorrect persisted title reference ownership: %+v", refs[0])+ }+ }+ readCallout := func() *ast.Node {+ t.Helper()+ tree, err := filesys.LoadTree(boxID, reference.Path, l)+ if err != nil {+ t.Fatal(err)+ }+ node := treenode.GetNodeInTree(tree, callout.ID)+ if node == nil || node.Type != ast.NodeCallout || node.FirstChild == nil || node.FirstChild.Next != nil {+ t.Fatal("persisted callout must retain its body without temporary title blocks")+ }+ return node+ }+ perform(&Operation{Action: "insert", ID: callout.ID, ParentID: reference.ID, Data: l.RenderNodeBlockDOM(callout)})+ assertRefs(1)+ callout = readCallout()++ treenode.SetDynamicBlockRefText(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref",+ TextMarkBlockRefID: definition.ID, Box: boxID}, "Cached title")+ t.Cleanup(func() {+ treenode.DynamicRefTexts.Delete(definition.ID)+ treenode.RemoveDynamicRefTexts(boxID)+ })+ perform(&Operation{Action: "update", ID: callout.ID, Data: l.RenderNodeBlockDOM(callout)})+ callout = readCallout()+ if !strings.Contains(callout.CalloutTitle, "Cached title") || !strings.Contains(callout.CalloutTitle, "Static") {+ t.Fatalf("transaction did not normalize dynamic title text: %s", callout.CalloutTitle)+ }+ assertRefs(1)++ definition.Root.SetIALAttr("title", "Renamed definition")+ save(definition)+ refreshDynamicRefText(definition.Root, definition)+ sql.FlushQueue()+ callout = readCallout()+ if !strings.Contains(callout.CalloutTitle, "Renamed definition") || !strings.Contains(callout.CalloutTitle, "Static") {+ t.Fatalf("rename did not persist the dynamic title anchor: %s", callout.CalloutTitle)+ }+ assertRefs(1)+ backlinks, _ := GetBacklinkDoc(definition.ID, reference.ID, "", false, false)+ if len(backlinks) == 0 {+ t.Fatal("title references must be visible through the backlink query")+ }++ callout.CalloutTitle = "Plain title"+ perform(&Operation{Action: "update", ID: callout.ID, Data: l.RenderNodeBlockDOM(callout)})+ assertRefs(0)+ callout = readCallout()+ callout.CalloutTitle = "((" + definition.ID + ` "Restored"))`+ perform(&Operation{Action: "update", ID: callout.ID, Data: l.RenderNodeBlockDOM(callout)})+ assertRefs(1)+ perform(&Operation{Action: "delete", ID: callout.ID})+ assertRefs(0)+}diff --git a/kernel/model/callout_reference_sqlcipher_test.go b/kernel/model/callout_reference_sqlcipher_test.gonew file mode 100644index 0000000000..71b42aa4fb--- /dev/null+++ b/kernel/model/callout_reference_sqlcipher_test.go@@ -0,0 +1,24 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package model++import "testing"++func TestCalloutTitleEncryptedReferenceLifecycle(t *testing.T) {+ if !calloutReferenceTestProcess(t) {+ return+ }+ prepareHPathRefreshTest(t)+ const password = "callout-reference-test-password"+ if err := EnableEncryptedNotebook(password); err != nil {+ t.Fatal(err)+ }+ boxID, err := CreateEncryptedBox("Callout", password)+ if err != nil {+ t.Fatal(err)+ }+ if _, err = Mount(boxID); err != nil {+ t.Fatal(err)+ }+ testCalloutTitleReferenceLifecycle(t, boxID)+}diff --git a/kernel/model/callout_reference_test.go b/kernel/model/callout_reference_test.gonew file mode 100644index 0000000000..27975ce9a5--- /dev/null+++ b/kernel/model/callout_reference_test.go@@ -0,0 +1,56 @@+package model++import (+ "slices"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestCalloutTitleReferenceTextUpdate(t *testing.T) {+ const defID = "20261015120000-ref0001"+ def := &ast.Node{Type: ast.NodeDocument, ID: defID}+ def.SetIALAttr("name", "New title")+ t.Cleanup(func() { treenode.DynamicRefTexts.Delete(defID) })+ callout := &ast.Node{Type: ast.NodeCallout, ID: ast.NewNodeID(),+ CalloutTitle: `((` + defID + ` "Static")) <span data-type="block-ref" data-id="` + defID + `" data-subtype="d">Old title</span>`}+ body := treenode.NewParagraph("")+ callout.AppendChild(body)+ if ids := getRefDefIDs(callout); !slices.Equal(ids, []string{defID}) {+ t.Fatalf("title targets must be collected once, got %v", ids)+ }+ changed, defs := updateRefText(callout, map[string]*ast.Node{defID: def})+ if !changed || len(defs) != 1 || defs[0].id != defID || defs[0].refText != "New title" {+ t.Fatalf("dynamic title update was not reported: %v %+v", changed, defs)+ }+ if !strings.Contains(callout.CalloutTitle, "Static") || !strings.Contains(callout.CalloutTitle, "New title") ||+ strings.Contains(callout.CalloutTitle, "Old title") || callout.FirstChild != body {+ t.Fatal("dynamic title update changed static text or body")+ }+ if changed, _ = updateRefText(callout, map[string]*ast.Node{defID: def}); changed {+ t.Fatal("unchanged dynamic text must not rewrite the title")+ }+}++func TestCalloutTitleReferenceBoundary(t *testing.T) {+ const allowedID = "20261015120000-ref0001"+ const missingID = "20261015120000-ref0002"+ callout := &ast.Node{Type: ast.NodeCallout, ID: ast.NewNodeID(),+ CalloutTitle: `((` + allowedID + ` 'Allowed')) ((` + missingID + ` 'Private anchor'))`}+ callout.AppendChild(treenode.NewParagraph(""))+ if count := degradeCrossBoundaryBlockRefsWithAllowed(callout, "20261015120000-box0001", nil, map[string]bool{allowedID: true}); count != 1 {+ t.Fatalf("expected one denied title reference, got %d", count)+ }+ if strings.Contains(callout.CalloutTitle, missingID) || !strings.Contains(callout.CalloutTitle, "Private anchor") {+ t.Fatalf("denied title reference must retain only its anchor: %s", callout.CalloutTitle)+ }+ if ids := getRefDefIDs(callout); !slices.Equal(ids, []string{allowedID}) {+ t.Fatalf("denied reference must not enter the index: %v", ids)+ }+ callout.CalloutTitle = "((" + callout.FirstChild.ID + " 'Local'))"+ if count := degradeCrossBoundaryBlockRefs(callout, "20261015120000-box0001"); count != 0 {+ t.Fatal("references to new blocks in the same subtree must survive")+ }+}diff --git a/kernel/model/duplicate_doc_tree.go b/kernel/model/duplicate_doc_tree.goindex 6c752d7adb..0cdf272208 100644--- a/kernel/model/duplicate_doc_tree.go+++ b/kernel/model/duplicate_doc_tree.go@@ -227,7 +227,7 @@ func remapDuplicateDocTreeReferences(root *ast.Node, ids map[string]string) {}return link}- treenode.WalkWithTabTitles(root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}diff --git a/kernel/model/export.go b/kernel/model/export.goindex 6e5292f954..1b378cdb67 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -3294,8 +3294,8 @@ func exportMarkdownContent0(id string, tree *parse.Tree, exportOpts markdownExpologging.LogErrorf("prepare Markdown export failed: %s", exportTreeErr)return ""}- finishTabTitles := treenode.MaterializeTabTitles(tree.Root)- defer finishTabTitles()+ finishInlineTitles := treenode.MaterializeInlineTitlesForExport(tree.Root)+ defer finishInlineTitles()if exportOpts.AdjustHeadingLevel {bt := treenode.GetBlockTreeInBox(id, tree.Box)adjustHeadingLevel(bt, tree, exportOpts.Config.AddTitle)@@ -3415,7 +3415,7 @@ func exportMarkdownContent0(id string, tree *parse.Tree, exportOpts markdownExpoluteEngine.SetUnorderedListMarker("-")luteEngine.SetImgTag(exportOpts.ImgTag)prepareMarkdownFontFamilyTextMarks(tree.Root)- finishTabTitles()+ finishInlineTitles()renderer := render.NewProtyleExportMdRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)ret = gulu.Str.FromBytes(renderer.Render())return@@ -3432,7 +3432,7 @@ func exportMarkdownRelativePath(currentDocDir, href string) string {sameDir := path.Dir(href) == currentDocDir || strings.HasPrefix(href, "#")href = util.FilterFilePath(href)if sameDir {- return strings.TrimPrefix(href, currentDocDir+"/")+ return strings.TrimPrefix(href, strings.TrimRight(currentDocDir, "/")+"/")}relative, err := filepath.Rel(currentDocDir, href)if nil != err {@@ -3455,8 +3455,8 @@ func exportTree(tree *parse.Tree, exportOpts treeExportOptions) (ret *parse.Treereturn nil, err}}- finishTabTitles := treenode.MaterializeTabTitles(ret.Root)- defer finishTabTitles()+ finishInlineTitles := treenode.MaterializeInlineTitlesForExport(ret.Root)+ defer finishInlineTitles()// 将当前文档的块超链接转换为引用blockLink2Ref(ret)@@ -4402,7 +4402,7 @@ func addRefFootnoteAndRecurse(currentTree *parse.Tree, defID, anchorText string,}func collectFootnotesDefs0(currentTree *parse.Tree, node *ast.Node, refFootnoteOrder *[]string, refFootnotesByID map[string]*refAsFootnotes, depth *int, references *markdownExportReferences) {- ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}@@ -4825,8 +4825,8 @@ func setExportAssetLinkDest(node *ast.Node, oldDest, dest string) {}func removeAssetsID(tree *parse.Tree, assetsOldNew, assetsNewOld map[string]string, enabled bool) {- finishTabTitles := treenode.MaterializeTabTitles(tree.Root)- defer finishTabTitles()+ finishInlineTitles := treenode.MaterializeInlineTitles(tree.Root)+ defer finishInlineTitles()assetNodes := getAssetsLinkDestsInTree(tree, false)for _, node := range assetNodes {dests := getAssetsLinkDests(node, false)@@ -4945,7 +4945,7 @@ func exportRefTreesWithConfig(tree *parse.Tree, defBlockIDs *[]string, retTrees}retTrees[tree.ID] = tree- treenode.WalkWithTabTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}diff --git a/kernel/model/export_markdown_refs.go b/kernel/model/export_markdown_refs.goindex 82ff697017..b9b2f47107 100644--- a/kernel/model/export_markdown_refs.go+++ b/kernel/model/export_markdown_refs.go@@ -53,8 +53,6 @@ func prepareMarkdownExportReferences(docPaths []string, defBlockIDs []string, co}func collectMarkdownExportReferences(tree *parse.Tree, refs *markdownExportReferences) {- finishTabTitles := treenode.MaterializeTabTitles(tree.Root)- defer finishTabTitles()var order []stringfootnotes := map[string]*refAsFootnotes{}depth := 0diff --git a/kernel/model/export_markdown_refs_test.go b/kernel/model/export_markdown_refs_test.goindex 3a66d8638d..4db4478690 100644--- a/kernel/model/export_markdown_refs_test.go+++ b/kernel/model/export_markdown_refs_test.go@@ -248,3 +248,74 @@ func TestExportMarkdownOtherReferenceModes(t *testing.T) {})}}++func TestExportMarkdownCalloutTitleReferences(t *testing.T) {+ for _, mode := range []int{2, 3, 4} {+ for _, related := range []bool{false, true} {+ t.Run(strconv.Itoa(mode)+"/related="+strconv.FormatBool(related), func(t *testing.T) {+ const boxID = "20261015120000-box0001"+ setupMarkdownReferencesTest(t, boxID)+ Conf.Export.Load().BlockRefMode = mode+ Conf.Export.Load().IncludeRelatedDocs = related+ source := newFootnoteTestDoc(t, boxID, "Source")+ target := newFootnoteTestDoc(t, boxID, "Target")+ defID := target.Root.FirstChild.ID+ callout := &ast.Node{Type: ast.NodeCallout, ID: ast.NewNodeID(), CalloutType: "NOTE", CalloutTitleExplicit: true,+ CalloutTitle: `<span data-type="block-ref" data-id="` + defID + `" data-subtype="s">Unique title anchor</span>`}+ callout.SetIALAttr("id", callout.ID)+ body := treenode.NewParagraph("")+ body.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Callout body")})+ callout.AppendChild(body)+ source.Root.AppendChild(callout)+ for _, tree := range []*parse.Tree{source, target} {+ writeAssetDownloadDocumentTest(t, tree)+ sql.IndexTreeQueue(tree)+ }+ sql.FlushQueue()+ _, zipPath := ExportPandocConvertZip([]string{source.ID}, "", ".md")+ archive := openExportArchive(t, zipPath)+ md := markdownArchiveDocument(t, archive, "Source")+ if !strings.Contains(md, "> [!NOTE] ") || !strings.Contains(md, "Callout body") || strings.Contains(md, `data-type="block-ref"`) {+ t.Fatalf("callout structure or title reference conversion failed: %s", md)+ }+ switch mode {+ case 2:+ if !strings.Contains(md, "siyuan://blocks/"+defID) {+ t.Fatalf("title lost its block link: %s", md)+ }+ case 3:+ if strings.Contains(md, defID) || strings.Contains(md, "[^") || !strings.Contains(md, "Unique title anchor") {+ t.Fatalf("text-only title mode retained a reference: %s", md)+ }+ case 4:+ if related {+ if !strings.Contains(md, "[Unique title anchor](Target.md#"+defID+")") || strings.Contains(md, "[^") {+ t.Fatalf("related document is not linked from its callout title: %s", md)+ }+ if targetMD := markdownArchiveDocument(t, archive, "Target"); !strings.Contains(targetMD, `id="`+defID+`"`) {+ t.Fatalf("related target is missing its anchor: %s", targetMD)+ }+ } else if !strings.Contains(md, "Unique title anchor[^1]") || !strings.Contains(md, "[^1]:") {+ t.Fatalf("title reference lost its footnote: %s", md)+ }+ }+ if mode != 4 && strings.Count(md, "Unique title anchor") != 1 {+ t.Fatalf("temporary title was duplicated in the body: %s", md)+ }+ })+ }+ }+}++func TestExportMarkdownRelativePath(t *testing.T) {+ for _, tc := range []struct{ current, href, want string }{+ {"/", "/Target.md#block", "Target.md#block"},+ {"/Folder", "/Folder/Target.md#block", "Target.md#block"},+ {"/Folder", "/Other/Target.md#block", "../Other/Target.md#block"},+ {"/", "#block", "#block"},+ } {+ if got := exportMarkdownRelativePath(tc.current, tc.href); got != tc.want {+ t.Fatalf("relative path from %q to %q: got %q, want %q", tc.current, tc.href, got, tc.want)+ }+ }+}diff --git a/kernel/model/import.go b/kernel/model/import.goindex a58b42d88a..869e44f3b9 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -668,7 +668,7 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, sfor _, tree := range trees {treenode.RemapTabsActiveIDs(tree.Root, blockIDs)util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))- treenode.WalkWithTabTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}diff --git a/kernel/model/template.go b/kernel/model/template.goindex 463145599a..d08f34dd42 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -1144,7 +1144,7 @@ func renderTemplateSourceAt(p, id string, mode TemplateRenderMode, content *strirestoreTabsSelection()// 用映射成套改写模板内部的自引用,并补全指向外部块的引用锚文本// 仅命中 blockIDs 的引用(模板内部块)才会改写 ID;未命中的(外部块)保持不变- treenode.WalkWithTabTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 5bf2c5c92e..f3d8321c5d 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2057,23 +2057,6 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {// 剔除空白的行级公式unlinks = append(unlinks, n)}- } else if n.IsTextMarkType("block-ref") {- if "" == n.TextMarkBlockRefID {- // 已被 degradeCrossBoundaryBlockRefs 降级为纯文本,跳过引用处理- return ast.WalkContinue- }-- sql.CacheRef(subTree, n)-- if "d" == n.TextMarkBlockRefSubtype {- // 偶发编辑文档标题后引用处的动态锚文本不更新 https://github.com/siyuan-note/siyuan/issues/5891- // 使用缓存的动态锚文本强制覆盖当前块中的引用节点动态锚文本- if dRefText := treenode.GetDynamicRefText(n.TextMarkBlockRefID, tree.Box); "" != dRefText {- n.TextMarkTextContent = dRefText- }- }-- newDefIDs = append(newDefIDs, n.TextMarkBlockRefID)}}return ast.WalkContinue@@ -2081,6 +2064,30 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {for _, n := range unlinks {n.Unlink()}+ treenode.WalkWithInlineTitles(subTree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if ast.NodeTextMark == n.Type && n.IsTextMarkType("block-ref") {+ if "" == n.TextMarkBlockRefID {+ // 已被 degradeCrossBoundaryBlockRefs 降级为纯文本,跳过引用处理+ return ast.WalkContinue+ }++ sql.CacheRef(subTree, n)++ if "d" == n.TextMarkBlockRefSubtype {+ // 偶发编辑文档标题后引用处的动态锚文本不更新 https://github.com/siyuan-note/siyuan/issues/5891+ // 使用缓存的动态锚文本强制覆盖当前块中的引用节点动态锚文本+ if dRefText := treenode.GetDynamicRefText(n.TextMarkBlockRefID, tree.Box); "" != dRefText {+ n.TextMarkTextContent = dRefText+ }+ }++ newDefIDs = append(newDefIDs, n.TextMarkBlockRefID)+ }+ return ast.WalkContinue+ })oldDefIDs = gulu.Str.RemoveDuplicatedElem(oldDefIDs)newDefIDs = gulu.Str.RemoveDuplicatedElem(newDefIDs)@@ -2195,7 +2202,7 @@ func unfoldHeading(heading, currentNode *ast.Node) {}func getRefDefIDs(node *ast.Node) (refDefIDs []string) {- treenode.WalkWithTabTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}@@ -2239,7 +2246,7 @@ func degradeCrossBoundaryBlockRefsWithAllowed(root *ast.Node, srcBox string, res}return ast.WalkContinue})- ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}@@ -2258,6 +2265,7 @@ func degradeCrossBoundaryBlockRefsWithAllowed(root *ast.Node, srcBox string, reslogging.LogWarnf("block ref crosses encrypted boundary, src box [%s] -> def block [%s], degrade to text", srcBox, n.TextMarkBlockRefID)n.TextMarkBlockRefID = ""n.TextMarkBlockRefSubtype = ""+ n.TextMarkType = strings.TrimSpace(strings.ReplaceAll(n.TextMarkType, "block-ref", ""))n.TextMarkTextContent = strings.TrimSpace(n.TextMarkTextContent)degraded++}@@ -3343,7 +3351,7 @@ type changedDefNode struct {}func updateRefText(refNode *ast.Node, changedDefNodes map[string]*ast.Node) (changed bool, defNodes []*changedDefNode) {- treenode.WalkWithTabTitles(refNode, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(refNode, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}diff --git a/kernel/sql/callout_test.go b/kernel/sql/callout_test.gonew file mode 100644index 0000000000..b383729c50--- /dev/null+++ b/kernel/sql/callout_test.go@@ -0,0 +1,60 @@+package sql++import (+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestCalloutTitleReferenceIndex(t *testing.T) {+ const defID = "20261015120000-ref0001"+ for _, title := range []string{+ `<span data-type="block-ref" data-id="` + defID + `" data-subtype="d">Dynamic</span>`,+ `((` + defID + ` "Static"))`,+ } {+ tree := treenode.NewTree("20261015120000-box0001", "/20261015120000-doc0001.sy", "/Callout", "Callout")+ callout := &ast.Node{Type: ast.NodeCallout, ID: ast.NewNodeID(), CalloutType: "NOTE", CalloutTitle: title + " " + title}+ body := treenode.NewParagraph("")+ callout.AppendChild(body)+ tree.Root.AppendChild(callout)+ refs, _ := refsFromTree(tree)+ if len(refs) != 1 || refs[0].BlockID != callout.ID || refs[0].DefBlockID != defID || refs[0].RootID != tree.ID {+ t.Fatalf("title reference ownership or deduplication failed: %+v", refs)+ }+ if callout.FirstChild != body || body.Next != nil || callout.CalloutTitle != title+" "+title {+ t.Fatal("indexing must preserve title and body")+ }+ body.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: defID,+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: "Body"})+ refs, _ = refsFromTree(tree)+ if len(refs) != 2 || refs[0].BlockID == refs[1].BlockID {+ t.Fatalf("body references must retain independent ownership: %+v", refs)+ }+ callout.CalloutTitle = "Plain title"+ refs, _ = refsFromTree(tree)+ if len(refs) != 1 || refs[0].BlockID != body.ID {+ t.Fatal("removing the title reference must retain only the body reference")+ }+ }+}++func TestCalloutMarkdownTitleIndex(t *testing.T) {+ l := util.NewLute()+ tree := parse.Parse("", []byte("> [!NOTE] ((20261015120000-ref0001 'Title'))\n> Body\n"), l.ParseOptions)+ parse.NestedInlines2FlattedSpans(tree, false)+ tree.ID, tree.Box, tree.Path = "20261015120000-doc0001", "20261015120000-box0001", "/20261015120000-doc0001.sy"+ tree.Root.ID = tree.ID+ callout := tree.Root.FirstChild+ callout.ID = ast.NewNodeID()+ if callout.Type != ast.NodeCallout {+ t.Fatal("expected a callout parsed from Markdown")+ }+ refs, _ := refsFromTree(tree)+ if len(refs) != 1 || refs[0].BlockID != callout.ID || !strings.Contains(nodeStaticContent(callout, nil, false, false, false, false), "Title") {+ t.Fatalf("parsed callout title was not indexed: %+v", refs)+ }+}diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex 25bec3e3b9..9b4ab542a0 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -553,7 +553,7 @@ func SetIndexAssetPath(b bool) {}func refsFromTree(tree *parse.Tree) (refs []*Ref, fileAnnotationRefs []*FileAnnotationRef) {- treenode.WalkWithTabTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if entering {if ast.NodeCustomBlock == n.Type {return ast.WalkSkipChildren@@ -685,7 +685,7 @@ func fromTree(node *ast.Node, tree *parse.Tree) (blocks []*Block, spans []*Span,rootID := tree.Root.IDboxID := tree.Boxp := tree.Path- treenode.WalkWithTabTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {+ treenode.WalkWithInlineTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}diff --git a/kernel/treenode/inline_titles.go b/kernel/treenode/inline_titles.gonew file mode 100644index 0000000000..213a62c7c5--- /dev/null+++ b/kernel/treenode/inline_titles.go@@ -0,0 +1,143 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package treenode++import (+ "strings"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func inlineTitleParagraph(owner *ast.Node, title string) *ast.Node {+ if "" == title {+ return nil+ }+ tree := parse.Inline("", []byte(title), util.NewLute().ParseOptions)+ if nil == tree || nil == tree.Root || nil == tree.Root.FirstChild {+ return nil+ }+ parse.NestedInlines2FlattedSpans(tree, false)+ paragraph := tree.Root.FirstChild+ paragraph.ID = ""+ paragraph.KramdownIAL = nil+ paragraph.Parent = owner+ return paragraph+}++// WalkWithInlineTitles 遍历正文及页签、提示块标题中的行级内容,标题修改后写回字符串字段。+// 标题仅提供临时行级节点,引用和资源归属于原容器块,不向正文添加持久化子块。+func WalkWithInlineTitles(root *ast.Node, walker ast.Walker) {+ if nil == root {+ return+ }+ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ status := walker(node, entering)+ if !entering || ast.WalkContinue != status {+ return status+ }+ var paragraph *ast.Node+ switch node.Type {+ case ast.NodeTabItem:+ paragraph = TabTitleParagraph(node)+ case ast.NodeCallout:+ paragraph = inlineTitleParagraph(node, node.CalloutTitle)+ }+ if nil == paragraph {+ return status+ }+ luteEngine := util.NewLute()+ before := FormatNode(paragraph, luteEngine)+ stop := false+ ast.Walk(paragraph, func(inline *ast.Node, titleEntering bool) ast.WalkStatus {+ if inline == paragraph {+ return ast.WalkContinue+ }+ result := walker(inline, titleEntering)+ stop = ast.WalkStop == result+ return result+ })+ if after := FormatNode(paragraph, luteEngine); after != before {+ after = strings.TrimSpace(after)+ if ast.NodeCallout == node.Type {+ node.CalloutTitle = after+ } else {+ node.TabItemTitle = after+ }+ }+ if stop {+ return ast.WalkStop+ }+ return status+ })+}++// MaterializeInlineTitles 在批量改写期间提供临时标题子树,收尾函数必须在渲染或写盘前执行。+// 临时清空字符串字段,避免嵌套遍历重复解析同一标题;未修改的标题按原字符串恢复。+func MaterializeInlineTitles(root *ast.Node) func() {+ return materializeInlineTitles(root, nil)+}++// MaterializeInlineTitlesForExport 将转换后的标题写回标准 Markdown,保留链接和脚注的导出语义。+func MaterializeInlineTitlesForExport(root *ast.Node) func() {+ luteEngine := util.NewLute()+ return materializeInlineTitles(root, func(node *ast.Node) string {+ return ExportNodeStdMd(node, luteEngine)+ })+}++func materializeInlineTitles(root *ast.Node, formatTitle func(*ast.Node) string) func() {+ type titleFragment struct {+ title *string+ original string+ paragraph *ast.Node+ before string+ }+ luteEngine := util.NewLute()+ var fragments []titleFragment+ if nil != root {+ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ var title *string+ switch node.Type {+ case ast.NodeTabItem:+ if nil == node.TabTitleBlock() {+ title = &node.TabItemTitle+ }+ case ast.NodeCallout:+ title = &node.CalloutTitle+ }+ if nil != title {+ if paragraph := inlineTitleParagraph(node, *title); nil != paragraph {+ paragraph.Parent = nil+ fragments = append(fragments, titleFragment{title, *title, paragraph, FormatNode(paragraph, luteEngine)})+ *title = ""+ node.PrependChild(paragraph)+ }+ }+ return ast.WalkContinue+ })+ }+ finished := false+ return func() {+ if finished {+ return+ }+ finished = true+ for _, fragment := range fragments {+ fragment.paragraph.Unlink()+ *fragment.title = fragment.original+ if after := FormatNode(fragment.paragraph, luteEngine); after != fragment.before || nil != formatTitle {+ if nil != formatTitle {+ after = formatTitle(fragment.paragraph)+ }+ *fragment.title = strings.TrimSpace(after)+ }+ }+ }+}diff --git a/kernel/treenode/inline_titles_test.go b/kernel/treenode/inline_titles_test.gonew file mode 100644index 0000000000..6b8f924a41--- /dev/null+++ b/kernel/treenode/inline_titles_test.go@@ -0,0 +1,124 @@+package treenode++import (+ "strings"+ "testing"++ "github.com/88250/lute/ast"+)++func TestCalloutTitleWalkerOwnershipAndRewrite(t *testing.T) {+ title := `**Title** <span data-type="block-ref" data-id="20261015120000-ref0001" data-subtype="d">Dynamic</span> ((20261015120000-ref0002 "Static"))`+ callout := &ast.Node{Type: ast.NodeCallout, ID: ast.NewNodeID(), CalloutType: "NOTE",+ CalloutTitle: title, CalloutTitleExplicit: true, CalloutIcon: "custom-icon.png", CalloutIconType: 1}+ body := NewParagraph("")+ callout.AppendChild(body)+ refs, exits := 0, 0+ WalkWithInlineTitles(callout, func(n *ast.Node, entering bool) ast.WalkStatus {+ if IsBlockRef(n) {+ if ParentBlock(n) != callout {+ t.Fatal("title reference must belong to the callout")+ }+ if entering {+ refs+++ } else {+ exits+++ }+ }+ return ast.WalkContinue+ })+ if refs != 2 || exits != 2 || callout.CalloutTitle != title || callout.FirstChild != body || body.Previous != nil {+ t.Fatal("read traversal missed references or changed the source")+ }+ WalkWithInlineTitles(callout, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && IsBlockRef(n) && n.TextMarkBlockRefSubtype == "d" {+ n.TextMarkBlockRefID = "20261015120000-ref0003"+ n.TextMarkTextContent = "Renamed"+ }+ return ast.WalkContinue+ })+ if !strings.Contains(callout.CalloutTitle, "ref0003") || !strings.Contains(callout.CalloutTitle, "Renamed") ||+ !strings.Contains(callout.CalloutTitle, "Static") || callout.FirstChild != body || body.Next != nil ||+ callout.CalloutIcon != "custom-icon.png" || callout.CalloutIconType != 1 || !callout.CalloutTitleExplicit {+ t.Fatalf("title rewrite changed callout structure or attributes: %+v", callout)+ }+}++func TestInlineTitleWalkerControlFlow(t *testing.T) {+ for _, typ := range []ast.NodeType{ast.NodeCallout, ast.NodeTabItem} {+ for _, status := range []ast.WalkStatus{ast.WalkSkipChildren, ast.WalkStop} {+ root := &ast.Node{Type: typ, ID: ast.NewNodeID(), CalloutTitle: "Title", TabItemTitle: "Title"}+ root.AppendChild(NewParagraph(""))+ visits := 0+ WalkWithInlineTitles(root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering {+ visits+++ return status+ }+ return ast.WalkContinue+ })+ if visits != 1 {+ t.Fatalf("type %s status %d visited skipped content", typ, status)+ }+ }+ }+ callout := &ast.Node{Type: ast.NodeCallout, ID: ast.NewNodeID(), CalloutTitle: "Title"}+ callout.AppendChild(NewParagraph(""))+ visits := 0+ WalkWithInlineTitles(callout, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering {+ visits+++ if !n.IsBlock() {+ return ast.WalkStop+ }+ }+ return ast.WalkContinue+ })+ if visits != 2 {+ t.Fatal("stopping in the title must stop before visiting the body")+ }+}++func TestMaterializeInlineTitlesRewriteAndNesting(t *testing.T) {+ for _, typ := range []ast.NodeType{ast.NodeCallout, ast.NodeTabItem} {+ title := `**Title** ((20261015120000-ref0001 "Reference"))`+ node := &ast.Node{Type: typ, ID: ast.NewNodeID(), CalloutTitle: title, TabItemTitle: title}+ body := NewParagraph("")+ node.AppendChild(body)+ finish := MaterializeInlineTitles(node)+ finishNested := MaterializeInlineTitles(node)+ refs := 0+ WalkWithInlineTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && IsBlockRef(n) {+ refs+++ }+ return ast.WalkContinue+ })+ finishNested()+ finish()+ finish()+ if refs != 1 || node.FirstChild != body || body.Previous != nil || node.CalloutTitle != title || node.TabItemTitle != title {+ t.Fatalf("type %s duplicated or changed a materialized title", typ)+ }+ finish = MaterializeInlineTitlesForExport(node)+ var unlinks []*ast.Node+ WalkWithInlineTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && IsBlockRef(n) {+ n.InsertBefore(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "a", TextMarkTextContent: "Reference", TextMarkAHref: "Target.md"})+ unlinks = append(unlinks, n)+ }+ return ast.WalkContinue+ })+ for _, n := range unlinks {+ n.Unlink()+ }+ finish()+ updated := node.CalloutTitle+ if typ == ast.NodeTabItem {+ updated = node.TabItemTitle+ }+ if !strings.Contains(updated, "[Reference](Target.md)") || strings.Contains(updated, "block-ref") || node.FirstChild != body {+ t.Fatalf("type %s did not retain the exported link: %s", typ, updated)+ }+ }+}diff --git a/kernel/treenode/tabs.go b/kernel/treenode/tabs.goindex 258a2c64f7..6a9a0ae747 100644--- a/kernel/treenode/tabs.go+++ b/kernel/treenode/tabs.go@@ -9,7 +9,6 @@ import ("strings""github.com/88250/lute/ast"- "github.com/88250/lute/parse""github.com/siyuan-note/siyuan/kernel/util")@@ -138,84 +137,5 @@ func TabTitleParagraph(item *ast.Node) *ast.Node {if nil == item || ast.NodeTabItem != item.Type || nil != item.TabTitleBlock() || "" == item.TabItemTitle {return nil}- luteEngine := util.NewLute()- tree := parse.Inline("", []byte(item.TabItemTitle), luteEngine.ParseOptions)- if nil == tree || nil == tree.Root || nil == tree.Root.FirstChild {- return nil- }- parse.NestedInlines2FlattedSpans(tree, false)- paragraph := tree.Root.FirstChild- paragraph.ID = ""- paragraph.KramdownIAL = nil- paragraph.Parent = item- return paragraph-}--// WalkWithTabTitles 遍历正文及页签标题中的行级内容,标题修改后写回字符串字段。-func WalkWithTabTitles(root *ast.Node, walker ast.Walker) {- if nil == root {- return- }- ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {- status := walker(node, entering)- if !entering || ast.WalkContinue != status || ast.NodeTabItem != node.Type {- return status- }- paragraph := TabTitleParagraph(node)- if nil == paragraph {- return status- }- luteEngine := util.NewLute()- before := FormatNode(paragraph, luteEngine)- stop := false- ast.Walk(paragraph, func(inline *ast.Node, titleEntering bool) ast.WalkStatus {- if inline == paragraph {- return ast.WalkContinue- }- result := walker(inline, titleEntering)- stop = ast.WalkStop == result- return result- })- if after := FormatNode(paragraph, luteEngine); after != before {- node.TabItemTitle = strings.TrimSpace(after)- }- if stop {- return ast.WalkStop- }- return status- })-}--// MaterializeTabTitles 在批量改写期间提供临时标题子树,返回的收尾函数必须在渲染或写盘前执行。-func MaterializeTabTitles(root *ast.Node) func() {- type titleFragment struct {- item *ast.Node- paragraph *ast.Node- before string- }- luteEngine := util.NewLute()- var fragments []titleFragment- ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {- if entering && ast.NodeTabItem == node.Type {- if paragraph := TabTitleParagraph(node); nil != paragraph {- paragraph.Parent = nil- fragments = append(fragments, titleFragment{node, paragraph, FormatNode(paragraph, luteEngine)})- node.PrependChild(paragraph)- }- }- return ast.WalkContinue- })- finished := false- return func() {- if finished {- return- }- finished = true- for _, fragment := range fragments {- fragment.paragraph.Unlink()- if after := FormatNode(fragment.paragraph, luteEngine); after != fragment.before {- fragment.item.TabItemTitle = strings.TrimSpace(after)- }- }- }+ return inlineTitleParagraph(item, item.TabItemTitle)}diff --git a/kernel/treenode/tabs_test.go b/kernel/treenode/tabs_test.goindex dc9fd321ae..cb979bed6e 100644--- a/kernel/treenode/tabs_test.go+++ b/kernel/treenode/tabs_test.go@@ -47,7 +47,7 @@ func TestTabTitleWalkerOwnershipAndRewrite(t *testing.T) {body := NewParagraph("")item.AppendChild(body)references := 0- WalkWithTabTitles(item, func(n *ast.Node, entering bool) ast.WalkStatus {+ WalkWithInlineTitles(item, func(n *ast.Node, entering bool) ast.WalkStatus {if entering && IsBlockRef(n) {references++if ParentBlock(n) != item {@@ -59,7 +59,7 @@ func TestTabTitleWalkerOwnershipAndRewrite(t *testing.T) {if references != 1 || item.TabItemTitle != title || item.FirstChild != body {t.Fatal("read traversal changed the document")}- WalkWithTabTitles(item, func(n *ast.Node, entering bool) ast.WalkStatus {+ WalkWithInlineTitles(item, func(n *ast.Node, entering bool) ast.WalkStatus {if entering && IsBlockRef(n) {n.TextMarkBlockRefID = "20260905120000-ref0002"}@@ -72,7 +72,7 @@ func TestTabTitleWalkerOwnershipAndRewrite(t *testing.T) {t.Fatal(item.TabItemTitle)}l := util.NewLute()- finish := MaterializeTabTitles(item)+ finish := MaterializeInlineTitles(item)item.FirstChild.FirstChild.Unlink()finish()if item.FirstChild != body || strings.Contains(FormatNode(TabTitleParagraph(item), l), "Title") {@@ -98,7 +98,7 @@ func TestTabsOriginalTitleOwnershipAndNormalization(t *testing.T) {t.Fatal("normalization must be stable")}references := 0- WalkWithTabTitles(item, func(n *ast.Node, entering bool) ast.WalkStatus {+ WalkWithInlineTitles(item, func(n *ast.Node, entering bool) ast.WalkStatus {if entering && IsBlockRef(n) {references++if ParentBlock(n) != title {@@ -111,7 +111,7 @@ func TestTabsOriginalTitleOwnershipAndNormalization(t *testing.T) {if references != 1 || !strings.Contains(FormatNode(title, l), "ref0002") {t.Fatal("title reference traversal or rewrite failed")}- finish := MaterializeTabTitles(item)+ finish := MaterializeInlineTitles(item)finish()if item.TabTitleBlock() != title || title.IALAttr("custom-test") != "retained" || TabTitleParagraph(item) != nil {t.Fatal("title identity was replaced or synthesized twice")