nuxt / content

The file-based CMS for your Nuxt application, powered by Markdown and Vue components.
https://content.nuxt.com
MIT License
3.12k stars 623 forks source link

Using rehype plugins for syntax highlighting #1956

Open cossssmin opened 1 year ago

cossssmin commented 1 year ago

Hi there,

Using @nuxt/content@2.5.2.

Since the highlight.theme option does not currently accept a path to a local .json theme file, I tried using rehype-shiki in order to highlight code with a custom Shiki theme. But either I'm doing something wrong or they can't be used right now?

So for example I have this:

export default defineNuxtConfig({
  content: {
    markdown: {
      rehypePlugins: [
        ['rehype-shiki',  {
            theme: 'nord',
          },
        ],
      ]
    },
  },
  modules: [
    '@nuxt/content',
    // ...
  ]
})

Doing this in a Markdown file:

```js
if (true) {
  console.log(true)
}

... renders this HTML:

```html
<pre style="background: #2e3440">
    <code style="color: undefined">if (true) {
  console.log(true)
}</code>
</pre>

If there's some conflict that would prevent other rehype/shiki plugins from working, would you consider allowing passing a custom theme .json file path in content.highlight.theme? Thanks!

farnabaz commented 1 year ago

rehype-shiki requires highlighter to be passed in options, which is not possible in nuxt.config. For now, you can create a custom transformer to use Shiki and highlight with your custom theme

See:

Feel free to open PR for this feature, contribution is more than welcome 🙂

cossssmin commented 1 year ago

I ended up writing a custom ProseCode.vue component where instead of <slot /> I use a custom Shiki renderer. Works even better than I hoped, as I can now do stuff like adding classes to highlighted lines, and even highlight diffs based on the original language so everything is highlighted, not just the diffes lines (through meta prop).

Would love to contribute but right now don’t know how to do it, so I’d leave this open in case someone wants to pick it up - the original motivation was to be able to use a custom theme through a local json theme file, rehype was just what I found at that time but isn’t what I was really looking for :)