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: Apply case sensitivity consistently across replacement types https://github.com/siyuan-note/siyuan/issues/20276
Daniel5d98038afb50
diff --git a/kernel/apicontract/search_query.go b/kernel/apicontract/search_query.goindex 4d3ed882c5..a63e81f26e 100644--- a/kernel/apicontract/search_query.go+++ b/kernel/apicontract/search_query.go@@ -68,6 +68,8 @@ type FullTextSearchBlockData struct {type FindReplaceRequest struct {// Method 缺省或为 null 时使用文本替换;支持文本(0)、查询语法(1)和正则表达式(3)。// SQL(2)和语义搜索(4)返回 code=1 与提示信息,不执行替换;IDs 为空时表示替换全部。+ // 文本与查询语法替换的所有启用类型遵循搜索配置的 CaseSensitive,替换串按字面量写入。+ // 正则模式的大小写匹配由表达式决定,替换串保留捕获组展开语义。SearchBlockRequestK string `json:"k"`R string `json:"r"`diff --git a/kernel/model/search.go b/kernel/model/search.goindex d0a1aeeb05..36c7c8af87 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -723,16 +723,15 @@ func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,title := node.IALAttr("title")tags := node.IALAttr("tags")if 0 == method {- if strings.Contains(title, keyword) {- docTitleReplacement := strings.ReplaceAll(replacement, "/", "/")- renameRootTitles[node.ID] = strings.ReplaceAll(title, keyword, docTitleReplacement)+ if newTitle, matched := replaceSearchText(title, method, keyword, strings.ReplaceAll(replacement, "/", "/"), r); matched {+ renameRootTitles[node.ID] = newTitlerenameRoots = append(renameRoots, node)}- if strings.Contains(tags, keyword) {+ if newTags, matched := replaceSearchText(tags, method, keyword, strings.TrimSuffix(strings.TrimPrefix(replacement, "#"), "#"), r); matched {replacement = strings.TrimPrefix(replacement, "#")replacement = strings.TrimSuffix(replacement, "#")- tags = strings.ReplaceAll(tags, keyword, replacement)+ tags = newTagstags = strings.ReplaceAll(tags, editor.Zwsp, "")node.SetIALAttr("tags", tags)ReloadTag()@@ -843,10 +842,10 @@ func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,if replaceTypes["aTitle"] {if 0 == method {title := util.UnescapeHTML(n.TextMarkATitle)- if strings.Contains(title, escapedKey) {- n.TextMarkATitle = strings.ReplaceAll(title, escapedKey, replacement)- } else if strings.Contains(n.TextMarkATitle, keyword) {- n.TextMarkATitle = strings.ReplaceAll(title, keyword, replacement)+ if content, matched := replaceSearchText(title, method, escapedKey, replacement, r); matched {+ n.TextMarkATitle = content+ } else if content, matched = replaceSearchText(title, method, keyword, replacement, r); matched {+ n.TextMarkATitle = content}} else if 3 == method {if nil != r && r.MatchString(n.TextMarkATitle) {@@ -858,10 +857,10 @@ func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,if replaceTypes["aHref"] {if 0 == method {href := util.UnescapeHTML(n.TextMarkAHref)- if strings.Contains(href, escapedKey) {- n.TextMarkAHref = strings.ReplaceAll(href, escapedKey, util.EscapeHTML(replacement))- } else if strings.Contains(href, keyword) {- n.TextMarkAHref = strings.ReplaceAll(href, keyword, strings.TrimSpace(replacement))+ if content, matched := replaceSearchText(href, method, escapedKey, util.EscapeHTML(replacement), r); matched {+ n.TextMarkAHref = content+ } else if content, matched = replaceSearchText(href, method, keyword, strings.TrimSpace(replacement), r); matched {+ n.TextMarkAHref = content}} else if 3 == method {if nil != r && r.MatchString(n.TextMarkAHref) {@@ -972,15 +971,7 @@ func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,return ast.WalkContinue}- if 0 == method {- if strings.Contains(n.TextMarkInlineMathContent, keyword) {- n.TextMarkInlineMathContent = strings.ReplaceAll(n.TextMarkInlineMathContent, keyword, replacement)- }- } else if 3 == method {- if nil != r && r.MatchString(n.TextMarkInlineMathContent) {- n.TextMarkInlineMathContent = r.ReplaceAllString(n.TextMarkInlineMathContent, replacement)- }- }+ n.TextMarkInlineMathContent, _ = replaceSearchText(n.TextMarkInlineMathContent, method, keyword, replacement, r)if "" == n.TextMarkInlineMathContent {unlinks = append(unlinks, n)@@ -990,16 +981,9 @@ func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,return ast.WalkContinue}- if 0 == method {- if strings.Contains(n.TextMarkInlineMemoContent, keyword) {- n.TextMarkInlineMemoContent = strings.ReplaceAll(n.TextMarkInlineMemoContent, keyword, replacement)- n.TextMarkTextContent, _ = replaceEscapedTextMarkContent(n.TextMarkTextContent, method, keyword, replacement, r)- }- } else if 3 == method {- if nil != r && r.MatchString(n.TextMarkInlineMemoContent) {- n.TextMarkInlineMemoContent = r.ReplaceAllString(n.TextMarkInlineMemoContent, replacement)- n.TextMarkTextContent, _ = replaceEscapedTextMarkContent(n.TextMarkTextContent, method, keyword, replacement, r)- }+ if content, matched := replaceSearchText(n.TextMarkInlineMemoContent, method, keyword, replacement, r); matched {+ n.TextMarkInlineMemoContent = content+ n.TextMarkTextContent, _ = replaceEscapedTextMarkContent(n.TextMarkTextContent, method, keyword, replacement, r)}if "" == n.TextMarkTextContent {@@ -1086,15 +1070,15 @@ func replaceNodeTextMarkTextContent(n *ast.Node, method int, keyword, escapedKeyif strings.HasPrefix(replacement, "#") && strings.HasSuffix(replacement, "#") {replacement = strings.TrimPrefix(replacement, "#")replacement = strings.TrimSuffix(replacement, "#")- } else if n.TextMarkTextContent == keyword || n.TextMarkTextContent == escapedKey {+ } else if equalSearchText(n.TextMarkTextContent, keyword) || equalSearchText(n.TextMarkTextContent, escapedKey) {// 将标签转换为纯文本if "tag" == n.TextMarkType { // 没有其他类型,仅是标签时直接转换content := n.TextMarkTextContent- if strings.Contains(content, escapedKey) {- content = strings.ReplaceAll(content, escapedKey, replacement)- } else if strings.Contains(content, keyword) {- content = strings.ReplaceAll(content, keyword, replacement)+ if replaced, matched := replaceSearchText(content, method, escapedKey, replacement, r); matched {+ content = replaced+ } else {+ content, _ = replaceSearchText(content, method, keyword, replacement, r)}content = strings.ReplaceAll(content, editor.Zwsp, "")@@ -1122,7 +1106,7 @@ func replaceNodeTextMarkTextContent(n *ast.Node, method int, keyword, escapedKey// 存在其他类型时仅移除标签类型n.TextMarkType = strings.ReplaceAll(n.TextMarkType, "tag", "")n.TextMarkType = strings.TrimSpace(n.TextMarkType)- } else if strings.Contains(n.TextMarkTextContent, keyword) || strings.Contains(n.TextMarkTextContent, escapedKey) { // 标签包含了部分关键字的情况+ } else { // 标签包含部分关键字时保留标签类型。if "tag" == n.TextMarkType { // 没有其他类型,仅是标签时保持标签类型不变,仅替换标签部分内容content, _ := replaceEscapedTextMarkContent(n.TextMarkTextContent, method, keyword, replacement, r)content = strings.ReplaceAll(content, editor.Zwsp, "")@@ -1143,15 +1127,41 @@ func replaceNodeTextMarkTextContent(n *ast.Node, method int, keyword, escapedKey// replaceEscapedTextMarkContent 在正文上匹配和展开捕获组,写回时统一转义,避免替换结果变成 HTML 标签。func replaceEscapedTextMarkContent(content string, method int, keyword, replacement string, r *regexp.Regexp) (string, bool) {text := util.UnescapeHTML(content)- if 0 == method && strings.Contains(text, keyword) {- return util.EscapeHTML(strings.ReplaceAll(text, keyword, replacement)), true- }- if 3 == method && nil != r && r.MatchString(text) {- return util.EscapeHTML(r.ReplaceAllString(text, replacement)), true+ if replaced, matched := replaceSearchText(text, method, keyword, replacement, r); matched {+ return util.EscapeHTML(replaced), true}return content, false}+// replaceSearchText 的文本匹配遵循大小写设置并按字面量替换,正则模式保持捕获组展开语义。+func replaceSearchText(input string, method int, keyword, replacement string, r *regexp.Regexp) (string, bool) {+ if method == 0 {+ if !Conf.Search.CaseSensitive {+ return replaceCaseInsensitiveText(input, keyword, replacement)+ }+ if strings.Contains(input, keyword) {+ return strings.ReplaceAll(input, keyword, replacement), true+ }+ } else if method == 3 && r != nil && r.MatchString(input) {+ return r.ReplaceAllString(input, replacement), true+ }+ return input, false+}++func replaceSearchTokens(input []byte, method int, keyword, replacement string, r *regexp.Regexp) ([]byte, bool) {+ if content, matched := replaceSearchText(string(input), method, keyword, replacement, r); matched {+ return []byte(content), true+ }+ return input, false+}++func equalSearchText(input, keyword string) bool {+ if Conf.Search.CaseSensitive {+ return input == keyword+ }+ return strings.EqualFold(input, keyword)+}+type replaceTextFragment struct {start intend int@@ -1489,30 +1499,7 @@ func applyReplaceTextRunOutput(run *replaceTextRun, output []*ast.Node, skipNode// Supports replacing text elements with other elements https://github.com/siyuan-note/siyuan/issues/11058func replaceTextNode(text *ast.Node, method int, keyword string, replacement string, r *regexp.Regexp, luteEngine *lute.Lute) bool {if 0 == method {- newContent := text.Tokens- if Conf.Search.CaseSensitive {- if bytes.Contains(text.Tokens, []byte(keyword)) {- newContent = bytes.ReplaceAll(text.Tokens, []byte(keyword), []byte(replacement))- }- } else {- if "" != strings.TrimSpace(keyword) {- // 当搜索结果中的文本元素包含大小写混合时替换失败- // Replace fails when search results contain mixed case in text elements https://github.com/siyuan-note/siyuan/issues/9171- keywords := strings.Split(keyword, " ")- // keyword 可能是 "foo Foo" 使用空格分隔的大小写命中情况,这里统一转换小写后去重- if 0 < len(keywords) {- var lowerKeywords []string- for _, k := range keywords {- lowerKeywords = append(lowerKeywords, strings.ToLower(k))- }- keyword = strings.Join(lowerKeywords, " ")- }- }-- if bytes.Contains(bytes.ToLower(text.Tokens), []byte(keyword)) {- newContent = replaceCaseInsensitive(text.Tokens, []byte(keyword), []byte(replacement))- }- }+ newContent, _ := replaceSearchTokens(text.Tokens, method, keyword, replacement, r)if !bytes.Equal(newContent, text.Tokens) {tree := parse.Inline("", newContent, luteEngine.ParseOptions)if nil == tree.Root.FirstChild {@@ -1557,15 +1544,7 @@ func replaceTextNode(text *ast.Node, method int, keyword string, replacement str}func replaceNodeTokens(n *ast.Node, method int, keyword string, replacement string, r *regexp.Regexp) {- if 0 == method {- if bytes.Contains(n.Tokens, []byte(keyword)) {- n.Tokens = bytes.ReplaceAll(n.Tokens, []byte(keyword), []byte(replacement))- }- } else if 3 == method {- if nil != r && r.MatchString(string(n.Tokens)) {- n.Tokens = []byte(r.ReplaceAllString(string(n.Tokens), replacement))- }- }+ n.Tokens, _ = replaceSearchTokens(n.Tokens, method, keyword, replacement, r)}func mergeSamePreNext(n *ast.Node) {@@ -3445,8 +3424,14 @@ func filterQueryInvisibleChars(query string) string {}func replaceCaseInsensitive(input, old, new []byte) []byte {- re := regexp.MustCompile("(?i)" + regexp.QuoteMeta(string(old)))- return re.ReplaceAllFunc(input, func([]byte) []byte {- return new- })+ content, _ := replaceCaseInsensitiveText(string(input), string(old), string(new))+ return []byte(content)+}++func replaceCaseInsensitiveText(input, keyword, replacement string) (string, bool) {+ r := regexp.MustCompile("(?i)" + regexp.QuoteMeta(keyword))+ if !r.MatchString(input) {+ return input, false+ }+ return r.ReplaceAllStringFunc(input, func(string) string { return replacement }), true}diff --git a/kernel/model/search_case_replace_fts5_test.go b/kernel/model/search_case_replace_fts5_test.gonew file mode 100644index 0000000000..a0243bb668--- /dev/null+++ b/kernel/model/search_case_replace_fts5_test.go@@ -0,0 +1,138 @@+//go:build fts5++package model++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "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/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestFindReplaceCaseSensitivityAcrossTypes(t *testing.T) {+ for _, tc := range []struct {+ name, keyword, replacement string+ method int+ caseSensitive, replaced, enabled bool+ }{+ {"literal-insensitive", "foo", "bar$1", 0, false, true, true},+ {"query-insensitive", "foo", "bar$1", 1, false, true, true},+ {"literal-sensitive", "foo", "bar", 0, true, false, true},+ {"regex-sensitive", "foo", "bar", 3, false, false, true},+ {"regex-folded-capture", "(?i)(foo)", "${1}bar", 3, true, true, true},+ {"disabled-types", "foo", "bar", 0, false, false, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Search = conf.NewSearch()+ Conf.Search.CaseSensitive = tc.caseSensitive+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ tree.Root.SetIALAttr("title", "FOO")+ tree.Root.SetIALAttr("tags", "FOO")+ engine := util.NewLute()+ markdown := "FOO\n\n\n\n```text\nFOO\n```\n\n$$\nFOO\n$$\n\n<div>FOO</div>"+ parsed := parse.Parse("", []byte(markdown), engine.ParseOptions)+ parse.NestedInlines2FlattedSpans(parsed, false)+ for child := parsed.Root.FirstChild; child != nil; {+ next := child.Next+ child.Unlink()+ tree.Root.AppendChild(child)+ child = next+ }+ for _, mark := range []string{"a", "code", "em", "strong", "u", "s", "mark", "sup", "sub", "kbd", "tag", "inline-math", "inline-memo", "block-ref", "file-annotation-ref"} {+ paragraph := &ast.Node{Type: ast.NodeParagraph}+ node := &ast.Node{Type: ast.NodeTextMark, TextMarkType: mark, TextMarkTextContent: "FOO"}+ switch mark {+ case "a":+ node.TextMarkAHref, node.TextMarkATitle = "https://example.com/FOO", "FOO"+ case "inline-math":+ node.TextMarkInlineMathContent = "FOO"+ case "inline-memo":+ node.TextMarkInlineMemoContent = "FOO"+ case "block-ref":+ node.TextMarkBlockRefID, node.TextMarkBlockRefSubtype = fixture.targetID, "d"+ case "file-annotation-ref":+ node.TextMarkFileAnnotationRefID = "assets/test.pdf/" + fixture.targetID+ }+ paragraph.AppendChild(node)+ tree.Root.AppendChild(paragraph)+ }+ ids := []string{tree.ID}+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && node != tree.Root && node.IsBlock() {+ if node.ID == "" {+ node.ID = ast.NewNodeID()+ node.SetIALAttr("id", node.ID)+ }+ ids = append(ids, node.ID)+ }+ return ast.WalkContinue+ })+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ before, _ := json.Marshal(tree.Root)+ replaceTypes := map[string]bool{}+ for _, key := range []string{"text", "imgText", "imgTitle", "imgSrc", "aText", "aTitle", "aHref", "code", "em", "strong", "inlineMath", "inlineMemo", "blockRef", "fileAnnotationRef", "kbd", "mark", "s", "sub", "sup", "tag", "u", "docTitle", "codeBlock", "mathBlock", "htmlBlock"} {+ replaceTypes[key] = tc.enabled+ }+ if err = FindReplaceInBox(tc.keyword, tc.replacement, replaceTypes, ids, nil, nil, nil, nil, tc.method, ""); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeData(tree.ID)+ restored, err := filesys.LoadTree(tree.Box, tree.Path, engine)+ if err != nil {+ t.Fatal(err)+ }+ after, _ := json.Marshal(restored.Root)+ want := strings.Count(string(before), "FOO")+ if !tc.replaced {+ if got := strings.Count(string(after), "FOO"); got != want {+ t.Fatalf("case-sensitive content changed: got %d original matches, want %d\n%s", got, want, after)+ }+ return+ }+ expected := tc.replacement+ if tc.method == 3 {+ expected = "FOObar"+ }+ if got := strings.Count(string(after), expected); got < want {+ t.Fatalf("not all fields replaced literally: got %d matches, want at least %d\n%s", got, want, after)+ }+ if tc.method != 3 && strings.Contains(string(after), "FOO") {+ t.Fatalf("unreplaced case-folded field: %s", after)+ }+ historyFound := false+ err = filepath.WalkDir(util.HistoryDir, func(path string, entry os.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if !entry.IsDir() && strings.HasSuffix(path, ".sy") {+ data, readErr := os.ReadFile(path)+ if readErr != nil {+ return readErr+ }+ historyFound = historyFound || strings.Contains(string(data), "FOO")+ }+ return nil+ })+ if err != nil || !historyFound {+ t.Fatalf("source history was not preserved: %v", err)+ }+ })+ }+}diff --git a/kernel/model/search_escape_test.go b/kernel/model/search_escape_test.goindex 0e6ea9840b..51117f895b 100644--- a/kernel/model/search_escape_test.go+++ b/kernel/model/search_escape_test.go@@ -10,6 +10,7 @@ import ()func TestReplaceTextMarkEscapedContent(t *testing.T) {+ setSearchCaseSensitive(t, true)engine := util.NewLute()for _, mark := range []string{"em", "strong", "u", "s", "mark", "sup", "sub", "kbd", "text", "tag"} {for _, tc := range []struct {diff --git a/kernel/model/search_literal_replace_test.go b/kernel/model/search_literal_replace_test.goindex 4627a14bf1..8f334b2187 100644--- a/kernel/model/search_literal_replace_test.go+++ b/kernel/model/search_literal_replace_test.go@@ -25,6 +25,25 @@ func TestReplaceCaseInsensitiveLiteralReplacement(t *testing.T) {}}+func TestReplaceSearchLiteralCaseFolding(t *testing.T) {+ setSearchCaseSensitive(t, false)+ for _, tc := range []struct{ input, keyword, want string }{+ {"foo FOO", "foo", "$1<& $1<&"},+ {"a.b A.B axb", "a.b", "$1<& $1<& axb"},+ {"K k K", "k", "$1<& $1<& $1<&"},+ {"Σ σ ς", "σ", "$1<& $1<& $1<&"},+ } {+ got, matched := replaceSearchText(tc.input, 0, tc.keyword, "$1<&", nil)+ if !matched || got != tc.want {+ t.Fatalf("literal fold: got %q, %v, want %q", got, matched, tc.want)+ }+ tokens, matched := replaceSearchTokens([]byte(tc.input), 0, tc.keyword, "$1<&", nil)+ if !matched || string(tokens) != tc.want {+ t.Fatalf("token fold: got %q, %v, want %q", tokens, matched, tc.want)+ }+ }+}+func TestReplaceTextNodeLiteralAndRegexReplacement(t *testing.T) {engine := util.NewLute()for _, tc := range []struct {