mirror of
https://github.com/alecthomas/chroma.git
synced 2025-07-03 00:37:01 +02:00
Add newlines in line number spans when wrapping in an HTML table.
Since these are wrapped in a `<pre>`, newlines hint the browser that the line numbers should be on separate lines. This helps when rendering content with broken CSS, or in a text-only browser.
This commit is contained in:
committed by
Alec Thomas
parent
10c530a975
commit
d7ee3c10b0
@ -169,7 +169,7 @@ func (f *Formatter) writeHTML(w io.Writer, style *chroma.Style, tokens []*chroma
|
||||
fmt.Fprintf(w, "<span%s>", f.styleAttr(css, chroma.LineHighlight))
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "<span%s>%*d</span>", f.styleAttr(css, chroma.LineNumbersTable), lineDigits, line)
|
||||
fmt.Fprintf(w, "<span%s>%*d\n</span>", f.styleAttr(css, chroma.LineNumbersTable), lineDigits, line)
|
||||
|
||||
if highlight {
|
||||
fmt.Fprintf(w, "</span>")
|
||||
@ -327,7 +327,7 @@ func (f *Formatter) styleToCSS(style *chroma.Style) map[chroma.TokenType]string
|
||||
lineNumbersStyle := "margin-right: 0.4em; padding: 0 0.4em 0 0.4em;"
|
||||
// All rules begin with default rules followed by user provided rules
|
||||
classes[chroma.LineNumbers] = lineNumbersStyle + classes[chroma.LineNumbers]
|
||||
classes[chroma.LineNumbersTable] = lineNumbersStyle + " display: block;" + classes[chroma.LineNumbersTable]
|
||||
classes[chroma.LineNumbersTable] = lineNumbersStyle + classes[chroma.LineNumbersTable]
|
||||
classes[chroma.LineHighlight] = "display: block; width: 100%;" + classes[chroma.LineHighlight]
|
||||
classes[chroma.LineTable] = "border-spacing: 0; padding: 0; margin: 0; border: 0; width: auto; overflow: auto; display: block;" + classes[chroma.LineTable]
|
||||
classes[chroma.LineTableTD] = "vertical-align: top; padding: 0; margin: 0; border: 0;" + classes[chroma.LineTableTD]
|
||||
|
@ -92,3 +92,22 @@ func TestClassPrefix(t *testing.T) {
|
||||
t.Error("Stylesheets should have a class prefix")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTableLineNumberNewlines(t *testing.T) {
|
||||
f := New(WithClasses(), WithLineNumbers(), LineNumbersInTable())
|
||||
it, err := lexers.Get("go").Tokenise(nil, "package main\nfunc main()\n{\nprintln(`hello world`)\n}\n")
|
||||
assert.NoError(t, err)
|
||||
|
||||
var buf bytes.Buffer
|
||||
err = f.Format(&buf, styles.Fallback, it)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Don't bother testing the whole output, just verify it's got line numbers
|
||||
// in a <pre>-friendly format.
|
||||
// Note: placing the newlines inside the <span> lets browser selections look
|
||||
// better, instead of "skipping" over the span margin.
|
||||
assert.Contains(t, buf.String(), `<span class="lnt">2
|
||||
</span><span class="lnt">3
|
||||
</span><span class="lnt">4
|
||||
</span>`)
|
||||
}
|
||||
|
Reference in New Issue
Block a user