Skip to content

Commit aea7f9e

Browse files
Ovyerusantfu
andauthoredAug 14, 2024··
feat(rehype): trim trailing new line passed in from rehype/remark (#729)
Co-authored-by: Anthony Fu <github@antfu.me>
1 parent b68ee52 commit aea7f9e

File tree

6 files changed

+38
-15
lines changed

6 files changed

+38
-15
lines changed
 

‎packages/rehype/src/core.ts

+16-1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@ export interface RehypeShikiExtraOptions {
2828
*/
2929
fallbackLanguage?: string
3030

31+
/**
32+
* `mdast-util-to-hast` adds a newline to the end of code blocks
33+
*
34+
* This option strips that newline from the code block
35+
*
36+
* @default true
37+
* @see https://github.com/syntax-tree/mdast-util-to-hast/blob/f511a93817b131fb73419bf7d24d73a5b8b0f0c2/lib/handlers/code.js#L22
38+
*/
39+
stripEndNewline?: boolean
40+
3141
/**
3242
* Custom meta string parser
3343
* Return an object to merge with `meta`
@@ -73,6 +83,7 @@ function rehypeShikiFromHighlighter(
7383
defaultLanguage,
7484
fallbackLanguage,
7585
onError,
86+
stripEndNewline = true,
7687
...rest
7788
} = options
7889

@@ -107,7 +118,11 @@ function rehypeShikiFromHighlighter(
107118
if (fallbackLanguage && !langs.includes(lang))
108119
lang = fallbackLanguage
109120

110-
const code = toString(head)
121+
let code = toString(head)
122+
123+
if (stripEndNewline && code.endsWith('\n'))
124+
code = code.slice(0, -1)
125+
111126
const cachedValue = cache?.get(code)
112127

113128
if (cachedValue) {

‎packages/rehype/test/fixtures/a.core.out.html

+2-4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/rehype/test/fixtures/a.out.html

+2-4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/rehype/test/fixtures/b.out.html

+1-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/rehype/test/fixtures/c.out.html

+2-4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/rehype/test/index.test.ts

+15
Original file line numberDiff line numberDiff line change
@@ -63,3 +63,18 @@ it('add-custom-cache', async () => {
6363

6464
expect(file.toString()).toMatchFileSnapshot('./fixtures/c.out.html')
6565
})
66+
67+
it('does not add extra trailing blank line', async () => {
68+
const file = await unified()
69+
.use(remarkParse)
70+
.use(remarkRehype)
71+
.use(rehypeShiki, {
72+
theme: 'vitesse-light',
73+
defaultLanguage: 'text',
74+
})
75+
.use(rehypeStringify)
76+
.process('```\nthis should only have one .line\n```')
77+
78+
const lineCount = file.toString().match(/class="line"/g)?.length ?? 0
79+
expect(lineCount).toEqual(1)
80+
})

0 commit comments

Comments
 (0)
Please sign in to comment.