Skip to content

Commit 49f62a4

Browse files
committed
use Split+Trim to replace tag parser
1 parent 4defb8f commit 49f62a4

File tree

1 file changed

+8
-50
lines changed

1 file changed

+8
-50
lines changed

modules/highlight/highlight.go

Lines changed: 8 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -195,54 +195,17 @@ func File(fileName, language string, code []byte) ([]string, error) {
195195

196196
m := make([]string, 0, bytes.Count(code, []byte{'\n'})+1)
197197

198+
// at the moment, Chroma generates stable output `<span class="line"><span class="cl">...\n</span></span>` for each line
198199
htmlStr := htmlBuf.String()
199-
line := strings.Builder{}
200-
insideLine := 0 // every <span class="cl"> makes it increase one level, every closed <span class="cl"> makes it decrease one level
201-
tagStack := make([]string, 0, 4)
202-
for len(htmlStr) > 0 {
203-
pos1 := strings.IndexByte(htmlStr, '<')
204-
pos2 := strings.IndexByte(htmlStr, '>')
205-
if pos1 == -1 || pos2 == -1 || pos1 > pos2 {
206-
break
207-
}
208-
tag := htmlStr[pos1 : pos2+1]
209-
if insideLine > 0 {
210-
line.WriteString(htmlStr[:pos1])
211-
}
212-
if tag[1] == '/' {
213-
if len(tagStack) == 0 {
214-
return nil, fmt.Errorf("can't find matched tag: %q", tag)
215-
}
216-
popped := tagStack[len(tagStack)-1]
217-
tagStack = tagStack[:len(tagStack)-1]
218-
if popped == `<span class="cl">` {
219-
insideLine--
220-
lineStr := line.String()
221-
if newLineInHTML != "" && lineStr != "" && lineStr[len(lineStr)-1] == '\n' {
222-
lineStr = lineStr[:len(lineStr)-1] + newLineInHTML
223-
}
224-
m = append(m, lineStr)
225-
line = strings.Builder{}
226-
}
227-
if insideLine > 0 {
228-
line.WriteString(tag)
229-
}
230-
} else {
231-
tagStack = append(tagStack, tag)
232-
if insideLine > 0 {
233-
line.WriteString(tag)
234-
}
235-
if tag == `<span class="cl">` {
236-
insideLine++
237-
}
200+
lines := strings.Split(htmlStr, `<span class="line"><span class="cl">`)
201+
for i := 1; i < len(lines); i++ {
202+
line := lines[i]
203+
line = strings.TrimSuffix(line, "</span></span>")
204+
if newLineInHTML != "" && line != "" && line[len(line)-1] == '\n' {
205+
line = line[:len(line)-1] + newLineInHTML
238206
}
239-
htmlStr = htmlStr[pos2+1:]
240-
}
241-
242-
if len(m) == 0 {
243-
m = append(m, "") // maybe we do not want to return 0 lines
207+
m = append(m, line)
244208
}
245-
246209
return m, nil
247210
}
248211

@@ -265,10 +228,5 @@ func PlainText(code []byte) []string {
265228
}
266229
m = append(m, s)
267230
}
268-
269-
if len(m) == 0 {
270-
m = append(m, "") // maybe we do not want to return 0 lines
271-
}
272-
273231
return m
274232
}

0 commit comments

Comments
 (0)