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 Markdown footnote block references https://github.com/siyuan-note/siyuan/issues/20050
Daniel70b637b1b40c
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100808-j9sddk9.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100808-j9sddk9.syindex acbf6e2dbb..a74603c1cc 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100808-j9sddk9.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100808-j9sddk9.sy@@ -6,7 +6,7 @@"id": "20200924100808-j9sddk9","title": "Import and Export","type": "doc",- "updated": "20260809232000"+ "updated": "20261002211013"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20220317223639-oaxmz7d",- "updated": "20260803163440"+ "updated": "20261002211013"},"Children": [{@@ -30,7 +30,7 @@"HeadingLevel": 3,"Properties": {"id": "20220511185728-as165rt",- "updated": "20260803163440"+ "updated": "20261002211013"},"Children": [{@@ -53,6 +53,20 @@}]},+ {+ "ID": "20261002211013-n0y2i86",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261002211013-n0y2i86",+ "updated": "20261002211013"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "When importing Markdown, footnote definitions such as [^note]: become separate numbered list items, and references such as [^note] become superscript block references. Click a reference to open its definition, and use the definition’s backlinks to return to the referring blocks. Multiple paragraphs in a definition stay in the same list item. Undefined footnotes do not become block references. Code examples and escaped footnote syntax remain literal text."+ }+ ]+ },{"ID": "20220317223639-u3fan6w","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813125307-pxsjela.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813125307-pxsjela.syindex dfc54216e3..2a94b4e6a3 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813125307-pxsjela.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813125307-pxsjela.sy@@ -6,7 +6,7 @@"id": "20200813125307-pxsjela","title": "导入和导出","type": "doc",- "updated": "20260809232000"+ "updated": "20261002211013"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20201229120428-dgzkno8",- "updated": "20260803171606"+ "updated": "20261002211013"},"Children": [{@@ -30,7 +30,7 @@"HeadingLevel": 3,"Properties": {"id": "20220511184321-um53ppo",- "updated": "20260803163440"+ "updated": "20261002211013"},"Children": [{@@ -53,6 +53,20 @@}]},+ {+ "ID": "20261002211013-ujtdqw0",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261002211013-ujtdqw0",+ "updated": "20261002211013"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "导入 Markdown 时,[^note]: 形式的脚注定义会转换为独立的有序列表项,正文中的 [^note] 会转换为上标块引用。点击引用可打开定义,通过定义的反向链接可返回引用它的正文块。脚注中的多个段落会保留在同一列表项内。没有对应定义的脚注不生成块引用,代码示例和转义的脚注语法保留为字面文本。"+ }+ ]+ },{"ID": "20220317221825-c0ydyo2","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123302-akitvb1.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123302-akitvb1.syindex 42562cddab..51258289c8 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123302-akitvb1.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123302-akitvb1.sy@@ -6,7 +6,7 @@"id": "20211226123302-akitvb1","title": "導入和導出","type": "doc",- "updated": "20260809232000"+ "updated": "20261002211013"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20220317223850-m1y2b2z",- "updated": "20260803171606"+ "updated": "20261002211013"},"Children": [{@@ -30,7 +30,7 @@"HeadingLevel": 3,"Properties": {"id": "20220511185953-vjaca7x",- "updated": "20260803163402"+ "updated": "20261002211013"},"Children": [{@@ -53,6 +53,20 @@}]},+ {+ "ID": "20261002211013-g6lzmsj",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261002211013-g6lzmsj",+ "updated": "20261002211013"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "導入 Markdown 時,[^note]: 形式的註腳定義會轉換為獨立的有序清單項目,正文中的 [^note] 會轉換為上標區塊引用。點擊引用可開啟定義,透過定義的反向連結可返回引用它的正文區塊。註腳中的多個段落會保留在同一清單項目內。沒有對應定義的註腳不產生區塊引用,程式碼範例和跳脫的註腳語法保留為字面文字。"+ }+ ]+ },{"ID": "20220317223850-hjeb6n7","Type": "NodeParagraph",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-d31i9v5.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-d31i9v5.syindex d8ee7e43cd..381854c330 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-d31i9v5.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-d31i9v5.sy@@ -7,7 +7,7 @@"id": "20240530101000-d31i9v5","title": "インポートとエクスポート","type": "doc",- "updated": "20260809232000"+ "updated": "20261002211013"},"Children": [{@@ -17,7 +17,7 @@"Properties": {"ID": "20240530101000-058gztf","id": "20240530101000-ouqp9ym",- "updated": "20260803171606"+ "updated": "20261002211013"},"Children": [{@@ -33,7 +33,7 @@"Properties": {"ID": "20240530101000-yv1nqub","id": "20240530101000-3sblps4",- "updated": "20260803170332"+ "updated": "20261002211013"},"Children": [{@@ -57,6 +57,20 @@}]},+ {+ "ID": "20261002211013-0k8wpj6",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261002211013-0k8wpj6",+ "updated": "20261002211013"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Markdown をインポートすると、[^note]: 形式の脚注定義は独立した番号付きリスト項目に、本文中の [^note] は上付きのブロック参照に変換されます。参照をクリックすると定義を開くことができ、定義のバックリンクから参照元のブロックに戻れます。脚注内の複数の段落は同じリスト項目内に保持されます。定義のない脚注はブロック参照に変換されません。コード例とエスケープされた脚注構文は、そのままのテキストとして保持されます。"+ }+ ]+ },{"ID": "20240530101000-u9v0mpo","Type": "NodeParagraph",diff --git a/kernel/api/contract_import_footnotes_test.go b/kernel/api/contract_import_footnotes_test.gonew file mode 100644index 0000000000..aec12b7af3--- /dev/null+++ b/kernel/api/contract_import_footnotes_test.go@@ -0,0 +1,172 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package api++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/internal/testutil"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractMarkdownFootnotes(t *testing.T) {+ const helper = "SIYUAN_TEST_MARKDOWN_FOOTNOTES"+ if os.Getenv(helper) != "1" {+ // 独立进程隔离导入事务、数据库及加密笔记本状态。+ ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)+ defer cancel()+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAPIContractMarkdownFootnotes$", "-test.v")+ command.Env = append(os.Environ(), helper+"=1")+ if output, err := command.CombinedOutput(); err != nil {+ t.Fatalf("footnote import subprocess failed: %v\n%s", err, output)+ }+ return+ }+ root := t.TempDir()+ util.WorkspaceDir = root+ util.DataDir, util.TempDir = filepath.Join(root, "data"), filepath.Join(root, "temp")+ util.ConfDir, util.HistoryDir = filepath.Join(root, "conf"), filepath.Join(root, "history")+ util.QueueDir = filepath.Join(util.TempDir, "queue")+ util.DBPath, util.HistoryDBPath = filepath.Join(util.TempDir, "siyuan.db"), filepath.Join(util.TempDir, "history.db")+ util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, "asset_content.db"), filepath.Join(util.TempDir, "blocktree.db")+ util.WorkingDir = filepath.Join(root, "working")+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir} {+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ }+ model.Conf = model.NewAppConf()+ model.Conf.Lang = "footnotes-test"+ util.TimeLangs[model.Conf.Lang] = map[string]any{+ "albl": "ago", "blbl": "from now", "now": "now", "1s": "1 second %s", "xs": "%d seconds %s",+ "1m": "1 minute %s", "xm": "%d minutes %s", "1h": "1 hour %s", "xh": "%d hours %s", "1d": "1 day %s",+ "xd": "%d days %s", "1w": "1 week %s", "xw": "%d weeks %s", "1M": "1 month %s", "xM": "%d months %s",+ "1y": "1 year %s", "2y": "2 years %s", "xy": "%d years %s", "max": "a long while %s",+ }+ model.Conf.NotebookCrypto, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewFileTree()+ model.Conf.Sync, model.Conf.System = conf.NewSync(), conf.NewSystem()+ model.Conf.Editor, model.Conf.Search, model.Conf.Export = conf.NewEditor(), conf.NewSearch(), conf.NewExport()+ model.Conf.Api = &conf.API{Token: "footnotes-test"}+ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ defer sql.CloseDatabase()+ treenode.InitBlockTree(true)+ defer treenode.CloseDatabase()+ const markdown = "First[^note].\n\nSecond[^note].\n\n[^note]: Confidential footnote\n\n Second paragraph\n"+ source := filepath.Join(testutil.PublicDataDir(t), "footnotes.md")+ if err := os.WriteFile(source, []byte(markdown), 0600); err != nil {+ t.Fatal(err)+ }+ directory := filepath.Join(filepath.Dir(source), "directory")+ if err := os.Mkdir(directory, 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(directory, "nested.md"), []byte(markdown), 0600); err != nil {+ t.Fatal(err)+ }+ engine := gin.New()+ engine.Use(boxLeaseMiddleware)+ engine.POST("/api/filetree/createDocWithMd", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDocWithMd)+ engine.POST("/api/import/importStdMd", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importStdMd)+ post := func(route string, payload map[string]string, success bool) json.RawMessage {+ t.Helper()+ body, _ := json.Marshal(payload)+ request := httptest.NewRequest(http.MethodPost, route, bytes.NewReader(body))+ request.Header.Set("Authorization", "Token footnotes-test")+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ requireAPIContract(t, http.MethodPost, route, recorder)+ var response struct {+ Code int `json:"code"`+ Data json.RawMessage `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || (response.Code == 0) != success {+ t.Fatalf("%s: %s, %v", route, recorder.Body.String(), err)+ }+ return response.Data+ }+ for _, encrypted := range []bool{false, true} {+ var boxID string+ var err error+ if encrypted {+ const password = "footnotes-test-password"+ if err = model.EnableEncryptedNotebook(password); err != nil {+ t.Fatal(err)+ }+ boxID, err = model.CreateEncryptedBox("Encrypted footnotes", password)+ } else {+ boxID, err = model.CreateBox("Footnotes")+ }+ if err != nil {+ t.Fatal(err)+ }+ if _, err = model.Mount(boxID); err != nil {+ t.Fatal(err)+ }+ create := map[string]string{"notebook": boxID, "path": "/API footnotes", "markdown": markdown}+ var id string+ if err = json.Unmarshal(post("/api/filetree/createDocWithMd", create, true), &id); err != nil || id == "" {+ t.Fatalf("invalid document ID: %q, %v", id, err)+ }+ importRequest := map[string]string{"notebook": boxID, "localPath": source, "toPath": "/"}+ if data := post("/api/import/importStdMd", importRequest, true); string(data) != "null" {+ t.Fatalf("unexpected import result: %s", data)+ }+ post("/api/import/importStdMd", map[string]string{"notebook": boxID, "localPath": directory, "toPath": "/"}, true)+ model.FlushTxQueue()+ sql.FlushQueue()+ for _, hpath := range []string{"/API footnotes", "/footnotes", "/directory/nested"} {+ block := treenode.GetBlockTreeRootByHPath(boxID, hpath)+ if block == nil {+ t.Fatalf("missing imported document %s", hpath)+ }+ tree, err := filesys.LoadTree(boxID, block.Path, util.NewLute())+ if err != nil {+ t.Fatal(err)+ }+ count := 0+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && treenode.IsBlockRef(n) {+ count+++ def := treenode.GetNodeInTree(tree, n.TextMarkBlockRefID)+ if def == nil || def.Type != ast.NodeListItem || !n.IsTextMarkType("sup") || def.Text() != "Confidential footnoteSecond paragraph" {+ t.Errorf("lost footnote target or content in %s", hpath)+ }+ if refs := sql.QueryRefsByDefIDInBox(n.TextMarkBlockRefID, false, boxID); len(refs) != 2 {+ t.Errorf("expected two backlinks in %s, got %d", hpath, len(refs))+ }+ }+ return ast.WalkContinue+ })+ if count != 2 {+ t.Fatalf("expected two references in %s, got %d", hpath, count)+ }+ data, err := os.ReadFile(filepath.Join(util.DataDir, boxID, block.Path))+ if err != nil || util.IsCiphertext(data) != encrypted {+ t.Fatalf("document encryption changed: %v", err)+ }+ }+ if encrypted {+ model.LockBox(boxID)+ post("/api/filetree/createDocWithMd", create, false)+ post("/api/import/importStdMd", importRequest, false)+ }+ }+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex bd32328bfc..bc645ca147 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -584,10 +584,13 @@ var StartObsidianVaultImport = define[ObsidianImportRequest, *ObsidianVaultTask]var CancelObsidianVaultTask = define[ObsidianTaskRequest, *ObsidianVaultTask]("cancelObsidianVaultTask", "/api/import/cancelObsidianVaultTask", JSONBody, ResponseOptions{DataOnError: true}, "POST")+// ImportStdMd 将标准脚注定义导入为独立列表项,正文脚注转换为指向列表项的上标静态块引用。+// 多次引用共享同一目标;未定义的脚注不生成块引用,代码中的脚注文本保持原样,反链复用块引用索引。var ImportStdMd = define[ImportMarkdownRequest, Null]("importStdMd", "/api/import/importStdMd", JSONBody, ResponseOptions{}, "POST")var ImportData = define[ImportDataRequest, Null]("importData", "/api/import/importData", MultipartBody, ResponseOptions{}, "POST")+// ImportZipMd 对压缩包中的 Markdown 使用与 ImportStdMd 相同的脚注转换规则。var ImportZipMd = define[ImportZipMarkdownRequest, Null]("importZipMd", "/api/import/importZipMd", MultipartBody, ResponseOptions{}, "POST")var ImportSY = define[ImportSYRequest, Null]("importSY", "/api/import/importSY", MultipartBody, ResponseOptions{}, "POST")@@ -791,6 +794,9 @@ var DuplicateDoc = define[FileTreeIDRequest, FileTreeDuplicateData]("duplicateDovar DuplicateDocTree = define[FileTreeIDRequest, FileTreeDuplicateData]("duplicateDocTree", "/api/filetree/duplicateDocTree", JSONBody, ResponseOptions{}, "POST")var CreateDoc = define[FileTreeCreateRequest, FileTreeCreateData]("createDoc", "/api/filetree/createDoc", JSONBody, ResponseOptions{}, "POST")var CreateDailyNote = define[FileTreeDailyNoteRequest, FileTreeCreateData]("createDailyNote", "/api/filetree/createDailyNote", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// CreateDocWithMd 保留编辑器 Markdown 语法选项,并按 ImportStdMd 的规则自动转换标准脚注。+// 请求字段、文档 ID 响应和笔记本权限规则不变;转义的脚注语法可用于保留字面文本。var CreateDocWithMd = define[FileTreeCreateMarkdownRequest, string]("createDocWithMd", "/api/filetree/createDocWithMd", JSONBody, ResponseOptions{}, "POST")var GetDocCreateSavePath = define[FileTreeNotebookRequest, FileTreeCreateSavePathData]("getDocCreateSavePath", "/api/filetree/getDocCreateSavePath", JSONBody, ResponseOptions{}, "POST")var GetRefCreateSavePath = define[FileTreeNotebookRequest, FileTreeSavePathData]("getRefCreateSavePath", "/api/filetree/getRefCreateSavePath", JSONBody, ResponseOptions{}, "POST")diff --git a/kernel/model/file.go b/kernel/model/file.goindex 5ef8161f8f..e3020a5d32 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1363,7 +1363,7 @@ func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bo// 改进链滴剪藏 https://github.com/siyuan-note/siyuan/issues/13117enableLuteInlineSyntax(luteEngine)}- dom := luteEngine.Md2BlockDOM(md, false)+ dom := markdownWithFootnotes2BlockDOM(luteEngine, md)titleEmpty := falseif nil != arg {if titleEmptyArg, ok := arg["titleEmpty"]; ok {diff --git a/kernel/model/import.go b/kernel/model/import.goindex 93a55870bf..b1de9bfd22 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -1985,11 +1985,13 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)func parseStdMd(markdown []byte) (ret *parse.Tree, yfmRootID, yfmTitle, yfmUpdated string) {luteEngine := util.NewStdLute()+ luteEngine.SetFootnotes(true)luteEngine.SetYamlFrontMatter(true) // 解析 YAML Front Matter https://github.com/siyuan-note/siyuan/issues/10878ret = parse.Parse("", markdown, luteEngine.ParseOptions)if nil == ret {return}+ convertMarkdownFootnotes(ret)parse.NormalizeInlineHTMLTextStyles(ret)normalizeImportedHTMLTextStyles(ret)yfmRootID, yfmTitle, yfmUpdated = normalizeTree(ret)@@ -2315,11 +2317,13 @@ func htmlBlock2Inline(tree *parse.Tree) {}func reassignIDUpdated(tree *parse.Tree, rootID, updated string) {+ blockIDs := map[string]string{}ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering || "" == n.ID {return ast.WalkContinue}+ oldID := n.IDn.ID = ast.NewNodeID()if ast.NodeDocument == n.Type && "" != rootID {n.ID = rootID@@ -2335,6 +2339,16 @@ func reassignIDUpdated(tree *parse.Tree, rootID, updated string) {} else {n.SetIALAttr("updated", util.TimeFromID(n.ID))}+ blockIDs[oldID] = n.ID+ return ast.WalkContinue+ })+ // 导入时为块分配新 ID,同时更新文档内脚注等块引用的目标。+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && treenode.IsBlockRef(n) {+ if id := blockIDs[n.TextMarkBlockRefID]; id != "" {+ n.TextMarkBlockRefID = id+ }+ }return ast.WalkContinue})tree.ID = tree.Root.IDdiff --git a/kernel/model/import_footnotes.go b/kernel/model/import_footnotes.gonew file mode 100644index 0000000000..6f630f779e--- /dev/null+++ b/kernel/model/import_footnotes.go@@ -0,0 +1,81 @@+package model++import (+ "html"+ "strconv"+ "strings"++ "github.com/88250/lute"+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/88250/lute/render"+)++// convertMarkdownFootnotes 将脚注定义转换为列表项,引用转换为带上标的静态块引用。+func convertMarkdownFootnotes(tree *parse.Tree) {+ var blocks, definitions, refs []*ast.Node+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering {+ switch n.Type {+ case ast.NodeFootnotesDefBlock:+ blocks = append(blocks, n)+ case ast.NodeFootnotesDef:+ if n.ID == "" {+ n.ID = ast.NewNodeID()+ }+ n.SetIALAttr("id", n.ID)+ definitions = append(definitions, n)+ case ast.NodeFootnotesRef:+ refs = append(refs, n)+ }+ }+ return ast.WalkContinue+ })+ for _, ref := range refs {+ _, def := tree.FindFootnotesDef(ref.FootnotesRefLabel)+ if def == nil {+ continue+ }+ ref.InsertBefore(&ast.Node{+ Type: ast.NodeTextMark, TextMarkType: "block-ref sup",+ TextMarkBlockRefID: def.ID, TextMarkBlockRefSubtype: "s",+ TextMarkTextContent: html.EscapeString("[" + strings.TrimPrefix(string(ref.FootnotesRefLabel), "^") + "]"),+ })+ ref.Unlink()+ }+ for _, block := range blocks {+ block.Type = ast.NodeList+ block.ListData = &ast.ListData{Typ: 1, Num: 1, Delimiter: '.', Marker: []byte("1.")}+ number := 0+ for def := block.FirstChild; def != nil; def = def.Next {+ if def.Type != ast.NodeFootnotesDef {+ continue+ }+ number+++ def.ListData = &ast.ListData{Typ: 1, Num: number, Delimiter: '.', Marker: []byte(strconv.Itoa(number) + ".")}+ }+ }+ for _, def := range definitions {+ def.Type = ast.NodeListItem+ def.Tokens = nil+ def.FootnotesRefs = nil+ if def.FirstChild == nil {+ def.AppendChild(&ast.Node{Type: ast.NodeParagraph})+ }+ }+}++// markdownWithFootnotes2BlockDOM 保留建文档时的编辑器语法选项,并转换标准脚注。+func markdownWithFootnotes2BlockDOM(engine *lute.Lute, markdown string) string {+ if !strings.Contains(markdown, "[^") {+ return engine.Md2BlockDOM(markdown, false)+ }+ footnotes := engine.ParseOptions.Footnotes+ engine.SetFootnotes(true)+ defer engine.SetFootnotes(footnotes)+ tree := parse.Parse("", []byte(markdown), engine.ParseOptions)+ convertMarkdownFootnotes(tree)+ parse.TextMarks2Inlines(tree)+ parse.NestedInlines2FlattedSpansHybrid(tree, false)+ return string(render.NewProtyleRenderer(tree, engine.RenderOptions, engine.ParseOptions).Render())+}diff --git a/kernel/model/import_footnotes_test.go b/kernel/model/import_footnotes_test.gonew file mode 100644index 0000000000..fedac369c0--- /dev/null+++ b/kernel/model/import_footnotes_test.go@@ -0,0 +1,115 @@+package model++import (+ "fmt"+ "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 TestMarkdownFootnotes(t *testing.T) {+ for _, separator := range []string{"\n", "\n\n", "\r\n", "\r\n\r\n"} {+ for _, api := range []bool{false, true} {+ t.Run(fmt.Sprintf("separator=%q/api=%v", separator, api), func(t *testing.T) {+ markdown := "Text[^one] and[^two] and again[^ONE].\n\n[^one]: First **bold**\n\n Second paragraph\n\n - Nested item" + separator + "[^two]: Second [link](https://example.com)\n"+ var tree *parse.Tree+ if api {+ engine := util.NewLute()+ tree = engine.BlockDOM2Tree(markdownWithFootnotes2BlockDOM(engine, markdown))+ } else {+ tree, _, _, _ = parseStdMd([]byte(markdown))+ reassignIDUpdated(tree, ast.NewNodeID(), "20260901000000")+ }+ refs := markdownFootnoteRefs(t, tree)+ if len(refs) != 3 || refs[0].TextMarkBlockRefID != refs[2].TextMarkBlockRefID || refs[0].TextMarkBlockRefID == refs[1].TextMarkBlockRefID {+ t.Fatalf("incorrect footnote targets: %+v", refs)+ }+ for i, want := range []string{"First boldSecond paragraphNested item", "Second link"} {+ target := treenode.GetNodeInTree(tree, refs[i].TextMarkBlockRefID)+ if target == nil || target.Type != ast.NodeListItem || strings.ReplaceAll(target.Text(), "\n", "") != want {+ t.Fatalf("lost footnote definition %d: %+v", i, target)+ }+ }+ })+ }+ }+}++func markdownFootnoteRefs(t *testing.T, tree *parse.Tree) (refs []*ast.Node) {+ t.Helper()+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if n.Type == ast.NodeFootnotesRef || n.Type == ast.NodeFootnotesDef || n.Type == ast.NodeFootnotesDefBlock {+ t.Errorf("unconverted footnote: %s", n.Type)+ }+ if treenode.IsBlockRef(n) {+ if !n.IsTextMarkType("sup") || n.TextMarkBlockRefSubtype != "s" {+ t.Errorf("expected superscript static reference: %+v", n)+ }+ if n.TextMarkBlockRefID == "" || treenode.GetNodeInTree(tree, n.TextMarkBlockRefID) == nil {+ t.Errorf("missing footnote target: %s", n.TextMarkBlockRefID)+ }+ refs = append(refs, n)+ }+ return ast.WalkContinue+ })+ return+}++func TestMarkdownFootnotesPreserveLiteralAndUnreferencedContent(t *testing.T) {+ markdown := "Text[^note].\n\nUnknown[^missing].\n\n`[^note]` and \\[^note].\n\n```md\n[^code]: code definition\n```\n\n[^note]: First\n[^NOTE]: Duplicate\n[^unused]: Unreferenced\n[^empty]:\n"+ for _, api := range []bool{false, true} {+ engine := util.NewLute()+ tree, _, _, _ := parseStdMd([]byte(markdown))+ if api {+ tree = engine.BlockDOM2Tree(markdownWithFootnotes2BlockDOM(engine, markdown))+ }+ refs := markdownFootnoteRefs(t, tree)+ if len(refs) != 1 {+ t.Fatalf("api=%v: converted literal or undefined reference: %d", api, len(refs))+ }+ target := treenode.GetNodeInTree(tree, refs[0].TextMarkBlockRefID)+ if target.Text() != "First" {+ t.Fatalf("api=%v: duplicate label did not resolve to the first definition: %s", api, target.Text())+ }+ text := tree.Root.Text()+ for _, want := range []string{"[^missing]", "[^note]", "Duplicate", "Unreferenced"} {+ if !strings.Contains(text, want) {+ t.Errorf("api=%v: lost %q in %q", api, want, text)+ }+ }+ code := tree.Root.ChildByType(ast.NodeCodeBlock)+ if code == nil || !strings.Contains(code.ChildByType(ast.NodeCodeBlockCode).TokensStr(), "[^code]: code definition") {+ t.Errorf("api=%v: modified code example", api)+ }+ }+}++func TestMarkdownFootnotesLargeDocument(t *testing.T) {+ var source strings.Builder+ for i := 1; i <= 1459; i++ {+ fmt.Fprintf(&source, "Text[^%d]\n\n", i)+ }+ for i := 1; i <= 1459; i++ {+ fmt.Fprintf(&source, "[^%d]: Definition %d\n", i, i)+ }+ tree, _, _, _ := parseStdMd([]byte(source.String()))+ refs := markdownFootnoteRefs(t, tree)+ if len(refs) != 1459 {+ t.Fatalf("lost references: %d", len(refs))+ }+ seen := map[string]bool{}+ for i, ref := range refs {+ id := ref.TextMarkBlockRefID+ if seen[id] || treenode.GetNodeInTree(tree, id).Text() != fmt.Sprintf("Definition %d", i+1) {+ t.Fatalf("merged or misdirected definition %d", i+1)+ }+ seen[id] = true+ }+}