feat(search): highlight and navigate scrollback matches in place
Searching the scrollback used to replace the whole screen with an external pager, losing the surrounding context. Highlight every match with a marker instead, show the [current/total] counter and provide temporary n/N/Escape bindings, restoring the previous marker and title when the search ends.
This commit is contained in:
5 files changed
+342
No files matched your search
@@ -4140,6 +4140,21 @@ For more sophisticated control, such as using the current selection, use :ac:`re
|
||||
|
||||
map('Search the scrollback within a pager', 'search_scrollback --allow-fallback=shifted,ascii cmd+f search_scrollback', only='macos')
|
||||
|
||||
map(
|
||||
'Search and highlight the scrollback in place',
|
||||
'search_scrollback_prompt kitty_mod+shift+f search_scrollback_prompt',
|
||||
long_text="""
|
||||
Search the scrollback without opening a pager. Every match is highlighted in
|
||||
the scrollback and the ``[current/total]`` counter is shown in the window title.
|
||||
Prefix the query with ``\\c`` to match case sensitively and with ``\\r`` to use
|
||||
a regular expression. While a search is active, :kbd:`n` and :kbd:`N` jump to
|
||||
the next and previous match and :kbd:`Escape` ends the search.
|
||||
|
||||
The :ac:`scrollback_search_next`, :ac:`scrollback_search_prev` and
|
||||
:ac:`clear_scrollback_search` actions can be mapped to other keys.
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
egr() # }}}
|
||||
|
||||
|
||||
Generated
+2
@@ -934,6 +934,8 @@ defaults.map = [
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=103), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='show_last_command_output'),
|
||||
# search_scrollback
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=47), definition='search_scrollback'),
|
||||
# search_scrollback_prompt
|
||||
KeyDefinition(trigger=SingleKey(mods=257, key=102), definition='search_scrollback_prompt'),
|
||||
# new_window
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57345), definition='new_window'),
|
||||
# new_os_window
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
"""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.
|
||||
"""
|
||||
|
||||
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 == 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))
|
||||
+138
@@ -825,6 +825,11 @@ class Window:
|
||||
self.actions_on_focus_change: list[Callable[['Window', bool], None]] = []
|
||||
self.actions_on_removal: list[Callable[['Window'], None]] = []
|
||||
self.current_marker_spec: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
|
||||
self.scrollback_search: ScrollbackSearch | None = None
|
||||
self.scrollback_search_mode: str = ''
|
||||
self.scrollback_search_saved_marker: tuple[str, str | tuple[tuple[int, str], ...]] | None = None
|
||||
self.scrollback_search_saved_title: str | None = None
|
||||
self.actions_on_focus_change.append(self._on_focus_change_clear_scrollback_search)
|
||||
self.kitten_result_processors: list[Callable[['Window', Any], None]] = []
|
||||
self.child_is_launched = False
|
||||
self.restored_scrollback = b''
|
||||
@@ -2666,6 +2671,139 @@ class Window:
|
||||
w.screen.paste_bytes(sanitized)
|
||||
w.send_key('enter')
|
||||
|
||||
@ac(
|
||||
'sc',
|
||||
"""
|
||||
Search the scrollback in place, highlighting every match. Prefix the query with \\c for a case
|
||||
sensitive search and with \\r for a regular expression. Matches are navigated with n and N and
|
||||
the search ends with Escape. The [current/total] counter is shown in the window title.
|
||||
""",
|
||||
)
|
||||
def search_scrollback_prompt(self) -> bool | None:
|
||||
if not self.screen.is_main_linebuf():
|
||||
return True
|
||||
|
||||
def done(text: str) -> None:
|
||||
if text:
|
||||
self.start_scrollback_search(text)
|
||||
else:
|
||||
self.clear_scrollback_search()
|
||||
|
||||
get_boss().get_line(
|
||||
_('Search the scrollback. Prefix the query with \\c for a case sensitive search and \\r for a regular expression.'),
|
||||
done,
|
||||
window=self,
|
||||
prompt=_('search> '),
|
||||
window_title=_('Search scrollback'),
|
||||
)
|
||||
return None
|
||||
|
||||
def scrollback_search_lines(self) -> list[str]:
|
||||
# Read the history buffer and the visible screen directly instead of using
|
||||
# as_text(), so that line numbers are the ones scrolling actions use.
|
||||
lines: list[str] = []
|
||||
self.screen.as_text_for_history_buf(lines.append, False, True)
|
||||
self.screen.as_text(lines.append, False, True)
|
||||
return [line.replace('\r', '').replace('\n', '') for line in lines]
|
||||
|
||||
def start_scrollback_search(self, raw_query: str) -> None:
|
||||
from .scrollback_search import InvalidQuery, ScrollbackSearch, compile_query, find_matches, parse_query
|
||||
|
||||
try:
|
||||
query = parse_query(raw_query)
|
||||
pattern = compile_query(query)
|
||||
except InvalidQuery as err:
|
||||
get_boss().show_error(_('Invalid search query'), str(err))
|
||||
return
|
||||
lines = self.scrollback_search_lines()
|
||||
matches = find_matches(lines, query, pattern)
|
||||
if not matches:
|
||||
from .fast_data_types import ring_bell
|
||||
|
||||
ring_bell(self.os_window_id)
|
||||
return
|
||||
self.clear_scrollback_search()
|
||||
from .marks import marker_from_regex
|
||||
|
||||
self.scrollback_search = ScrollbackSearch(query, pattern, matches, total_lines=len(lines))
|
||||
self.scrollback_search_saved_marker = self.current_marker_spec
|
||||
self.scrollback_search_saved_title = self.override_title
|
||||
self.screen.set_marker(marker_from_regex(pattern, 1))
|
||||
self._push_scrollback_search_mode()
|
||||
self._goto_scrollback_match(0)
|
||||
|
||||
@ac('sc', 'Stop the in-place scrollback search and remove its highlights')
|
||||
def clear_scrollback_search(self) -> None:
|
||||
if self.scrollback_search is None:
|
||||
return
|
||||
self.scrollback_search = None
|
||||
self.screen.set_marker()
|
||||
self.current_marker_spec = None
|
||||
saved = self.scrollback_search_saved_marker
|
||||
self.scrollback_search_saved_marker = None
|
||||
if saved is not None:
|
||||
# Restore the marker that was displayed before the search started.
|
||||
from .marks import marker_from_spec
|
||||
|
||||
ftype, spec = saved
|
||||
self.screen.set_marker(marker_from_spec(ftype, spec, 0))
|
||||
self.current_marker_spec = saved
|
||||
self.set_title(self.scrollback_search_saved_title)
|
||||
self.scrollback_search_saved_title = None
|
||||
if self.scrollback_search_mode:
|
||||
get_boss().mappings.pop_keyboard_mode_if_is(self.scrollback_search_mode)
|
||||
self.scrollback_search_mode = ''
|
||||
|
||||
@ac('sc', 'Jump to the next match of the in-place scrollback search')
|
||||
def scrollback_search_next(self) -> bool | None:
|
||||
return self._scrollback_search_step(1)
|
||||
|
||||
@ac('sc', 'Jump to the previous match of the in-place scrollback search')
|
||||
def scrollback_search_prev(self) -> bool | None:
|
||||
return self._scrollback_search_step(-1)
|
||||
|
||||
def _scrollback_search_step(self, step: int) -> bool | None:
|
||||
search = self.scrollback_search
|
||||
if search is None:
|
||||
return None
|
||||
if not self.screen.is_main_linebuf():
|
||||
return True
|
||||
self._goto_scrollback_match(search.index + step)
|
||||
return None
|
||||
|
||||
def _goto_scrollback_match(self, index: int) -> None:
|
||||
from .scrollback_search import scroll_offset_for
|
||||
|
||||
search = self.scrollback_search
|
||||
if search is None or not search.matches:
|
||||
return
|
||||
search.index = index % len(search.matches)
|
||||
match = search.matches[search.index]
|
||||
self.set_title(f'[{search.index + 1}/{len(search.matches)}] {search.query.text}')
|
||||
self.screen.scroll_to_absolute(scroll_offset_for(match, search.total_lines, self.screen.lines))
|
||||
|
||||
def _push_scrollback_search_mode(self) -> None:
|
||||
from .fast_data_types import GLFW_FKEY_ESCAPE, GLFW_MOD_SHIFT
|
||||
from .options.utils import KeyDefinition, KeyboardMode, SingleKey
|
||||
|
||||
km = KeyboardMode('__scrollback_search__')
|
||||
km.on_unknown = 'passthrough'
|
||||
km.on_action = 'keep'
|
||||
next_match = KeyDefinition(definition='scrollback_search_next')
|
||||
prev_match = KeyDefinition(definition='scrollback_search_prev')
|
||||
km.keymap[SingleKey(key=ord('n'))].append(next_match)
|
||||
km.keymap[SingleKey(mods=GLFW_MOD_SHIFT, key=ord('n'))].append(prev_match)
|
||||
km.keymap[SingleKey(mods=GLFW_MOD_SHIFT, key=ord('N'))].append(prev_match)
|
||||
km.keymap[SingleKey(key=GLFW_FKEY_ESCAPE)].append(KeyDefinition(definition='clear_scrollback_search'))
|
||||
self.scrollback_search_mode = km.name
|
||||
get_boss().mappings._push_keyboard_mode(km)
|
||||
|
||||
def _on_focus_change_clear_scrollback_search(self, window: 'Window', focused: bool) -> None:
|
||||
# The n/N bindings live in a temporary keyboard mode, so the search must
|
||||
# end when this window stops being the one receiving keys.
|
||||
if not focused and self.scrollback_search is not None:
|
||||
self.clear_scrollback_search()
|
||||
|
||||
def show_cmd_output(self, which: CommandOutput, title: str = 'Command output', as_ansi: bool = True, add_wrap_markers: bool = True) -> None:
|
||||
text = self.cmd_output(which, as_ansi=as_ansi, add_wrap_markers=add_wrap_markers)
|
||||
text = text.replace('\r\n', '\n').replace('\r', '\n')
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import re
|
||||
import time
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
from kitty.scrollback_search import (
|
||||
InvalidQuery,
|
||||
Match,
|
||||
compile_query,
|
||||
find_matches,
|
||||
parse_query,
|
||||
scroll_offset_for,
|
||||
)
|
||||
|
||||
|
||||
class TestScrollbackSearch(BaseTest):
|
||||
def test_parse_query(self):
|
||||
q = parse_query('needle')
|
||||
self.ae((q.text, q.case_sensitive, q.is_regex), ('needle', False, False))
|
||||
self.assertTrue(compile_query(q).flags & re.IGNORECASE)
|
||||
|
||||
q = parse_query(' padded ')
|
||||
self.ae(q.text, 'padded')
|
||||
|
||||
def test_parse_query_modifiers(self):
|
||||
q = parse_query('\\c Needle')
|
||||
self.ae((q.text, q.case_sensitive, q.is_regex), ('Needle', True, False))
|
||||
self.ae(compile_query(q).flags & re.IGNORECASE, 0)
|
||||
|
||||
q = parse_query('\\r a.c')
|
||||
self.ae((q.text, q.case_sensitive, q.is_regex), ('a.c', False, True))
|
||||
|
||||
for raw in ('\\r\\c a+b', '\\c\\r a+b', '\\C\\R a+b'):
|
||||
q = parse_query(raw)
|
||||
self.ae((q.text, q.case_sensitive, q.is_regex), ('a+b', True, True), raw)
|
||||
|
||||
with self.assertRaises(InvalidQuery):
|
||||
parse_query('')
|
||||
with self.assertRaises(InvalidQuery):
|
||||
parse_query(' ')
|
||||
with self.assertRaises(InvalidQuery):
|
||||
parse_query('\\c')
|
||||
with self.assertRaises(InvalidQuery):
|
||||
compile_query(parse_query('\\r ('))
|
||||
|
||||
def test_find_matches_plain(self):
|
||||
lines = ['needle at start', 'Needle again', 'nothing', 'a needle here']
|
||||
matches = find_matches(lines, parse_query('needle'))
|
||||
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 0, 6), (1, 0, 6), (3, 2, 8)])
|
||||
|
||||
matches = find_matches(lines, parse_query('\\c Needle'))
|
||||
self.ae([(m.line, m.start, m.end) for m in matches], [(1, 0, 6)])
|
||||
|
||||
# Regex metacharacters are literal in a plain query
|
||||
self.ae(find_matches(['a+b', 'aab'], parse_query('a+b')), [Match(0, 0, 3)])
|
||||
|
||||
def test_find_matches_regex(self):
|
||||
matches = find_matches(['abc abc', 'nothing here'], parse_query('\\r a.c'))
|
||||
self.ae([(m.line, m.start, m.end) for m in matches], [(0, 0, 3), (0, 4, 7)])
|
||||
|
||||
# Empty matches are skipped and do not loop forever
|
||||
self.ae(find_matches(['abc'], parse_query('\\r x*')), [])
|
||||
|
||||
def test_scroll_offset(self):
|
||||
self.ae(scroll_offset_for(Match(0, 0, 1), 100, 10), 90)
|
||||
self.ae(scroll_offset_for(Match(50, 0, 1), 100, 10), 43)
|
||||
self.ae(scroll_offset_for(Match(99, 0, 1), 100, 10), 0)
|
||||
# No scrollback: the visible screen is always shown as is
|
||||
self.ae(scroll_offset_for(Match(3, 0, 1), 5, 5), 0)
|
||||
|
||||
def test_performance_on_large_scrollback(self):
|
||||
lines = [f'line {i} with some ordinary text' for i in range(10_000)]
|
||||
for i in range(0, 10_000, 10):
|
||||
lines[i] = 'needle ' + lines[i]
|
||||
query = parse_query('needle')
|
||||
start = time.monotonic()
|
||||
matches = find_matches(lines, query)
|
||||
elapsed = time.monotonic() - start
|
||||
self.ae(len(matches), 1000)
|
||||
self.assertLess(elapsed, 0.05, f'searching 10 000 lines took {elapsed * 1000:.1f} ms')
|
||||
Reference in new issue
Block a user