#!/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 dataclasses import dataclass, field CASE_SENSITIVE_MODIFIER = 'c' REGEX_MODIFIER = 'r' 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) 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))