@@ -6,7 +6,6 @@ package code
66import (
77 "bytes"
88 "context"
9- "fmt"
109 "html/template"
1110 "strings"
1211
@@ -76,7 +75,6 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
7675
7776 contentLines := strings .SplitAfter (result .Content [startIndex :endIndex ], "\n " )
7877 lines := make ([]ResultLine , 0 , len (contentLines ))
79- highlightedLines := make ([]string , 0 , len (contentLines ))
8078 index := startIndex
8179 for i , line := range contentLines {
8280 var err error
@@ -101,22 +99,15 @@ func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Res
10199
102100 lines = append (lines , ResultLine {Num : startLineNum + i })
103101 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- }
110102 }
111103
112104 // we should highlight the whole code block first, otherwise it doesn't work well with multiple line highlighting
113105 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 " )
119107
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 )]
120111 for i := 0 ; i < len (lines ); i ++ {
121112 lines [i ].FormattedContent = template .HTML (highlightedLines [i ])
122113 }
0 commit comments