Skip to content

Commit

Permalink
Merge pull request #37 from l-vo/fix_sublanguages_highlight
Browse files Browse the repository at this point in the history
Fix sublanguages highlight
  • Loading branch information
segayuu authored Aug 29, 2019
2 parents 95f791a + 5e0deb9 commit 05fe5a3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 21 deletions.
24 changes: 3 additions & 21 deletions lib/highlight.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use strict';

const hljs = require('highlight.js/lib/highlight');
const hljs = require('highlight.js');
const Entities = require('html-entities').XmlEntities;
const entities = new Entities();
const alias = require('../highlight_alias.json'); //eslint-disable-line
const alias = require('../highlight_alias.json');

function highlightUtil(str, options = {}) {
if (typeof str !== 'string') throw new TypeError('str must be a string!');
Expand Down Expand Up @@ -88,31 +88,13 @@ function replaceTabs(str, tab) {
});
}

function loadLanguage(lang) {
hljs.registerLanguage(lang, require(`highlight.js/lib/languages/${lang}`));
}

function tryLanguage(lang) {
if (hljs.getLanguage(lang)) return true;
if (!alias.aliases[lang]) return false;

loadLanguage(alias.aliases[lang]);
return true;
}

function loadAllLanguages() {
alias.languages.filter(lang => !hljs.getLanguage(lang)).forEach(loadLanguage);
}

function highlight(str, options) {
let { lang } = options;
const { autoDetect = false } = options;

if (!lang && autoDetect) {
loadAllLanguages();
const result = hljs.highlightAuto(str);
if (result.relevance > 0 && result.language) lang = result.language;

}

if (!lang) {
Expand All @@ -128,7 +110,7 @@ function highlight(str, options) {
return result;
}

if (!tryLanguage(result.language)) {
if (!alias.aliases[result.language]) {
result.language = 'plain';
return result;
}
Expand Down
12 changes: 12 additions & 0 deletions test/scripts/highlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,18 @@ describe('highlight', () => {
validateHtmlAsync(result, done);
});

it('highlight sublanguages', function(done) {
var str = '<node><?php echo "foo"; ?></node>';
var result = highlight(str, {lang: 'xml'});
result.should.eql([
'<figure class="highlight xml"><table><tr>',
gutter(1, 1),
code('<span class="tag">&lt;<span class="name">node</span>&gt;</span><span class="php"><span class="meta">&lt;?php</span> <span class="keyword">echo</span> <span class="string">"foo"</span>; <span class="meta">?&gt;</span></span><span class="tag">&lt;/<span class="name">node</span>&gt;</span>', null),
end
].join(''));
validateHtmlAsync(result, done);
});

it('parse multi-line strings correctly', done => {
const str = [
'var string = `',
Expand Down

0 comments on commit 05fe5a3

Please sign in to comment.