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: Replace text across escaped nodes https://github.com/siyuan-note/siyuan/issues/15256
Daniel4c39be9926ed
diff --git a/kernel/model/search.go b/kernel/model/search.goindex 0e4c62eeea..8616cc7733 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -717,33 +717,29 @@ func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,}} else {var unlinks []*ast.Node+ skipReplaceNodes := map[*ast.Node]struct{}{}+ if replaceTypes["text"] {+ skipReplaceNodes, _ = replaceTextAcrossBackslashes(node, method, keyword, replacement, r, luteEngine)+ }ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue}+ if _, ok := skipReplaceNodes[n]; ok {+ return ast.WalkSkipChildren+ }switch n.Type {case ast.NodeText:if !replaceTypes["text"] {return ast.WalkContinue}+ if nil != n.Parent && ast.NodeBackslash == n.Parent.Type {+ return ast.WalkContinue+ }if replaceTextNode(n, method, keyword, replacement, r, luteEngine) {- if nil != n.Parent && ast.NodeBackslash == n.Parent.Type {- unlinks = append(unlinks, n.Parent)-- prev, next := n.Parent.Previous, n.Parent.Next- for ; prev != nil && ((ast.NodeText == prev.Type && prev.Tokens == nil) || ast.NodeBackslash == prev.Type); prev = prev.Previous {- // Tokens 为空的节点或者转义节点之前已经处理,需要跳过- }- if nil != prev && ast.NodeText == prev.Type && nil != next && ast.NodeText == next.Type {- prev.Tokens = append(prev.Tokens, next.Tokens...)- next.Tokens = nil // 将 Tokens 设置为空,表示该节点已经被处理过- unlinks = append(unlinks, next)- }- } else {- unlinks = append(unlinks, n)- }+ unlinks = append(unlinks, n)}case ast.NodeLinkDest:if !replaceTypes["imgSrc"] {@@ -1151,6 +1147,339 @@ func replaceNodeTextMarkTextContent(n *ast.Node, method int, keyword, escapedKey}}+type replaceTextFragment struct {+ start int+ end int+ node *ast.Node+ contentNode *ast.Node+ escaped bool+}++type replaceTextRun struct {+ start int+ end int+ fragments []*replaceTextFragment+}++type replaceTextRunPlan struct {+ run *replaceTextRun+ matches [][]int+}++// replaceTextAcrossBackslashes 在可见文本投影上处理跨转义节点的匹配。+func replaceTextAcrossBackslashes(root *ast.Node, method int, keyword, replacement string, r *regexp.Regexp,+ luteEngine *lute.Lute) (skipNodes map[*ast.Node]struct{}, changed bool) {+ skipNodes = map[*ast.Node]struct{}{}+ if nil == root || "" == keyword || (0 != method && 3 != method) {+ return+ }++ var parents []*ast.Node+ parentSet := map[*ast.Node]struct{}{}+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering || ast.NodeBackslash != n.Type || nil == n.Parent {+ return ast.WalkContinue+ }+ if _, ok := parentSet[n.Parent]; !ok {+ parentSet[n.Parent] = struct{}{}+ parents = append(parents, n.Parent)+ }+ return ast.WalkSkipChildren+ })++ for _, parent := range parents {+ content, runs := buildReplaceTextRuns(parent)+ if "" == content || 1 > len(runs) {+ continue+ }++ indexes := findReplaceTextMatchIndexes(content, method, keyword, r)+ if 1 > len(indexes) {+ continue+ }++ var plans []*replaceTextRunPlan+ for _, run := range runs {+ var matches [][]int+ hasEscapedMatch := false+ for _, index := range indexes {+ if !replaceTextMatchInRun(index, run, len(content)) {+ continue+ }+ matches = append(matches, index)+ if replaceTextMatchTouchesBackslash(index, run) {+ hasEscapedMatch = true+ }+ }+ if hasEscapedMatch {+ plans = append(plans, &replaceTextRunPlan{run: run, matches: matches})+ }+ }++ for i := len(plans) - 1; 0 <= i; i-- {+ plan := plans[i]+ output, ok := buildReplaceTextRunOutput(content, plan, method, replacement, r, luteEngine)+ if !ok {+ continue+ }+ if applyReplaceTextRunOutput(plan.run, output, skipNodes) {+ changed = true+ }+ }+ }+ return+}++func buildReplaceTextRuns(parent *ast.Node) (content string, runs []*replaceTextRun) {+ var buf strings.Builder+ var current *replaceTextRun+ for child := parent.FirstChild; nil != child; child = child.Next {+ contentNode, escaped := replaceTextContentNode(child)+ if nil == contentNode {+ if nil != current {+ current.end = buf.Len()+ runs = append(runs, current)+ current = nil+ }+ buf.WriteString(child.Content())+ continue+ }++ if nil == current {+ current = &replaceTextRun{start: buf.Len()}+ }+ start := buf.Len()+ buf.Write(contentNode.Tokens)+ current.fragments = append(current.fragments, &replaceTextFragment{+ start: start,+ end: buf.Len(),+ node: child,+ contentNode: contentNode,+ escaped: escaped,+ })+ }+ if nil != current {+ current.end = buf.Len()+ runs = append(runs, current)+ }+ return buf.String(), runs+}++func replaceTextContentNode(node *ast.Node) (contentNode *ast.Node, escaped bool) {+ if ast.NodeText == node.Type {+ return node, false+ }+ if ast.NodeBackslash != node.Type {+ return nil, false+ }+ for child := node.FirstChild; nil != child; child = child.Next {+ if ast.NodeText == child.Type || ast.NodeBackslashContent == child.Type {+ return child, true+ }+ }+ return nil, false+}++func findReplaceTextMatchIndexes(content string, method int, keyword string, r *regexp.Regexp) (ret [][]int) {+ if 3 == method {+ if nil != r {+ ret = r.FindAllStringSubmatchIndex(content, -1)+ }+ return+ }++ exp := regexp.QuoteMeta(keyword)+ if !Conf.Search.CaseSensitive {+ exp = "(?i:" + exp + ")"+ }+ matcher, err := regexp.Compile(exp)+ if nil != err {+ return+ }+ return matcher.FindAllStringSubmatchIndex(content, -1)+}++func replaceTextMatchInRun(index []int, run *replaceTextRun, contentLength int) bool {+ if 2 > len(index) || 0 > index[0] || 0 > index[1] {+ return false+ }+ if index[0] == index[1] {+ return run.start <= index[0] && (index[0] < run.end || index[0] == run.end && run.end == contentLength)+ }+ return run.start <= index[0] && index[1] <= run.end+}++func replaceTextMatchTouchesBackslash(index []int, run *replaceTextRun) bool {+ if 2 > len(index) {+ return false+ }+ if index[0] == index[1] {+ for _, fragment := range run.fragments {+ if fragment.escaped && fragment.start <= index[0] && index[0] <= fragment.end {+ return true+ }+ }+ return false+ }+ for _, fragment := range run.fragments {+ if fragment.escaped && index[0] < fragment.end && fragment.start < index[1] {+ return true+ }+ }+ return false+}++func buildReplaceTextRunOutput(content string, plan *replaceTextRunPlan, method int, replacement string, r *regexp.Regexp,+ luteEngine *lute.Lute) (ret []*ast.Node, ok bool) {+ cursor := plan.run.start+ for _, index := range plan.matches {+ ret = appendReplaceOriginalText(ret, plan.run, cursor, index[0])++ replacementText := replacement+ if 3 == method {+ replacementText = string(r.ExpandString(nil, replacement, content, index))+ }+ replacementNodes, parsed := parseReplaceText(replacementText, luteEngine)+ if !parsed {+ return nil, false+ }+ for _, replacementNode := range replacementNodes {+ ret = appendReplaceOutputNode(ret, replacementNode)+ }+ cursor = index[1]+ }+ ret = appendReplaceOriginalText(ret, plan.run, cursor, plan.run.end)+ return ret, true+}++func appendReplaceOriginalText(output []*ast.Node, run *replaceTextRun, start, end int) []*ast.Node {+ if end <= start {+ return output+ }+ for _, fragment := range run.fragments {+ fragmentStart := max(start, fragment.start)+ fragmentEnd := min(end, fragment.end)+ if fragmentEnd <= fragmentStart {+ continue+ }++ node := cloneReplaceTextFragment(fragment, fragmentStart-fragment.start, fragmentEnd-fragment.start)+ if nil != node {+ output = appendReplaceOutputNode(output, node)+ }+ }+ return output+}++func cloneReplaceTextFragment(fragment *replaceTextFragment, start, end int) *ast.Node {+ ret := cloneReplaceTextNode(fragment.node)+ if nil == ret {+ return nil+ }+ tokens := bytes.Clone(fragment.contentNode.Tokens[start:end])+ if fragment.escaped {+ contentNode, _ := replaceTextContentNode(ret)+ if nil == contentNode {+ return nil+ }+ contentNode.Tokens = tokens+ } else {+ ret.Tokens = tokens+ }+ return ret+}++func cloneReplaceTextNode(node *ast.Node) *ast.Node {+ if nil == node {+ return nil+ }+ ret := *node+ ret.Parent, ret.Previous, ret.Next = nil, nil, nil+ ret.FirstChild, ret.LastChild = nil, nil+ ret.Children = nil+ ret.Tokens = bytes.Clone(node.Tokens)+ if nil != node.Properties {+ ret.Properties = map[string]string{}+ for key, value := range node.Properties {+ ret.Properties[key] = value+ }+ }+ if nil != node.KramdownIAL {+ ret.KramdownIAL = make([][]string, len(node.KramdownIAL))+ for i, item := range node.KramdownIAL {+ ret.KramdownIAL[i] = append([]string(nil), item...)+ }+ }+ for child := node.FirstChild; nil != child; child = child.Next {+ ret.AppendChild(cloneReplaceTextNode(child))+ }+ return &ret+}++func parseReplaceText(replacement string, luteEngine *lute.Lute) (ret []*ast.Node, ok bool) {+ tree := parse.Inline("", []byte(replacement), luteEngine.ParseOptions)+ if nil == tree.Root.FirstChild {+ return nil, "" == replacement+ }+ parse.NestedInlines2FlattedSpans(tree, false)+ for child := tree.Root.FirstChild.FirstChild; nil != child; {+ next := child.Next+ child.Unlink()+ ret = append(ret, child)+ child = next+ }+ return ret, true+}++func appendReplaceOutputNode(output []*ast.Node, node *ast.Node) []*ast.Node {+ if nil == node || (ast.NodeText == node.Type && 1 > len(node.Tokens)) {+ return output+ }+ if 0 < len(output) && ast.NodeText == output[len(output)-1].Type && ast.NodeText == node.Type &&+ 0 == len(output[len(output)-1].KramdownIAL) && 0 == len(node.KramdownIAL) {+ output[len(output)-1].Tokens = append(output[len(output)-1].Tokens, node.Tokens...)+ return output+ }+ return append(output, node)+}++func applyReplaceTextRunOutput(run *replaceTextRun, output []*ast.Node, skipNodes map[*ast.Node]struct{}) bool {+ if 1 > len(run.fragments) {+ return false+ }+ first := run.fragments[0].node+ last := run.fragments[len(run.fragments)-1].node+ parent := first.Parent+ if nil == parent || parent != last.Parent {+ return false+ }+ after := last.Next+ block := treenode.ParentBlock(first)++ for current := first; current != after; {+ next := current.Next+ current.Unlink()+ current = next+ }+ for _, node := range output {+ if nil != after {+ after.InsertBefore(node)+ } else {+ parent.AppendChild(node)+ }+ ast.Walk(node, func(current *ast.Node, entering bool) ast.WalkStatus {+ if entering {+ skipNodes[current] = struct{}{}+ }+ return ast.WalkContinue+ })+ }+ if nil != block {+ treenode.RefreshUpdated(block)+ }+ return true+}+// replaceTextNode 替换文本节点为其他节点。// 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 {diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex f2c5bb01a5..fb040356c3 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -18,12 +18,15 @@ package modelimport (gosql "database/sql"+ "regexp""slices""strings""testing"+ "github.com/88250/lute/ast""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/util")func TestFromSQLBlockMapsTimestamps(t *testing.T) {@@ -532,6 +535,194 @@ func setSearchCaseSensitive(t *testing.T, caseSensitive bool) {})}+func TestReplaceTextAcrossBackslashes(t *testing.T) {+ setSearchCaseSensitive(t, true)+ luteEngine := util.NewLute()+ tests := []struct {+ name string+ nodes func() []*ast.Node+ method int+ keyword string+ replacement string+ expected string+ changed bool+ backslashes []string+ }{+ {+ name: "consecutive backslashes",+ nodes: func() []*ast.Node {+ return []*ast.Node{+ replaceTextTestText("前 "),+ replaceTextTestBackslash("=", ast.NodeText),+ replaceTextTestBackslash(">", ast.NodeBackslashContent),+ replaceTextTestText(" 后"),+ }+ },+ keyword: "=>",+ replacement: "to",+ expected: "前 to 后",+ changed: true,+ },+ {+ name: "cite marker",+ nodes: func() []*ast.Node {+ return []*ast.Node{+ replaceTextTestText("[cite"),+ replaceTextTestBackslash("_", ast.NodeText),+ replaceTextTestText("start]A[cite"),+ replaceTextTestBackslash("_", ast.NodeBackslashContent),+ replaceTextTestText("start]B"),+ }+ },+ method: 3,+ keyword: `\[cite.*?\]`,+ replacement: "",+ expected: "AB",+ changed: true,+ },+ {+ name: "task marker",+ nodes: func() []*ast.Node {+ return []*ast.Node{+ replaceTextTestBackslash("[", ast.NodeText),+ replaceTextTestText("v"),+ replaceTextTestBackslash("]", ast.NodeBackslashContent),+ replaceTextTestText(" item"),+ }+ },+ keyword: "[v]",+ replacement: "",+ expected: " item",+ changed: true,+ },+ {+ name: "preserve unmatched backslash",+ nodes: func() []*ast.Node {+ return []*ast.Node{+ replaceTextTestBackslash("*", ast.NodeBackslashContent),+ replaceTextTestText(" keep "),+ replaceTextTestBackslash("=", ast.NodeText),+ replaceTextTestBackslash(">", ast.NodeBackslashContent),+ replaceTextTestText(" end"),+ }+ },+ keyword: "=>",+ replacement: "to",+ expected: "* keep to end",+ changed: true,+ backslashes: []string{"*"},+ },+ {+ name: "regular expression uses full run context",+ nodes: func() []*ast.Node {+ return []*ast.Node{+ replaceTextTestText("prefix "),+ replaceTextTestBackslash("=", ast.NodeText),+ replaceTextTestBackslash(">", ast.NodeBackslashContent),+ }+ },+ method: 3,+ keyword: `^=>`,+ replacement: "to",+ expected: "prefix =>",+ backslashes: []string{"=", ">"},+ },+ {+ name: "regular expression capture",+ nodes: func() []*ast.Node {+ return []*ast.Node{+ replaceTextTestBackslash("=", ast.NodeText),+ replaceTextTestBackslash(">", ast.NodeBackslashContent),+ replaceTextTestText(" rest"),+ }+ },+ method: 3,+ keyword: `(=>)`,+ replacement: `${1}x`,+ expected: "=>x rest",+ changed: true,+ },+ {+ name: "zero width regular expression",+ nodes: func() []*ast.Node {+ return []*ast.Node{+ replaceTextTestBackslash("=", ast.NodeText),+ replaceTextTestBackslash(">", ast.NodeBackslashContent),+ }+ },+ method: 3,+ keyword: `$`,+ replacement: "x",+ expected: "=>x",+ changed: true,+ backslashes: []string{"=", ">"},+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ root := &ast.Node{Type: ast.NodeParagraph}+ for _, node := range test.nodes() {+ root.AppendChild(node)+ }+ var matcher *regexp.Regexp+ if 3 == test.method {+ matcher = regexp.MustCompile(test.keyword)+ }++ skipNodes, changed := replaceTextAcrossBackslashes(root, test.method, test.keyword, test.replacement, matcher, luteEngine)+ if test.changed != changed {+ t.Fatalf("替换状态错误:期望 %t,实际 %t", test.changed, changed)+ }+ if actual := root.Content(); test.expected != actual {+ t.Fatalf("替换结果错误:期望 %q,实际 %q", test.expected, actual)+ }+ if test.changed && 1 > len(skipNodes) {+ t.Fatal("替换后的节点未加入跳过集合")+ }+ if actual := replaceTextTestBackslashes(root); !slices.Equal(test.backslashes, actual) {+ t.Fatalf("转义节点错误:期望 %q,实际 %q", test.backslashes, actual)+ }+ })+ }+}++func TestReplaceTextAcrossBackslashesCaseInsensitive(t *testing.T) {+ setSearchCaseSensitive(t, false)+ root := &ast.Node{Type: ast.NodeParagraph}+ root.AppendChild(replaceTextTestText("A"))+ root.AppendChild(replaceTextTestBackslash("_", ast.NodeBackslashContent))+ root.AppendChild(replaceTextTestText("B"))++ _, changed := replaceTextAcrossBackslashes(root, 0, "a_b", "x", nil, util.NewLute())+ if !changed {+ t.Fatal("大小写不敏感的跨节点替换未执行")+ }+ if actual := root.Content(); "x" != actual {+ t.Fatalf("大小写不敏感的跨节点替换结果错误:期望 %q,实际 %q", "x", actual)+ }+}++func replaceTextTestText(content string) *ast.Node {+ return &ast.Node{Type: ast.NodeText, Tokens: []byte(content)}+}++func replaceTextTestBackslash(content string, contentType ast.NodeType) *ast.Node {+ ret := &ast.Node{Type: ast.NodeBackslash}+ ret.AppendChild(&ast.Node{Type: contentType, Tokens: []byte(content)})+ return ret+}++func replaceTextTestBackslashes(root *ast.Node) (ret []string) {+ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeBackslash == node.Type {+ ret = append(ret, node.Content())+ }+ return ast.WalkContinue+ })+ return+}+func assertOrderBySequence(t *testing.T, orderBy string, fragments ...string) {t.Helper()previous := -1