nextjs-prism-markdown icon indicating copy to clipboard operation
nextjs-prism-markdown copied to clipboard

Adding line numbers?

Open epleaner opened this issue 2 years ago • 4 comments

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.

epleaner avatar Jan 17 '22 04:01 epleaner

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 avatar Mar 03 '22 18:03 arackaf

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)

arackaf avatar Mar 04 '22 06:03 arackaf

Thank you!

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

leerob avatar Mar 04 '22 16:03 leerob

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.

Noorts avatar Aug 12 '22 16:08 Noorts