import 'file_change.dart'; /// One occurrence of a search query in a rendered diff line: the file's index /// in the viewed list, the hunk and line within its parsed patch, and the /// match's character range in the line's text. class DiffMatch { const DiffMatch({ required this.file, required this.hunk, required this.line, required this.start, required this.end, }); final int file; final int hunk; final int line; final int start; final int end; /// Whether this match lies on the given line. bool isOn(int file, int hunk, int line) => this.file == file && this.hunk == hunk && this.line == line; @override bool operator ==(Object other) => other is DiffMatch && other.file == file && other.hunk == hunk && other.line == line && other.start == start; @override int get hashCode => Object.hash(file, hunk, line, start); } /// Every case-insensitive occurrence of [query] in the rendered lines of /// [files], in reading order. A blank query matches nothing. Only hunk lines /// are searched: the rendered view does not draw the `---`/`+++` headers. List diffMatches(List files, String query) { final needle = query.toLowerCase(); if (needle.trim().isEmpty) return const []; final matches = []; for (var f = 0; f < files.length; f++) { final file = files[f]; if (!file.hasPatch) continue; final hunks = file.parsedPatch.hunks; for (var h = 0; h < hunks.length; h++) { final lines = hunks[h].lines; for (var l = 0; l < lines.length; l++) { for (final range in matchRanges(lines[l].text, needle)) { matches.add( DiffMatch( file: f, hunk: h, line: l, start: range.$1, end: range.$2, ), ); } } } } return matches; } /// The non-overlapping case-insensitive ranges of [query] in [text]. List<(int, int)> matchRanges(String text, String query) { final needle = query.toLowerCase(); if (needle.isEmpty) return const []; final haystack = text.toLowerCase(); final ranges = <(int, int)>[]; var from = 0; while (true) { final at = haystack.indexOf(needle, from); if (at < 0) break; ranges.add((at, at + needle.length)); from = at + needle.length; } return ranges; } /// The index of the first match in [matches] at or after file [file], wrapping /// to the first match; null when there are none. Opening a search starts at /// the file being read rather than at the top of the list. int? firstMatchFrom(List matches, int file) { if (matches.isEmpty) return null; final index = matches.indexWhere((match) => match.file >= file); return index < 0 ? 0 : index; }