Skip to content
This repository was archived by the owner on Nov 25, 2021. It is now read-only.

Commit 5b658cc

Browse files
sqsfelixfbecker
authored andcommitted
fix: don't highlight plaintext, but do correctly escape HTML
Previously, if `language == "plaintext"`, it would log a warning: ``` Error syntax-highlighting hover markdown code block Error: Unknown language: "plaintext" ``` and it would return a string like `hello%20world` for `hello world` because the `escape` function replaces certain characters with `%` hex codes. It should not be used for escaping HTML.
1 parent 2087a2a commit 5b658cc

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/helpers.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import assert from 'assert'
2+
import { highlightCodeSafe } from './helpers'
3+
4+
describe('helpers', () => {
5+
describe('highlightCodeSafe()', () => {
6+
it('escapes HTML and does not attempt to highlight plaintext', () => {
7+
assert.strictEqual(highlightCodeSafe('foo<"bar>', 'plaintext'), 'foo&lt;"bar&gt;')
8+
})
9+
})
10+
})

src/helpers.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,15 @@ export const scrollIntoCenterIfNeeded = (container: HTMLElement, content: HTMLEl
5454
}
5555
}
5656

57+
/**
58+
* Escapes HTML by replacing characters like `<` with their HTML escape sequences like `&lt;`
59+
*/
60+
const escapeHTML = (html: string): string => {
61+
const span = document.createElement('span')
62+
span.textContent = html
63+
return span.innerHTML
64+
}
65+
5766
/**
5867
* Attempts to syntax-highlight the given code.
5968
* If the language is not given, it is auto-detected.
@@ -65,13 +74,16 @@ export const scrollIntoCenterIfNeeded = (container: HTMLElement, content: HTMLEl
6574
*/
6675
export const highlightCodeSafe = (code: string, language?: string): string => {
6776
try {
77+
if (language === 'plaintext' || language === 'text') {
78+
return escapeHTML(code)
79+
}
6880
if (language) {
6981
return highlight(language, code, true).value
7082
}
7183
return highlightAuto(code).value
7284
} catch (err) {
7385
console.warn('Error syntax-highlighting hover markdown code block', err)
74-
return escape(code)
86+
return escapeHTML(code)
7587
}
7688
}
7789

0 commit comments

Comments
 (0)