DEV Community

Seog-Jun Hong
Seog-Jun Hong

Posted on

New Feature: Syntax Highlighting

Describe feature

New feature is syntax highlighting, code blocks are text blocks wrapped around by strings of 3 backticks.

What did you build it?

I modified the unwrapMdxCodeBlocks function from Docusaurus and created a new function unwrapCodeBlocks to my project.

export function unwrapCodeBlocks(content: string): string {
  const regex = /```
{% endraw %}
(.*?)\n(.*?)\n
{% raw %}
```/gs;
  content.replace(regex, function (match, lang, code) {
    if (lang === "") {
      content = `<pre><code>
      ${code}
   </code></pre>`;
    } else {
      content =
        `<pre><code class="language-${lang}">` +
        `
      ${code}
      </code></pre>`;
    }

    return content;
  });
  return content;
}

Enter fullscreen mode Exit fullscreen mode

Also, I added Prism to the .html to highlight code blocks automatically.

  <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/0.0.1/prism.min.js"></script>
      <link
        href="https://cdnjs.cloudflare.com/ajax/libs/prism/0.0.1/prism.min.css"
        rel="stylesheet"
      />
Enter fullscreen mode Exit fullscreen mode

There are lots of supported languages on Prism and the class name depends on what user put in.

function helloWord(){
    console.log("helloWord");
}
Enter fullscreen mode Exit fullscreen mode

This is codeblocks.txt and javascript value is going to be class name like class="language-javascript" and when I run the app the output is as below:

Image description

Issues

The app looks fine when I run codeblocks.txt file, but there are couple of issues, one is that <p> tags are automatically added to code blocks in .html file. The other is that code blocks and other tags are not working together, so when unwrapCodeBlocks function runs it replaces other texts with <pre><code> tags. The next step is to fix these bugs.

Top comments (0)