No internet connection
  1. Home
  2. Documentation
  3. How To

How to add Syntax Highlighting

By KajMagnus @KajMagnus2022-04-21 12:29:23.061Z2022-04-21 13:38:58.925Z

(Some time in the future, this'll be a built-in feature so you can just tick a checkbox (assuming you're admin).)

To add syntax highlighting of source code, you can use Prism.js:

  1. Go to Prism.js' website and configure what languages you'd like to add highlighting for: (but seems this'll work for just one language, for now — see the Only one language? section below)

    https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript

  2. At the bottom of that page, click the two big buttons: Download JS and Download CSS, to download Javascript and CSS.

  3. In Talkyard, go to the admin area, the Look and feel tab, then the CSS and JS tab.

  4. In the Stylesheet field, copy-paste the contents of the CSS file you downloaded from Prism.js' website. And in the javascript field (at the bottom), copy-paste the javascript.

  5. Add a bit more javascript — this tells Prism.js where to find the posts to highlight. Also, change the language in elem.className = 'language-typescript' to the language you want to use:

    if (window.talkyard) talkyard.postElemPostProcessor = function(elemId) {
      var selector = '#' + elemId + ' code';
      console.debug('Telling PrismJS to post process: ' + selector);
      var codeElems = document.querySelectorAll(selector);
      for (var i = 0; i < codeElems.length; ++i) {
        var elem = codeElems[i];
        elem.className = 'language-typescript';  // can't Prism detect this itself?
        Prism.highlightElement(elem);
      }
    }
    
  6. Click Save twice, to save the CSS and the javascript.

Now, if you post some code snippets, wrapped in ``` ...```, it'll be syntax highlighted (example below).

Only one language?

It seems Prism needs to be told what language to highlight. Currently, see above, we do this: elem.className = 'language-(some-language)' but then Prism will highlight only that particular language. Would be nice to fix this somehow, someday, so Prism could highlight different languages not just one.

Example

Here's an example of a code block in ``` that gets highlighted:

```
// Like setTimeout, but is magic: Lets you fast-forward time, or pause time. And
// can make time flow backwards [...]
function magicTimeout(millis, callback) {
  const doAtMs = getNowMs() + millis;
  pendingMagicTimeouts.push({ doAtMs, callback });
}
```

The result:

// Like setTimeout, but is magic: Lets you fast-forward time, or pause time. And
// can make time flow backwards [...]
function magicTimeout(millis, callback) {
  const doAtMs = getNowMs() + millis;
  pendingMagicTimeouts.push({ doAtMs, callback });
}
  • 0 replies