From 38086246559145b41c82be3ff7762723aca9e09e Mon Sep 17 00:00:00 2001 From: Vishesh Handa Date: Mon, 1 Jun 2020 17:16:52 +0200 Subject: [PATCH] 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 --- lib/editors/markdown_editor.dart | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lib/editors/markdown_editor.dart b/lib/editors/markdown_editor.dart index 272b69a8..ce96a2cf 100644 --- a/lib/editors/markdown_editor.dart +++ b/lib/editors/markdown_editor.dart @@ -54,12 +54,15 @@ class MarkdownEditorState extends State 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 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 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 addImage(File file) async { await getNote().addImage(file);