Skip to content

Commit

Permalink
Fix to prefer no-highlight class over language-* class
Browse files Browse the repository at this point in the history
Related-to: rehypejs/rehype#154.
  • Loading branch information
wooorm committed Oct 4, 2023
1 parent 81f7dd1 commit 8fbc0eb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
21 changes: 13 additions & 8 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,26 +155,31 @@ export default function rehypeHighlight(options) {
* is used.
*/
function language(node) {
const className = node.properties.className
const list = node.properties.className
let index = -1

if (!Array.isArray(className)) {
if (!Array.isArray(list)) {
return
}

while (++index < className.length) {
const value = String(className[index])
/** @type {string | undefined} */
let name

while (++index < list.length) {
const value = String(list[index])

if (value === 'no-highlight' || value === 'nohighlight') {
return false
}

if (value.slice(0, 5) === 'lang-') {
return value.slice(5)
if (!name && value.slice(0, 5) === 'lang-') {
name = value.slice(5)
}

if (value.slice(0, 9) === 'language-') {
return value.slice(9)
if (!name && value.slice(0, 9) === 'language-') {
name = value.slice(9)
}
}

return name
}
17 changes: 17 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,23 @@ test('rehypeHighlight', async function (t) {
)
})

await t.test(
'should prefer `no-highlight` over a `language-*` class',
async function () {
const file = await rehype()
.data('settings', {fragment: true})
.use(rehypeHighlight)
.process(
'<h1>Hello World!</h1>\n<pre><code class="lang-js no-highlight">alert(1)</code></pre>'
)

assert.equal(
String(file),
'<h1>Hello World!</h1>\n<pre><code class="lang-js no-highlight">alert(1)</code></pre>'
)
}
)

await t.test('should not highlight (`nohighlight`)', async function () {
const file = await rehype()
.data('settings', {fragment: true})
Expand Down

0 comments on commit 8fbc0eb

Please sign in to comment.