Added case sensitive and whole word search parameters

pull/1341/head
Alspb 2 years ago
parent 5ff09327db
commit 3a69551191
  1. 31
      lib/src/models/documents/document.dart

@ -195,16 +195,21 @@ class Document {
return block.queryChild(res.offset, true); return block.queryChild(res.offset, true);
} }
/// Search the whole document for any substring matching the pattern /// Search given [substring] in the whole document
/// Returns the offsets that matches the pattern /// Supports [caseSensitive] and [wholeWord] options
List<int> search(Pattern other) { /// Returns correspondent offsets
List<int> search(
String substring, {
bool caseSensitive = false,
bool wholeWord = false,
}) {
final matches = <int>[]; final matches = <int>[];
for (final node in _root.children) { for (final node in _root.children) {
if (node is Line) { if (node is Line) {
_searchLine(other, node, matches); _searchLine(substring, caseSensitive, wholeWord, node, matches);
} else if (node is Block) { } else if (node is Block) {
for (final line in Iterable.castFrom<dynamic, Line>(node.children)) { for (final line in Iterable.castFrom<dynamic, Line>(node.children)) {
_searchLine(other, line, matches); _searchLine(substring, caseSensitive, wholeWord, line, matches);
} }
} else { } else {
throw StateError('Unreachable.'); throw StateError('Unreachable.');
@ -213,10 +218,22 @@ class Document {
return matches; return matches;
} }
void _searchLine(Pattern other, Line line, List<int> matches) { void _searchLine(
String substring,
bool caseSensitive,
bool wholeWord,
Line line,
List<int> matches,
) {
var index = -1; var 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) { while (true) {
index = line.toPlainText().indexOf(other, index + 1); index = lineText.indexOf(searchExpression, index + 1);
if (index < 0) { if (index < 0) {
break; break;
} }

Loading…
Cancel
Save