@@ -16,14 +16,18 @@ import (
16
16
17
17
// Result a search result to display
18
18
type Result struct {
19
- RepoID int64
20
- Filename string
21
- CommitID string
22
- UpdatedUnix timeutil.TimeStamp
23
- Language string
24
- Color string
25
- LineNumbers []int
26
- FormattedLines template.HTML
19
+ RepoID int64
20
+ Filename string
21
+ CommitID string
22
+ UpdatedUnix timeutil.TimeStamp
23
+ Language string
24
+ Color string
25
+ Lines []ResultLine
26
+ }
27
+
28
+ type ResultLine struct {
29
+ Num int
30
+ FormattedContent template.HTML
27
31
}
28
32
29
33
type SearchResultLanguages = internal.SearchResultLanguages
@@ -70,7 +74,7 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
70
74
var formattedLinesBuffer bytes.Buffer
71
75
72
76
contentLines := strings .SplitAfter (result .Content [startIndex :endIndex ], "\n " )
73
- lineNumbers := make ([]int , len (contentLines ))
77
+ lines := make ([]ResultLine , 0 , len (contentLines ))
74
78
index := startIndex
75
79
for i , line := range contentLines {
76
80
var err error
@@ -93,21 +97,29 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
93
97
return nil , err
94
98
}
95
99
96
- lineNumbers [ i ] = startLineNum + i
100
+ lines = append ( lines , ResultLine { Num : startLineNum + i })
97
101
index += len (line )
98
102
}
99
103
100
- highlighted , _ := highlight .Code (result .Filename , "" , formattedLinesBuffer .String ())
104
+ // we should highlight the whole code block first, otherwise it doesn't work well with multiple line highlighting
105
+ hl , _ := highlight .Code (result .Filename , "" , formattedLinesBuffer .String ())
106
+ highlightedLines := strings .Split (string (hl ), "\n " )
107
+
108
+ // The lines outputted by highlight.Code might not match the original lines, because "highlight" removes the last `\n`
109
+ lines = lines [:min (len (highlightedLines ), len (lines ))]
110
+ highlightedLines = highlightedLines [:len (lines )]
111
+ for i := 0 ; i < len (lines ); i ++ {
112
+ lines [i ].FormattedContent = template .HTML (highlightedLines [i ])
113
+ }
101
114
102
115
return & Result {
103
- RepoID : result .RepoID ,
104
- Filename : result .Filename ,
105
- CommitID : result .CommitID ,
106
- UpdatedUnix : result .UpdatedUnix ,
107
- Language : result .Language ,
108
- Color : result .Color ,
109
- LineNumbers : lineNumbers ,
110
- FormattedLines : highlighted ,
116
+ RepoID : result .RepoID ,
117
+ Filename : result .Filename ,
118
+ CommitID : result .CommitID ,
119
+ UpdatedUnix : result .UpdatedUnix ,
120
+ Language : result .Language ,
121
+ Color : result .Color ,
122
+ Lines : lines ,
111
123
}, nil
112
124
}
113
125
0 commit comments