MarkdownEditor: Auto add bullet points when editing

If the user presses Enter and were previously editing a bullet point,
then we should add a new bullet point with the same indentation.

This is a massive hack, and I don't like the way it is implemented. It
sucks that I cannot seem to access the keyboard events for the
TextField.

Fixes #140
This commit is contained in:
Vishesh Handa
2020-06-01 17:16:52 +02:00
parent 327fddcae2
commit 3808624655

View File

@ -54,12 +54,15 @@ class MarkdownEditorState extends State<MarkdownEditor> implements EditorState {
TextEditingController _textController = TextEditingController();
TextEditingController _titleTextController = TextEditingController();
int _textLength;
bool editingMode = true;
bool _noteModified;
MarkdownEditorState(this.note) {
_textController = TextEditingController(text: note.body);
_titleTextController = TextEditingController(text: note.title);
_textLength = note.body.length;
editingMode = Settings.instance.markdownDefaultView ==
SettingsMarkdownDefaultView.Edit;
@ -149,6 +152,7 @@ class MarkdownEditorState extends State<MarkdownEditor> implements EditorState {
}
void _noteTextChanged() {
_insertExtraCharactersOnEnter();
if (_noteModified && !widget.isNewNote) return;
var newState = !(widget.isNewNote && _textController.text.trim().isEmpty);
@ -159,6 +163,32 @@ class MarkdownEditorState extends State<MarkdownEditor> implements EditorState {
}
}
void _insertExtraCharactersOnEnter() {
var text = _textController.text;
if (text.length <= _textLength) {
_textLength = text.length;
return;
}
_textLength = text.length;
if (!text.endsWith('\n')) {
return;
}
var prevLineStart = text.lastIndexOf('\n', text.length - 2);
prevLineStart = prevLineStart == -1 ? 0 : prevLineStart + 1;
var prevLine = text.substring(prevLineStart, text.length - 2);
var pattern = RegExp(r'^(\s*)([*\-])');
var match = pattern.firstMatch(prevLine);
if (match == null) {
return;
}
var indentation = match.group(1) ?? "";
_textController.text = text + indentation + match.group(2) + ' ';
_textLength = _textController.text.length;
_textController.selection = TextSelection.collapsed(offset: _textLength);
}
@override
Future<void> addImage(File file) async {
await getNote().addImage(file);