Skip to content

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

:art: Match search highlights before HTML escaping https://github.com/siyuan-note/siyuan/issues/18361

Daniel4ad016ae96c5
diff --git a/kernel/model/file.go b/kernel/model/file.go
index c52bb86ee5..8e0c11da34 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -880,8 +880,8 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,
if ast.NodeCodeBlockCode == n.Type && !treenode.IsChartCodeBlockCode(n) {
// 支持代码块搜索定位 https://github.com/siyuan-note/siyuan/issues/5520
code := string(n.Tokens)
- markedCode := search.EncloseHighlighting(code, keywords, search.SearchMarkLeft, search.SearchMarkRight, Conf.Search.CaseSensitive, false)
- if code != markedCode {
+ markedCode, matched := search.EncloseHighlightingRaw(code, keywords, search.SearchMarkLeft, search.SearchMarkRight, Conf.Search.CaseSensitive, false)
+ if matched {
n.Tokens = gulu.Str.ToBytes(markedCode)
return ast.WalkContinue
}
diff --git a/kernel/model/search.go b/kernel/model/search.go
index 88348c7d10..2291d056e5 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -37,7 +37,6 @@ import (
"github.com/88250/lute"
"github.com/88250/lute/ast"
"github.com/88250/lute/editor"
- "github.com/88250/lute/html"
"github.com/88250/lute/lex"
"github.com/88250/lute/parse"
"github.com/88250/vitess-sqlparser/sqlparser"
@@ -2429,14 +2428,9 @@ func stringQuery(query string) string {
func markReplaceSpan(n *ast.Node, unlinks *[]*ast.Node, keywords []string, markSpanDataType string, luteEngine *lute.Lute) bool {
if ast.NodeText == n.Type {
text := n.Content()
- escapedText := util.EscapeHTML(text)
- escapedKeywords := make([]string, len(keywords))
- for i, keyword := range keywords {
- escapedKeywords[i] = util.EscapeHTML(keyword)
- }
- hText := search.EncloseHighlighting(escapedText, escapedKeywords, search.GetMarkSpanStart(markSpanDataType), search.GetMarkSpanEnd(), Conf.Search.CaseSensitive, false)
- if hText != escapedText {
- text = hText
+ text, matched := search.EncloseHighlightingRaw(text, keywords, search.GetMarkSpanStart(markSpanDataType), search.GetMarkSpanEnd(), Conf.Search.CaseSensitive, false)
+ if !matched {
+ return false
}
n.Tokens = gulu.Str.ToBytes(text)
if bytes.Contains(n.Tokens, []byte(search.MarkDataType)) {
@@ -2458,20 +2452,10 @@ func markReplaceSpan(n *ast.Node, unlinks *[]*ast.Node, keywords []string, markS
return false
}
- var text string
- if n.IsTextMarkType("code") {
- // code 在前面的 n.
- for i, k := range keywords {
- keywords[i] = html.EscapeString(k)
- }
- text = n.TextMarkTextContent
- } else {
- text = n.Content()
- }
-
+ text := n.Content()
startTag := search.GetMarkSpanStart(markSpanDataType)
- text = search.EncloseHighlighting(text, keywords, startTag, search.GetMarkSpanEnd(), Conf.Search.CaseSensitive, false)
- if strings.Contains(text, search.MarkDataType) {
+ text, matched := search.EncloseHighlightingRaw(text, keywords, startTag, search.GetMarkSpanEnd(), Conf.Search.CaseSensitive, false)
+ if matched {
dataType := search.GetMarkSpanStart(n.TextMarkType + " " + search.MarkDataType)
text = strings.ReplaceAll(text, startTag, dataType)
tokens := gulu.Str.ToBytes(text)
diff --git a/kernel/model/search_highlight_test.go b/kernel/model/search_highlight_test.go
new file mode 100644
index 0000000000..2480fad0ff
--- /dev/null
+++ b/kernel/model/search_highlight_test.go
@@ -0,0 +1,131 @@
+// SiYuan - Refactor your thinking
+// 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 (
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/html"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/search"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestMarkReplaceSpanMatchesRawText(t *testing.T) {
+ previousConf := Conf
+ Conf = NewAppConf()
+ Conf.Search = conf.NewSearch()
+ t.Cleanup(func() {
+ Conf = previousConf
+ })
+
+ luteEngine := util.NewLute()
+ t.Run("plain text", func(t *testing.T) {
+ root := &ast.Node{Type: ast.NodeDocument}
+ text := &ast.Node{Type: ast.NodeText, Tokens: []byte("1&2amp")}
+ root.AppendChild(text)
+
+ var unlinks []*ast.Node
+ if !markReplaceSpan(text, &unlinks, []string{"amp"}, search.MarkDataType, luteEngine) {
+ t.Fatal("真实的 amp 没有生成搜索高亮")
+ }
+ for _, unlink := range unlinks {
+ unlink.Unlink()
+ }
+ assertSearchMarkContents(t, root, []string{"amp"})
+ })
+
+ t.Run("entity only", func(t *testing.T) {
+ root := &ast.Node{Type: ast.NodeDocument}
+ text := &ast.Node{Type: ast.NodeText, Tokens: []byte("A&B")}
+ root.AppendChild(text)
+
+ var unlinks []*ast.Node
+ if markReplaceSpan(text, &unlinks, []string{"amp"}, search.MarkDataType, luteEngine) {
+ t.Fatal("HTML 实体中的 amp 被误判为搜索命中")
+ }
+ if "A&B" != string(text.Tokens) {
+ t.Fatalf("未命中的文本被修改为 %q", text.Tokens)
+ }
+ })
+
+ for _, textMarkType := range []string{"code", "tag", "strong", "em", "a"} {
+ t.Run(textMarkType, func(t *testing.T) {
+ root := &ast.Node{Type: ast.NodeDocument}
+ textMark := &ast.Node{
+ Type: ast.NodeTextMark,
+ TextMarkType: textMarkType,
+ TextMarkTextContent: "1&amp;2amp",
+ }
+ if "a" == textMarkType {
+ textMark.TextMarkAHref = "https://example.com"
+ }
+ root.AppendChild(textMark)
+
+ var unlinks []*ast.Node
+ keywords := []string{"amp"}
+ if !markReplaceSpan(textMark, &unlinks, keywords, search.MarkDataType, luteEngine) {
+ t.Fatalf("%s 中真实的 amp 没有生成搜索高亮", textMarkType)
+ }
+ if "amp" != keywords[0] {
+ t.Fatalf("关键字被修改为 %q", keywords[0])
+ }
+ for _, unlink := range unlinks {
+ unlink.Unlink()
+ }
+ assertSearchMarkContents(t, root, []string{"amp"})
+ })
+ }
+
+ t.Run("code entity only", func(t *testing.T) {
+ root := &ast.Node{Type: ast.NodeDocument}
+ textMark := &ast.Node{
+ Type: ast.NodeTextMark,
+ TextMarkType: "code",
+ TextMarkTextContent: "A&amp;B",
+ }
+ root.AppendChild(textMark)
+
+ var unlinks []*ast.Node
+ if markReplaceSpan(textMark, &unlinks, []string{"amp"}, search.MarkDataType, luteEngine) {
+ t.Fatal("行级代码实体中的 amp 被误判为搜索命中")
+ }
+ if "A&amp;B" != textMark.TextMarkTextContent {
+ t.Fatalf("未命中的行级代码被修改为 %q", textMark.TextMarkTextContent)
+ }
+ })
+}
+
+func assertSearchMarkContents(t *testing.T, root *ast.Node, want []string) {
+ t.Helper()
+ var got []string
+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeTextMark == n.Type && n.IsTextMarkType(search.MarkDataType) {
+ got = append(got, html.UnescapeString(n.TextMarkTextContent))
+ }
+ return ast.WalkContinue
+ })
+ if len(want) != len(got) {
+ t.Fatalf("搜索高亮内容为 %q,期望 %q", got, want)
+ }
+ for i := range want {
+ if want[i] != got[i] {
+ t.Fatalf("搜索高亮内容为 %q,期望 %q", got, want)
+ }
+ }
+}
diff --git a/kernel/search/mark.go b/kernel/search/mark.go
index b059e87340..241a3dd8ac 100644
--- a/kernel/search/mark.go
+++ b/kernel/search/mark.go
@@ -33,26 +33,7 @@ func MarkText(text string, keyword string, beforeLen int, caseSensitive bool) (p
return -1, text
}
keywords := SplitKeyword(keyword)
- marked = EncloseHighlighting(text, keywords, "<mark>", "</mark>", caseSensitive, false)
-
- pos = strings.Index(marked, "<mark>")
- if 0 > pos {
- return
- }
-
- var before []rune
- var count int
- for i := pos; 0 < i; { // 关键字前面太长的话缩短一些
- r, size := utf8.DecodeLastRuneInString(marked[:i])
- i -= size
- before = append([]rune{r}, before...)
- count++
- if beforeLen < count {
- before = append([]rune("..."), before...)
- break
- }
- }
- marked = string(before) + marked[pos:]
+ pos, marked, _ = encloseHighlightingRaw(text, keywords, "<mark>", "</mark>", caseSensitive, false, beforeLen)
return
}
@@ -82,29 +63,20 @@ func SplitKeyword(keyword string) (keywords []string) {
}
func EncloseHighlighting(text string, keywords []string, openMark, closeMark string, caseSensitive, splitWords bool) (ret string) {
- reg, err := compileHighlightingRegexp(keywords, caseSensitive, splitWords, true)
- ret = util.EscapeHTML(text)
-
- ret = strings.ReplaceAll(ret, "&#34;", "\ue000")
- ret = strings.ReplaceAll(ret, "&lt;", "\ue001")
- ret = strings.ReplaceAll(ret, "&gt;", "\ue002")
- ret = strings.ReplaceAll(ret, "&#39;", "\ue003")
- if err == nil {
- ret = reg.ReplaceAllStringFunc(ret, func(s string) string { return openMark + s + closeMark })
- }
- ret = strings.ReplaceAll(ret, "\ue000", "&#34;")
- ret = strings.ReplaceAll(ret, "\ue001", "&lt;")
- ret = strings.ReplaceAll(ret, "\ue002", "&gt;")
- ret = strings.ReplaceAll(ret, "\ue003", "&#39;")
-
- // 搜索结果预览包含转义符问题 Search results preview contains escape character issue https://github.com/siyuan-note/siyuan/issues/9790
- ret = strings.ReplaceAll(ret, "\\<span", "\\\\<span")
+ ret, _ = EncloseHighlightingRaw(text, keywords, openMark, closeMark, caseSensitive, splitWords)
return
}
// EncloseHighlightingRaw 在原始文本中匹配关键字,并在插入高亮标记时转义文本。
func EncloseHighlightingRaw(text string, keywords []string, openMark, closeMark string, caseSensitive, splitWords bool) (ret string, matched bool) {
- reg, err := compileHighlightingRegexp(keywords, caseSensitive, splitWords, false)
+ _, ret, matched = encloseHighlightingRaw(text, keywords, openMark, closeMark, caseSensitive, splitWords, -1)
+ return
+}
+
+// encloseHighlightingRaw 在原始文本上完成上下文截取和高亮,beforeLen 小于零时保留全部前文。
+func encloseHighlightingRaw(text string, keywords []string, openMark, closeMark string, caseSensitive, splitWords bool, beforeLen int) (pos int, ret string, matched bool) {
+ pos = -1
+ reg, err := compileHighlightingRegexp(keywords, caseSensitive, splitWords)
if err != nil {
ret = html.EscapeString(text)
return
@@ -116,26 +88,48 @@ func EncloseHighlightingRaw(text string, keywords []string, openMark, closeMark
return
}
+ start := 0
+ truncated := false
+ if 0 <= beforeLen {
+ start = indexes[0][0]
+ var count int
+ for 0 < start { // 关键字前面太长的话缩短一些
+ _, size := utf8.DecodeLastRuneInString(text[:start])
+ start -= size
+ count++
+ if beforeLen < count {
+ truncated = true
+ break
+ }
+ }
+ }
+
var buf strings.Builder
- buf.Grow(len(text) + len(indexes)*(len(openMark)+len(closeMark)))
- last := 0
+ buf.Grow(len(text) - start + len(indexes)*(len(openMark)+len(closeMark)))
+ if truncated {
+ buf.WriteString("...")
+ }
+ last := start
for _, index := range indexes {
buf.WriteString(html.EscapeString(text[last:index[0]]))
+ if !matched {
+ pos = buf.Len()
+ }
buf.WriteString(openMark)
buf.WriteString(html.EscapeString(text[index[0]:index[1]]))
buf.WriteString(closeMark)
last = index[1]
+ matched = true
}
buf.WriteString(html.EscapeString(text[last:]))
ret = buf.String()
// 避免反斜杠转义生成的高亮标签 https://github.com/siyuan-note/siyuan/issues/9790
ret = strings.ReplaceAll(ret, "\\<span", "\\\\<span")
- matched = true
return
}
-func compileHighlightingRegexp(keywords []string, caseSensitive, splitWords, escapeHTML bool) (ret *regexp.Regexp, err error) {
+func compileHighlightingRegexp(keywords []string, caseSensitive, splitWords bool) (ret *regexp.Regexp, err error) {
ic := "(?i)"
if caseSensitive {
ic = "(?)"
@@ -152,9 +146,6 @@ func compileHighlightingRegexp(keywords []string, caseSensitive, splitWords, esc
if splitWords {
wordBoundary = lex.IsASCIILetterNums(gulu.Str.ToBytes(k)) // Improve virtual reference split words https://github.com/siyuan-note/siyuan/issues/7833
}
- if escapeHTML {
- k = util.EscapeHTML(k)
- }
if !util.SearchHanSensitive {
// 不区分繁简:将关键字逐字符展开为繁简等价字符类,如 "诗经" -> "[诗詩][经經]"
k = hanInsensitiveRegexp(k)
diff --git a/kernel/search/mark_test.go b/kernel/search/mark_test.go
index fd2c05e9b4..a45848f26e 100644
--- a/kernel/search/mark_test.go
+++ b/kernel/search/mark_test.go
@@ -22,6 +22,68 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+func TestMarkTextMatchesRawText(t *testing.T) {
+ old := util.SearchHanSensitive
+ util.SearchHanSensitive = true
+ t.Cleanup(func() {
+ util.SearchHanSensitive = old
+ })
+
+ tests := []struct {
+ name string
+ text string
+ keyword string
+ beforeLen int
+ wantPos int
+ want string
+ }{
+ {
+ name: "template name",
+ text: "1&2amp",
+ keyword: "amp",
+ beforeLen: 32,
+ wantPos: len("1&amp;2"),
+ want: "1&amp;2<mark>amp</mark>",
+ },
+ {
+ name: "entity only",
+ text: "A&B",
+ keyword: "amp",
+ beforeLen: 32,
+ wantPos: -1,
+ want: "A&amp;B",
+ },
+ {
+ name: "entity at context boundary",
+ text: "a&xamp",
+ keyword: "amp",
+ beforeLen: 1,
+ wantPos: len("...&amp;x"),
+ want: "...&amp;x<mark>amp</mark>",
+ },
+ {
+ name: "multibyte context",
+ text: "前🙂xamp",
+ keyword: "amp",
+ beforeLen: 1,
+ wantPos: len("...🙂x"),
+ want: "...🙂x<mark>amp</mark>",
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ pos, got := MarkText(test.text, test.keyword, test.beforeLen, true)
+ if test.want != got {
+ t.Fatalf("result = %q, want %q", got, test.want)
+ }
+ if test.wantPos != pos {
+ t.Fatalf("pos = %d, want %d", pos, test.wantPos)
+ }
+ })
+ }
+}
+
func TestEncloseHighlightingRaw(t *testing.T) {
old := util.SearchHanSensitive
util.SearchHanSensitive = true