@@ -16,14 +16,18 @@ import (
1616
1717// Result a search result to display
1818type 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
2731}
2832
2933type SearchResultLanguages = internal.SearchResultLanguages
@@ -70,7 +74,7 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
7074 var formattedLinesBuffer bytes.Buffer
7175
7276 contentLines := strings .SplitAfter (result .Content [startIndex :endIndex ], "\n " )
73- lineNumbers := make ([]int , len (contentLines ))
77+ lines := make ([]ResultLine , 0 , len (contentLines ))
7478 index := startIndex
7579 for i , line := range contentLines {
7680 var err error
@@ -93,21 +97,29 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
9397 return nil , err
9498 }
9599
96- lineNumbers [ i ] = startLineNum + i
100+ lines = append ( lines , ResultLine { Num : startLineNum + i })
97101 index += len (line )
98102 }
99103
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+ }
101114
102115 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 ,
111123 }, nil
112124}
113125
0 commit comments