diff --git a/lib/src/utils/markdown.dart b/lib/src/utils/markdown.dart index 93a37eaca..7e8ba81df 100644 --- a/lib/src/utils/markdown.dart +++ b/lib/src/utils/markdown.dart @@ -250,29 +250,33 @@ String markdown( } } } - if (stripPTags) { - ret = ret.replaceAll('
', '').replaceAll('
', ''); - } ret = ret .trim() // Remove trailing linebreaks .replaceAll(RegExp(r'(blocks - ret = ret.convertLinebreaksToBr(); + ret = ret.convertLinebreaksToBr('p'); + // Delete other linebreaks except for pre blocks: + ret = ret.convertLinebreaksToBr('pre', exclude: true, replaceWith: ''); + } + + if (stripPTags) { + ret = ret.replaceAll('', '').replaceAll('
', ''); } return ret; } extension on String { - String convertLinebreaksToBr() { - final parts = split('pre>'); - var convertLinebreaks = true; + String convertLinebreaksToBr(String tagName, + {bool exclude = false, String replaceWith = '
'}) { + final parts = split('$tagName>'); + var convertLinebreaks = exclude; for (var i = 0; i < parts.length; i++) { - if (convertLinebreaks) parts[i] = parts[i].replaceAll('\n', '
'); + if (convertLinebreaks) parts[i] = parts[i].replaceAll('\n', replaceWith); convertLinebreaks = !convertLinebreaks; } - return parts.join('pre>'); + return parts.join('$tagName>'); } } diff --git a/test/markdown_test.dart b/test/markdown_test.dart index 4e88b5a4a..cd2ef2a09 100644 --- a/test/markdown_test.dart +++ b/test/markdown_test.dart @@ -59,14 +59,20 @@ void main() { 'Snape killed Dumbledoor bold'); }); test('multiple paragraphs', () { - expect(markdown('Heya!\n\nBeep'), 'Heya!
Beep
'); + expect(markdown('Heya!\n\nBeep'), 'Heya!
Beep
'); }); test('Other block elements', () { - expect(markdown('# blah\n\nblubb'), 'blah
blubb
'); + expect(markdown('# blah\n\nblubb'), 'blah
blubb
'); }); test('linebreaks', () { expect(markdown('foxies\ncute'), 'foxies
cute'); }); + test('lists', () { + expect( + markdown('So we have:\n- foxies\n- cats\n- dogs'), + 'So we have:
The first
codeblock
void main(){\nprint(something);\n}\n
And the second code block
meow\nmeow\n
',
+ 'The first
codeblock
void main(){\nprint(something);\n}\n
And the second code block
meow\nmeow\n
',
);
});
});