Skip to content

Commit 7ff28fb

Browse files
committed
Fix trimming of whitespace around breaks
Related-to: remarkjs/remark#1202.
1 parent b4ec6fa commit 7ff28fb

File tree

3 files changed

+55
-2
lines changed

3 files changed

+55
-2
lines changed

lib/state.js

+22-2
Original file line numberDiff line numberDiff line change
@@ -291,14 +291,14 @@ export function createState(tree, options) {
291291
if (result) {
292292
if (index && nodes[index - 1].type === 'break') {
293293
if (!Array.isArray(result) && result.type === 'text') {
294-
result.value = result.value.replace(/^\s+/, '')
294+
result.value = trimMarkdownSpaceStart(result.value)
295295
}
296296

297297
if (!Array.isArray(result) && result.type === 'element') {
298298
const head = result.children[0]
299299

300300
if (head && head.type === 'text') {
301-
head.value = head.value.replace(/^\s+/, '')
301+
head.value = trimMarkdownSpaceStart(head.value)
302302
}
303303
}
304304
}
@@ -447,3 +447,23 @@ export function wrap(nodes, loose) {
447447

448448
return result
449449
}
450+
451+
/**
452+
* Trim spaces and tabs at the start of `value`.
453+
*
454+
* @param {string} value
455+
* Value to trim.
456+
* @returns {string}
457+
* Result.
458+
*/
459+
function trimMarkdownSpaceStart(value) {
460+
let index = 0
461+
let code = value.charCodeAt(index)
462+
463+
while (code === 9 || code === 32) {
464+
index++
465+
code = value.charCodeAt(index)
466+
}
467+
468+
return value.slice(index)
469+
}

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@
109109
"import/no-cycle": "error",
110110
"max-depth": "off",
111111
"unicorn/prefer-at": "off",
112+
"unicorn/prefer-code-point": "off",
112113
"unicorn/prefer-string-replace-all": "off"
113114
}
114115
}

test/break.js

+32
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,36 @@ test('break', async function (t) {
4545
h('p', ['alpha', h('br'), '\n', h('em', 'bravo')])
4646
)
4747
})
48+
49+
await t.test('should trim text after a `br` (#3)', async function () {
50+
assert.deepEqual(
51+
toHast({
52+
type: 'paragraph',
53+
children: [
54+
{type: 'text', value: 'a'},
55+
{type: 'break'},
56+
// U+3000 (ideographic space).
57+
{type: 'text', value: ' b'},
58+
{type: 'break'},
59+
// U+2003 (em space).
60+
{type: 'text', value: ' c'},
61+
{type: 'break'},
62+
// U+00A0 (no-break space).
63+
{type: 'text', value: ' d'}
64+
]
65+
}),
66+
h('p', [
67+
'a',
68+
h('br'),
69+
'\n',
70+
' b',
71+
h('br'),
72+
'\n',
73+
' c',
74+
h('br'),
75+
'\n',
76+
' d'
77+
])
78+
)
79+
})
4880
})

0 commit comments

Comments
 (0)