Git Product home page Git Product logo

marked-highlight's Introduction

marked-highlight

Highlight code blocks

Installation

npm install marked-highlight

Usage

You will need to provide a function that transforms the code to html.

import { Marked } from "marked";
import { markedHighlight } from "marked-highlight";
import hljs from 'highlight.js';

// or UMD script
// <script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js"></script>
// <script src="https://cdn.jsdelivr.net/npm/marked-highlight/lib/index.umd.js"></script>
// const {markedHighlight} = globalThis.markedHighlight;
const marked = new Marked(
  markedHighlight({
    langPrefix: 'hljs language-',
    highlight(code, lang, info) {
      const language = hljs.getLanguage(lang) ? lang : 'plaintext';
      return hljs.highlight(code, { language }).value;
    }
  })
);


marked.parse(`
\`\`\`javascript
const highlight = "code";
\`\`\`
`);
// <pre><code class="hljs language-javascript">
//   <span class="hljs-keyword">const</span> highlight = <span class="hljs-string">&quot;code&quot;</span>;
// </code></pre>

The async option should be set to true if the highlight function returns a Promise.

import { Marked } from "marked";
import { markedHighlight } from "marked-highlight";
import pygmentize from 'pygmentize-bundled';

const marked = new Marked(
  markedHighlight({
    async: true,
    highlight(code, lang, info) {
      return new Promise((resolve, reject) => {
        pygmentize({ lang, format: 'html' }, code, function (err, result) {
          if (err) {
            reject(err);
            return;
          }

          resolve(result.toString());
        });
      });
    }
  })
)

await marked.parse(`
\`\`\`javascript
const highlight = "code";
\`\`\`
`);
// <pre><code class="language-javascript">
//   <div class="highlight">
//     <pre>
//       <span class="kr">const</span> <span class="nx">highlight</span> <span class="o">=</span> <span class="s2">&quot;code&quot;</span><span class="p">;</span>
//     </pre>
//   </div>
// </code></pre>

options

option type default description
async boolean false If the highlight function returns a promise set this to true. Don't forget to await the call to marked.parse
langPrefix string 'language-' A prefix to add to the class of the code tag.
highlight function (code: string, lang: string) => {} Required. The function to transform the code to html.

marked-highlight's People

Contributors

baseplate-admin avatar dependabot[bot] avatar github-actions[bot] avatar hyrious avatar ignacemaes avatar nwylzw avatar semantic-release-bot avatar storytellerf avatar tigriz avatar toastwaffle avatar uzitech 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

Watchers

 avatar  avatar  avatar

marked-highlight's Issues

How to customize the generated pre

Take the following code as an example:

marked.parse('```javascript'+
'const highlight = "code";' +
'```');

// Now:
// <pre><code class="hljs language-javascript">
//   <span class="hljs-keyword">const</span> highlight = <span class="hljs-string">&quot;code&quot;</span>;
// </code></pre>


// I need:
// <pre class="hljs-code"><div class="pre-header"><span class="lang-info">javascript</span><svg aria-hidden="true" class="svg-icon icon-copy"><use xlink:href="#icon-copy" fill="currentColor"></use></svg></div><code class="hljs language-javascript"><span class="hljs-keyword">const</span> highlight = <span class="hljs-string">&quot;code&quot;</span>;</code></pre>

renderer.code(code, infostring, escaped) and marked.use(markedHighlight()) will overwrite each other

I can't customize it in renderer.code(), hope to provide a good solution.

Namespace has no exported member "MarkedExtension"

I was using highlight in marked.parse like so:

marked.parse(input, { highlight: function (code, lang) { return highlightjs.highlightAuto(code).value; }, async: true, })

And because of the deprecaion warning I changed it to this:

marked.use( markedHighlight({ highlight: function (code, lang) { return highlightjs.highlightAuto(code).value; }, }), );

However when building my application I get the following error:

../node_modules/marked-highlight/src/index.d.ts(68,82): error TS2694: Namespace '"/home/myApp/node_modules/@types/marked/index"' has no exported member 'MarkedExtension'.

I already updated the typedefinitions of marked to "@types/marked": "^5.0.0",
and I tried several settings in tsconfig, but nothing helped.

Consider adding a note for `mangle` and `headerIds`

Hi, when I'm using this plugin with marked, it shows this error:

marked(): mangle parameter is enabled by default, but is deprecated since version 5.0.0, and will be removed in the future. To clear this warning, install https://www.npmjs.com/package/marked-mangle, or disable by setting `{mangle: false}`.
marked(): headerIds and headerPrefix parameters enabled by default, but are deprecated since version 5.0.0, and will be removed in the future. To clear this warning, install  https://www.npmjs.com/package/marked-gfm-heading-id, or disable by setting `{headerIds: false}`.

I can confirm this is fixed by setting these two options: https://github.com/markedjs/marked/releases/tag/v5.0.1

Adding a note in readme can be helpful!

deprecation warning when using this package.

Edit as my initial assumption was slightly off

After upgrading to marked v5, I started encountering deprecation warnings for how I was using code block highlighting.

After following the deprecation warning and updating this package. I was still encountering the same deprecation warning.

It appears that this package is setting langPrefix to "", which triggers the deprecation warning.

image

image

Unclear instructions

What does this mean?

You will need to provide a function that transforms the code to html.

I thought this library does that. If not, what does it do?

`marked-highlight` is not outputting the correct value

Hi, Thanks for this awesome repo.

Disclaimer : So i have seen this issue before when i was trying to output a specific class with the marked.renderer.

Lets say i have this code :

    const marked = new Marked(
        // Highlight.js
        markedHighlight({
            langPrefix: "hljs language-",
            highlight: (code, lang) => {
                const language = hljs.getLanguage(lang) ? lang : "plaintext";
                const return_value = hljs.highlight(code, { language }).value;
                console.log(return_value);
                return return_value;
            }
        }),
        // Emoji plugin
        markedEmoji(emoji_options),
        {
            renderer,
            // Disable it as marked-mangle doesn't support typescript
            mangle: false,
            // We dont need github like header prefix
            headerIds: false
        }
    );

Given this input :

marked.parse(
  \`\`\`javascript
  console.log('hello');
  \`\`\`
)

while in console we get

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;hello&#x27;</span>)

we get this as output :

image

Reproducible on : https://core-project-v3-ui-git-marked-tokitou-san.vercel.app/mal/1

Using :

  • sveltejs 4.0.3
  • sveltekit 1.22.3

Feature Request: Expose the full infostring

Currently it only passes first word as lang to the highlight() function, which is usable but lacks the possibility to implement things using custom attributes, like:

Possible Patch
diff --git a/src/index.d.ts b/src/index.d.ts
index 0162a9c52e727fd3b0f0bec797a9dfc7d4eed4c3..6a0a366b7d47e79ab295f2cab30c0f9a4b6e178b 100644
--- a/src/index.d.ts
+++ b/src/index.d.ts
@@ -5,9 +5,11 @@ declare module 'marked-highlight' {
    * @param code The raw code to be highlighted
    * @param language The language tag found immediately after the code block
    *   opening marker (e.g. ```typescript -> language='typescript')
+   * @param info The full string after the code block opening marker
+   *   (e.g. ```ts twoslash -> info='ts twoslash')
    * @return The highlighted code as a HTML string
    */
-  type SyncHighlightFunction = (code: string, language: string) => string;
+  type SyncHighlightFunction = (code: string, language: string, info: string) => string;
 
   /**
    * An asynchronous function to highlight code
@@ -15,9 +17,11 @@ declare module 'marked-highlight' {
    * @param code The raw code to be highlighted
    * @param language The language tag found immediately after the code block
    *   opening marker (e.g. ```typescript -> language='typescript')
+   * @param info The full string after the code block opening marker
+   *   (e.g. ```ts twoslash -> info='ts twoslash')
    * @return A Promise for the highlighted code as a HTML string
    */
-  type AsyncHighlightFunction = (code: string, language: string) => Promise<string>;
+  type AsyncHighlightFunction = (code: string, language: string, info: string) => Promise<string>;
 
   /**
    * Options for configuring the marked-highlight extension using a synchronous
diff --git a/src/index.js b/src/index.js
index b267e4d87dfb45bbb387a0c8290cba485f1ffbae..a65ff5c77aed7da369270be650be0e279b25c91e 100644
--- a/src/index.js
+++ b/src/index.js
@@ -23,10 +23,10 @@ export function markedHighlight(options) {
       const lang = getLang(token);
 
       if (options.async) {
-        return Promise.resolve(options.highlight(token.text, lang)).then(updateToken(token));
+        return Promise.resolve(options.highlight(token.text, lang, token.lang)).then(updateToken(token));
       }
 
-      const code = options.highlight(token.text, lang);
+      const code = options.highlight(token.text, lang, token.lang);
       if (code instanceof Promise) {
         throw new Error('markedHighlight is not set to async but the highlight function is async. Set the async option to true on markedHighlight to await the async highlight function.');
       }

Types support

Hi!
I appreciate that this is a very recent change when moving to version 5, but it would be very appreciated to have typescript support either through the package itself or @types.

Languege Undefined causes stylesheet to not apply

Consider the code:

markedHighlight({ langPrefix: 'hljs ', highlight(code, lang) { const language = hljs.getLanguage(lang) ? lang : 'plaintext' return hljs.highlight(code, { language }).value }, })

If hljs.getLanguage(lang) === undefined, then the langPrefix classes are not applied to the codeblock including 'hljs'. This means that the formatting for the code block breaks.

Below images, are examples of formatting working, broken, and what it should look like if hljs class was still aplied correctly.

image
image
image

In the middle image, you can see that the class "hljs" isn't applied to the code block. And so, it doesn't get the proper background color and padding that it should have as seen in the bottom image. (bottom image had the hljs class applied manually)

marked-highlight interfering with custom TokenizerExtensions

Upgraded an older project to a newer version of marked and started receiving the following deprecation notice:

marked(): highlight and langPrefix parameters are deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-highlight.

However, upon upgrading and using marked-highlight, some of the other tokenizer extensions have stopped working, removing marked-highlight allows them to start working again.

import * as marked from 'marked';
import hljs from 'highlight.js';
import { markedHighlight } from "marked-highlight";

const emote: marked.TokenizerExtension & marked.RendererExtension = {
    name: 'discord-emote',
    level: 'inline',
    start: (src: string) => {
        console.log('Hit Emote Check', src);
        return src.match(/\<(a)?:(.*?):([0-9]{1,})>/)?.index;
    },
    tokenizer(src: string, tokens: any) {
        const rule = /^\<(a)?:(.*?):([0-9]{1,})>/;
        const match = rule.exec(src);

        if (match) return {
            type: 'discord-emote',
            raw: match[0],
            animated: !!match[1],
            emoteName: match[2],
            emoteId: match[3]
        };

        return;
    },
    renderer(token) {
        const animated = token['animated'] ? 'gif' : 'png';
        const name = token['emoteName'];
        const id = token['emoteId'];

        return `<img src="https://cdn.discordapp.com/emojis/${id}.${animated}" class="emote" alt="${name}" />`;
    },
    childTokens: ['animated', 'emoteName', 'emoteId']
};

marked.marked.use(
  { extensions: [ emote ] },
  markedHighlight({
      langPrefix: 'hljs language-',
      highlight(code, lang) {
          const language = hljs.getLanguage(lang) ? lang : 'plaintext';
          return hljs.highlight(code, { language }).value;
      }
  }),
);

const output = marked.parse('<:test:1234567>');

output in this example yields: <:test:1234567>

Removing markedHighlight(...) it yields:
<img src="https://cdn.discordapp.com/emojis/1234567.png" class="emote" alt="test">

Edit: Forgot to mention - using marked 9.1.2 and marked-highlight 2.0.6

Need support marked.js 6.0.0 +

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/marked
npm ERR!   marked@"^6.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer marked@"^4 || ^5" from [email protected]
npm ERR! node_modules/marked-highlight
npm ERR!   marked-highlight@"^2.0.1" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/marked
npm ERR!   peer marked@"^4 || ^5" from [email protected]
npm ERR!   node_modules/marked-highlight
npm ERR!     marked-highlight@"^2.0.1" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! 
npm ERR! For a full report see:
npm ERR! /Users/why/.npm/_logs/2023-08-01T07_32_21_650Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in: /Users/why/.npm/_logs/2023-08-01T07_32_21_650Z-debug-0.log

code is not displayed correctly

my code is:

// 18.2.0
import { useEffect } from "react"
// 11.8.0
import hljs  from 'highlight.js'
// 5.0.5
import { marked } from "marked";
// 1.0.2
import { markedHighlight } from "marked-highlight";
// 1.0.1
import { mangle } from "marked-mangle";

export default function Index() {

  useEffect(() => {
    marked.use({ headerIds: false,}, mangle(), markedHighlight({
      langPrefix: 'hljs language-',
      highlight(code, lang) {
        const language = hljs.getLanguage(lang) ? lang : 'plaintext';
        return hljs.highlight(code, { language }).value;
      }
    }));
    let res = marked.parse('# Marked in the browser\n\nRendered by **marked**.\n```java\nInteger a = 3;\n```\n');
    console.log(res)
    document.getElementById('test-m').innerHTML = res;
  }, [])
  return (
    <>
      <div id="test-m"></div>
    </>
  )
}

result:
image

Can you help me point out where I am wrong?

Issue with rendering in `sveltekit`

Hi so here's my svelte code :

<script lang="ts">
    import { emojis } from "$data/emojis";
    import hljs from "highlight.js";
    import "highlight.js/scss/dark.scss";
    import { marked } from "marked";
    import { markedEmoji } from "marked-emoji";
    import { markedHighlight } from "marked-highlight";

    export { klass as class };

    let klass = "";

    const emoji_options = {
        emojis,
        unicode: false
    };

    // Override function
    const renderer: marked.RendererObject = {
        del(text: string) {
            /** Dont convert s (tag) -> del (tag)
             * Reason 1: Skeleton.dev is formatting `del` tag | Source : https://www.skeleton.dev/elements/typography
             * Reason 2: Marked.js is not allowing us to add unstyled class to rendered text.
             */

            return `<s>${text}</s>`;
        }
    };

    marked.use(
        // Highlight.js
        markedHighlight({
            langPrefix: "hljs language-",
            highlight: (code, lang) => {
                const language = hljs.getLanguage(lang) ? lang : "plaintext";
                return hljs.highlight(code, { language }).value;
            }
        }),

        // Emoji plugin
        markedEmoji(emoji_options),
        {
            renderer,
            // Disable it as marked-mangle doesn't support typescript
            mangle: false,
            // We dont need github like header prefix
            headerIds: false
        }
    );
</script>

<markdown class={klass}>
    {@html marked.parse(`
\`\`\`javascript
const highlight = "code";
\`\`\`
    `)}
</markdown>

The first render looks correct :

<pre>
	<code class="hljs language-javascript">
		<span class="hljs-keyword">const</span> highlight = 
		<span class="hljs-string">"code"</span>;

	</code>
</pre>

The next render looks like this ( incorrect | looks like some of the html from first render got into here? ) :

<pre>
	<code class="hljs language-javascript">&lt;span 
		<span class="hljs-keyword">class</span>=
		<span class="hljs-string">"hljs-keyword"</span>&gt;
		<span class="hljs-keyword">const</span>&lt;
		<span class="hljs-regexp">/span&gt; highlight = &lt;span class="hljs-string"&gt;&amp;quot;code&amp;quot;&lt;/</span>span&gt;;

	</code>
</pre>

The next render even is more incorrect :

<pre>
	<code class="hljs language-javascript">&amp;lt;span &lt;span 
		<span class="hljs-keyword">class</span>=
		<span class="hljs-string">"hljs-keyword"</span>&gt;
		<span class="hljs-keyword">class</span>&lt;
		<span class="hljs-regexp">/span&gt;=&lt;span class="hljs-string"&gt;&amp;quot;hljs-keyword&amp;quot;&lt;/</span>span&gt;&amp;gt;
		<span class="language-xml">
			<span class="hljs-tag">&lt;
				<span class="hljs-name">span</span>
				<span class="hljs-attr">class</span>=
				<span class="hljs-string">"hljs-keyword"</span>&gt;
			</span>const
			<span class="hljs-tag">&lt;/
				<span class="hljs-name">span</span>&gt;
			</span>
		</span>&amp;lt;
		<span class="language-xml">
			<span class="hljs-tag">&lt;
				<span class="hljs-name">span</span>
				<span class="hljs-attr">class</span>=
				<span class="hljs-string">"hljs-regexp"</span>&gt;
			</span>/span
			<span class="hljs-symbol">&amp;gt;</span> highlight = 
			<span class="hljs-symbol">&amp;lt;</span>span class=
			<span class="hljs-symbol">&amp;quot;</span>hljs-string
			<span class="hljs-symbol">&amp;quot;</span>
			<span class="hljs-symbol">&amp;gt;</span>
			<span class="hljs-symbol">&amp;amp;</span>quot;code
			<span class="hljs-symbol">&amp;amp;</span>quot;
			<span class="hljs-symbol">&amp;lt;</span>/
			<span class="hljs-tag">&lt;/
				<span class="hljs-name">span</span>&gt;
			</span>
		</span>span&amp;gt;;

	</code>
</pre>

This is how it looks ( screenshot ):
image


I think this is an issue in marked-highlight side instead of svelte side :)

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.