shiki
shiki copied to clipboard
Line numbers
Would it be possible to add support for line numbers?
Bonus points for not restricting you to auto-generate them either. For example, when showing a Git diff, the line numbers will change.
It's possible, just need to add that to the HTML renderer.
You can do it too if you have time:
const shiki = require('shiki')
shiki.getHighlighter({
theme: 'nord'
}).then(highlighter => {
const tokens = highlighter.codeToThemedTokens(`console.log('shiki');`, 'js')
const html = shiki.renderToHtml(tokens) // default renderer, replace with yours
})
As an alternative to writing a custom renderToHtml
function: since v0.2.3 each line is wrapped in a <span class='line'>
which makes it quite easy to do line numbering using CSS counters. I added some CSS like this:
code {
counter-reset: step;
counter-increment: step 0;
}
code .line::before {
content: counter(step);
counter-increment: step;
width: 1rem;
margin-right: 1.5rem;
display: inline-block;
text-align: right;
color: rgba(115,138,148,.4)
}
Which yields:
Building further upon @alexpeattie's code: using Custom Properties you can set a different start number.
code {
counter-reset: step;
counter-increment: step calc(var(--start, 1) - 1);
}
<code style="--start: 13;">…</code>
If no --start
is set, it will fall back to start numbering at 1.
Demo: https://codepen.io/bramus/pen/mdmmdQB
(You might want to opt for a more unique name for the Custom Property)
Given that line numbers is pretty much a normal expectation of syntax highlighting and that this issue has been open for three and a half years now, could one of the above solutions be built in?
Given that line numbers is pretty much a normal expectation of syntax highlighting and that this issue has been open for three and a half years now, could one of the above solutions be built in?
I'd also love to see code diff highlighting, so for example showing added and removed lines of code (with highlighting for whatever lang).
prefer the style of shiki, but compared with other similar plugins, such as Prism and highlight, they all have the line number function, hope shiki can also support it