Added terminal search function, case (in)sensetive match, regex
Moorly CI / windows-build (push) Successful in 3m40s
Moorly CI / linux-build (push) Successful in 4m17s

This commit is contained in:
Squid committed 2026-11-17 22:33:51 +01:00
1 parent f6a2f65cd4
commit f3ba9e1aeb
4 files changed
+554 -10

No files matched your search

Generated
+39
View File
@@ -74,6 +74,15 @@ dependencies = [
"zerocopy", "zerocopy",
] ]
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "android-activity" name = "android-activity"
version = "0.6.1" version = "0.6.1"
@@ -2590,6 +2599,7 @@ dependencies = [
"nix", "nix",
"num-format", "num-format",
"png", "png",
"regex",
"russh", "russh",
"russh-sftp", "russh-sftp",
"serde", "serde",
@@ -3666,6 +3676,35 @@ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
] ]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]] [[package]]
name = "renderdoc-sys" name = "renderdoc-sys"
version = "1.1.0" version = "1.1.0"
+1
View File
@@ -9,6 +9,7 @@ iced_aw = { path = "vendor/iced_aw", default-features = false, features = ["colo
instance-handoff = "=0.1.0-alpha.2" instance-handoff = "=0.1.0-alpha.2"
num-format = "0.4" num-format = "0.4"
png = "0.18" png = "0.18"
regex = "1"
russh = "0.65.0" russh = "0.65.0"
russh-sftp = "3.0.1" russh-sftp = "3.0.1"
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }
+398 -10
View File
@@ -429,6 +429,33 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
.with(terminal_target) .with(terminal_target)
.filter_map(|(target, text)| Some(Message::TerminalText { id: target?, text })); .filter_map(|(target, text)| Some(Message::TerminalText { id: target?, text }));
let search_target = terminal_search_target(state);
let search_keys = keyboard::listen()
.with(search_target)
.filter_map(|(target, event)| {
let keyboard::Event::KeyPressed {
key,
modifiers,
repeat: false,
..
} = event
else {
return None;
};
let target = target?;
match key {
keyboard::Key::Named(keyboard::key::Named::Escape) => {
Some(Message::CloseTerminalSearch(target))
}
keyboard::Key::Named(keyboard::key::Named::Enter) if modifiers.shift() => {
Some(Message::TerminalSearchPrev(target))
}
_ => None,
}
});
let modifiers = keyboard::listen().filter_map(|event| match event { let modifiers = keyboard::listen().filter_map(|event| match event {
keyboard::Event::ModifiersChanged(modifiers) => Some(Message::ModifiersChanged(modifiers)), keyboard::Event::ModifiersChanged(modifiers) => Some(Message::ModifiersChanged(modifiers)),
_ => None, _ => None,
@@ -440,6 +467,7 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
modifiers, modifiers,
terminal_keys, terminal_keys,
terminal_text, terminal_text,
search_keys,
hotkeys::subscription().map(Message::Hotkey), hotkeys::subscription().map(Message::Hotkey),
tray::subscription().map(Message::Tray), tray::subscription().map(Message::Tray),
single_instance::subscription(), single_instance::subscription(),
@@ -1811,6 +1839,32 @@ struct TabDrag {
detach: bool, detach: bool,
} }
/// Search state for a terminal's scrollback.
#[derive(Debug)]
struct TerminalSearch {
open: bool,
query: String,
case_sensitive: bool,
regex: bool,
matches: Vec<terminal::SearchMatch>,
current: usize,
error: Option<String>,
}
impl Default for TerminalSearch {
fn default() -> Self {
Self {
open: false,
query: String::new(),
case_sensitive: false,
regex: false,
matches: Vec::new(),
current: 0,
error: None,
}
}
}
/// A local terminal tab. The profile is kept so Reconnect/Restart can start a /// A local terminal tab. The profile is kept so Reconnect/Restart can start a
/// fresh shell with the same settings after the old process ends. /// fresh shell with the same settings after the old process ends.
struct TerminalSession { struct TerminalSession {
@@ -1821,6 +1875,7 @@ struct TerminalSession {
exit: Option<terminal::ExitInfo>, exit: Option<terminal::ExitInfo>,
/// Mouse selection as anchor and focus cells in screen coordinates. /// Mouse selection as anchor and focus cells in screen coordinates.
selection: Option<TerminalSelection>, selection: Option<TerminalSelection>,
search: TerminalSearch,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -2085,7 +2140,32 @@ fn terminal_input_target(state: &Moorly) -> Option<u32> {
} }
match window_state.active_tab { match window_state.active_tab {
Some(Tab::Terminal(id)) if state.terminal_sessions.contains_key(&id) => Some(id), Some(Tab::Terminal(id))
if state
.terminal_sessions
.get(&id)
.is_some_and(|terminal| !terminal.search.open) =>
{
Some(id)
}
_ => None,
}
}
/// The terminal whose search bar is open, if any.
fn terminal_search_target(state: &Moorly) -> Option<u32> {
let window = state.focused_window.or(state.main_window)?;
let window_state = state.windows.get(&window)?;
match window_state.active_tab {
Some(Tab::Terminal(id))
if state
.terminal_sessions
.get(&id)
.is_some_and(|terminal| terminal.search.open) =>
{
Some(id)
}
_ => None, _ => None,
} }
} }
@@ -5315,6 +5395,13 @@ enum Message {
id: u32, id: u32,
text: String, text: String,
}, },
ToggleTerminalSearch(u32),
TerminalSearchChanged(u32, String),
TerminalSearchCaseToggled(u32),
TerminalSearchRegexToggled(u32),
TerminalSearchNext(u32),
TerminalSearchPrev(u32),
CloseTerminalSearch(u32),
RestartTerminal(u32), RestartTerminal(u32),
ToggleTabsSubmenu(window::Id), ToggleTabsSubmenu(window::Id),
AddTab(window::Id), AddTab(window::Id),
@@ -5748,6 +5835,10 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
text, text,
modifiers, modifiers,
} => { } => {
if terminal_search_shortcut(&key, modifiers) {
return update(state, Message::ToggleTerminalSearch(id));
}
match terminal_clipboard_action( match terminal_clipboard_action(
&key, &key,
modifiers, modifiers,
@@ -5780,6 +5871,31 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
let _ = terminal.session.write(text.as_bytes()); let _ = terminal.session.write(text.as_bytes());
} }
} }
Message::ToggleTerminalSearch(id) => return toggle_terminal_search(state, id),
Message::TerminalSearchChanged(id, query) => {
if let Some(terminal) = state.terminal_sessions.get_mut(&id) {
terminal.search.query = query;
}
refresh_terminal_search(state, id);
}
Message::TerminalSearchCaseToggled(id) => {
if let Some(terminal) = state.terminal_sessions.get_mut(&id) {
terminal.search.case_sensitive = !terminal.search.case_sensitive;
}
refresh_terminal_search(state, id);
}
Message::TerminalSearchRegexToggled(id) => {
if let Some(terminal) = state.terminal_sessions.get_mut(&id) {
terminal.search.regex = !terminal.search.regex;
}
refresh_terminal_search(state, id);
}
Message::TerminalSearchNext(id) => step_terminal_search(state, id, true),
Message::TerminalSearchPrev(id) => step_terminal_search(state, id, false),
Message::CloseTerminalSearch(id) => {
close_terminal_search(state, id);
return Task::none();
}
Message::RestartTerminal(id) => { Message::RestartTerminal(id) => {
restart_terminal(state, id); restart_terminal(state, id);
} }
@@ -11752,6 +11868,8 @@ fn tab_scroll_limits(state: &Moorly, window: window::Id) -> (bool, bool) {
} }
const TERMINAL_FOOTER_HEIGHT: f32 = 38.0; const TERMINAL_FOOTER_HEIGHT: f32 = 38.0;
const TERMINAL_SEARCH_HEIGHT: f32 = 38.0;
const TERMINAL_SEARCH_INPUT: &str = "terminal-search-input";
/// Local profile kinds that can start a shell on this platform. PowerShell is /// Local profile kinds that can start a shell on this platform. PowerShell is
/// resolved at runtime so profiles stay portable across operating systems; SSH /// resolved at runtime so profiles stay portable across operating systems; SSH
@@ -11829,7 +11947,7 @@ fn start_terminal_profile(
.get(&window) .get(&window)
.map(|window_state| window_state.size) .map(|window_state| window_state.size)
.unwrap_or(Size::new(900.0, 600.0)); .unwrap_or(Size::new(900.0, 600.0));
let (rows, cols) = terminal_grid(state, size, false); let (rows, cols) = terminal_grid(state, size, false, false);
let session = match terminal::Session::spawn_with_scrollback( let session = match terminal::Session::spawn_with_scrollback(
&start_dir, &start_dir,
@@ -11865,6 +11983,7 @@ fn start_terminal_profile(
title, title,
exit: None, exit: None,
selection: None, selection: None,
search: TerminalSearch::default(),
}, },
); );
@@ -11891,16 +12010,142 @@ fn start_terminal_profile(
scroll_tabs_to_end(state, window) scroll_tabs_to_end(state, window)
} }
fn terminal_area(size: Size, ended: bool) -> Size { /// Ctrl+Shift+F opens the scrollback search for the focused terminal.
fn terminal_search_shortcut(key: &keyboard::Key, modifiers: keyboard::Modifiers) -> bool {
matches!(key, keyboard::Key::Character(key) if key.eq_ignore_ascii_case("f"))
&& modifiers.control()
&& modifiers.shift()
}
fn toggle_terminal_search(state: &mut Moorly, id: u32) -> Task<Message> {
let open = state
.terminal_sessions
.get(&id)
.is_some_and(|terminal| terminal.search.open);
if open {
close_terminal_search(state, id);
return Task::none();
}
let Some(terminal) = state.terminal_sessions.get_mut(&id) else {
return Task::none();
};
terminal.search.open = true;
terminal.search.error = None;
refresh_terminal_search(state, id);
iced::widget::operation::focus(Id::new(TERMINAL_SEARCH_INPUT))
}
fn close_terminal_search(state: &mut Moorly, id: u32) {
if let Some(terminal) = state.terminal_sessions.get_mut(&id) {
terminal.search.open = false;
terminal.search.matches.clear();
terminal.search.current = 0;
terminal.search.error = None;
terminal.session.screen_mut().set_scrollback(0);
}
}
fn refresh_terminal_search(state: &mut Moorly, id: u32) {
let Some(terminal) = state.terminal_sessions.get_mut(&id) else {
return;
};
let query = terminal.search.query.clone();
let case_sensitive = terminal.search.case_sensitive;
let regex = terminal.search.regex;
match terminal.session.search(&query, case_sensitive, regex) {
Ok(matches) => {
terminal.search.current = matches.len().saturating_sub(1);
terminal.search.matches = matches;
terminal.search.error = None;
}
Err(_) => {
terminal.search.matches.clear();
terminal.search.current = 0;
terminal.search.error = Some("Invalid regex".to_owned());
}
}
jump_to_terminal_match(terminal);
}
fn step_terminal_search(state: &mut Moorly, id: u32, forward: bool) {
if state
.terminal_sessions
.get(&id)
.is_none_or(|terminal| terminal.search.query.is_empty())
{
return;
}
let empty = state
.terminal_sessions
.get(&id)
.is_none_or(|terminal| terminal.search.matches.is_empty());
if empty {
refresh_terminal_search(state, id);
return;
}
let Some(terminal) = state.terminal_sessions.get_mut(&id) else {
return;
};
let count = terminal.search.matches.len();
if count == 0 {
return;
}
terminal.search.current = if forward {
(terminal.search.current + 1) % count
} else {
(terminal.search.current + count - 1) % count
};
jump_to_terminal_match(terminal);
}
fn jump_to_terminal_match(terminal: &mut TerminalSession) {
let Some(found) = terminal
.search
.matches
.get(terminal.search.current)
.copied()
else {
return;
};
let (rows, _) = terminal.session.screen().size();
let scrollback = terminal.session.screen().scrollback_len();
let total = scrollback + usize::from(rows.get());
let line = total.saturating_sub(1 + found.from_bottom);
let offset = scrollback.saturating_sub(line);
terminal.session.screen_mut().set_scrollback(offset);
}
fn terminal_area(size: Size, ended: bool, searching: bool) -> Size {
let footer = if ended { TERMINAL_FOOTER_HEIGHT } else { 0.0 }; let footer = if ended { TERMINAL_FOOTER_HEIGHT } else { 0.0 };
let search = if searching {
TERMINAL_SEARCH_HEIGHT
} else {
0.0
};
Size::new( Size::new(
size.width.max(1.0), size.width.max(1.0),
(size.height - MENUBAR_HEIGHT - footer).max(1.0), (size.height - MENUBAR_HEIGHT - footer - search).max(1.0),
) )
} }
fn terminal_grid(state: &Moorly, size: Size, ended: bool) -> (u16, u16) { fn terminal_grid(state: &Moorly, size: Size, ended: bool, searching: bool) -> (u16, u16) {
terminal::grid_size(terminal_area(size, ended), state.typography.terminal.size) terminal::grid_size(
terminal_area(size, ended, searching),
state.typography.terminal.size,
)
} }
fn window_for_terminal(state: &Moorly, id: u32) -> Option<window::Id> { fn window_for_terminal(state: &Moorly, id: u32) -> Option<window::Id> {
@@ -11937,8 +12182,10 @@ fn terminal_tick(state: &mut Moorly) -> Task<Message> {
} }
if let Some(size) = size { if let Some(size) = size {
let (rows, cols) = let (rows, cols) = terminal::grid_size(
terminal::grid_size(terminal_area(size, terminal.exit.is_some()), font_size); terminal_area(size, terminal.exit.is_some(), terminal.search.open),
font_size,
);
let (current_rows, current_cols) = terminal.session.screen().size(); let (current_rows, current_cols) = terminal.session.screen().size();
if (rows, cols) != (current_rows.get(), current_cols.get()) { if (rows, cols) != (current_rows.get(), current_cols.get()) {
@@ -12035,7 +12282,7 @@ fn restart_terminal(state: &mut Moorly, id: u32) {
); );
} }
let (rows, cols) = terminal_grid(state, size, false); let (rows, cols) = terminal_grid(state, size, false, false);
let Some(shell) = local_shell(profile.kind) else { let Some(shell) = local_shell(profile.kind) else {
return; return;
}; };
@@ -12061,6 +12308,7 @@ fn restart_terminal(state: &mut Moorly, id: u32) {
terminal.start_dir = start_dir; terminal.start_dir = start_dir;
terminal.exit = None; terminal.exit = None;
terminal.selection = None; terminal.selection = None;
terminal.search = TerminalSearch::default();
} }
} }
Err(error) => { Err(error) => {
@@ -12109,6 +12357,8 @@ struct TerminalCanvas<'a> {
id: u32, id: u32,
screen: &'a vt100::Screen, screen: &'a vt100::Screen,
selection: Option<TerminalSelection>, selection: Option<TerminalSelection>,
search: &'a [terminal::SearchMatch],
search_current: usize,
theme: terminal::Theme, theme: terminal::Theme,
font: Font, font: Font,
font_size: f32, font_size: f32,
@@ -12274,6 +12524,33 @@ impl canvas::Program<Message> for TerminalCanvas<'_> {
} }
} }
if !self.search.is_empty() {
let scrollback = self.screen.scrollback_len();
let top = scrollback.saturating_sub(self.screen.scrollback());
let total = scrollback + usize::from(rows.get());
for (index, hit) in self.search.iter().enumerate() {
let line = total.saturating_sub(1 + hit.from_bottom);
if line < top || line >= top + usize::from(rows.get()) {
continue;
}
let row = (line - top) as f32;
let highlight = if index == self.search_current {
Color::from_rgba(1.0, 0.72, 0.1, 0.55)
} else {
Color::from_rgba(1.0, 0.85, 0.2, 0.3)
};
frame.fill_rectangle(
Point::new(hit.start as f32 * cell.width, row * cell.height),
Size::new(f32::from(hit.len.max(1)) * cell.width, cell.height),
highlight,
);
}
}
if let Some(selection) = self.selection { if let Some(selection) = self.selection {
let (start, end) = selection.ordered(); let (start, end) = selection.ordered();
@@ -12297,7 +12574,7 @@ impl canvas::Program<Message> for TerminalCanvas<'_> {
} }
} }
if !self.screen.hide_cursor() { if self.screen.scrollback() == 0 && !self.screen.hide_cursor() {
let (row, col) = self.screen.cursor_position(); let (row, col) = self.screen.cursor_position();
let position = Point::new(col as f32 * cell.width, row as f32 * cell.height); let position = Point::new(col as f32 * cell.width, row as f32 * cell.height);
frame.fill_rectangle(position, cell, self.theme.cursor); frame.fill_rectangle(position, cell, self.theme.cursor);
@@ -12589,6 +12866,8 @@ fn terminal_page<'a>(state: &'a Moorly, window: window::Id, id: u32) -> Element<
id, id,
screen: terminal_session.session.screen(), screen: terminal_session.session.screen(),
selection: terminal_session.selection, selection: terminal_session.selection,
search: &terminal_session.search.matches,
search_current: terminal_session.search.current,
theme, theme,
font: typography_font(&state.typography.terminal), font: typography_font(&state.typography.terminal),
font_size: state.typography.terminal.size, font_size: state.typography.terminal.size,
@@ -12647,9 +12926,90 @@ fn terminal_page<'a>(state: &'a Moorly, window: window::Id, id: u32) -> Element<
content = content.push(footer); content = content.push(footer);
} }
if terminal_session.search.open {
content = content.push(terminal_search_bar(&terminal_session.search, id));
}
content.into() content.into()
} }
/// Bottom search bar for the terminal scrollback.
fn terminal_search_bar(search: &TerminalSearch, id: u32) -> Element<'_, Message> {
let theme = terminal::Theme::DARK;
let has_matches = !search.matches.is_empty();
let count = if let Some(error) = &search.error {
error.clone()
} else if search.query.is_empty() {
String::new()
} else if search.matches.is_empty() {
"0/0".to_owned()
} else {
format!("{}/{}", search.current + 1, search.matches.len())
};
let bar = row![
text_input("Search scrollback", &search.query)
.id(Id::new(TERMINAL_SEARCH_INPUT))
.on_input(move |query| Message::TerminalSearchChanged(id, query))
.on_submit(Message::TerminalSearchNext(id))
.padding(4)
.style(theme::filter_field)
.width(Length::Fill),
text(count).size(11).color(if search.error.is_some() {
theme::DANGER
} else {
theme.foreground
}),
button("Aa")
.on_press(Message::TerminalSearchCaseToggled(id))
.padding([2, 6])
.style(if search.case_sensitive {
theme::selected_option
} else {
theme::outlined_option
}),
button(".*")
.on_press(Message::TerminalSearchRegexToggled(id))
.padding([2, 6])
.style(if search.regex {
theme::selected_option
} else {
theme::outlined_option
}),
button("↑")
.on_press_maybe(has_matches.then_some(Message::TerminalSearchPrev(id)))
.padding([2, 6])
.style(theme::outlined_option),
button("↓")
.on_press_maybe(has_matches.then_some(Message::TerminalSearchNext(id)))
.padding([2, 6])
.style(theme::outlined_option),
button("×")
.on_press(Message::CloseTerminalSearch(id))
.padding([2, 8])
.style(theme::outlined_option),
]
.spacing(6)
.align_y(Alignment::Center);
container(bar)
.width(Length::Fill)
.height(TERMINAL_SEARCH_HEIGHT)
.padding([0, 10])
.align_y(Alignment::Center)
.style(move |_| container::Style {
background: Some(theme.background.into()),
text_color: Some(theme.foreground),
border: Border {
color: theme.foreground.scale_alpha(0.2),
width: 1.0,
radius: 0.0.into(),
},
..container::Style::default()
})
.into()
}
fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> { fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> {
let Some(window_state) = state.windows.get(&window) else { let Some(window_state) = state.windows.get(&window) else {
return container(space::horizontal()) return container(space::horizontal())
@@ -15984,6 +16344,7 @@ start_path = "/tmp"
title: "Shell".to_owned(), title: "Shell".to_owned(),
exit: None, exit: None,
selection: None, selection: None,
search: super::TerminalSearch::default(),
}, },
); );
state state
@@ -16112,6 +16473,32 @@ start_path = "/tmp"
); );
} }
#[test]
fn terminal_search_bar_closes() {
let (mut state, window, id) = terminal_for_session_end(super::SessionEnd::Keep);
state.terminal_sessions.get_mut(&id).unwrap().search.open = true;
let mut ui = iced_test::simulator(super::terminal_page(&state, window, id));
ui.click("×").unwrap();
assert!(
ui.into_messages()
.any(|message| matches!(message, Message::CloseTerminalSearch(tab) if tab == id))
);
}
#[test]
fn ctrl_shift_f_opens_terminal_search() {
assert!(super::terminal_search_shortcut(
&keyboard::Key::Character("f".into()),
keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT
));
assert!(!super::terminal_search_shortcut(
&keyboard::Key::Character("f".into()),
keyboard::Modifiers::CTRL
));
}
#[test] #[test]
fn running_a_terminal_profile_opens_and_closes_a_session() { fn running_a_terminal_profile_opens_and_closes_a_session() {
let mut state = state(); let mut state = state();
@@ -16165,6 +16552,7 @@ start_path = "/tmp"
title: "Shell".to_owned(), title: "Shell".to_owned(),
exit: None, exit: None,
selection: None, selection: None,
search: super::TerminalSearch::default(),
}, },
); );
state state
+116
View File
@@ -96,6 +96,17 @@ pub const DEFAULT_SCROLLBACK_SIZE: usize = 10_000;
/// Upper bound for the configurable scrollback size. /// Upper bound for the configurable scrollback size.
pub const MAX_SCROLLBACK_SIZE: usize = 1_000_000; pub const MAX_SCROLLBACK_SIZE: usize = 1_000_000;
/// One scrollback/visible-screen search hit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SearchMatch {
/// Rows between this hit and the newest row.
pub from_bottom: usize,
/// Starting cell column.
pub start: u16,
/// Width in cells.
pub len: u16,
}
/// Parsed terminal screen. This has no knowledge of where the bytes came from. /// Parsed terminal screen. This has no knowledge of where the bytes came from.
pub struct Emulator { pub struct Emulator {
parser: vt100::Parser, parser: vt100::Parser,
@@ -124,6 +135,83 @@ impl Emulator {
pub fn screen(&self) -> &vt100::Screen { pub fn screen(&self) -> &vt100::Screen {
self.parser.screen() self.parser.screen()
} }
pub fn screen_mut(&mut self) -> &mut vt100::Screen {
self.parser.screen_mut()
}
/// Finds `query` in the full scrollback and the visible screen.
///
/// Matches are stored relative to the newest row so new output does not
/// invalidate them.
pub fn search(
&mut self,
query: &str,
case_sensitive: bool,
regex: bool,
) -> Result<Vec<SearchMatch>, String> {
if query.is_empty() {
return Ok(Vec::new());
}
let pattern = if regex {
query.to_owned()
} else {
regex::escape(query)
};
let pattern = regex::RegexBuilder::new(&pattern)
.case_insensitive(!case_sensitive)
.build()
.map_err(|error| error.to_string())?;
let screen = self.parser.screen_mut();
let (rows, cols) = screen.size();
let rows = usize::from(rows.get());
let scrollback = screen.scrollback_len();
let saved = screen.scrollback();
let total = scrollback + rows;
let mut matches = Vec::new();
let collect = |text: &str, from_bottom: usize, matches: &mut Vec<SearchMatch>| {
for found in pattern.find_iter(text) {
let start = text[..found.start()].chars().count();
let len = found.as_str().chars().count();
if len == 0 {
continue;
}
matches.push(SearchMatch {
from_bottom,
start: start.min(usize::from(u16::MAX)) as u16,
len: len.min(usize::from(u16::MAX)) as u16,
});
}
};
for line in 0..scrollback {
screen.set_scrollback(scrollback - line);
if let Some(text) = screen.rows(0, cols.get()).next() {
collect(&text, total - 1 - line, &mut matches);
}
}
screen.set_scrollback(0);
for (row, text) in screen.rows(0, cols.get()).take(rows).enumerate() {
collect(&text, total - 1 - (scrollback + row), &mut matches);
}
screen.set_scrollback(saved);
matches.sort_by(|a, b| {
a.from_bottom
.cmp(&b.from_bottom)
.then(a.start.cmp(&b.start))
});
Ok(matches)
}
} }
/// How a process ended. /// How a process ended.
@@ -304,6 +392,19 @@ impl Session {
self.emulator.screen() self.emulator.screen()
} }
pub fn screen_mut(&mut self) -> &mut vt100::Screen {
self.emulator.screen_mut()
}
pub fn search(
&mut self,
query: &str,
case_sensitive: bool,
regex: bool,
) -> Result<Vec<SearchMatch>, String> {
self.emulator.search(query, case_sensitive, regex)
}
#[cfg(all(test, unix))] #[cfg(all(test, unix))]
fn pid(&self) -> i32 { fn pid(&self) -> i32 {
self.pty.pid() self.pty.pid()
@@ -1389,6 +1490,21 @@ mod tests {
assert!(resized, "the shell did not observe the new window size"); assert!(resized, "the shell did not observe the new window size");
} }
#[test]
fn search_scans_scrollback_and_keeps_the_offset() {
let mut emulator = Emulator::new(2, 20, 100);
emulator.process(b"alpha\r\nbravo\r\ncharlie\r\n");
emulator.screen_mut().set_scrollback(1);
let matches = emulator.search("alpha", true, false).unwrap();
assert!(!matches.is_empty());
let matches = emulator.search("^char", false, true).unwrap();
assert!(!matches.is_empty());
assert_eq!(emulator.screen().scrollback(), 1);
}
#[test] #[test]
fn emulator_uses_the_configured_scrollback() { fn emulator_uses_the_configured_scrollback() {
let emulator = Emulator::new(24, 80, 12_345); let emulator = Emulator::new(24, 80, 12_345);