leerob / nextjs-prism-markdown

Example using Prism / Markdown with Next.js including switching syntax highlighting themes.
https://nextjs-prism.vercel.app
102 stars 42 forks source link

Adding line numbers? #3

Open epleaner opened 2 years ago

epleaner commented 2 years ago

Hi,

Wondering if you can help me understand how to configure remark-prism to show line numbers. I added this line:

import remark from 'remark';
import html from 'remark-html';
import prism from 'remark-prism';

export default async function markdownToHtml(markdown) {
  const result = await remark()
    .use(html)
    .use(prism, {
      plugins: ['line-numbers']
    })
    .process(markdown);
  return result.toString();
}

But the proper classnames are not being added to the generated <pre> tags.

Any ideas? Tried following https://github.com/sergioramos/remark-prism#plugins but didn't work.

arackaf commented 2 years ago

Ok debugging this ... Prism's isActive check fails, even if a line-numbers class is present in a higher dom element, since this check only gets access to the markdown code content. Even wrapping the code block with a div with the line-numbers class, does not work, since the isActive check does not get the div. The element passed to isActive gets the <code>, whose parent is the <pre> which has no parent, so the check returns false, and no line numbers are inserted.

Checking now how to somehow wrap the pre tag in an html tag, or inject class names onto the pre tag. Back with Gatsby I used to do

```js{numberLines: true}

in the markdown, but that's not working here

arackaf commented 2 years ago

I've never felt dumber. To enable line numbers, just do this

```js[class="line-numbers"]

(in addition to the setup in OP's code)

leerob commented 2 years ago

Thank you!

P.S. I just went ahead and updated all the dependencies in this repo 👍

Noorts commented 2 years ago

For those still running into trouble getting the line numbers working, feel free to check out https://github.com/sergioramos/remark-prism/issues/79#issuecomment-1213313852.