Skip to content

Commit

Permalink
Improve title parsing (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcospassos authored Sep 25, 2024
1 parent e179ed1 commit 5ee27da
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/parsing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,14 +290,24 @@ class MarkdownParser {

this.match('](');

const [href, titleWithEndQuote] = this.parseText(')').split(/\s+"/);
const href = this.parseText(')', '"');

let title: string|undefined;

if (this.matches('"')) {
this.match('"');

title = this.parseText('"');

this.match('"');
}

this.match(')');

return {
type: 'link',
href: href,
title: titleWithEndQuote?.slice(0, -1) /* remove quote character at the end */,
href: href.trim(),
...(title !== undefined ? {title: title} : {}),
children: label,
source: this.getSlice(startIndex, this.index),
};
Expand All @@ -308,7 +318,7 @@ class MarkdownParser {
}
}

private parseText(end: string): string {
private parseText(...end: string[]): string {
let text = '';

while (!this.done) {
Expand All @@ -322,7 +332,7 @@ class MarkdownParser {
continue;
}

if (end === '' || this.matches(end) || this.matches(...MarkdownParser.NEWLINE)) {
if (end.some(token => (token === '' || this.matches(token))) || this.matches(...MarkdownParser.NEWLINE)) {
break;
}

Expand Down
59 changes: 59 additions & 0 deletions test/parsing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,35 @@ describe('A Markdown parser function', () => {
],
},
},
'link with spaces': {
input: 'Hello, [world]( image.png )!',
output: {
type: 'fragment',
source: 'Hello, [world]( image.png )!',
children: [
{
type: 'text',
source: 'Hello, ',
content: 'Hello, ',
},
{
type: 'link',
source: '[world]( image.png )',
href: 'image.png',
children: {
type: 'text',
source: 'world',
content: 'world',
},
},
{
type: 'text',
source: '!',
content: '!',
},
],
},
},
'fenced code (unsupported)': {
input: 'Hello, ```world```!',
output: {
Expand Down Expand Up @@ -1149,6 +1178,36 @@ describe('A Markdown parser function', () => {
],
},
},
'link with title and escaped quote': {
input: 'Hello, [world](image.png "The \\"world\\"")!',
output: {
type: 'fragment',
source: 'Hello, [world](image.png "The \\"world\\"")!',
children: [
{
type: 'text',
source: 'Hello, ',
content: 'Hello, ',
},
{
type: 'link',
source: '[world](image.png "The \\"world\\"")',
href: 'image.png',
title: 'The "world"',
children: {
type: 'text',
source: 'world',
content: 'world',
},
},
{
type: 'text',
source: '!',
content: '!',
},
],
},
},
image: {
input: 'Hello, ![world](image.png)!',
output: {
Expand Down

0 comments on commit 5ee27da

Please sign in to comment.