Files
GitJournal/lib/utils/markdown.dart
Vishesh Handa c81e539a76 StripMarkdownFormatting: Only consider '* ' as lists
If we let the space be optional then this picks up bold/italics as well.
Ideally, the stripMarkdown formatting could be made smarter, but I would
prefer to just rid of it in the future, and use the proper markdown
parser.

The only thing that is stopping me right now is performance. So in the
future when the stripped version is cached, this should be fine.

Fixes #420
2021-08-02 11:12:54 +02:00

52 lines
1.2 KiB
Dart

import 'dart:convert';
import 'dart:core';
String stripMarkdownFormatting(String markdown) {
var output = StringBuffer();
var lines = LineSplitter.split(markdown);
for (var line in lines) {
line = line.trim();
if (line.startsWith('#')) {
line = line.replaceAll('#', '');
}
if (line.isEmpty) {
continue;
}
line = replaceMarkdownChars(line);
output.write(line.trim());
output.write(' ');
}
return output.toString().trimRight();
}
String replaceMarkdownChars(String line) {
line = line.replaceFirst('- [ ]', '');
line = line.replaceFirst('- [x]', '');
line = line.replaceFirst('- [X]', '');
line = replaceListChar(line, '* ');
line = replaceListChar(line, '- ');
line = replaceListChar(line, '+ ');
return line;
}
String replaceListChar(String line, String char) {
const String bullet = '';
var starPos = line.indexOf(char);
if (starPos == 0) {
line = line.replaceFirst(char, bullet);
} else if (starPos != -1) {
var beforeStar = line.substring(0, starPos);
if (beforeStar.trim().isEmpty) {
line = line.replaceFirst(char, bullet, starPos);
}
}
return line;
}