shiki icon indicating copy to clipboard operation
shiki copied to clipboard

Line numbers

Open jbrooksuk opened this issue 5 years ago • 5 comments

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.

jbrooksuk avatar Jan 04 '19 09:01 jbrooksuk

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
})

octref avatar Jan 04 '19 18:01 octref

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: Capture d’écran 2021-05-01 à 08 35 14

alexpeattie avatar May 01 '21 06:05 alexpeattie

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)

bramus avatar Jul 16 '21 09:07 bramus

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?

lloydjatkinson avatar Jul 04 '22 21:07 lloydjatkinson

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).

heychazza avatar Jul 21 '22 11:07 heychazza

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

zasuNan avatar Nov 22 '22 15:11 zasuNan