wooorm / refractor

Lightweight, robust, elegant virtual syntax highlighting using Prism

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Grouping by line

Hypercubed opened this issue · comments

I've been considering how to add line highlights similar to https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-remark-prismjs . This is what I came up with:

const refractor = require("refractor")
const rehype = require('rehype')

const code = `
(function(win) {
    console.log(win);
))(window || global);
`;

const highlightLines = [3];

const nodes = code.split('\n',)
  .map((line, index) => {
    return {
      type: 'element',
      tagName: 'span',
      properties: { className: ['line', highlightLines.includes(index) ? 'highlight' : ''] },
      children: refractor.highlight(line, 'js')
    };
  });

const html = rehype()
  .stringify({type: 'root', children: nodes})
  .toString();

Do you think this is something we could add to refractor itself?

Here is a more complete (and working) example: https://stackblitz.com/edit/js-r2mz9b

commented

@conorhastings anything we could port over from your library to here? Seems you've worked out a few things already that I'd like to implement in refractor too, and maybe it doesn't make sense to have them in two places. What do you think?

@wooorm definitely, line handling in prism was the easier of the two, let me see if i can pull out my code and take away lowlight specific stuff

@Hypercubed sorry been super busy traveling for work, I'll compare our implementations this weekend for sure and I if think i have any worthwhile contribution here, sorry about the long delay

No worries... I'm willing to contribute if I can.

commented

I’m not sure anymore if refractor should include this here. It could be a plugin though, working the same way as prism’s line-numbers.

I do think the core of react-syntax-highlighters line mechanism could be externalised. And it could be a HAST utility for use with refractor and inside react-syntax-highlighter. And be published as refractor-line-numbers?

I do think having the plugins work with refractor, and I’d include links to ports here!

commented

Closing as I don’t think it needs code changes here btw, but would like to chat about a plugin!

Any luck using line highlighting here?

commented

Here I made a utility to group refractor ASTs by lines: https://github.com/suin/refractor-group-by-lines