Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added support for diff with syntax highlight #53

Merged
merged 3 commits into from Aug 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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()