MarkdownToolbar: Navigate across multiple lines properly

This commit is contained in:
Vishesh Handa
2020-09-01 23:32:14 +02:00
parent 9990b2baf0
commit fefe354e83
2 changed files with 43 additions and 13 deletions

View File

@ -198,20 +198,23 @@ TextEditingValue modifyCurrentWord(
}
// FIXME: This will fail in non space delimited languages
final _wordSepRegex = RegExp('((\\s|\\n)|[.!?])');
int nextWordPos(TextEditingValue textEditingValue) {
var cursorPos = textEditingValue.selection.baseOffset;
var text = textEditingValue.text;
var nextSpacePos = text.indexOf(RegExp('(\\s|[.!?])'), cursorPos);
if (cursorPos >= text.length) {
return text.length;
}
var nextSpacePos = text.indexOf(_wordSepRegex, cursorPos);
if (nextSpacePos == -1) {
return text.length;
}
if (nextSpacePos == cursorPos) {
nextSpacePos++;
}
if (nextSpacePos > text.length) {
nextSpacePos = text.length;
}
return nextSpacePos;
}
@ -220,17 +223,17 @@ int prevWordPos(TextEditingValue textEditingValue) {
var cursorPos = textEditingValue.selection.baseOffset;
var text = textEditingValue.text;
var lastSpacePos = text.lastIndexOf(RegExp('(\\s|[.!?])'), cursorPos);
if (cursorPos <= 1) {
return 0;
}
var lastSpacePos = text.lastIndexOf(_wordSepRegex, cursorPos - 1);
if (lastSpacePos == -1) {
return 0;
}
if (lastSpacePos == cursorPos) {
lastSpacePos = text.lastIndexOf(RegExp('(\\s|[.!?])'), cursorPos - 1);
if (lastSpacePos == -1) {
return 0;
}
lastSpacePos++;
if (lastSpacePos == cursorPos - 1) {
lastSpacePos--;
}
return lastSpacePos;
return lastSpacePos + 1;
}

View File

@ -225,5 +225,32 @@ void main() {
_testPrevWord(text, 6, 5);
_testPrevWord(text, 5, 0);
});
// Test for navigating between newlines
test('Navigation with multiple lines', () {
const text = 'Hello.\nHow are you?';
_testNextWord(text, 0, 5);
_testNextWord(text, 5, 6);
_testNextWord(text, 6, 7);
_testNextWord(text, 7, 10);
_testNextWord(text, 10, 11);
_testNextWord(text, 11, 14);
_testNextWord(text, 14, 15);
_testNextWord(text, 15, 18);
_testNextWord(text, 18, 19);
_testNextWord(text, 19, 19);
_testPrevWord(text, 19, 18);
_testPrevWord(text, 18, 15);
_testPrevWord(text, 15, 14);
_testPrevWord(text, 14, 11);
_testPrevWord(text, 11, 10);
_testPrevWord(text, 10, 7);
_testPrevWord(text, 7, 6);
_testPrevWord(text, 6, 5);
_testPrevWord(text, 5, 0);
_testPrevWord(text, 0, 0);
});
// Test that clicking on h2 removes h1 and then adds h2
}