fix: highlightjs custom highlighting function(#1016)

* Added line for syntax definition #960

* chore: nits & fix for v2 as well
This commit is contained in:
Erik Sultanaliev 2018-10-05 13:59:24 +06:00 committed by Endilie Yacop Sucipto
parent bdbbfaee91
commit aae5c4dc85
3 changed files with 38 additions and 24 deletions

View file

@ -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') {

View file

@ -1,22 +0,0 @@
const hljs = require('highlight.js');
const chalk = require('chalk');
const escapeHtml = require('escape-html');
export default (str, rawLang) => {
if (rawLang === 'text' || !rawLang) {
return escapeHtml(str);
}
const lang = rawLang.toLowerCase();
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;
};

View file

@ -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 {
@ -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,
});