Custom Code Fence Syntax Highlight

Joshua Wright's Avatar

Joshua Wright

24 Apr, 2018 01:43 PM

Looking through the discussions for syntax highlighting in code fences, I understand that Marked uses Highlight.js for syntax highlighting, either automatically detecting the language or relying on the type of code fence following triple-backtick.

I have been using ```text code fence blocks for Linux shell terminal examples, but I'd like to make a simple tweak to that output where text following a shell prompt of $ or # is bold (so the reader knows this is content they should type in a lab, as opposed to output from a tool itself).

It seems like a custom output processor isn't the right solution, and editing Highlight.js would make my tweak subject to overwrite with future Marked releases. Is there another path to customizing the code fence syntax highlight output?

Thank you,

-Josh

  1. Support Staff 1 Posted by Brett on 24 Apr, 2018 02:18 PM

    Brett's Avatar

    I'm afraid there's not really a great way to customize the syntax
    highlighting code that Marked uses automatically.

    You do have the option of disabling syntax highlighting and then using
    your own, either manually including a <script> in the markdown file, or
    with a custom processor that injects it automatically when rendering the
    page.

    Hope that provides some options, though I know it's a hassle.

    -Brett

  2. 2 Posted by Joshua Wright on 24 Apr, 2018 06:20 PM

    Joshua Wright's Avatar

    No worries, thanks for the quick reply. If others stumble across this post, I was able to solve this using custom JavaScript. The regex below will have to be adjusted for different prompt usage (e.g. hostname $, etc.)

    Thanks Brett!

    -Josh

    const codeTags = document.querySelectorAll('code.text');  
    codeTags.forEach(updateTag);
    
    function updateTag(tag) {  
      let text = tag.innerText;
      text = text.replace(/^(# )(.*)$/gm, '$1<strong>$2</strong>');
      text = text.replace(/^($ )(.*)$/gm, '$1<strong>$2</strong>');
      tag.innerHTML = text;
    }
    <pre><code></code>
    </pre>
    
  3. Support Staff 3 Posted by Brett on 24 Apr, 2018 06:36 PM

    Brett's Avatar

    I salute your resourcefulness!

    -Brett

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac