Skip to content

Commit

Permalink
fix: highlightjs custom highlighting function(#1016)
Browse files Browse the repository at this point in the history
* Added line for syntax definition #960

* chore: nits & fix for v2 as well
  • Loading branch information
Erik Sultanaliev authored and endiliey committed Oct 5, 2018
1 parent bdbbfae commit aae5c4d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 24 deletions.
5 changes: 5 additions & 0 deletions v1/lib/core/renderMarkdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ class MarkdownRenderer {
// This results in <pre><code class="hljs css languages-jsx">
langPrefix: 'hljs css language-',
highlight(str, lang) {
// User's own custom highlighting function
if (siteConfig.highlight && siteConfig.highlight.hljs) {
siteConfig.highlight.hljs(hljs);
}
// Fallback to default language
lang =
lang || (siteConfig.highlight && siteConfig.highlight.defaultLang);
if (lang === 'text') {
Expand Down
22 changes: 0 additions & 22 deletions v2/lib/theme/Markdown/highlight.js

This file was deleted.

35 changes: 33 additions & 2 deletions v2/lib/theme/Markdown/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import React from 'react';
import Markdown from 'remarkable';
import Helmet from 'react-helmet';
import highlight from './highlight';
import hljs from 'highlight.js';
import chalk from 'chalk';
import escapeHtml from 'escape-html';
import anchors from './anchors';

class MarkdownBlock extends React.Component {
Expand Down Expand Up @@ -36,7 +38,36 @@ class MarkdownBlock extends React.Component {
const {siteConfig} = this.props;
const md = new Markdown({
langPrefix: 'hljs css language-',
highlight: highlight,
highlight: function(str, rawLang) {
// Default language fallback
const defaultLang =
siteConfig.highlight && siteConfig.highlight.defaultLang;

// No syntax highlighting
if (rawLang === 'text' || (!rawLang && !defaultLang)) {
return escapeHtml(str);
}

// User's own hljs function to register additional languages
if (siteConfig.highlight && siteConfig.highlight.hljs) {
siteConfig.highlight.hljs(hljs);
}

// Syntax highlighting
const lang = rawLang.toLowerCase() || defaultLang;
try {
if (hljs.getLanguage(lang)) {
return hljs.highlight(lang, str).value;
}
} catch (e) {
console.error(
chalk.yellow(
`Highlight.js syntax highlighting for language "${lang}" is not supported.`,
),
);
}
return hljs.highlightAuto(str).value;
},
html: true,
linkify: true,
});
Expand Down

0 comments on commit aae5c4d

Please sign in to comment.