#!/usr/bin/env python # License: GPLv3 Copyright: 2026, Kovid Goyal """In-place scrollback search. The query parser and the matcher live here, away from the screen code, so that they can be tested without a running terminal. A query can start with two modifiers, in any order: ``\\c`` makes matching case sensitive and ``\\r`` treats the query as a regular expression. A doubled backslash escapes the modifier syntax, so that the two prefixes can be searched for literally. """ from __future__ import annotations import re from collections.abc import Sequence from dataclasses import dataclass, field CASE_SENSITIVE_MODIFIER = 'c' REGEX_MODIFIER = 'r' # Mark numbers (see :opt:`mark1_background`) used to highlight the matches. The # current match gets its own color so that it stands out from the other ones. MATCH_COLOR = 1 CURRENT_MATCH_COLOR = 2 class InvalidQuery(ValueError): pass @dataclass(frozen=True) class Query: text: str case_sensitive: bool = False is_regex: bool = False @property def flags(self) -> int: return 0 if self.case_sensitive else re.IGNORECASE @dataclass(frozen=True) class Match: line: int start: int end: int @dataclass class ScrollbackSearch: query: Query pattern: re.Pattern[str] matches: list[Match] = field(default_factory=list) index: int = 0 total_lines: int = 0 def __len__(self) -> int: return len(self.matches) @property def current_match(self) -> Match | None: return self.matches[self.index] if self.matches else None def marker_spans(self, lines: Sequence[str]) -> dict[str, tuple[tuple[int, int, int], ...]]: """Spans to highlight, keyed by the text of the line holding them. Marker functions are called once per line with only its text, never with its number, so the spans are grouped by line text. Lines that are identical to the current one are therefore highlighted alike, which the user cannot tell apart since their text is the same. """ current = self.current_match spans: dict[str, list[tuple[int, int, int]]] = {} for match in self.matches: color = CURRENT_MATCH_COLOR if match == current else MATCH_COLOR spans.setdefault(lines[match.line], []).append((match.start, match.end, color)) return {text: tuple(found) for text, found in spans.items()} def parse_query(raw: str) -> Query: text = (raw or '').strip() case_sensitive = is_regex = False while len(text) > 1 and text[0] == '\\': modifier = text[1].lower() if modifier == '\\': # A doubled backslash stands for a literal one and ends the modifier # section, which is the only way to search for \c or \r themselves. text = text[1:] break if modifier == CASE_SENSITIVE_MODIFIER: case_sensitive = True elif modifier == REGEX_MODIFIER: is_regex = True else: # Not a modifier, the backslash is part of the searched text. break text = text[2:] text = text.strip() if not text: raise InvalidQuery('the search query is empty') return Query(text, case_sensitive, is_regex) def compile_query(query: Query) -> re.Pattern[str]: source = query.text if query.is_regex else re.escape(query.text) try: return re.compile(source, query.flags) except re.error as err: raise InvalidQuery(f'invalid regular expression: {err}') from err def find_matches(lines: list[str] | tuple[str, ...], query: Query, pattern: re.Pattern[str] | None = None) -> list[Match]: pat = pattern if pattern is not None else compile_query(query) ans: list[Match] = [] append = ans.append for line_number, line in enumerate(lines): for match in pat.finditer(line): # Empty matches cannot be navigated to and would make the count # meaningless, so they are ignored. if match.end() > match.start(): append(Match(line_number, match.start(), match.end())) return ans def scroll_offset_for(match: Match, total_lines: int, visible_lines: int) -> int: """Number of lines to scroll up so that the match is visible. The searched text is the history buffer followed by the visible screen, so line 0 is the oldest line. The match is placed roughly a third of the way down the screen, except near the top and bottom of the scrollback. """ history = max(0, total_lines - visible_lines) margin = max(0, visible_lines // 3) return max(0, min(history, history - match.line + margin))