How to use prismjs

Comprehensive prismjs code examples:

How to use prismjs.highlightElement:

6
7
8
9
10
11

ctx.Prism = { manual: true, disableWorkerMessageHandler: true }

const Prism = require('prismjs')

export default (el) => Prism.highlightElement(el)

How to use prismjs.highlightAllUnder:

15
16
17
18
19
20
21
22
23
24

function highlight(str, lang) {
        if (lang) loadLanguages([ lang ]);
        let document = dom.window.document;
        document.body.innerHTML = `<pre class="language-${ lang } line-numbers"><code>${ require('escape-html')(str) }</code></pre>`;
        Prism.highlightAllUnder(document);
        return document.body.innerHTML.trim();
}

let md = MarkdownIt({

How to use prismjs.highlightAll:

220
221
222
223
224
225
226
227
228
route: {
  activate () {
    this.$nextTick(() => {
      $('.toc-wrapper').pushpin({ top: $('nav').height() });
      $('.scrollspy').scrollSpy();
      prism.highlightAll();
    });
  }
},

How to use prismjs.hooks:

12
13
14
15
16
17
18
19
20

function loader(input, options) {

    options = option.assignDefault(options);

    Prism.hooks.run('before-highlightall', {selector: SELECTOR});

    const $ = cheerio.load(input, options.cheerioOptions);
    const $elements = $(SELECTOR);

How to use prismjs.tokenize:

202
203
204
205
206
207
208
209
210
211
  new URLSearchParams(this.resourceQuery).get('highlight') ||
  this.resourcePath.split('.').pop()
let isDiff = lang.startsWith('diff-')
let prismLang = isDiff ? lang.substr(5) : lang
let grammar = Prism.languages[isDiff ? 'diff' : prismLang]
let tokens = Prism.tokenize(source, grammar, lang)

if (lang === 'css') {
  fixSelectorEscapeTokens(tokens)
}

How to use prismjs.languages:

52
53
54
55
56
57
58
59
60
61
Prism.languages.js = Prism.languages.javascript;
Prism.languages['c#'] = Prism.languages.csharp;
Prism.languages['f#'] = Prism.languages.fsharp;
Prism.languages.sh = Prism.languages.bash;
Prism.languages.md = Prism.languages.markdown;
Prism.languages.py = Prism.languages.python;
Prism.languages.yml = Prism.languages.yaml;
Prism.languages.rb = Prism.languages.ruby;

const Parser = function (options) {

How to use prismjs.highlight:

16
17
18
19
20
21
22
23
24
25
    // html 的高亮使用 haml 语法
    if (lang.toLocaleLowerCase() === 'html') {
      lang = 'haml';
    }
    loadLanguages([lang]);
    return prism.highlight(str, prism.languages[lang], lang);
  }
  return he.encode(str);
} catch (err) {
  return he.encode(str);