GithubHelp home page GithubHelp logo

timlrx / rehype-prism-plus Goto Github PK

View Code? Open in Web Editor NEW
163.0 4.0 17.0 712 KB

rehype plugin to highlight code blocks in HTML with Prism (via refractor) with line highlighting and line numbers

License: MIT License

JavaScript 99.72% Shell 0.28%
rehype-plugin syntax-highlighting prismjs

rehype-prism-plus's People

Contributors

andyeskridge avatar code-victor avatar dawchihliou avatar jaywcjlove avatar jrson83 avatar oedotme avatar psygik avatar timlrx avatar wilkmaia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

rehype-prism-plus's Issues

Code moves when line number goes from 9 to 10

Hi. Thank you for an awesome plugin.

I noticed that when the line number goes from an n-digit number to an n+1-digit number, the position of the code shifts to the right as well. It is more noticeable with unindented lines of code (red line added for emphasis).

Current

alignment

Expected

It should probably look something like this.
alignment_2

Syntax highlighting solution

Currently i see only classes such as punctuation, annotation like that is there any way to highlight this instead of CSS?

Wrapping code snippets in a `div` puts the code title at a wrong position

In a standard setup of Tailwind Nextjs Starter Blog I want to write a blog post that includes a very long code snippet.
My idea was to wrap it in a div as follows:

<div style={{height: '300px', overflow: 'scroll'}}>
```json:fileName.json
A very long code snippet
```
</div>

However, this generates the problem that the code title, i.e., the bar with the name of the file, will be placed at the beginning of the entire blog post and not directly above the code snippet.

A workaround might be to define a max-height for all code snippets, but I would like to have this customizable for each code block.

Unable to compile TypeScript file that imports the module due to missing/ incorrect type

Problem

This is the error message when compiling TypeScript file that imports the module.

error TS2315: Type 'Visitor' is not generic.

9 export type Visitor = import('unist-util-visit').Visitor<Node>;

Reduced test case

This is a reduced test case written in TypeScript

import rehypePrism from 'rehype-prism-plus';
import rehypeStringify from 'rehype-stringify';
import remarkGfm from 'remark-gfm';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import { unified } from 'unified';
import type { VFile } from 'vfile';

export async function mdParse(value: string): Promise<VFile> {
  return unified()
    // remark
    .use(remarkParse)
    .use(remarkGfm)
    .use(remarkRehype)
    // rehype
    .use(rehypePrism)
    .use(rehypeStringify)
    .process(value);
}

Expected behavior

TypeScript file that imports the module should compile successfully without any typing issue

Actual behavior

TypeScript file fails to compile due to missing/ incorrect type

Other information

  1. TypeScript: 4.5.4
  2. vite: 2.7.2
  3. vue-tsc: 0.30.2
  4. rehype-prism-plus: 1.1.3

missing pre tag with language-* class

hey there! First of all great work on the plugin.

One issue that I've noticed is that this isn't actually compatible with most prism theme styles out of the box because it doesn't generate a pre tag with the language- class copied over.

Context from similar rehype-prism's FAQ: https://github.com/mapbox/rehype-prism#faq

As a clear example if you look at any typical theme css for prism, like NightOwl as given example in the README, you'll notice that most of the CSS have the following as selectors (to apply styles to the actual code block, relying on prismJS behavior):

pre[class*="language-"] { }

In the README you have:

To style the language tokens, you can just copy them from any prismjs compatible ones. Here's a list of themes.

Which does style the tokens, but not the greater code block, which the screenshot provided makes you assume also happens.

I could be wrong but looking at your usage of this plugin in tailwind-nextjs-starter-blog it seems as if the code block styles are dependent on your use of the prose class from @tailwindcss/typography, making this plugin not really as usable on it's own.

Perhaps there is missing documentation that could be added to call that out? Or maybe an option added so that you can toggle to add the language- class to the pre tag?

Thoughts? thanks.

How to test this plugin locally?

I'm trying to test this plugin locally but I'm getting an error.

Current Behavior

node_modules/esbuild/lib/main.js:869:33: error: [plugin: esbuild-xdm] Cannot read property 'start' of undefined
    869 │               let result = await callback2({
        ╵                                  ^
node_modules/esbuild/lib/main.js:736:22: note: This error came from the "onLoad" callback registered here
    736 │         let promise = setup({
        ╵                       ^

Steps to Reproduce

  1. Fork the repo
  2. Run npm run build
  3. Run npm link
  4. Go to a project where you wanna use this plugin. (e.g. timlrx/tailwind-nextjs-starter-blog)
  5. Run npm link rehype-prism-plus
  6. Run npm run dev
  7. Visit any blog post and you will get the error mentioned above.

Context

I wanna see if I can implement a new feature to this plugin. The one inside the mdx-bundler branch of timlrx/tailwind-nextjs-starter-blog works fine. But as soon as I switch to the local build, I get the error.

Hightlight line number bug?

This work

```bash {5,14,23,34} showLineNumbers
```

This doesn't work

```bash {5, 14, 23, 34} showLineNumbers
```

The `node.position` data is lost after using the `[email protected]` plugin.

The node.position data is lost after using the [email protected] plugin. @timlrx

<MarkdownPreview
  components={{
    code:  ({ inline, node, ...props }) => {
      if (inline) {
        return <code {...props} />;
      }
      console.log('>>>>does not exist!!!!:::', node.position)
      // `node.position` does not exist
      // position:
      //   end: {line: 44, column: 35, offset: 2393}
      //   start: {line: 44, column: 30, offset: 2388}
      return (
        <div></div>
      )
    }
  }}
  className="App-markdown"
  source={MDStr.replace(/([\s\S]*)<!--dividing-->/, '')}
/>

receive custom attributes.

```js expanded
***
```
export default function Pre({ children, className, ...props }: React.ComponentProps<'pre'>) {
  console.log(props)
  return null
}

i wanna get expanded

Wrapping lines

Is there any way to instruct a code block to wrap lines after a specific number of characters?

Here's an example of my current problem.
image

Thanks!

Rehype-prism-plus with @next/mdx & @mdx-js/loader

Hi, new to MDX. I am currently using @next/mdx, @mdx-js/loader and @mdx-js/react. My code looks like:

import mdx from "@next/mdx";
import rehypePrism from "rehype-prism-plus";

const withMDX = mdx({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [],
    rehypePlugins: [rehypePrism],
  },
});

export default withMDX({
  reactStrictMode: true,
  pageExtensions: ["ts", "tsx", "js", "jsx", "md", "mdx"],
});

I keep getting TypeError: Converting circular structure to JSON --> starting at object with constructor 'State'

Other rehype plugins like rehypeKatex work normally.

Is there some other remark or rehype plugin that needs to be integrated before or after rehype-prism-plus? Thanks.

How to disable showLineNumbers on a per block basis

Hi there ☺️

I enabled showLineNumbers in the plugin's settings, so they're always enabled, how can I disable line numbers on a specific block?

I tried

```toml showLineNumbers=false
```toml showLineNumbers="false"
```toml showLineNumbers={false}

without any luck 😬 and peeking at the code looks like it's not supported at the moment?

Appropriate stylesheet is missing border solid for line highlighting when not using TailwindCSS

The plugin is really great, but I don't use Next.js and the line highlighting border-left did not work for me at all. I tried to figure out why.

I checked out your website and the Next.js starter. Both using Tailwind CSS which in it's preflight resets border-style to solid for all elements. After inspecting both websites I see:

*, ::after, ::before {
  box-sizing: border-box;
  border: 0 solid #e5e5e5;
}

I don't use tailwind, so I don't have boder-style set to solid and I don't see any of the line highlighting borders.

To fix this issue for people who not using Tailwind CSS, you should add border-left-style: solid to the appropriate stylesheet, for which you should now use the shorthand property "border-left" and also set the color of the placeholder to transparent:

.code-line {
  display: block;
  padding-left: 16px;
  padding-right: 16px;
  margin-left: -16px;
  margin-right: -16px;
  border-left: 4px solid transparent; /* Set code block color */
}

.highlight-line {
  margin-left: -16px;
  margin-right: -16px;
  background-color: rgba(55, 65, 81, 0.5); /* Set highlight bg color */
  border-left: 4px solid rgb(59, 130, 246); /* Set highlight accent border color */
}

Highlight lines without specifying a language

When I write down a code block without specifying any language but put line numbers for highlighting like below:

```{2}

it is interpreted as the language is language-{2}.

I know the documentation says that :

Note: This will wrongly assign a language class and the class might appear as language-{1,3} or language-showLineNumbers, but allow the language highlighting and line number function to work. An possible approach would be to add a placeholder like unknown so the div will have class="language-unknown"

I see in the playground that the above code produces the below AST (the rest is omitted)

{
  "type": "code",
  "lang": "{2}",
  "meta": null,
}

Is it possible to put a logic in the plugin like below as a pseudo code:

  • Check if the lang starts with "{"
    • if the meta is null then copy the content of the lang into the meta and make the lang is "unknown" or null,
    • if the meta is not null then prepend the lang into the meta and make the lang again "unknown" or null,

Here is two AST examples before and after :

// ```{2}

// before
{
  "type": "code",
  "lang": "{2}",
  "meta": null,
}

// after
{
  "type": "code",
  "lang": "unknown", // or null, I could not figure out which is better
  "meta": "{2}",
}
// ```{2} showLineNumbers

// before
{
  "type": "code",
  "lang": "{2}",
  "meta":"showLineNumbers,
}

// after
{
  "type": "code",
  "lang": "unknown", // or null, I could not figure out which is better
  "meta": "{2} showLineNumbers",
}

Then maybe we can highlight any line without specifying any language or without the text unknown as a dummy language.

Dont work with SvelteKit & mdsvex

Hi. I use Sveltekit and the mdsvex plugin, as well as the rehype-code-titles plugin. Below is my configuration in the file svelte.config.js .

import adapter from '@sveltejs/adapter-static';
//import adapter from '@sveltejs/adapter-vercel'
import sveltePreprocess from 'svelte-preprocess'
import { mdsvex } from 'mdsvex'
import rehypeCodeTitles from 'rehype-code-titles'
import rehypePrism from 'rehype-prism-plus'

const mdsvexOptions = {
	extensions: ['.md'],
    highlight: false,
    rehypePlugins: [rehypeCodeTitles, rehypePrism]
}

/** @type {import('@sveltejs/kit').Config} */
const config = {
	kit: {
		adapter: adapter()
	},
    extensions: ['.svelte', '.md'],
    preprocess: [
        sveltePreprocess(),
        mdsvex(mdsvexOptions),
      ]


};

export default config;
This is an example of my code block in the markdown file. Your plugin does syntax highlighting perfectly, according to my styles, but highlighting specific lines and showing line numbers does not work at all
```js:src/lib/javascripts {1,3-4} showLineNumbers
    onMount(() => {
        carouselItemRef = document.querySelector('.carousel > *');

          // Добавляем обработчики событий прокрутки карусели, чтобы следить за ее концами
        carouselRef.addEventListener('scroll', updateCarouselEnds);
        window.addEventListener('resize', updateCarouselEnds);

        // Обновляем состояние, когда компонент отрисован впервые
        updateCarouselEnds();
    });

The `ignoreMissing` parameter is invalid.

uiwjs/react-md-editor#406

While using code snippet syntax in editor and trying to edit extension text beside "```" I'm getting following error:

Cannot read properties of null (reading 'children')

./node_modules/rehype-prism-plus/dist/rehype-prism-plus.es.js:1

> 1 | import{visit as e}from"unist-util-visit";import{toString as t}from"hast-util-to-string";import{filter as r}from"unist-util-filter";import n from"parse-numeric-range";import{refractor as i}from"refractor/lib/common.js";import{refractor as o}from"refractor/lib/all.js";function a(){a=function(e,t){return new r(e,void 0,t)};var e=RegExp.prototype,t=new WeakMap;function r(e,n,i){var o=new RegExp(e,n);return t.set(o,i||t.get(e)),l(o,r.prototype)}function n(e,r){var n=t.get(r);return Object.keys(n).reduce(function(t,r){return t[r]=e[n[r]],t},Object.create(null))}return s(r,RegExp),r.prototype.exec=function(t){var r=e.exec.call(this,t);return r&&(r.groups=n(r,this)),r},r.prototype[Symbol.replace]=function(r,i){if("string"==typeof i){var o=t.get(this);return e[Symbol.replace].call(this,r,i.replace(/\$<([^>]+)>/g,function(e,t){return"$"+o[t]}))}if("function"==typeof i){var a=this;return e[Symbol.replace].call(this,r,function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(n(e,a)),i.apply(this,e)})}return e[Symbol.replace].call(this,r,i)},a.apply(this,arguments)}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&l(e,t)}function l(e,t){return l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},l(e,t)}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function c(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return u(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?u(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var p=function e(t){return t.reduce(function(t,r){if("text"===r.type){if(-1===r.value.indexOf("\n"))return t.push(r),t;for(var n,i=r.value.split("\n"),o=c(i.entries());!(n=o()).done;){var a=n.value,s=a[0],l=a[1];t.push({type:"text",value:s===i.length-1?l:l+"\n",position:{start:{line:r.position.start.line+s},end:{line:r.position.start.line+s}}})}return t}return Object.prototype.hasOwnProperty.call(r,"children")?(r.children=e(r.children),t.push(r),t):(t.push(r),t)},[])},f=function(i){return function(o){return void 0===o&&(o={}),function(t){e(t,"element",s)};function s(e,s,l){if(l&&"pre"===l.tagName&&"code"===e.tagName){var u=e.data&&e.data.meta?e.data.meta:"";e.properties.className?"boolean"==typeof e.properties.className?e.properties.className=[]:Array.isArray(e.properties.className)||(e.properties.className=[e.properties.className]):e.properties.className=[],e.properties.className.push("code-highlight");var f,h=function(e){for(var t,r=c(e.properties.className);!(t=r()).done;){var n=t.value;if("language-"===n.slice(0,9))return n.slice(9).toLowerCase()}return null}(e);if(h)try{f=i.highlight(t(e),h),l.properties.className=(l.properties.className||[]).concat("language-"+h)}catch(t){if(!o.ignoreMissing||!/Unknown language/.test(t.message))throw t;f=e}else f=e;var m,d=(m=1,function e(t){return t.reduce(function(t,r){if("text"===r.type){var n=(r.value.match(/\n/g)||"").length;return r.position={start:{line:m,column:0},end:{line:m+n,column:0}},m+=n,t.push(r),t}if(Object.prototype.hasOwnProperty.call(r,"children")){var i=m;return r.children=e(r.children),t.push(r),r.position={start:{line:i,column:0},end:{line:m,column:0}},t}return t.push(r),t},[])})(f.children);f.children=p(d),f.children.length>0&&(f.position={start:{line:f.children[0].position.start.line,column:0},end:{line:f.children[f.children.length-1].position.end.line,column:0}});for(var g,y,v=function(e){var t=/{([\d,-]+)}/,r=e.split(",").map(function(e){return e.trim()}).join();if(t.test(r)){var i=t.exec(r)[1],o=n(i);return function(e){return o.includes(e+1)}}return function(){return!1}}(u),b=function(e){var t=/*#__PURE__*/a(/showLineNumbers=([0-9]+)/i,{lines:1});if(t.test(e)){var r=t.exec(e);return Number(r.groups.lines)}return 1}(u),N=(""===(g=t(e).split(/\n/))[g.length-1].trim()&&g.pop(),g.map(function(e){return{type:"element",tagName:"span",properties:{className:["code-line"]},children:[{type:"text",value:e}]}})),w=function(){var e=y.value,n=e[0],i=e[1];(u.toLowerCase().includes("showLineNumbers".toLowerCase())||o.showLineNumbers)&&(i.properties.line=[(n+b).toString()],i.properties.className.push("line-number")),v(n)&&i.properties.className.push("highlight-line"),"diff"===h&&"-"===t(i).substring(0,1)?i.properties.className.push("deleted"):"diff"===h&&"+"===t(i).substring(0,1)&&i.properties.className.push("inserted");var a=r(f,function(e){return e.position.start.line<=n+1&&e.position.end.line>=n+1});i.children=a.children},x=c(N.entries());!(y=x()).done;)w();e.children=N}}}},h=f(i),m=f(o);export{m as default,h as rehypePrismCommon,f as rehypePrismGenerator};
    |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                ^
  2 | //# sourceMappingURL=rehype-prism-plus.es.js.map
  3 |

This happens when user try to edit "```jsx" part inside the editor:

// (Sometimes when I try to edit/remove `"```jsx"` in the following line  it breaks the application and gives the above error)
```jsx
import React from "react";
import MDEditor from '@uiw/react-md-editor';

export default function App() {
  const [value, setValue] = React.useState("**Hello world!!!**");
  return (
    <div className="container">
      <MDEditor
        value={value}
        onChange={setValue}
      />
      <MDEditor.Markdown source={value} style={{ whiteSpace: 'pre-wrap' }} />
    </div>
  );
}

Also the code snippets are not getting highlighted in my markdown preview.

NOTE: Your own website is also crashing due to the same issue.Kindly open https://uiwjs.github.io/react-md-editor/ and try to edit the following part:

Untitled.mp4

Line numbers not working when using rehype-raw

Using rehype-prism-plus in a project with react-markdown and rehype-raw plugin. It works fine if rehype-prism-plus is defined first in the plugins array but line numbers are not displayed (and related attributes are unset in DOM) if placing
rehype-raw first.

Dependencies versions:

"react-markdown": "^8.0.3",
"rehype-prism-plus": "^1.5.0",
"rehype-raw": "^6.1.1"

Sample code:

import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";
import rehypePrismPlus from "rehype-prism-plus";

import "./styles.css";

const markdown = `
Code block:

~~~js showLineNumbers
const test = 'Show line numbers'
~~~
`;

export default function App() {
  return (
    <div className="App">
      <ReactMarkdown rehypePlugins={[rehypePrismPlus, rehypeRaw]} >
        {markdown}
      </ReactMarkdown>
    </div>
  );
}

CodeSandbox: https://codesandbox.io/s/thirsty-williams-us0vg1?file=/src/App.js

Possible type issue with `@mdx-js/mdx`

Hello,

I am trying to use this plugin with @mdx-js/mdx version 3.0.0.

However I am getting type error while passing rehypePrism as an array item to rehypePlugins, (as shown in the example):

import { compile } from "@mdx-js/mdx";
import rehypePrism from "rehype-prism-plus";

const mdx = await compile(source, {
  rehypePlugins: [rehypePrism],
});

The type error:

Type 'Plugin<[(Options | undefined)?], Root, Root>' is not assignable to type 'Pluggable'.
  Type 'Plugin<[(Options | undefined)?], Root, Root>' is not assignable to type 'Plugin<any[], any, any>'.
    The 'this' types of each signature are incompatible.
      Type 'Processor<undefined, undefined, undefined, undefined, undefined>' is not assignable to type 'Processor<void, Root, void, void>'.
        Types of property 'use' are incompatible.
          Type '{ <Parameters_2 extends unknown[] = [], Input extends string | Node | undefined = undefined, Output = Input>(preset?: Preset | null | undefined): Processor<undefined, undefined, undefined, undefined, undefined>; <Parameters_2 extends unknown[] = [], Input extends string | ... 1 more ... | undefined = undefined, Outp...' is not assignable to type '{ <PluginParameters extends any[] = any[], Input = Root, Output = Input>(plugin: Plugin<PluginParameters, Input, Output>, ...settings: PluginParameters | [boolean]): UsePlugin<...>; <PluginParameters extends any[] = any[], Input = Root, Output = Input>(tuple: [...] | [...]): UsePlugin<...>; (presetOrList: Preset | P...'.
            Types of parameters 'preset' and 'plugin' are incompatible.
              Type 'Plugin<any, any, any>' has no properties in common with type 'Preset'.ts(2322)

It looks like a possible bug with rehype-prism-plus as I have tested it with the original rehype-prism and it works fine without any issue.

Build failed if I include the language

Repo: https://github.com/straw-hat-team/adr
Branch: yordis/add-website (important)
Usage: website/src/pages/adrs/[slug].tsx
File That Could Make it Fail: website/src/routes/adrs/routes/[slug]/routes/0000000001/index.mdx
URL: http://localhost:3000/adrs/0000000001


For some reason, if I include the language to the code-block then if fails,

Error: Build failed with 1 error:
_mdx_bundler_entry_point-73179c97-432a-46d2-b082-e985d451fa69.mdx:0:0: error: [plugin: esbuild-xdm] 
`

![Screen Shot 2021-10-31 at 6 23 48 AM](https://user-images.githubusercontent.com/4237280/139578173-5fcaeae9-09b6-45c7-98fe-dfb196084040.png)

![Screen Shot 2021-10-31 at 6 21 12 AM](https://user-images.githubusercontent.com/4237280/139578076-fd93647b-ed0d-4b7d-ad12-2ba25164cc68.png)
``

Throws an error when trying to use

This may not be prism-plus specific, but when I add this plugin to my rehypePlugins list, my test.mdx page throws this error:

Error: Unknown language: mdx is not registered

image

I can't figure out through online searches what the cause is.

Adding a new language

What's the recommended way of adding support for a language not currently available in Refactor? I'm currently trying to add highlighting support for Cython.

Git diff file coordinates don't always get labeled correctly

Hi Tim, I am not sure this is a problem with your plugin or some other one, but I would love it if you could point me in the right direction in any case. I'm using diff as the language BTW.

If I have the following:

diff --git a/blah.css b/blah.css
index 7b1cbad..a304d0b 100644
--- a/blah.css
+++ b/blah.css
@@ -1,11 +1,3 @@

Then it gets rendered as:

<span class="token coord">@@ -1,11 +1,3 @@</span>

However if I have this:

diff --git a/blah.tsx b/blah.tsx
index d617b6e..86dc6a3 100644
--- a/blah.tsx
+++ b/blah.tsx
@@ -152,9 +152,7 @@ export function MyFunction({

Then it gets rendered as:

<span class="code-line">@@ -152,9 +152,7 @@ export function MyFunction({
</span>

TypeError: Cannot read properties of undefined (reading 'source')

contentlayer.config.js

import { defineDocumentType, makeSource } from 'contentlayer/source-files'

import readingTime from 'reading-time'
import remarkGfm from 'remark-gfm'
import rehypeSlug from 'rehype-slug'
import rehypeCodeTitles from 'rehype-code-titles'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import rehypePrism from 'rehype-prism-plus'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'

const computedFields = {
	readingTime: { type: 'json', resolve: (doc) => readingTime(doc.body.raw) },
	wordCount: {
		type: 'number',
		resolve: (doc) => doc.body.raw.split(/\s+/gu).length
	},
	slug: {
		type: 'string',
		resolve: (doc) => doc._raw.sourceFileName.replace(/\.mdx$/, '')
	}
}

const Blog = defineDocumentType(() => ({
	name: 'Blog',
	filePathPattern: 'blog/*.mdx',
	contentType: 'mdx',
	fields: {
		title: { type: 'string', required: true },
		publishedAt: { type: 'string', required: true },
		summary: { type: 'string', required: true },
		image: { type: 'string', required: true },
		excerpt: { type: 'string', required: true }
	},
	computedFields
}))

const OtherPage = defineDocumentType(() => ({
	name: 'OtherPage',
	filePathPattern: '*.mdx',
	contentType: 'mdx',
	fields: {
		title: { type: 'string', required: true }
	},
	computedFields
}))

const contentLayerConfig = makeSource({
	contentDirPath: 'data',
	documentTypes: [Blog, OtherPage],
	mdx: {
		remarkPlugins: [remarkGfm, remarkParse, remarkRehype],
		rehypePlugins: [
			rehypeSlug,
			rehypeCodeTitles,
			rehypePrism,
			[
				rehypeAutolinkHeadings,
				{
					properties: {
						className: ['anchor']
					}
				}
			]
		]
	}
})

export default contentLayerConfig

Whenever I try to import something from rehype-prism-plus, it shows the error

ConfigReadError (..\blog\contentlayer.config.js): TypeError: Cannot read properties of undefined (reading 'source')

Not importing anything from rehype-prism-plus working fine.

Import resolves to `undefined`

Hey, thanks for the plugin.

I've been trying to update my blog to use ESM for the MDX stuff (mostly remark and rehype plugins). Everything seems to work, except this plugin. When loading the page, Next.js throws this obscure error:

image

In the terminal, the following error shows up:

image

Upon further inspection, it seems that the import for rehype-prism-plus resolves to undefined.

import rehypePrismPlus from 'rehype-prism-plus';
// ...
// DEBUG
console.log({ rehypePrismPlus });

image

However, if I try to console.log({ rehypePrismPlus }); in client-side code, it seems to resolve correctly:

image

I have no idea what's causing the issue. If I remove rehypePrismPlus from options.rehypePlugins, everything works fine.

This issue doesn't show up with your blog template, though I can't seem to find out any difference in my blog that may cause this.

I know that it's probably just an issue with my setup, and cloning my whole blog is probably too much. However, if you'd like to look into it, I'd really appreciate it. You can check out the branch of this PR: laymonage/base#35.

Thanks!

Doesn't Recognize JavaScript in HTML

Hi, this is an awesome plugin.

But I found an issue, this plugin can't recognize JavaScript in HTML.

Code:

`` `html
<script>
  console.log('Hello World');
  const hi = 'hi';
</script>
` ``

Result:

image

Expected behavior:

Should be the same as the @mapbox/rehype-prism plugin, it's recognized. Like this:

image

showLineNumbers occurs error in React

Using next-mdx-remote, then use some plugins:

  const content = await serialize(post.content, {
    mdxOptions: {
      remarkPlugins: [
        remarkHint,
        remarkBreaks,
      ],
      rehypePlugins: [
        rehypePrismPlus, // import rehypePrismPlus from "rehype-prism-plus";
        rehypeSlug,
      ]
    },
  })

then gets:

Warning: React does not recognize the `showLineNumbers` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `showlinenumbers` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

with:

```jsx showLineNumbers
const Component: VFC<Props> = ({ children }) => {
  return (
    <Hoge>
      <Foo />
    </Hoge>
  )
}

Tried showlinenumbers, showlinenumbers={true} and showLineNumbers but those all are throwing error (not exact same error)

Do I missed something or misconfigurated?
Thanks!

Type error fixes cause errors in next.js

          @timlrx Type error fixes cause errors in next.js

Originally posted by @jaywcjlove in #64 (comment)

"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/rehype-prism-plus.es.js"
},
"./common": {
"types": "./dist/src/common.d.ts",
"import": "./dist/common.es.js"
},
"./all": {
"types": "./dist/src/all.d.ts",
"import": "./dist/all.es.js"
},
"./generator": {
"types": "./dist/src/generator.d.ts",
"import": "./dist/generator.es.js"
}

The reason for the error is: import+require must be used in combination in the exports field in next.js.

Issues with providing highlighted lines

I have trouble to use the highlighted lines and showLineNumbers feature.

```js {1,3-4} showLineNumbers
function fancyAlert(arg) {
  if (arg) {
    $.facebox({ div: '#foo' })
  }
}
```

In general the line numbers work, if I force showLineNumbers on plugin creation. I'm using next-mdx-remote.

I played around a little bit and build myself a small plugin that prints the HAST before rehype-prism-plus is executed. I'm not a rehype or remark expert at all! This is what my HAST looks like:

{
  type: 'element',
  tagName: 'code',
  properties: {
    className: [ 'language-js' ],
    metastring: '{1,3-4} showLineNumbers',
    '{1,3-4}': true,
    showLineNumbers: true
  },
  children: [
    {
      type: 'text',
      value: 'function fancyAlert(arg) {\n' +
        '  if (arg) {\n' +
        "    $.facebox({ div: '#foo' })\n" +
        '  }\n' +
        '}\n'
    }
  ],
  position: {
    start: { line: 6, column: 1, offset: 40 },
    end: { line: 12, column: 4, offset: 150 }
  }
}

The issue seems to be, that a property called data is expected that should contain the meta, but instead I have a metastring property as part of properties.

I have no idea if that problem is on my side, or incompatible packages, or if we should just fix it here (by supporting both).
For now I solve this using a plugin on my side, that I run before this plugin:

const fixMetaPlugin = (options = {}) => {
  return (tree) => {
    visit(tree, 'element', visitor);
  };

  function visitor(node, index, parent) {
    if (!parent || parent.tagName !== 'pre' || node.tagName !== 'code') {
      return;
    }

    node.data = { ...node.data, meta: node.properties.metastring };
  }
};

Tailwind inline CSS not working

While testing the plugin locally, I tried replacing the CSS class name with Tailwind CSS classes but it didn't work.

For example:

properties: { className: ['code-line'] },

I tried replacing that line with this:

properties: { className: ['pl-4 -mx-4 border-l-4 border-gray-800'] },

Do you have any idea why it didn't work? And how to make it work?

Can't build when moduleResolution set to bundler.

my tsconfig.json:

{
    "compilerOptions": {
        "allowJs": true,
        "baseUrl": "./",
        "module": "ESNext",
        "moduleResolution": "bundler",
        "jsx": "react-jsx",
        "strict": true,
        "isolatedModules": true,
        "target": "ESNext",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "skipLibCheck": true,
        "paths": {
            "@/*": [
                "./resources/js/*"
            ],
            "@styles/*": [
                "./resources/css/*"
            ]
        }
    },
    "include": [
        "resources/js/**/*.ts",
        "resources/js/**/*.tsx",
        "resources/js/**/*.d.ts"
    ],
    "exclude": [
        "node_modules/*"
    ]
}

tsc error:

yarn run v1.22.19
$ tsc && vite build && vite build --ssr
resources/js/Pages/Articles/Show/index.tsx:5:25 - error TS7016: Could not find a declaration file for module 'rehype-prism-plus'. '/home/dairidong/code/react_blog/node_modules/rehype-prism-plus/dist/rehype-prism-plus.es.js' implicitly has an 'any' type.
  There are types at '/home/dairidong/code/react_blog/node_modules/rehype-prism-plus/dist/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'rehype-prism-plus' library may need to update its package.json or typings.

5 import rehypePrism from "rehype-prism-plus";

it's only can run success if i set "moduleResolution": "node" or "noImplicitAny": false

Default fallback language

Hi Tim, I love this plugin :)

Was wondering if you could add an option to have a default fallback language? I'd love this option vs on-the-fly modifying my markdown to inject it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.