From e91e5789eea286b3cfd2856fa957f3c5dc7f80a8 Mon Sep 17 00:00:00 2001 From: Filip Krawczyk Date: Mon, 4 Jul 2022 17:17:35 +0200 Subject: [PATCH] improve list continuation, add support for numbered list * make list continuation more universal * add support for indentation * add support for numbered list continuation --- lib/formatter.dart | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/lib/formatter.dart b/lib/formatter.dart index 70bafad..9f7c85c 100644 --- a/lib/formatter.dart +++ b/lib/formatter.dart @@ -37,18 +37,44 @@ class MarkdownFormatter extends TextInputFormatter { TextEditingValue oldValue, TextEditingValue newValue) { if (oldValue.text.length > newValue.text.length) return newValue; + var newVal = newValue; + final char = newValue.text[newValue.selection.baseOffset - 1]; + if (char == '\n') { final lineBefore = newValue.text.lineBefore(newValue.selection.baseOffset - 2); - if (lineBefore.startsWith('- ')) { - return newValue.append('- '); + + TextEditingValue listContinuation(String listChar, TextEditingValue tev) { + final regex = RegExp('(\\s*)${RegExp.escape(listChar)} '); + final match = regex.matchAsPrefix(lineBefore); + if (match == null) { + return tev; + } + final indent = match.group(1); + + return tev.append('$indent$listChar '); } - if (lineBefore.startsWith('* ')) { - return newValue.append('* '); + + TextEditingValue numberedListContinuation( + String afterNumberChar, TextEditingValue tev) { + final regex = RegExp('(\\s*)(\\d+)${RegExp.escape(afterNumberChar)} '); + final match = regex.matchAsPrefix(lineBefore); + if (match == null) { + return tev; + } + final indent = match.group(1); + final number = int.parse(match.group(2)!) + 1; + + return tev.append('$indent$number$afterNumberChar '); } + + newVal = listContinuation('-', newVal); + newVal = listContinuation('*', newVal); + newVal = numberedListContinuation('.', newVal); + newVal = numberedListContinuation(')', newVal); } - return newValue; + return newVal; } }