Skip to content

Commit

Permalink
Preserve word diffs when highlighting lines (#410)
Browse files Browse the repository at this point in the history
* Added a prism plugin to preserve `ins`, `del` tags

* Load the preserve word diffs plugin in new syntax highlighter

* Remove redundant check
  • Loading branch information
pastelsky committed Nov 4, 2021
1 parent 9921788 commit c9b2841
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/syntax-highlight/syntax-highlight-new.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export default function syntaxHighlight(
theme: string
) {
loadThemeOnce(theme)
require('../vendor/prism-preserve-word-diffs')

// Set up an observer to pay attention to all potential code changes in the diff section
allDiffsObserver.observe(sectionAllDiffs, {
Expand Down
59 changes: 59 additions & 0 deletions src/vendor/prism-preserve-word-diffs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
(function () {
if (!self.Prism) {
return;
}

var div = document.createElement('div');

Prism.hooks.add('before-highlight', function (env) {
var elt = env.element;
if (elt.parentNode.tagName.toLowerCase() === 'pre') {
elt = elt.parentNode;
}
var tags = ['del', 'ins']
if (!tags) {
return;
}
var placeholder = elt.getAttribute('data-keep-tags-placeholder') || '___KEEPTAGS{n}___';

env.keepTags = true;
env.keepTagsPlaceholder = placeholder;

tags = tags.join('|');
var tags_regex = RegExp('<(' + tags + ')>([\\s\\S]*?)</\\1>', 'g');

env.keepTagsRegex = tags_regex;

env.tokenStack = [];
env.backupCode = env.code;

var code = env.element.innerHTML;
code = code.replace(tags_regex, function (match) {
env.tokenStack.push(match);
return placeholder.replace('{n}', env.tokenStack.length);
});
env.element.innerHTML = code;
code = env.element.textContent;
code = code.replace(/^(?:\r?\n|\r)/,'');

env.code = code;
});

Prism.hooks.add('after-highlight', function (env) {
if (!env.keepTags) {
return;
}
for (var i = 0, t; t = env.tokenStack[i]; i++) {

t = t.replace(env.keepTagsRegex, function(match, tag, inside) {
div.innerHTML = inside;
inside = div.textContent;
return '<' + tag + '>' + Prism.highlight(inside, env.grammar, env.language) + '</' + tag + '>';
});

env.highlightedCode = env.highlightedCode.replace(env.keepTagsPlaceholder.replace('{n}', i + 1), t);
env.element.innerHTML = env.highlightedCode;
}
});

}());

0 comments on commit c9b2841

Please sign in to comment.