Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 56 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,56 @@ function encodeAttr(str) {

/** Parse Markdown into an HTML String. */
export default function parse(md, prevLinks) {
let tokenizer = /((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,
let tokenizer = /((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|___|\*\*\*|__|\*\*|[_*]|~~)/gm,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve double-delimiter boundaries in longer runs

For previously supported input such as **first****second** plain, the new alternative consumes the four-character boundary as *** + * rather than ** + **. The output changes from <strong>first</strong><strong>second</strong> plain to <strong>first</strong><em></em>second<strong> plain</strong>: second loses bold and the unformatted suffix becomes bold. The underscore equivalent regresses too. Account for longer delimiter runs before treating a three-character prefix as a combined emphasis token.

Useful? React with 👍 / 👎.

context = [],
out = '',
tripleStarts = [],
out = [],
links = prevLinks || {},
last = 0,
chunk, prev, token, inner, t;

function tag(token) {
// A triple run can close open emphasis or start a combined pair.
if (token === '***' || token === '___') {
let top = context[context.length-1], second = context[context.length-2];
if (top === token) {
context.pop();
tripleStarts.pop();
return '</strong></em>';
}
let single = token[0], dbl = single + single;
if (top === dbl && second === single) {
context.pop(); context.pop();
return '</strong></em>';
}
if (top === single && second === dbl) {
context.pop(); context.pop();
return '</em></strong>';
}
// Between spans, close the open marker and open the remainder.
if ((top === dbl || top === single) && /\S/.test(md.charAt(last-4)) && /\S/.test(md.charAt(last))) {
context[context.length-1] = top === dbl ? single : dbl;
return top === dbl ? '</strong><em>' : '</em><strong>';
}
context.push(token);
tripleStarts.push(out.length + 1); // The opening chunk follows prev.
return '<em><strong>';
Comment on lines +58 to +60

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Split triple runs that join bold and italic spans

For adjacent formatting such as **bold***italic* normal, the stack contains only ** when the triple run arrives. The new pair-closing checks require two stacked markers, so this fallback opens another <em><strong> pair instead of closing bold and starting italics. The parent returns <strong>bold</strong><em>italic</em> normal, while this version leaves the original <strong> open through normal. Handle the close-then-open split against a lone existing delimiter before opening a combined pair.

Useful? React with 👍 / 👎.

}
// Choose the opening order that leaves the closing tags properly nested.
let top = context[context.length-1];
if ((top === '***' || top === '___') && token[0] === top[0]) {
let before = md.charAt(last-token.length-1), next = md.charAt(last);
if (!next || /\s/.test(next) || (/\S/.test(before) && /[!-/:-@[-`{-~]/.test(next))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow partial asterisk closers within words

For valid intraword asterisk emphasis such as ***bold*ness** normal, the single * must close italics even though the next character is n. The updated boundary guard rejects this alphanumeric-successor case and opens another <em> instead, leaving normal bold and italic until flush(). The parent correctly renders <strong><em>bold</em>ness</strong> normal. Recognize right-flanking asterisk closers within words rather than requiring whitespace or punctuation after them.

Useful? React with 👍 / 👎.

let start = tripleStarts.pop();
if (token.length === 1) {
out[start] = '<strong><em>';
context[context.length-1] = top[0] + top[0];
return '</em>';
}
context[context.length-1] = top[0];
return '</strong>';
}
}
let desc = TAGS[token[1] || ''];
let end = context[context.length-1] == token;
if (!desc) return token;
Expand All @@ -54,8 +96,16 @@ export default function parse(md, prevLinks) {

while ( (token=tokenizer.exec(md)) ) {
prev = md.substring(last, token.index);
last = tokenizer.lastIndex;
chunk = token[0];
if (token[17] === '***' || token[17] === '___') {
let marker = chunk[0];
if (md.charAt(token.index-1) === marker || md.charAt(tokenizer.lastIndex) === marker) {
// Preserve the original double delimiters in runs longer than three.
chunk = token[17] = chunk.slice(0, 2);
tokenizer.lastIndex--;
}
}
last = tokenizer.lastIndex;
if (prev.match(/[^\\](\\\\)*\\$/)) {
// escaped
}
Expand All @@ -82,8 +132,8 @@ export default function parse(md, prevLinks) {
}
// Links:
else if (token[10]) {
out = out.replace('<a>', `<a href="${encodeAttr(token[11] || links[prev.toLowerCase()])}">`);
chunk = flush() + '</a>';
out = [out.join('').replace('<a>', `<a href="${encodeAttr(token[11] || links[prev.toLowerCase()])}">`)];
}
else if (token[9]) {
chunk = '<a>';
Expand All @@ -101,9 +151,8 @@ export default function parse(md, prevLinks) {
else if (token[17] || token[1]) {
chunk = tag(token[17] || '--');
}
out += prev;
out += chunk;
out.push(prev, chunk);
}

return (out + md.substring(last) + flush()).replace(/^\n+|\n+$/g, '');
return (out.join('') + md.substring(last) + flush()).replace(/^\n+|\n+$/g, '');
}
47 changes: 47 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,53 @@ describe('snarkdown()', () => {
it('parses italics with _', () => {
expect(snarkdown('I _like_ tiny libraries')).to.equal('I <em>like</em> tiny libraries');
});

it('parses nested bold+italic with ***', () => {
expect(snarkdown('I ***like*** tiny libraries')).to.equal('I <em><strong>like</strong></em> tiny libraries');
});

it('parses nested bold+italic with ___', () => {
expect(snarkdown('I ___like___ tiny libraries')).to.equal('I <em><strong>like</strong></em> tiny libraries');
});

it('closes an open single+double pair with ***', () => {
expect(snarkdown('*italic **bold*** normal')).to.equal('<em>italic <strong>bold</strong></em> normal');
});

it('closes each half of *** with single and double runs', () => {
expect(snarkdown('***bold* italic** normal')).to.equal('<strong><em>bold</em> italic</strong> normal');
expect(snarkdown('***italic** bold* normal')).to.equal('<em><strong>italic</strong> bold</em> normal');
});

it('splits a triple run between adjacent emphasis spans', () => {
expect(snarkdown('**bold***italic* normal')).to.equal('<strong>bold</strong><em>italic</em> normal');
expect(snarkdown('*italic***bold** normal')).to.equal('<em>italic</em><strong>bold</strong> normal');
expect(snarkdown('__bold___italic_ normal')).to.equal('<strong>bold</strong><em>italic</em> normal');
});

it('preserves adjacent bold spans separated by four delimiters', () => {
expect(snarkdown('**first****second** plain')).to.equal('<strong>first</strong><strong>second</strong> plain');
expect(snarkdown('__first____second__ plain')).to.equal('<strong>first</strong><strong>second</strong> plain');
});

it('does not treat the end of a longer run as a triple delimiter', () => {
const expected = '<strong>first</strong><strong><em>second</em> end</strong> plain';
expect(snarkdown('**first*****second* end** plain')).to.equal(expected);
expect(snarkdown('__first_____second_ end__ plain')).to.equal(expected);
});

it('closes partial triple runs before punctuation', () => {
expect(snarkdown('***bold*, italic** normal')).to.equal('<strong><em>bold</em>, italic</strong> normal');
expect(snarkdown('___bold_, italic__ normal')).to.equal('<strong><em>bold</em>, italic</strong> normal');
});

it('keeps a triple run after whitespace nested', () => {
expect(snarkdown('**bold ***nested*** bold** normal')).to.equal('<strong>bold <em><strong>nested</strong></em> bold</strong> normal');
});

it('opens emphasis before punctuation after whitespace', () => {
expect(snarkdown('***outer *!inner* outer*** normal')).to.equal('<em><strong>outer <em>!inner</em> outer</strong></em> normal');
});
});

describe('titles', () => {
Expand Down