Skip to content

Commit

Permalink
Merge pull request #53 from Code-Victor/diff-syntax-highlight
Browse files Browse the repository at this point in the history
feat: added support for diff with syntax highlight
  • Loading branch information
timlrx committed Aug 21, 2022
2 parents 331aa92 + 31f49aa commit fadb391
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/generator.js
Expand Up @@ -196,11 +196,17 @@ const rehypePrismGenerator = (refractor) => {
// Syntax highlight
if (lang) {
try {
let rootLang
if (lang?.includes('diff-')){
rootLang=lang.split('-')[1]
} else{
rootLang=lang
}
// @ts-ignore
refractorRoot = refractor.highlight(toString(node), lang)
refractorRoot = refractor.highlight(toString(node), rootLang)
// @ts-ignore className is already an array
parent.properties.className = (parent.properties.className || []).concat(
'language-' + lang
'language-' + rootLang
)
} catch (err) {
if (options.ignoreMissing && /Unknown language/.test(err.message)) {
Expand Down Expand Up @@ -267,9 +273,9 @@ const rehypePrismGenerator = (refractor) => {
}

// Diff classes
if (lang === 'diff' && toString(line).substring(0, 1) === '-') {
if ((lang === 'diff' || lang?.includes('diff-')) && toString(line).substring(0, 1) === '-') {
line.properties.className.push('deleted')
} else if (lang === 'diff' && toString(line).substring(0, 1) === '+') {
} else if ((lang === 'diff' || lang?.includes('diff-')) && toString(line).substring(0, 1) === '+') {
line.properties.className.push('inserted')
}
}
Expand Down
18 changes: 18 additions & 0 deletions test.js
Expand Up @@ -397,4 +397,22 @@ test('works as a remarkjs / unifiedjs plugin', () => {
assert.is(result, expected)
})

test('diff and code highlighting should work together', () => {
const result = processHtml(
dedent`
<pre><code class="language-diff-css">
.hello{
- background:url('./urel.png');
+ background-image:url('./urel.png');
}
</code></pre>
`,
{ ignoreMissing: true }
)
assert.ok(result.includes(`<pre class="language-css">`))
assert.ok(result.includes(`<span class="code-line inserted">`))
assert.ok(result.includes(`<span class="code-line deleted">`))
assert.ok(result.includes(`<span class="code-line">`))
})

test.run()

0 comments on commit fadb391

Please sign in to comment.