@@ -6,7 +6,6 @@ package code
6
6
import (
7
7
"bytes"
8
8
"context"
9
- "fmt"
10
9
"html/template"
11
10
"strings"
12
11
@@ -76,7 +75,6 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
76
75
77
76
contentLines := strings .SplitAfter (result .Content [startIndex :endIndex ], "\n " )
78
77
lines := make ([]ResultLine , 0 , len (contentLines ))
79
- highlightedLines := make ([]string , 0 , len (contentLines ))
80
78
index := startIndex
81
79
for i , line := range contentLines {
82
80
var err error
@@ -101,22 +99,15 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
101
99
102
100
lines = append (lines , ResultLine {Num : startLineNum + i })
103
101
index += len (line )
104
-
105
- // highlight.Code will remove the last `\n`, e.g. if input is `a\n`, output will be `a`
106
- // Then the length of `lines` and `highlightedLines` will not be equal, so we need to add an empty line manually
107
- if line == "" {
108
- highlightedLines = append (highlightedLines , "" )
109
- }
110
102
}
111
103
112
104
// we should highlight the whole code block first, otherwise it doesn't work well with multiple line highlighting
113
105
hl , _ := highlight .Code (result .Filename , "" , formattedLinesBuffer .String ())
114
- highlightedLines = append (strings .Split (string (hl ), "\n " ), highlightedLines ... )
115
-
116
- if len (highlightedLines ) != len (lines ) {
117
- return nil , fmt .Errorf ("the length of line numbers [%d] don't match the length of highlighted contents [%d]" , len (lines ), len (highlightedLines ))
118
- }
106
+ highlightedLines := strings .Split (string (hl ), "\n " )
119
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 )]
120
111
for i := 0 ; i < len (lines ); i ++ {
121
112
lines [i ].FormattedContent = template .HTML (highlightedLines [i ])
122
113
}
0 commit comments