From 3a69551191cd520b8a95a06335f3a1838a9ec8e3 Mon Sep 17 00:00:00 2001 From: Alspb <> Date: Sun, 6 Aug 2023 23:33:16 +0100 Subject: [PATCH] Added case sensitive and whole word search parameters --- lib/src/models/documents/document.dart | 33 +++++++++++++++++++------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/lib/src/models/documents/document.dart b/lib/src/models/documents/document.dart index 5f3b82fc..50925160 100644 --- a/lib/src/models/documents/document.dart +++ b/lib/src/models/documents/document.dart @@ -195,16 +195,21 @@ class Document { return block.queryChild(res.offset, true); } - /// Search the whole document for any substring matching the pattern - /// Returns the offsets that matches the pattern - List search(Pattern other) { + /// Search given [substring] in the whole document + /// Supports [caseSensitive] and [wholeWord] options + /// Returns correspondent offsets + List search( + String substring, { + bool caseSensitive = false, + bool wholeWord = false, + }) { final matches = []; for (final node in _root.children) { if (node is Line) { - _searchLine(other, node, matches); + _searchLine(substring, caseSensitive, wholeWord, node, matches); } else if (node is Block) { for (final line in Iterable.castFrom(node.children)) { - _searchLine(other, line, matches); + _searchLine(substring, caseSensitive, wholeWord, line, matches); } } else { throw StateError('Unreachable.'); @@ -213,10 +218,22 @@ class Document { return matches; } - void _searchLine(Pattern other, Line line, List matches) { + void _searchLine( + String substring, + bool caseSensitive, + bool wholeWord, + Line line, + List matches, + ) { var index = -1; - while (true) { - index = line.toPlainText().indexOf(other, index + 1); + final lineText = line.toPlainText(); + var pattern = RegExp.escape(substring); + if (wholeWord) { + pattern = r'\b' + pattern + r'\b'; + } + final searchExpression = RegExp(pattern, caseSensitive: caseSensitive); + while (true) { + index = lineText.indexOf(searchExpression, index + 1); if (index < 0) { break; }