Skip to content

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

:sparkles: Improve Markdown syntax support in flash notes https://github.com/siyuan-note/siyuan/issues/20092

Daniel139e9e25559e
diff --git a/app/guide/20210808180117-6v0mkxr/20240113110040-7sgw8kl.sy b/app/guide/20210808180117-6v0mkxr/20240113110040-7sgw8kl.sy
index 5cf6da9afe..9aec8ae7f4 100644
--- a/app/guide/20210808180117-6v0mkxr/20240113110040-7sgw8kl.sy
+++ b/app/guide/20210808180117-6v0mkxr/20240113110040-7sgw8kl.sy
@@ -7,7 +7,7 @@
"id": "20240113110040-7sgw8kl",
"title": "Mobile App",
"type": "doc",
- "updated": "20260921210136"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -820,7 +820,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260613174243-53h143k",
- "updated": "20260803171606"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -849,7 +849,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260613174243-r1hbexb",
- "updated": "20260613174243"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -935,6 +935,79 @@
}
]
},
+ {
+ "ID": "20261004052629-w95ysdy",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261004052629-w95ysdy",
+ "updated": "20261004052629"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "New shorthands use the Markdown syntax switches in "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Settings"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Editor"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " when imported. Enabled inline syntax, middle-dot code fences ("
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "···"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "), and full-width task shortcuts ("
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "【】"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " and "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "【X】"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ") are converted immediately, without editing the imported text again."
+ }
+ ]
+ },
+ {
+ "ID": "20261004052629-inj9eiy",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261004052629-inj9eiy",
+ "updated": "20261004052629"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Each shorthand is parsed separately, so an unclosed code block cannot affect the next one. Previously imported documents are not re-parsed."
+ }
+ ]
+ },
{
"ID": "20260613174243-tm05xft",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20240113102857-c63dmo5.sy b/app/guide/20210808180117-czj9bvb/20240113102857-c63dmo5.sy
index eabb5c4d93..bc9f6569ea 100644
--- a/app/guide/20210808180117-czj9bvb/20240113102857-c63dmo5.sy
+++ b/app/guide/20210808180117-czj9bvb/20240113102857-c63dmo5.sy
@@ -7,7 +7,7 @@
"id": "20240113102857-c63dmo5",
"title": "移动端 App",
"type": "doc",
- "updated": "20260921210136"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -823,7 +823,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260613174109-kf9rdvq",
- "updated": "20260803163243"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -852,7 +852,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260613174109-bccohoq",
- "updated": "20260613174109"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -938,6 +938,79 @@
}
]
},
+ {
+ "ID": "20261004052629-tczd7hi",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261004052629-tczd7hi",
+ "updated": "20261004052629"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新导入的闪念速记遵循 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "设置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "编辑器"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 中的 Markdown 语法开关。启用的行级语法、中点代码围栏("
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "···"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")和全角任务快捷语法("
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "【】"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "【X】"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")会在导入时直接转换,无需再次编辑触发转换。"
+ }
+ ]
+ },
+ {
+ "ID": "20261004052629-5dh5rgu",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261004052629-5dh5rgu",
+ "updated": "20261004052629"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "每条速记单独解析,未闭合的代码块不会影响下一条速记。已导入的文档不会重新解析。"
+ }
+ ]
+ },
{
"ID": "20260613174109-f6x4sin",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20240113110500-dz2ae4n.sy b/app/guide/20211226090932-5lcq56f/20240113110500-dz2ae4n.sy
index a41f82305d..47066e49f9 100644
--- a/app/guide/20211226090932-5lcq56f/20240113110500-dz2ae4n.sy
+++ b/app/guide/20211226090932-5lcq56f/20240113110500-dz2ae4n.sy
@@ -7,7 +7,7 @@
"id": "20240113110500-dz2ae4n",
"title": "行動端 App",
"type": "doc",
- "updated": "20260921210136"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -824,7 +824,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260613174315-dz9gat0",
- "updated": "20260803163243"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -853,7 +853,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260613174315-symmh66",
- "updated": "20260613174315"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -939,6 +939,79 @@
}
]
},
+ {
+ "ID": "20261004052629-xrvlusr",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261004052629-xrvlusr",
+ "updated": "20261004052629"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新匯入的速記遵循 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "編輯器"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 中的 Markdown 語法開關。啟用的行級語法、中點程式碼圍欄("
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "···"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")和全形任務快捷語法("
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "【】"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "【X】"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")會在匯入時直接轉換,無需再次編輯觸發轉換。"
+ }
+ ]
+ },
+ {
+ "ID": "20261004052629-5f4fen7",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261004052629-5f4fen7",
+ "updated": "20261004052629"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "每條速記單獨解析,未閉合的程式碼區塊不會影響下一條速記。已匯入的文件不會重新解析。"
+ }
+ ]
+ },
{
"ID": "20260613174315-uerjb05",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-e6z5okf.sy b/app/guide/20240530133126-axarxgx/20240530101000-e6z5okf.sy
index e72edf6f15..e63b50c87e 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-e6z5okf.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-e6z5okf.sy
@@ -8,7 +8,7 @@
"id": "20240530101000-e6z5okf",
"title": "モバイルアプリ",
"type": "doc",
- "updated": "20260921210136"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -528,7 +528,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260613174259-xwu9036",
- "updated": "20260803163243"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -557,7 +557,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260613174259-djgqfrn",
- "updated": "20260613174259"
+ "updated": "20261004052629"
},
"Children": [
{
@@ -643,6 +643,79 @@
}
]
},
+ {
+ "ID": "20261004052629-8qyrd3c",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261004052629-8qyrd3c",
+ "updated": "20261004052629"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新しいショートハンドを取り込む際は、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "エディタ"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " の Markdown 構文の有効・無効の設定が適用されます。有効なインライン構文、中点のコードフェンス("
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "···"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")、全角のタスク簡易構文("
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "【】"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "【X】"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")は取り込み時に変換され、再編集は不要です。"
+ }
+ ]
+ },
+ {
+ "ID": "20261004052629-mfqen9u",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261004052629-mfqen9u",
+ "updated": "20261004052629"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "各ショートハンドは個別に解析されるため、閉じられていないコードブロックが次のショートハンドに影響することはありません。取り込み済みのドキュメントは再解析されません。"
+ }
+ ]
+ },
{
"ID": "20260613174259-9bcdyay",
"Type": "NodeHeading",
diff --git a/kernel/model/shortcuts.go b/kernel/model/shortcuts.go
index 7a2d12b87f..397b5a4a95 100644
--- a/kernel/model/shortcuts.go
+++ b/kernel/model/shortcuts.go
@@ -187,10 +187,9 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {
}
buff := bytes.Buffer{}
for _, s := range shorthands {
- buff.WriteString(s.content)
- buff.WriteString("\n\n")
+ buff.WriteString(shorthandDOM(s.content, s.created))
}
- dom := shorthandDOM(buff.String(), earliest)
+ dom := buff.String()
docID := util.NodeIDByTime(earliest)
var retID string
retID, err = createShorthandDocByDOM(boxID, hPath, dom, docID)
@@ -215,14 +214,11 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {
luteEngine := util.NewStdLute()
var nodes []*ast.Node
for _, s := range shorthands {
- inputTree := parse.Parse("", []byte(s.content), luteEngine.ParseOptions)
+ inputTree := parseShorthandMarkdown(s.content, s.created, luteEngine)
if nil == inputTree {
continue
}
- // 将速记行内语法转换为文本标记,确保追加到文档后可直接建立索引。
- parse.NestedInlines2FlattedSpansHybrid(inputTree, false)
for c := inputTree.Root.FirstChild; nil != c; c = c.Next {
- resetBlockIDsByTime(c, s.created)
nodes = append(nodes, c)
}
}
@@ -277,11 +273,10 @@ func resetBlockIDsByTime(node *ast.Node, created time.Time) {
func shorthandDOM(md string, created time.Time) string {
luteEngine := util.NewLute()
luteEngine.SetHTMLTag2TextMark(true)
- _, tree := luteEngine.Md2BlockDOMTree(md, false)
+ tree := parseShorthandMarkdown(md, created, luteEngine)
if nil == tree {
return ""
}
- resetBlockIDsByTime(tree.Root, created)
return luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)
}
diff --git a/kernel/model/shortcuts_markdown_fts5_test.go b/kernel/model/shortcuts_markdown_fts5_test.go
new file mode 100644
index 0000000000..ba4c4a09f6
--- /dev/null
+++ b/kernel/model/shortcuts_markdown_fts5_test.go
@@ -0,0 +1,425 @@
+// 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/>.
+
+//go:build fts5
+
+package model
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "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 TestMoveLocalShorthandsMarkdownSettings(t *testing.T) {
+ const subprocessEnv = "SIYUAN_TEST_SHORTHAND_MARKDOWN"
+ if "1" != os.Getenv(subprocessEnv) {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestMoveLocalShorthandsMarkdownSettings$", "-test.v")
+ cmd.Env = append(os.Environ(), subprocessEnv+"=1")
+ output, err := cmd.CombinedOutput()
+ if nil != err {
+ t.Fatalf("shorthand markdown subprocess failed: %v\n%s", err, output)
+ }
+ return
+ }
+
+ fixture, shorthandsDir := setupShorthandMarkdownTest(t)
+ caseIndex := 0
+ for _, route := range []string{"separate", "merged", "append"} {
+ for _, enabled := range []bool{true, false} {
+ t.Run(fmt.Sprintf("%s/enabled=%t", route, enabled), func(t *testing.T) {
+ settings := shorthandMarkdownTestSettings(enabled)
+ util.MarkdownSettings = settings
+ Conf.Editor.Markdown = settings
+ created := time.Date(2026, 9, 9, 8, caseIndex, 0, 0, time.Local)
+ caseIndex++
+ secondCreated := created.Add(11 * time.Second)
+ label := fmt.Sprintf("shorthand-markdown-%s-%t", route, enabled)
+ secondLabel := fmt.Sprintf("shorthand-second-%s-%t", route, enabled)
+ inlineCases := []struct {
+ source string
+ content string
+ mark string
+ }{
+ {"**asterisk-strong**", "asterisk-strong", "strong"},
+ {"*asterisk-emphasis*", "asterisk-emphasis", "em"},
+ {"__underscore-strong__", "underscore-strong", "strong"},
+ {"_underscore-emphasis_", "underscore-emphasis", "em"},
+ {"^superscript^", "superscript", "sup"},
+ {"~subscript~", "subscript", "sub"},
+ {"测试#" + label + "#", label, "tag"},
+ {"$x+1$", "x+1", "inline-math"},
+ {"~~strikethrough~~", "strikethrough", "s"},
+ {"~~fullwidth-strikethrough~~", "fullwidth-strikethrough", "s"},
+ {"==highlight==", "highlight", "mark"},
+ }
+ parts := []string{"entry-first"}
+ for _, inline := range inlineCases {
+ parts = append(parts, inline.source)
+ }
+ parts = append(parts,
+ "【】 fullwidth-open", "【X】 fullwidth-done", "【/】 fullwidth-progress",
+ "···text\nmiddle-dot-body\n···",
+ "- [x] ascii-task", "[] bare-ascii-task", "¥¥\nyen-body\n¥¥",
+ "```text\nfirst-tail\n【X】 inside-code\n···not-a-fence")
+ contents := []string{strings.Join(parts, "\n\n")}
+ createdTimes := []time.Time{created}
+ if "separate" != route {
+ contents = append(contents, "entry-second\n\n测试#"+secondLabel+"#\n\n**second-strong**")
+ createdTimes = append(createdTimes, secondCreated)
+ }
+
+ hPath := "/Markdown-" + label
+ oldIDs := map[string]bool{}
+ switch route {
+ case "separate":
+ Conf.FileTree.ShorthandSavePath = ""
+ hPath = "/" + created.Format("2006-01-02 15:04:05")
+ case "merged":
+ Conf.FileTree.ShorthandSavePath = hPath
+ case "append":
+ hPath = "/Source"
+ Conf.FileTree.ShorthandSavePath = hPath
+ bt := treenode.GetBlockTreeRootByHPath(fixture.box.ID, hPath)
+ if nil == bt {
+ t.Fatal("existing shorthand document fixture missing")
+ }
+ before, err := loadTreeByBlockTree(bt)
+ if nil != err {
+ t.Fatal(err)
+ }
+ ast.Walk(before.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && "" != n.ID {
+ oldIDs[n.ID] = true
+ }
+ return ast.WalkContinue
+ })
+ }
+
+ var sourcePaths []string
+ for i, content := range contents {
+ p := filepath.Join(shorthandsDir, strconv.FormatInt(createdTimes[i].UnixMilli(), 10)+".md")
+ if err := os.WriteFile(p, []byte(content), 0644); nil != err {
+ t.Fatal(err)
+ }
+ sourcePaths = append(sourcePaths, p)
+ }
+ retIDs, err := MoveLocalShorthands(fixture.box.ID)
+ if nil != err {
+ t.Fatal(err)
+ }
+ sql.FlushQueue()
+ bt := treenode.GetBlockTreeRootByHPath(fixture.box.ID, hPath)
+ if nil == bt {
+ t.Fatal("shorthand document missing")
+ }
+ if "append" == route {
+ if 0 != len(retIDs) || bt.ID != fixture.sourceID {
+ t.Fatalf("append created a new document: ids=%v, root=%s", retIDs, bt.ID)
+ }
+ } else if 1 != len(retIDs) || retIDs[0] != bt.ID || !strings.HasPrefix(bt.ID, created.Format("20060102150405")) {
+ t.Fatalf("unexpected new document ID or creation time: ids=%v, root=%s", retIDs, bt.ID)
+ }
+
+ // 清除缓存后重新加载,校验实际落盘的结构、索引和各条速记的时间。
+ cache.RemoveTreeDataInBox(bt.ID, bt.BoxID)
+ persisted, err := loadTreeByBlockTree(bt)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if "append" != route && (persisted.Root.IALAttr("id") != bt.ID || persisted.Root.IALAttr("updated") != created.Format("20060102150405")) {
+ t.Errorf("new document attributes do not preserve the earliest shorthand time: %v", persisted.Root.KramdownIAL)
+ }
+ assertShorthandMarkdownBlockTimes(t, persisted.Root, createdTimes, oldIDs)
+ firstNodes := shorthandMarkdownNodesAtTime(persisted.Root, created)
+ for _, inline := range inlineCases {
+ got := shorthandMarkdownHasMark(firstNodes, inline.content, inline.mark)
+ if got != enabled {
+ t.Errorf("%q parsed as %s: got %t, want %t", inline.source, inline.mark, got, enabled)
+ }
+ if !enabled && !strings.Contains(shorthandMarkdownText(firstNodes), inline.source) {
+ t.Errorf("disabled syntax was not preserved: %q", inline.source)
+ }
+ }
+ for _, task := range []struct {
+ label string
+ source string
+ marker string
+ }{
+ {"fullwidth-open", "【】 fullwidth-open", " "},
+ {"fullwidth-done", "【X】 fullwidth-done", "X"},
+ {"fullwidth-progress", "【/】 fullwidth-progress", "/"},
+ } {
+ marker, found := shorthandMarkdownTaskMarker(firstNodes, task.label)
+ if found != enabled || (enabled && marker != task.marker) {
+ t.Errorf("%q task marker: got %q (%t), want %q (%t)", task.source, marker, found, task.marker, enabled)
+ }
+ if !enabled && !strings.Contains(shorthandMarkdownText(firstNodes), task.source) {
+ t.Errorf("disabled fullwidth task was not preserved: %q", task.source)
+ }
+ }
+ if marker, found := shorthandMarkdownTaskMarker(firstNodes, "ascii-task"); !found || "X" != marker {
+ t.Errorf("standard task syntax changed: marker=%q, found=%t", marker, found)
+ }
+ if got := shorthandMarkdownCodeContains(firstNodes, "middle-dot-body"); got != enabled {
+ t.Errorf("middle-dot code block: got %t, want %t", got, enabled)
+ }
+ if !enabled && !strings.Contains(shorthandMarkdownText(firstNodes), "···text") {
+ t.Error("disabled middle-dot fence was not preserved")
+ }
+ if !shorthandMarkdownCodeContains(firstNodes, "first-tail\n【X】 inside-code\n···not-a-fence") {
+ t.Error("standard code block content was changed by shorthand syntax normalization")
+ }
+ for _, literal := range []string{"[] bare-ascii-task", "¥¥\nyen-body\n¥¥"} {
+ if !strings.Contains(shorthandMarkdownText(firstNodes), literal) {
+ t.Errorf("unrelated syntax was changed: %q", literal)
+ }
+ }
+ assertShorthandMarkdownTagIndex(t, label, bt.ID, created, enabled)
+ if "separate" != route {
+ secondNodes := shorthandMarkdownNodesAtTime(persisted.Root, secondCreated)
+ if !strings.Contains(shorthandMarkdownText(secondNodes), "entry-second") || shorthandMarkdownCodeContains(firstNodes, "entry-second") {
+ t.Fatal("unclosed code block consumed the next shorthand")
+ }
+ if shorthandMarkdownHasMark(secondNodes, "second-strong", "strong") != enabled {
+ t.Error("second shorthand did not honor the inline settings")
+ }
+ assertShorthandMarkdownTagIndex(t, secondLabel, bt.ID, secondCreated, enabled)
+ }
+ for _, p := range sourcePaths {
+ if _, err := os.Stat(p); !os.IsNotExist(err) {
+ t.Errorf("consumed shorthand remains: %s (%v)", p, err)
+ }
+ }
+ })
+ }
+ }
+}
+
+func setupShorthandMarkdownTest(t *testing.T) (*fileOperationTestFixture, string) {
+ t.Helper()
+ originalMarkdown := util.MarkdownSettings
+ originalPaths := map[*string]string{
+ &util.TempDir: util.TempDir, &util.QueueDir: util.QueueDir, &util.ConfDir: util.ConfDir,
+ &util.ShortcutsPath: util.ShortcutsPath, &util.DBPath: util.DBPath,
+ &util.HistoryDBPath: util.HistoryDBPath, &util.AssetContentDBPath: util.AssetContentDBPath,
+ &util.WorkingDir: util.WorkingDir,
+ }
+ t.Cleanup(func() {
+ util.MarkdownSettings = originalMarkdown
+ for target, original := range originalPaths {
+ *target = original
+ }
+ })
+ fixture := setupFileOperationTest(t)
+ util.TempDir = t.TempDir()
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.ConfDir = filepath.Join(util.TempDir, "conf")
+ util.ShortcutsPath = filepath.Join(util.TempDir, "shortcuts")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ shorthandsDir := filepath.Join(util.ShortcutsPath, "shorthands")
+ for _, dir := range []string{util.QueueDir, util.ConfDir, shorthandsDir} {
+ if err := os.MkdirAll(dir, 0755); nil != err {
+ t.Fatal(err)
+ }
+ }
+ Conf.Lang = "en"
+ Conf.Search = conf.NewSearch()
+ Conf.Editor = conf.NewEditor()
+ util.WorkingDir = filepath.Clean(filepath.Join("..", "..", "app"))
+ initLang()
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ tree, err := filesys.LoadTree(fixture.box.ID, fixture.sourcePath, util.NewLute())
+ if nil != err {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ return fixture, shorthandsDir
+}
+
+func shorthandMarkdownTestSettings(enabled bool) *util.Markdown {
+ return &util.Markdown{
+ InlineAsterisk: enabled, InlineUnderscore: enabled, InlineSup: enabled, InlineSub: enabled,
+ InlineTag: enabled, InlineMath: enabled, InlineStrikethrough: enabled,
+ InlineFullWidthStrikethrough: enabled, InlineMark: enabled,
+ BlockFullWidthTaskList: new(enabled), CodeBlockMiddleDot: new(enabled),
+ }
+}
+
+func assertShorthandMarkdownBlockTimes(t *testing.T, root *ast.Node, createdTimes []time.Time, oldIDs map[string]bool) {
+ t.Helper()
+ prefixes := map[string]int{}
+ order := map[string]int{}
+ for i, created := range createdTimes {
+ prefix := created.Format("20060102150405")
+ prefixes[prefix] = 0
+ order[prefix] = i
+ }
+ seenIDs := map[string]bool{}
+ lastOrder := -1
+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeTag == n.Type {
+ t.Error("persisted shorthand contains an unnormalized tag")
+ }
+ if !entering || !n.IsBlock() || ast.NodeKramdownBlockIAL == n.Type {
+ return ast.WalkContinue
+ }
+ if seenIDs[n.ID] {
+ t.Errorf("duplicate block ID: %s", n.ID)
+ }
+ seenIDs[n.ID] = true
+ if oldIDs[n.ID] || ast.NodeDocument == n.Type {
+ return ast.WalkContinue
+ }
+ if len(n.ID) < 14 {
+ t.Fatalf("imported block has no timestamp: %s (%s)", n.ID, n.Type)
+ }
+ prefix := n.ID[:14]
+ if _, ok := prefixes[prefix]; !ok {
+ t.Errorf("imported block has an unexpected creation time: %s (%s)", n.ID, n.Type)
+ } else {
+ prefixes[prefix]++
+ if order[prefix] < lastOrder {
+ t.Errorf("shorthand blocks were persisted out of order: %s", n.ID)
+ }
+ lastOrder = order[prefix]
+ }
+ if n.IALAttr("id") != n.ID || n.IALAttr("updated") != prefix {
+ t.Errorf("imported block attributes do not preserve its timestamp: %s, %v", n.ID, n.KramdownIAL)
+ }
+ return ast.WalkContinue
+ })
+ for id := range oldIDs {
+ if !seenIDs[id] {
+ t.Errorf("existing block was removed: %s", id)
+ }
+ }
+ for prefix, count := range prefixes {
+ if 0 == count {
+ t.Errorf("no persisted blocks retain shorthand timestamp %s", prefix)
+ }
+ }
+}
+
+func shorthandMarkdownNodesAtTime(root *ast.Node, created time.Time) (ret []*ast.Node) {
+ prefix := created.Format("20060102150405")
+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && n != root && n.IsBlock() && strings.HasPrefix(n.ID, prefix) {
+ ret = append(ret, n)
+ return ast.WalkSkipChildren
+ }
+ return ast.WalkContinue
+ })
+ return
+}
+
+func shorthandMarkdownText(nodes []*ast.Node) string {
+ var parts []string
+ for _, n := range nodes {
+ var text strings.Builder
+ ast.Walk(n, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering {
+ switch n.Type {
+ case ast.NodeText:
+ text.Write(n.Tokens)
+ case ast.NodeTextMark:
+ text.WriteString(n.TextMarkTextContent)
+ case ast.NodeSoftBreak, ast.NodeHardBreak:
+ text.WriteByte('\n')
+ }
+ }
+ return ast.WalkContinue
+ })
+ parts = append(parts, text.String())
+ }
+ return strings.Join(parts, "\n\n")
+}
+
+func shorthandMarkdownHasMark(nodes []*ast.Node, content, typ string) (ret bool) {
+ for _, n := range nodes {
+ ast.Walk(n, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeTextMark == n.Type && n.IsTextMarkType(typ) &&
+ (content == n.TextMarkTextContent || ("inline-math" == typ && content == n.TextMarkInlineMathContent)) {
+ ret = true
+ }
+ return ast.WalkContinue
+ })
+ }
+ return
+}
+
+func shorthandMarkdownTaskMarker(nodes []*ast.Node, label string) (marker string, found bool) {
+ for _, n := range nodes {
+ ast.Walk(n, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeListItem == n.Type && strings.TrimSpace(n.Text()) == label {
+ task := n.ChildByType(ast.NodeTaskListItemMarker)
+ if nil == task && nil != n.ChildByType(ast.NodeParagraph) {
+ task = n.ChildByType(ast.NodeParagraph).ChildByType(ast.NodeTaskListItemMarker)
+ }
+ if nil != task {
+ marker, found = task.EffectiveTaskListItemMarker(), true
+ }
+ }
+ return ast.WalkContinue
+ })
+ }
+ return
+}
+
+func shorthandMarkdownCodeContains(nodes []*ast.Node, text string) (ret bool) {
+ for _, n := range nodes {
+ ast.Walk(n, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeCodeBlockCode == n.Type && strings.Contains(n.TokensStr(), text) {
+ ret = true
+ }
+ return ast.WalkContinue
+ })
+ }
+ return
+}
+
+func assertShorthandMarkdownTagIndex(t *testing.T, label, rootID string, created time.Time, enabled bool) {
+ t.Helper()
+ spans := sql.QueryTagSpansByLabel(label)
+ want := 0
+ if enabled {
+ want = 1
+ }
+ if len(spans) != want {
+ t.Fatalf("tag %q index count: got %d, want %d", label, len(spans), want)
+ }
+ if enabled && (spans[0].RootID != rootID || !strings.HasPrefix(spans[0].BlockID, created.Format("20060102150405"))) {
+ t.Errorf("tag %q index points to the wrong shorthand: %+v", label, spans[0])
+ }
+}
diff --git a/kernel/model/shorthand_markdown.go b/kernel/model/shorthand_markdown.go
new file mode 100644
index 0000000000..9c39704418
--- /dev/null
+++ b/kernel/model/shorthand_markdown.go
@@ -0,0 +1,420 @@
+// 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 model
+
+import (
+ "bytes"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/88250/lute"
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var shorthandContainerPrefix = regexp.MustCompile(`^[ \t]*(?:(?:>[ \t]*)|(?:(?:[*+-]|[0-9]{1,9}[.)])[ \t]+))*`)
+var shorthandListPrefix = regexp.MustCompile(`(?:[*+-]|[0-9]{1,9}[.)])[ \t]+$`)
+
+type shorthandMarker struct {
+ start, end int
+ token string
+ dots int
+ task byte
+ listed bool
+ rootPrefix bool
+ blankBefore bool
+ blankAfter bool
+ closing bool
+ opened bool
+ rejected bool
+ replacement string
+}
+
+// parseShorthandMarkdown 仅在消费速记时应用编辑器语法,不改变普通 Markdown 导入的解析配置。
+func parseShorthandMarkdown(md string, created time.Time, engine *lute.Lute) *parse.Tree {
+ engine.SetMark(util.MarkdownSettings.InlineMark)
+ md, tasks := normalizeShorthandMarkdown(md, engine.ParseOptions)
+ tree := parse.Parse("", []byte(md), engine.ParseOptions)
+ if nil == tree {
+ return nil
+ }
+ if 0 < len(tasks) {
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || ast.NodeText != node.Type || nil == node.Parent || ast.NodeParagraph != node.Parent.Type {
+ return ast.WalkContinue
+ }
+ item := node.Parent.Parent
+ if nil == item || ast.NodeListItem != item.Type {
+ return ast.WalkContinue
+ }
+ text := bytes.TrimLeft(node.Tokens, " \t")
+ end := bytes.IndexByte(text, 'z')
+ if 0 <= end {
+ if marker, ok := tasks[string(text[:end+1])]; ok {
+ node.Tokens = text[end+1:]
+ task := item.ChildByType(ast.NodeTaskListItemMarker)
+ if nil == task {
+ task = node.Parent.ChildByType(ast.NodeTaskListItemMarker)
+ }
+ if nil != task {
+ task.ReviveFromMarker(marker)
+ item.ListData.Checked = task.TaskListItemChecked
+ task.Unlink()
+ item.PrependChild(task)
+ }
+ }
+ }
+ return ast.WalkContinue
+ })
+ }
+ parse.TextMarks2Inlines(tree)
+ parse.NestedInlines2FlattedSpansHybrid(tree, false)
+ resetBlockIDsByTime(tree.Root, created)
+ return tree
+}
+
+// normalizeShorthandMarkdown 由解析器判断标记的上下文,避免修改代码、公式、HTML 块和转义正文。
+func normalizeShorthandMarkdown(md string, options *parse.Options) (string, map[string]byte) {
+ settings := util.MarkdownSettings
+ dotsEnabled := nil == settings.CodeBlockMiddleDot || *settings.CodeBlockMiddleDot
+ tasksEnabled := nil == settings.BlockFullWidthTaskList || *settings.BlockFullWidthTaskList
+ if !dotsEnabled && !tasksEnabled {
+ return md, nil
+ }
+ // 探针仅用于临时解析;使用不与原文冲突的前缀,最终只保留用户正文。
+ prefix := "siyuanshorthandprobe"
+ for strings.Contains(md, prefix) {
+ prefix += "q"
+ }
+ var markers []*shorthandMarker
+ previousBlank := true
+ for offset := 0; offset < len(md); {
+ end := strings.IndexByte(md[offset:], '\n')
+ if 0 > end {
+ end = len(md)
+ } else {
+ end += offset
+ }
+ line := strings.TrimSuffix(md[offset:end], "\r")
+ container := shorthandContainerPrefix.FindString(line)
+ text := line[len(container):]
+ marker := &shorthandMarker{start: offset + len(container), listed: shorthandListPrefix.MatchString(container),
+ rootPrefix: len(container) <= 3 && "" == strings.Trim(container, " "), blankBefore: previousBlank}
+ previousBlank = "" == strings.Trim(line, " \t")
+ marker.blankAfter = end+1 >= len(md)
+ if !marker.blankAfter {
+ nextLine := md[end+1:]
+ if nextEnd := strings.IndexByte(nextLine, '\n'); 0 <= nextEnd {
+ nextLine = nextLine[:nextEnd]
+ }
+ marker.blankAfter = "" == strings.Trim(nextLine, " \t\r")
+ }
+ if dotsEnabled && strings.HasPrefix(text, "···") {
+ for strings.HasPrefix(text[marker.dots*len("·"):], "·") {
+ marker.dots++
+ }
+ marker.end = marker.start + marker.dots*len("·")
+ suffix := text[marker.dots*len("·"):]
+ marker.closing = "" == strings.TrimSpace(suffix)
+ if strings.ContainsAny(suffix, "`·") || (options.ProtyleWYSIWYG && strings.Contains(suffix, "~")) {
+ marker.dots = 0
+ }
+ } else if tasksEnabled {
+ length, status := shorthandTaskMarker(text)
+ marker.end, marker.task = marker.start+length, status
+ }
+ if 0 < marker.dots || 0 != marker.task {
+ marker.token = prefix + strconv.Itoa(len(markers)) + "z"
+ markers = append(markers, marker)
+ }
+ offset = end + 1
+ }
+ if 0 == len(markers) {
+ return md, nil
+ }
+ // 探测时将完整 HTML 块视为不透明正文,避免所见即所得模式把 pre 等标签当作普通段落。
+ probeOptions := *options
+ probeOptions.ProtyleWYSIWYG = false
+ probeOptions.KramdownBlockIAL = false
+ fenceOptions := *options
+ fenceOptions.KramdownBlockIAL = false
+ build := func(probe bool) string {
+ var result strings.Builder
+ offset := 0
+ for _, marker := range markers {
+ result.WriteString(md[offset:marker.start])
+ if "" != marker.replacement {
+ result.WriteString(marker.replacement)
+ if probe && marker.opened {
+ result.WriteString(marker.token + " ")
+ }
+ } else {
+ if probe {
+ result.WriteString(marker.token)
+ }
+ result.WriteString(md[marker.start:marker.end])
+ }
+ offset = marker.end
+ }
+ result.WriteString(md[offset:])
+ return result.String()
+ }
+ // 使用原文中不存在的长围栏,代码正文里的普通围栏不会提前结束中点代码块。
+ fenceLen, run := 3, 0
+ for _, char := range md {
+ if '~' == char {
+ run++
+ if run >= fenceLen {
+ fenceLen = run + 1
+ }
+ } else {
+ run = 0
+ }
+ }
+ for {
+ probe := parse.Parse("", []byte(build(true)), &probeOptions)
+ plain := shorthandPlainMarkers(probe, markers, prefix, false)
+ if batchShorthandRootFences(probe, markers, prefix, strings.Repeat("~", fenceLen), build, &fenceOptions, &probeOptions) {
+ continue
+ }
+ var opening *shorthandMarker
+ for _, marker := range markers {
+ if 0 < marker.dots && !marker.rejected && "" == marker.replacement && plain[marker] {
+ opening = marker
+ break
+ }
+ }
+ if nil == opening {
+ break
+ }
+ fence := strings.Repeat("~", fenceLen)
+ opening.replacement = fence
+ opening.opened = true
+ probe = parse.Parse("", []byte(build(true)), &fenceOptions)
+ opened := false
+ ast.Walk(probe.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || ast.NodeCodeBlockCode != node.Type || nil == node.Parent ||
+ string(node.Parent.CodeBlockInfo) != opening.token {
+ return ast.WalkContinue
+ }
+ opened = true
+ for _, marker := range markers {
+ if marker.start <= opening.start || marker.dots < opening.dots || !marker.closing || "" != marker.replacement {
+ continue
+ }
+ at := bytes.Index(node.Tokens, []byte(marker.token))
+ if 0 > at {
+ continue
+ }
+ line := node.Tokens[bytes.LastIndexByte(node.Tokens[:at], '\n')+1 : at]
+ if len(line) > 3 || 0 != len(bytes.Trim(line, " ")) {
+ continue
+ }
+ // 代码正文已被解析器去掉部分缩进,必须让解析器再次确认这个位置确实能关闭围栏。
+ closingFence := fence + "~"
+ marker.replacement = closingFence
+ closed := false
+ trial := parse.Parse("", []byte(build(true)), &fenceOptions)
+ ast.Walk(trial.Root, func(candidate *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeCodeBlock == candidate.Type &&
+ string(candidate.CodeBlockInfo) == opening.token &&
+ string(candidate.CodeBlockCloseFence) == closingFence {
+ closed = true
+ }
+ return ast.WalkContinue
+ })
+ if closed {
+ break
+ }
+ marker.replacement = ""
+ }
+ return ast.WalkSkipChildren
+ })
+ if !opened {
+ opening.replacement = ""
+ opening.opened = false
+ opening.rejected = true
+ }
+ }
+ probe := parse.Parse("", []byte(build(true)), &probeOptions)
+ plain := shorthandPlainMarkers(probe, markers, prefix, false)
+ tasks := map[string]byte{}
+ for _, marker := range markers {
+ if 0 == marker.task || !plain[marker] {
+ continue
+ }
+ marker.replacement = "[ ] " + marker.token
+ if !marker.listed {
+ marker.replacement = "- " + marker.replacement
+ }
+ tasks[marker.token] = marker.task
+ }
+ // 缩进或容器上下文可能阻止列表形成;只有实际解析成任务的候选才保留替换。
+ for 0 < len(tasks) {
+ valid := map[string]bool{}
+ trial := parse.Parse("", []byte(build(false)), options)
+ ast.Walk(trial.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || ast.NodeText != node.Type || nil == node.Parent || ast.NodeParagraph != node.Parent.Type {
+ return ast.WalkContinue
+ }
+ item := node.Parent.Parent
+ if nil == item || ast.NodeListItem != item.Type ||
+ (nil == item.ChildByType(ast.NodeTaskListItemMarker) && nil == node.Parent.ChildByType(ast.NodeTaskListItemMarker)) {
+ return ast.WalkContinue
+ }
+ text := bytes.TrimLeft(node.Tokens, " \t")
+ if end := bytes.IndexByte(text, 'z'); 0 <= end {
+ valid[string(text[:end+1])] = true
+ }
+ return ast.WalkContinue
+ })
+ reverted := false
+ for _, marker := range markers {
+ if 0 != marker.task && "" != marker.replacement && !valid[marker.token] {
+ marker.replacement = ""
+ delete(tasks, marker.token)
+ reverted = true
+ }
+ }
+ if !reverted {
+ break
+ }
+ }
+ return build(false), tasks
+}
+
+// batchShorthandRootFences 对空行隔开的顶层围栏批量验证,避免长速记逐块重复解析全部正文。
+// 复杂容器或任何验证不通过的批次仍由逐块解析处理。
+func batchShorthandRootFences(tree *parse.Tree, markers []*shorthandMarker, prefix, fence string,
+ build func(bool) string, options, protectedOptions *parse.Options) bool {
+ plain := shorthandPlainMarkers(tree, markers, prefix, true)
+ type pair struct{ opening, closing *shorthandMarker }
+ var pairs []pair
+ for i := 0; i < len(markers); i++ {
+ opening := markers[i]
+ if 0 == opening.dots || opening.rejected || "" != opening.replacement {
+ continue
+ }
+ if !opening.rootPrefix || !plain[opening] || !opening.blankBefore {
+ break
+ }
+ matched := false
+ for j := i + 1; j < len(markers); j++ {
+ closing := markers[j]
+ if closing.dots >= opening.dots && closing.closing && closing.rootPrefix && "" == closing.replacement {
+ if !closing.blankAfter {
+ break
+ }
+ pairs = append(pairs, pair{opening, closing})
+ i = j
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ break
+ }
+ }
+ if len(pairs) < 2 {
+ return false
+ }
+ for _, pair := range pairs {
+ pair.opening.replacement, pair.opening.opened = fence, true
+ pair.closing.replacement = fence + "~"
+ }
+ for _, profile := range []*parse.Options{options, protectedOptions} {
+ valid := map[string]bool{}
+ trial := parse.Parse("", []byte(build(true)), profile)
+ ast.Walk(trial.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeCodeBlock == node.Type && ast.NodeDocument == node.Parent.Type &&
+ string(node.CodeBlockCloseFence) == fence+"~" {
+ valid[string(node.CodeBlockInfo)] = true
+ }
+ return ast.WalkContinue
+ })
+ for _, pair := range pairs {
+ if !valid[pair.opening.token] {
+ for _, pair := range pairs {
+ pair.opening.replacement, pair.opening.opened = "", false
+ pair.closing.replacement = ""
+ }
+ return false
+ }
+ }
+ }
+ return true
+}
+
+func shorthandPlainMarkers(tree *parse.Tree, markers []*shorthandMarker, prefix string, rootOnly bool) map[*shorthandMarker]bool {
+ ret := map[*shorthandMarker]bool{}
+ byToken := map[string]*shorthandMarker{}
+ for _, marker := range markers {
+ byToken[marker.token] = marker
+ }
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeText == node.Type && nil != node.Parent && ast.NodeParagraph == node.Parent.Type &&
+ (!rootOnly || node.Parent.Parent == tree.Root) {
+ text := string(node.Tokens)
+ for {
+ at := strings.Index(text, prefix)
+ if 0 > at {
+ break
+ }
+ text = text[at:]
+ end := strings.IndexByte(text, 'z')
+ if 0 > end {
+ break
+ }
+ if marker := byToken[text[:end+1]]; nil != marker {
+ ret[marker] = true
+ }
+ text = text[end+1:]
+ }
+ }
+ return ast.WalkContinue
+ })
+ return ret
+}
+
+func shorthandTaskMarker(text string) (int, byte) {
+ if strings.HasPrefix(text, "【】") {
+ return len("【】"), ' '
+ }
+ opening := 0
+ if strings.HasPrefix(text, "【") {
+ opening = len("【")
+ } else if strings.HasPrefix(text, "[") {
+ opening = 1
+ }
+ if 0 == opening || len(text) <= opening+1 {
+ return 0, 0
+ }
+ status := text[opening]
+ if ' ' > status || '~' < status || '[' == status || ']' == status {
+ return 0, 0
+ }
+ if strings.HasPrefix(text[opening+1:], "】") {
+ return opening + 1 + len("】"), status
+ }
+ if 1 < opening && ']' == text[opening+1] {
+ return opening + 2, status
+ }
+ return 0, 0
+}
diff --git a/kernel/model/shorthand_markdown_test.go b/kernel/model/shorthand_markdown_test.go
new file mode 100644
index 0000000000..7565744bc7
--- /dev/null
+++ b/kernel/model/shorthand_markdown_test.go
@@ -0,0 +1,266 @@
+// 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 model
+
+import (
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/88250/lute"
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func shorthandSyntaxTestSettings(t testing.TB) {
+ previous := util.MarkdownSettings
+ util.MarkdownSettings = util.NewMarkdown()
+ t.Cleanup(func() { util.MarkdownSettings = previous })
+}
+
+func shorthandSyntaxNodes(tree *parse.Tree, typ ast.NodeType) (ret []*ast.Node) {
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && node.Type == typ {
+ ret = append(ret, node)
+ }
+ return ast.WalkContinue
+ })
+ return
+}
+
+func TestShorthandMarkdownSettings(t *testing.T) {
+ shorthandSyntaxTestSettings(t)
+ for _, factory := range []struct {
+ name string
+ new func() *lute.Lute
+ }{{"new", util.NewLute}, {"append", util.NewStdLute}} {
+ for _, tc := range []struct {
+ name, md, mark string
+ set func(bool)
+ node ast.NodeType
+ }{
+ {"asterisk", "**text**", "strong", func(v bool) { util.MarkdownSettings.InlineAsterisk = v }, ast.NodeTextMark},
+ {"underscore", "__text__", "strong", func(v bool) { util.MarkdownSettings.InlineUnderscore = v }, ast.NodeTextMark},
+ {"sup", "^text^", "sup", func(v bool) { util.MarkdownSettings.InlineSup = v }, ast.NodeTextMark},
+ {"sub", "~text~", "sub", func(v bool) { util.MarkdownSettings.InlineSub = v }, ast.NodeTextMark},
+ {"tag", "#text#", "tag", func(v bool) { util.MarkdownSettings.InlineTag = v }, ast.NodeTextMark},
+ {"math", "$text$", "inline-math", func(v bool) { util.MarkdownSettings.InlineMath = v }, ast.NodeTextMark},
+ {"strikethrough", "~~text~~", "s", func(v bool) { util.MarkdownSettings.InlineStrikethrough = v }, ast.NodeTextMark},
+ {"full-width-strikethrough", "~~text~~", "s", func(v bool) { util.MarkdownSettings.InlineFullWidthStrikethrough = v }, ast.NodeTextMark},
+ {"mark", "==text==", "mark", func(v bool) { util.MarkdownSettings.InlineMark = v }, ast.NodeTextMark},
+ {"middle-dot", "···go\ntext\n···", "", func(v bool) { util.MarkdownSettings.CodeBlockMiddleDot = &v }, ast.NodeCodeBlock},
+ {"full-width-task", "【X】text", "", func(v bool) { util.MarkdownSettings.BlockFullWidthTaskList = &v }, ast.NodeListItem},
+ } {
+ for _, enabled := range []bool{false, true} {
+ name := factory.name + "/" + tc.name + "/disabled"
+ if enabled {
+ name = factory.name + "/" + tc.name + "/enabled"
+ }
+ t.Run(name, func(t *testing.T) {
+ util.MarkdownSettings = util.NewMarkdown()
+ tc.set(enabled)
+ tree := parseShorthandMarkdown(tc.md, time.Now(), factory.new())
+ found := false
+ for _, node := range shorthandSyntaxNodes(tree, tc.node) {
+ if "" == tc.mark || node.IsTextMarkType(tc.mark) {
+ found = true
+ }
+ }
+ if found != enabled {
+ t.Fatalf("syntax found = %v, enabled = %v", found, enabled)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestShorthandMiddleDotCodeProtection(t *testing.T) {
+ shorthandSyntaxTestSettings(t)
+ for _, tc := range []struct {
+ name, md, code string
+ tasks int
+ }{
+ {"markdown-body", "···go\n# heading\n- item\n<div>html</div>\n【X】literal\n```\n···\n\n【】task", "# heading\n- item\n<div>html</div>\n【X】literal\n```\n", 1},
+ {"quote", "> ···go\n> - item\n> ···\n\n【】task", "- item\n", 1},
+ {"list", "- ···go\n - item\n ···\n\n【】task", "- item\n", 1},
+ {"list-tab-close", "- ···go\n body\n\t···\n\n【】task", "body\n", 1},
+ {"root-tab-close", "···go\n\t···\nbody\n···", "\t···\nbody\n", 0},
+ {"short-close", "····go\n···\nbody\n····", "···\nbody\n", 0},
+ {"suffix-close", "···go\n···extra\nbody\n···", "···extra\nbody\n", 0},
+ {"indented-close", " ···go\n ···\nbody\n···\n\n【】task", " ···\nbody\n", 1},
+ {"unclosed", "···go\nbody\n【】literal", "body\n【】literal\n", 0},
+ {"exit-quote", "> ···go\n> body\n\n【】task", "body\n", 1},
+ {"native-code", "```go\n···\n【】literal\n```\n\n【】task", "···\n【】literal\n", 1},
+ {"unclosed-before-short-pairs", "····go\nhead\n···js\none\n···\n\n···js\ntwo\n···", "head\n···js\none\n···\n\n···js\ntwo\n···\n", 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tree := parseShorthandMarkdown(tc.md, time.Now(), util.NewLute())
+ codes := shorthandSyntaxNodes(tree, ast.NodeCodeBlockCode)
+ if 1 != len(codes) || string(codes[0].Tokens) != tc.code {
+ var actual []string
+ for _, code := range codes {
+ actual = append(actual, string(code.Tokens))
+ }
+ t.Fatalf("code = %q, want %q", actual, tc.code)
+ }
+ count := 0
+ for _, item := range shorthandSyntaxNodes(tree, ast.NodeListItem) {
+ if 3 == item.ListData.Typ {
+ count++
+ }
+ }
+ if count != tc.tasks {
+ t.Fatalf("task count = %d, want %d", count, tc.tasks)
+ }
+ })
+ }
+}
+
+func TestShorthandTaskMarkersAndLiteralProtection(t *testing.T) {
+ shorthandSyntaxTestSettings(t)
+ for _, tc := range []struct {
+ md string
+ marker string
+ }{
+ {"【】task", " "}, {"【X】task", "X"}, {"【x】task", "X"}, {"【/】task", "/"},
+ {"【\"】task", "&quot;"}, {"【&】task", "&amp;"}, {"[X】task", "X"}, {"【X]task", "X"},
+ {"【<】task", "&lt;"}, {"【>】task", "&gt;"},
+ {"> 【】task", " "}, {"- 【】task", " "}, {"- parent\n 【】task", " "},
+ {"\\【】literal", ""}, {"`【】literal`", ""}, {"`code\n【】literal\ncode`", ""},
+ {"<pre>\n【】literal\n···\n</pre>", ""}, {"$$\n【】literal\n···\n$$", ""},
+ {";;;plugin/test\n【】literal\n···\n;;;", ""}, {"【\t】literal", ""},
+ {"[]literal", ""}, {"¥¥literal", ""},
+ {" 【X】literal", ""}, {"text\n2. 【X】literal", ""},
+ } {
+ t.Run(tc.md, func(t *testing.T) {
+ tree := parseShorthandMarkdown(tc.md, time.Now(), util.NewLute())
+ var actual []string
+ for _, item := range shorthandSyntaxNodes(tree, ast.NodeListItem) {
+ if 3 == item.ListData.Typ {
+ actual = append(actual, item.ChildByType(ast.NodeTaskListItemMarker).EffectiveTaskListItemMarker())
+ }
+ }
+ if "" == tc.marker && 0 != len(actual) || "" != tc.marker && (1 != len(actual) || actual[0] != tc.marker) {
+ t.Fatalf("task markers = %q, want %q", actual, tc.marker)
+ }
+ dom := util.NewLute().Tree2BlockDOM(tree, util.NewLute().RenderOptions, util.NewLute().ParseOptions)
+ if strings.Contains(dom, "siyuanshorthandprobe") {
+ t.Fatal("temporary syntax marker persisted")
+ }
+ })
+ }
+ util.MarkdownSettings.CodeBlockMiddleDot = nil
+ util.MarkdownSettings.BlockFullWidthTaskList = nil
+ tree := parseShorthandMarkdown("···\ncode\n···\n\n【】task", time.Now(), util.NewLute())
+ if 1 != len(shorthandSyntaxNodes(tree, ast.NodeCodeBlock)) || 1 != len(shorthandSyntaxNodes(tree, ast.NodeListItem)) {
+ t.Fatal("missing default shortcut settings disabled conversion")
+ }
+}
+
+func TestShorthandRejectedMarkersPreserveOriginalText(t *testing.T) {
+ shorthandSyntaxTestSettings(t)
+ for _, md := range []string{" ···go\nbody", "text\n ···go\nbody", "···go~x\nbody", "\\···go\nbody", "`code\n···\ncode`", " 【X】literal", "text\n2. 【X】literal"} {
+ t.Run(md, func(t *testing.T) {
+ actual, tasks := normalizeShorthandMarkdown(md, util.NewLute().ParseOptions)
+ if actual != md || 0 != len(tasks) {
+ t.Fatalf("invalid marker changed: got %q, want %q", actual, md)
+ }
+ })
+ }
+}
+
+func TestShorthandBatchStopsAtEarlierContainer(t *testing.T) {
+ shorthandSyntaxTestSettings(t)
+ md := "> ···\n····\n\n···go\nx\n···\n\n···go\ny\n···"
+ tree := parseShorthandMarkdown(md, time.Now(), util.NewLute())
+ rootCodes := 0
+ for _, code := range shorthandSyntaxNodes(tree, ast.NodeCodeBlock) {
+ if code.Parent != tree.Root {
+ continue
+ }
+ rootCodes++
+ body := code.ChildByType(ast.NodeCodeBlockCode).TokensStr()
+ if !strings.Contains(body, "···go\nx\n···") || !strings.Contains(body, "···go\ny\n···") {
+ t.Fatalf("batch normalization changed an earlier unclosed fence body: %q", body)
+ }
+ }
+ if 1 != rootCodes {
+ t.Fatalf("root code blocks = %d, want one unclosed block", rootCodes)
+ }
+}
+
+func TestShorthandBatchPreservesNewlyExposedLiteralContexts(t *testing.T) {
+ shorthandSyntaxTestSettings(t)
+ for _, tc := range []struct{ md, literalTail string }{
+ {" ···go\n····\n</pre>\n···\n ···", "</pre>\n···\n ···"},
+ {"···go\n`text\n···\nend`\n···js\nbody\n···\ntail`", "end`\n···js\nbody\n···\ntail`"},
+ } {
+ actual, _ := normalizeShorthandMarkdown(tc.md, util.NewLute().ParseOptions)
+ if !strings.HasSuffix(actual, tc.literalTail) {
+ t.Fatalf("batch conversion changed a literal context exposed by an earlier fence: %q", actual)
+ }
+ }
+}
+
+func TestShorthandSyntaxKeepsOtherImportBehavior(t *testing.T) {
+ shorthandSyntaxTestSettings(t)
+ engine := util.NewStdLute()
+ if engine.ParseOptions.Mark {
+ t.Fatal("standard imports unexpectedly enabled marks")
+ }
+ tree := parseShorthandMarkdown("==mark==\n\n code\n\n- [/] literal", time.Now(), engine)
+ for _, item := range shorthandSyntaxNodes(tree, ast.NodeListItem) {
+ if 3 == item.ListData.Typ {
+ t.Fatal("full-width task support expanded ordinary task syntax")
+ }
+ }
+ if 1 != len(shorthandSyntaxNodes(tree, ast.NodeCodeBlock)) || util.NewStdLute().ParseOptions.Mark {
+ t.Fatal("shorthand parsing changed the standard import profile")
+ }
+ const literal = "siyuanshorthandprobe0z"
+ tree = parseShorthandMarkdown("【】"+literal, time.Now(), util.NewLute())
+ if tree.Root.Text() != literal {
+ t.Fatalf("user text collided with temporary syntax markers: %q", tree.Root.Text())
+ }
+}
+
+func BenchmarkShorthandMarkdownFences(b *testing.B) {
+ shorthandSyntaxTestSettings(b)
+ for _, count := range []int{100, 1000} {
+ md := strings.Repeat("···go\nbody\n···\n\n", count)
+ b.Run(strconv.Itoa(count), func(b *testing.B) {
+ engine := util.NewLute()
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ parseShorthandMarkdown(md, time.Now(), engine)
+ }
+ })
+ }
+}
+
+func BenchmarkShorthandMarkdownFalseClosings(b *testing.B) {
+ shorthandSyntaxTestSettings(b)
+ md := "····go\n" + strings.Repeat("···\n ····\n", 1000) + "····"
+ engine := util.NewLute()
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ parseShorthandMarkdown(md, time.Now(), engine)
+ }
+}