Skip to content

Commit

Permalink
fix: Do not convert linebreaks in pre blocks on markdown parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
krille-chan committed Oct 23, 2023
1 parent 8c638a7 commit 6f14419
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/src/utils/markdown.dart
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,21 @@ String markdown(
// Remove trailing linebreaks
.replaceAll(RegExp(r'(<br />)+$'), '');
if (convertLinebreaks) {
ret = ret.replaceAll('\n', '<br/>');
// Only convert linebreaks which are not in <pre> blocks
ret = ret.convertLinebreaksToBr();
}

return ret;
}

extension on String {
String convertLinebreaksToBr() {
final parts = split('pre>');
var convertLinebreaks = true;
for (var i = 0; i < parts.length; i++) {
if (convertLinebreaks) parts[i] = parts[i].replaceAll('\n', '<br/>');
convertLinebreaks = !convertLinebreaks;
}
return parts.join('pre>');
}
}
17 changes: 17 additions & 0 deletions test/markdown_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,5 +123,22 @@ void main() {
expect(markdown('meep `\$\\frac{2}{3}\$`'),
'meep <code>\$\\frac{2}{3}\$</code>');
});
test('Code blocks', () {
expect(
markdown(
'```dart\nvoid main(){\nprint(something);\n}\n```',
convertLinebreaks: true,
),
'<pre><code class="language-dart">void main(){\nprint(something);\n}\n</code></pre>',
);

expect(
markdown(
'The first \n codeblock\n```dart\nvoid main(){\nprint(something);\n}\n```\nAnd the second code block\n```js\nmeow\nmeow\n```',
convertLinebreaks: true,
),
'<p>The first<br/>codeblock</p><br/><pre><code class="language-dart">void main(){\nprint(something);\n}\n</code></pre><br/><p>And the second code block</p><br/><pre><code class="language-js">meow\nmeow\n</code></pre>',
);
});
});
}

0 comments on commit 6f14419

Please sign in to comment.