How to use the highlight function from highlight.js

Find comprehensive JavaScript highlight.js.highlight code examples handpicked from public code repositorys.

12
13
14
15
16
17
18
19
20
21
markedConfig: {
    renderer: (function() {
        var r = new marked.Renderer();
        r.code = function(code, language){
          return '<pre><code class="hljs ' + (language || "") + '">' + 
              hljs.highlight("javascript", code).value +
            '</code></pre>';
        };
        return r;
    })()
fork icon75
star icon85
watch icon16

+ 5 other calls in file

4
5
6
7
8
9
10
11
12
13
14
const checkCapitalization = require('./capitalization');
const log = require('./log');
const TypeUtils = require('./typeUtils');


marked.setOptions({
  highlight: (code, lang) => lang && highlight.highlight(code, {
    language: lang, ignoreIllegals: true,
  }).value,
});

fork icon40
star icon76
watch icon6

128
129
130
131
132
133
134
135
136
137
  break
case 'html':
  text = text.replace(/(@docs|others)/g, '<span class="directive" title="Leo Directive - does not appear in source file.">$1</span>')
  break
case 'htmlsource':
  muv = hljs.highlight('html', text)
  text = muv.value
  text = text.replace(/(@\w+)/, '<span class="directive" title="Leo Directive - does not appear in source file.">$1</span>')
  text = text.replace(/@others/g, '<span class="directive" title="Leo Directive: rest of tree goes here.">@others</span>')
  text = `<pre>${text}</pre>`
fork icon28
star icon156
watch icon10

+ 2 other calls in file

97
98
99
100
101
102
103
104
105
106
the corresponding opening and closing tags for the html string to be well-formed and
maintain the correct state per line.

Ref: https://github.com/MarkBind/markbind/pull/1521
*/
lines = hljs.highlight(str, { language: lang, ignoreIllegals: true }).value.split('\n');
const tokenStack = [];

lines = lines.map((line) => {
  const prepend = tokenStack.map(tok => `<span class="${tok}">`).join('');
fork icon105
star icon95
watch icon13

+ 5 other calls in file

70
71
72
73
74
75
76
77
78
79

```javascript
require(["highlight.js/build/highlight.pack"], function(hljs){

  // If you know the language
  hljs.highlight(lang, code).value;

  // Automatic language detection
  hljs.highlightAuto(code).value;
});
fork icon16
star icon19
watch icon31

70
71
72
73
74
75
76
77
78
79
typographer: true,
quotes: '“”‘’',
highlight: (str, lang) => {
  if (lang && hljs.getLanguage(lang)) {
    try {
      return hljs.highlight(str, { language: lang }).value;
    } catch (err) {
      console.log(err);
    }
  }
fork icon9
star icon32
watch icon2

+ 33 other calls in file

115
116
117
118
119
120
121
122
123
124
  return `<div class="mermaid">${text}</div>`;
}

let hlHtml = '';
if (lang) {
  hlHtml = hljs.highlight(lang, text).value
} else {
  hlHtml = hljs.highlightAuto(text).value
}
return `<code class="hljs code-block">${hlHtml}</code>`
fork icon13
star icon33
watch icon7

+ 9 other calls in file

17
18
19
20
21
22
23
24
25
26
const markdown = new markdownIt({
    html: true,
    highlight: (str, lang) => {
        if(lang && highlightjs.getLanguage(lang)){
            try{
                return highlightjs.highlight(str, { language: lang }).value;
            }catch(ex){
                console.log('Failed to highlight code block', ex);
            }
        }
fork icon7
star icon48
watch icon3

+ 25 other calls in file

142
143
144
145
146
147
148
149
150
151
	'ebnf': 'ebnf',
	'': '',
})[hjsMediaType];
if(hjsLanguage===undefined) throw new Error('Unknown media type '+JSON.stringify(hjsMediaType)+' at tag '+doc.localName);
const textContent = doc.getAttribute('w:space')=='indent' ? stripIndent(doc.textContent).trim() : doc.textContent ;
const hjsHTML = hjsLanguage ? hjs.highlight(textContent, {language: hjsLanguage}).value : escapeHTML(textContent);
return '<pre'+mapAttributes(doc, function(attr){
	if(attr.name=='w:space') return '';
	return applyTemplate(attr);
}).join('')+'>' + hjsHTML + '</'+doc.localName+'>';
fork icon1
star icon8
watch icon5

21
22
23
24
25
26
27
28
29
30
            throwOnUndefined: true,
        },
    )
)
environment._currentPageUrlPath = null;
environment.addFilter('highlight', (code, language) => highlight.highlight(code, {language}).value)
environment.addFilter('prettier', (code, parser) => prettier.format(code, {parser}))
environment.addTest('activeCurrentUrl', urlPath => {
    if (!environment._currentPageUrlPath) {
        throw new Error('No page is being templated right now.')
fork icon3
star icon3
watch icon2

+ 10 other calls in file

59
60
61
62
63
64
65
66
67
let html = marked( md, {
  highlight: function(code, lang){
    let ret;

    if( lang ){
      ret = hljs.highlight(lang, code).value;
    } else {
      ret = hljs.highlightAuto(code).value;
    }
fork icon3
star icon3
watch icon14

+ 19 other calls in file

296
297
298
299
300
301
302
303
304
305
renderer: renderer,
Lexer: CustomLexer,
highlight: function (code, lang) {
	const hljs = require('highlight.js');
	const language = hljs.getLanguage(lang) ? lang : 'plaintext';
	return hljs.highlight(code, { language }).value;
},
langPrefix: 'hljs language-', // highlight.js css expects a top-level 'hljs' class.
pedantic: false,
gfm: true,
fork icon0
star icon4
watch icon1

+ 11 other calls in file

422
423
424
425
426
427
428
429
430
431
const articleElement =
  markdownContent === emptyContent
    ? article(
        { class: "content" },
        pre({
          innerHTML: highlightJs.highlight(
            JSON.stringify(msg, null, 2),
            {language: "json", ignoreIllegals: true}
          ).value,
        })
fork icon1
star icon7
watch icon1

40
41
42
43
44
45
46
47
48
49
50
51
  }
  // Normalize language
  language = normalize(language);


  try {
    return hljs.highlight(code, {language}).value;
  } catch(e) { }


  return code;
}
fork icon0
star icon2
watch icon4

13
14
15
16
17
18
19
20
21
let components = {};
const highlight = (str, lang) => {
  if (!lang || !hljs.getLanguage(lang)) {
    return '<pre><code class="hljs">' + str + '</code></pre>';
  }
  const html = hljs.highlight(lang, str, true, undefined).value;
  return `<pre><code class="hljs language-${lang}">${html}</code></pre>`;
};
const md = new Config();
fork icon0
star icon2
watch icon1

+ 13 other calls in file

144
145
146
147
148
149
150
151
152
153
154
const _prettifyCode = pipe(
  join('\n'),
  split('\n'),
  map(_exampleSplitMultilineOutput),
  join('\n'),
  s => hljs.highlight(s, {language: 'javascript'}).value
)


/**
 * Replaces '...' with '…' and '->' with '→'.
fork icon0
star icon2
watch icon0

+ 4 other calls in file

76
77
78
79
80
81
82
83
84
85
                codeText += code
                if (typeof lang == 'undefined' || lang == '')
                    return hljs.highlightAuto(code).value
                else if (lang == 'nohighlight')
                    return code
                else return hljs.highlight(code, { language: lang }).value
            }
        })))
}

fork icon0
star icon2
watch icon1

+ 28 other calls in file

10
11
12
13
14
15
16
17
18
19
20
// 配置markdown-it常规代码高亮,相关文档:https://markdown-it.github.io/markdown-it/#MarkdownIt.new
const highlight = (str, lang) => {
    if (!lang || !hljs.getLanguage(lang)) {
        return '<pre><code class="hljs">' + str + '</code></pre>'
    }
    const html = hljs.highlight(lang, str, true, undefined).value
    return `<pre><code class="hljs language-${lang}">${html}</code></pre>`
}


config.options
fork icon0
star icon1
watch icon1

+ 2 other calls in file

182
183
184
185
186
187
188
189
190
191
    `No language set in ${filename}, ` +
    `line ${node.position.start.line}`);
}
const language = (node.lang || '').split(' ')[0];
const highlighted = getLanguage(language) ?
  highlight(language, node.value).value :
  node.value;
node.type = 'html';
node.value = '<pre>' +
  `<code class = 'language-${node.lang}'>` +
fork icon2
star icon0
watch icon2

6
7
8
9
10
11
12
13
14
15
const { disposeEmitNodes } = require('typescript');
const md = require('markdown-it')({
    highlight: function (str,  lang ) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(str, {"language": lang, "ignoreIllegals" : true }).value;
        } catch (__) {}
      }
      return '';
    }
fork icon2
star icon1
watch icon1