use anyhow::{Context, Result};
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span, Text},
widgets::{Block, Borders, Paragraph, Widget, Wrap},
};
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use crate::highlight::{
HiSpan, LangKind, LangRegistry, compute_line_starts, decode_semantic_tokens, lang_for_extension,
};
use crate::widgets::scrollbar;
const MAX_FILE_BYTES: u64 = 50 * 1024 * 1024;
const MAX_IMAGE_BYTES: u64 = 25 * 1024 * 1024;
const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "bmp", "webp"];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageView {
pub bytes: Vec<u8>,
pub format_label: String,
pub pixel_w: u32,
pub pixel_h: u32,
pub byte_size: u64,
pub generation: u64,
pub pdf: Option<PdfState>,
}
fn next_image_generation() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PdfState {
pub source_path: PathBuf,
pub current_page: u32,
pub page_count: Option<u32>,
pub backend: crate::pdf::PdfBackend,
pub source_byte_size: u64,
pub links: Option<crate::pdf::PageLinks>,
}
fn canvas_bg(host_is_iterm2: bool, theme: crate::theme::Theme) -> Color {
if host_is_iterm2 {
Color::Reset
} else {
theme.editor_bg()
}
}
fn image_canvas_bg(
protocol: crate::iterm2_inline::InlineImageProtocol,
theme: crate::theme::Theme,
) -> Color {
use crate::iterm2_inline::InlineImageProtocol;
match protocol {
InlineImageProtocol::ITerm2 | InlineImageProtocol::Kitty => Color::Reset,
InlineImageProtocol::Sixel | InlineImageProtocol::None => theme.editor_bg(),
}
}
fn render_image_placeholder(
image: &ImageView,
path: Option<&Path>,
inner: Rect,
buf: &mut Buffer,
bg: Color,
) {
let bg_style = Style::default().bg(bg);
for y in inner.y..inner.y + inner.height {
for x in inner.x..inner.x + inner.width {
buf[(x, y)].set_style(bg_style);
buf[(x, y)].set_symbol(" ");
}
}
let name = path
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("(unnamed image)"));
let header = if let Some(pdf) = image.pdf.as_ref() {
let page_label = match pdf.page_count {
Some(total) => format!("page {} / {}", pdf.current_page, total),
None => format!("page {}", pdf.current_page),
};
format!(
" {} · {} · {}×{} · {} · PDF (← / → to flip) ",
name,
page_label,
image.pixel_w,
image.pixel_h,
format_bytes_human(pdf.source_byte_size),
)
} else {
format!(
" {} · {}×{} · {} · {} ",
name,
image.pixel_w,
image.pixel_h,
format_bytes_human(image.byte_size),
image.format_label,
)
};
buf.set_string(
inner.x,
inner.y,
&header,
Style::default()
.fg(Color::White)
.bg(Color::Rgb(0x09, 0x4d, 0x77))
.add_modifier(Modifier::BOLD),
);
}
fn render_hex(
view: &mut crate::hex::HexView,
path: Option<&Path>,
inner: Rect,
buf: &mut Buffer,
bg: Color,
theme: crate::theme::Theme,
) {
let bg_style = Style::default().bg(bg);
for y in inner.y..inner.y + inner.height {
for x in inner.x..inner.x + inner.width {
buf[(x, y)].set_style(bg_style);
buf[(x, y)].set_symbol(" ");
}
}
view.layout = crate::hex::HexLayout::default();
if inner.height == 0 || inner.width == 0 {
return;
}
let offw = view.offset_digits() as u16;
let need8 = 1 + offw + 2 + (8 * 3 - 1) + 2 + 8;
let name = path
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("(unnamed)"));
let header = format!(" {} · HEX · {} bytes ", name, view.file_len);
buf.set_stringn(
inner.x,
inner.y,
&header,
inner.width as usize,
Style::default()
.fg(Color::White)
.bg(Color::Rgb(0x09, 0x4d, 0x77))
.add_modifier(Modifier::BOLD),
);
if inner.height < 3 || inner.width < need8 {
return;
}
let need16 = 1 + offw + 2 + (16 * 3 - 1) + 1 + 2 + 16;
let bpr: u64 = if inner.width >= need16 { 16 } else { 8 };
view.bytes_per_row = bpr;
let data_top = inner.y + 1;
let data_rows = inner.height - 2; view.scroll_by(0, data_rows as usize);
let hex_x = inner.x + 1 + offw + 2;
let mid_gap: u16 = if bpr == 16 { 1 } else { 0 };
let ascii_x = hex_x + (bpr as u16) * 3 - 1 + mid_gap + 2;
view.layout = crate::hex::HexLayout {
data_top,
data_rows,
hex_x,
ascii_x,
};
let sel = view.selection();
let dim = Style::default().fg(Color::DarkGray).bg(bg);
for r in 0..data_rows {
let row = view.top_row + r as u64;
if row >= view.total_rows() {
break;
}
let y = data_top + r;
let base = row * bpr;
buf.set_string(
inner.x + 1,
y,
format!("{base:0w$X}", w = offw as usize),
dim,
);
for i in 0..bpr {
let off = base + i;
if off >= view.file_len {
break;
}
let x = hex_x + (i as u16) * 3 + if i >= 8 { mid_gap } else { 0 };
let ax = ascii_x + i as u16;
if ax >= inner.x + inner.width || x + 1 >= inner.x + inner.width {
break;
}
let (hex_s, ascii_ch, byte_dim) = match view.byte(off) {
Some(v) => (
format!("{v:02X}"),
if (0x20..0x7f).contains(&v) {
(v as char).to_string()
} else {
String::from("·")
},
v == 0,
),
None => (String::from("··"), String::from("·"), true),
};
let selected = sel.map(|(a, b)| off >= a && off < b).unwrap_or(false);
let is_cursor = off == view.cursor;
let style = if is_cursor {
Style::default().fg(Color::Black).bg(theme.accent())
} else if selected {
Style::default().fg(Color::White).bg(theme.selection())
} else if byte_dim {
dim
} else {
Style::default().fg(Color::Gray).bg(bg)
};
buf.set_string(x, y, &hex_s, style);
buf.set_string(ax, y, &ascii_ch, style);
}
}
let status = format!(" {} ", view.status_line());
buf.set_stringn(
inner.x,
inner.y + inner.height - 1,
&status,
inner.width as usize,
Style::default()
.fg(Color::Gray)
.bg(Color::Rgb(0x07, 0x33, 0x55)),
);
}
fn render_sheet(
view: &crate::sheet::SheetView,
path: Option<&Path>,
inner: Rect,
buf: &mut Buffer,
bg: Color,
) {
let bg_style = Style::default().bg(bg);
for y in inner.y..inner.y + inner.height {
for x in inner.x..inner.x + inner.width {
buf[(x, y)].set_style(bg_style);
buf[(x, y)].set_symbol(" ");
}
}
if inner.height < 3 || inner.width < 8 {
return;
}
let name = path
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("(unnamed sheet)"));
let sheet = match view.sheets.get(view.current_sheet) {
Some(s) => s,
None => return,
};
let row_count = sheet.row_count();
let col_count = sheet.col_count();
let header = format!(
" {} · {} · sheet {}/{} ({}) · {} rows × {} cols ",
name,
view.kind.label(),
view.current_sheet + 1,
view.sheets.len(),
sheet.name,
row_count,
col_count,
);
buf.set_string(
inner.x,
inner.y,
&header,
Style::default()
.fg(Color::White)
.bg(Color::Rgb(0x09, 0x4d, 0x77))
.add_modifier(Modifier::BOLD),
);
let grid_top = inner.y + 1;
let grid_height = inner.height.saturating_sub(2); let grid_w = inner.width;
if grid_height < 2 || col_count == 0 {
return;
}
let gutter_w = (row_count.max(1).to_string().len() as u16 + 2).max(4);
if grid_w <= gutter_w + 2 {
return;
}
let body_x = inner.x + gutter_w;
let body_w = grid_w - gutter_w;
let header_y = grid_top;
let data_top = grid_top + 1;
let data_rows = grid_height.saturating_sub(1) as usize;
let head_style = Style::default()
.fg(Color::White)
.bg(Color::Rgb(0x07, 0x33, 0x55))
.add_modifier(Modifier::BOLD);
for x in inner.x..inner.x + inner.width {
buf[(x, header_y)].set_style(head_style);
buf[(x, header_y)].set_symbol(" ");
}
let mut visible: Vec<(usize, u16)> = Vec::new(); let mut x_off = 0u16;
for (c, w) in sheet.col_widths.iter().enumerate().skip(sheet.scroll_col) {
if x_off + w + 1 > body_w {
break;
}
visible.push((c, x_off));
x_off += w + 1; }
for (c, x_off) in &visible {
let label = sheet.headers.get(*c).map(|s| s.as_str()).unwrap_or("");
let cell_x = body_x + *x_off;
let w = sheet.col_widths[*c];
write_cell(buf, cell_x, header_y, w, label, head_style);
}
let row_end = (sheet.scroll_row + data_rows).min(row_count);
let row_style = Style::default().fg(Color::White).bg(bg);
let alt_row_style = Style::default()
.fg(Color::White)
.bg(Color::Rgb(0x24, 0x29, 0x37));
let gutter_style = Style::default().fg(Color::DarkGray);
for (display_row, row_idx) in (sheet.scroll_row..row_end).enumerate() {
let y = data_top + display_row as u16;
let style = if display_row % 2 == 0 {
row_style
} else {
alt_row_style
};
for x in inner.x..inner.x + inner.width {
buf[(x, y)].set_style(style);
buf[(x, y)].set_symbol(" ");
}
let row_label = format!(" {:>width$} ", row_idx + 1, width = (gutter_w - 2) as usize);
buf.set_string(
inner.x,
y,
&row_label,
gutter_style.bg(style.bg.unwrap_or(Color::Reset)),
);
let row = &sheet.rows[row_idx];
for (c, x_off) in &visible {
let cell_text = row.get(*c).map(|s| s.as_str()).unwrap_or("");
let w = sheet.col_widths[*c];
write_cell(buf, body_x + *x_off, y, w, cell_text, style);
}
}
let status_y = inner.y + inner.height - 1;
let visible_first = sheet.scroll_row + 1;
let visible_last = (sheet.scroll_row + data_rows).min(row_count);
let visible_col_first = sheet.scroll_col + 1;
let visible_col_last = visible
.last()
.map(|(c, _)| *c + 1)
.unwrap_or(visible_col_first);
let status = format!(
" rows {visible_first}–{visible_last} of {row_count} · cols {visible_col_first}–{visible_col_last} of {col_count} · ←/→ ↑/↓ PgUp/PgDn Tab=next sheet "
);
buf.set_string(
inner.x,
status_y,
&status,
Style::default()
.fg(Color::Gray)
.bg(Color::Rgb(0x14, 0x18, 0x22)),
);
}
fn render_diff(
diff: &mut crate::widgets::diff::DiffData,
inner: Rect,
buf: &mut Buffer,
bg: Color,
) -> (Rect, Rect) {
use crate::widgets::diff::DiffRow;
let bg_style = Style::default().bg(bg);
for y in inner.y..inner.y + inner.height {
for x in inner.x..inner.x + inner.width {
buf[(x, y)].set_style(bg_style);
buf[(x, y)].set_symbol(" ");
}
}
if inner.height < 3 || inner.width < 16 {
return (Rect::default(), Rect::default());
}
if diff.unified {
return render_unified_deletion(diff, inner, buf, bg);
}
let left_name = diff
.left_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| diff.left_path.display().to_string());
let right_is_real = diff.right_path != std::path::Path::new("/dev/null")
&& !diff.right_path.as_os_str().is_empty();
let right_name = if right_is_real {
Some(
diff.right_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| diff.right_path.display().to_string()),
)
} else {
None
};
let header = match (&right_name, diff.bytes_differ_but_lines_equal) {
(Some(r), true) => format!(
" diff: {left_name} \u{2194} {r} \u{2022} whitespace-only change (trailing newline / CRLF / BOM) — no line-level diff "
),
(Some(r), false) => format!(" diff: {left_name} \u{2194} {r} "),
(None, _) => format!(" {left_name} "),
};
let head_bg = if diff.bytes_differ_but_lines_equal {
Color::Rgb(0x8a, 0x4a, 0x10)
} else {
Color::Rgb(0x09, 0x4d, 0x77)
};
let head_style = Style::default()
.fg(Color::White)
.bg(head_bg)
.add_modifier(Modifier::BOLD);
for x in inner.x..inner.x + inner.width {
buf[(x, inner.y)].set_style(head_style);
buf[(x, inner.y)].set_symbol(" ");
}
buf.set_string(inner.x, inner.y, &header, head_style);
let (prev_arrow, next_arrow) = paint_diff_nav_arrows(inner, head_bg, buf);
let body_top = inner.y + 1;
let body_height = inner.height.saturating_sub(2);
let status_y = inner.y + inner.height - 1;
if body_height == 0 {
return (prev_arrow, next_arrow);
}
let half = inner.width / 2;
if half < 8 {
return (prev_arrow, next_arrow);
}
let left_max = diff.left_lines.len();
let right_max = diff.right_lines.len();
let l_gutter = (left_max + 1).to_string().len() as u16 + 1;
let r_gutter = (right_max + 1).to_string().len() as u16 + 1;
let l_x = inner.x;
let l_sign_x = l_x + l_gutter;
let l_text_x = l_sign_x + 2;
let l_text_w = half.saturating_sub(l_gutter + 2 + 1); let r_x = inner.x + half + 1;
let r_sign_x = r_x + r_gutter;
let r_text_x = r_sign_x + 2;
let r_text_w = (inner.width - (half + 1)).saturating_sub(r_gutter + 2);
let seam_x = inner.x + half;
for y in body_top..body_top + body_height {
buf[(seam_x, y)].set_symbol("\u{2502}");
buf[(seam_x, y)].set_style(Style::default().fg(Color::Rgb(0x3a, 0x42, 0x52)));
}
let total = diff.rows.len();
let viewport = body_height as usize;
let max_scroll = total.saturating_sub(viewport);
if diff.scroll > max_scroll {
diff.scroll = max_scroll;
}
let removed_bg = Color::Rgb(0x4a, 0x1f, 0x1f);
let removed_fg = Color::Rgb(0xff, 0xb3, 0xb3);
let added_bg = Color::Rgb(0x1f, 0x42, 0x2a);
let added_fg = Color::Rgb(0xb6, 0xee, 0xc4);
let equal_fg = Color::Rgb(0xc5, 0xcd, 0xd9);
let gutter_fg = Color::Rgb(0x6c, 0x7d, 0x9c);
let find_needle = diff.find.needle.clone();
let find_opts = diff.find.opts;
let find_active = diff.find.active;
let occ_needle = diff.selection_occurrence_needle();
let end = (diff.scroll + viewport).min(total);
for (vis_row, row_idx) in (diff.scroll..end).enumerate() {
let y = body_top + vis_row as u16;
let row = diff.rows[row_idx];
let (l_cell_bg, l_sign, l_text) = match row {
DiffRow::Equal { left, .. } => (
bg,
' ',
diff.left_lines.get(left).cloned().unwrap_or_default(),
),
DiffRow::Removed { left } => (
removed_bg,
'-',
diff.left_lines.get(left).cloned().unwrap_or_default(),
),
DiffRow::Replaced { left, .. } => (
removed_bg,
'-',
diff.left_lines.get(left).cloned().unwrap_or_default(),
),
DiffRow::Added { .. } => (added_bg, ' ', String::new()),
};
let (r_cell_bg, r_sign, r_text) = match row {
DiffRow::Equal { right, .. } => (
bg,
' ',
diff.right_lines.get(right).cloned().unwrap_or_default(),
),
DiffRow::Added { right } => (
added_bg,
'+',
diff.right_lines.get(right).cloned().unwrap_or_default(),
),
DiffRow::Replaced { right, .. } => (
added_bg,
'+',
diff.right_lines.get(right).cloned().unwrap_or_default(),
),
DiffRow::Removed { .. } => (removed_bg, ' ', String::new()),
};
let l_left_idx = match row {
DiffRow::Equal { left, .. }
| DiffRow::Removed { left }
| DiffRow::Replaced { left, .. } => Some(left),
DiffRow::Added { .. } => None,
};
let l_label = l_left_idx
.map(|i| format!("{:>width$} ", i + 1, width = l_gutter as usize - 1))
.unwrap_or_else(|| " ".repeat(l_gutter as usize));
buf.set_string(
l_x,
y,
&l_label,
Style::default().fg(gutter_fg).bg(l_cell_bg),
);
buf.set_string(
l_sign_x,
y,
format!("{l_sign} "),
Style::default()
.fg(if l_cell_bg == removed_bg {
removed_fg
} else {
equal_fg
})
.bg(l_cell_bg)
.add_modifier(Modifier::BOLD),
);
let l_clipped: String = l_text
.chars()
.skip(diff.scroll_x)
.take(l_text_w as usize)
.collect();
let mut l_padded = l_clipped.clone();
let l_pad = (l_text_w as usize).saturating_sub(l_padded.chars().count());
for _ in 0..l_pad {
l_padded.push(' ');
}
buf.set_string(
l_text_x,
y,
&l_padded,
Style::default()
.fg(if l_cell_bg == removed_bg {
removed_fg
} else {
equal_fg
})
.bg(l_cell_bg),
);
let r_right_idx = match row {
DiffRow::Equal { right, .. }
| DiffRow::Added { right }
| DiffRow::Replaced { right, .. } => Some(right),
DiffRow::Removed { .. } => None,
};
let r_label = r_right_idx
.map(|i| format!("{:>width$} ", i + 1, width = r_gutter as usize - 1))
.unwrap_or_else(|| " ".repeat(r_gutter as usize));
buf.set_string(
r_x,
y,
&r_label,
Style::default().fg(gutter_fg).bg(r_cell_bg),
);
buf.set_string(
r_sign_x,
y,
format!("{r_sign} "),
Style::default()
.fg(if r_cell_bg == added_bg {
added_fg
} else {
equal_fg
})
.bg(r_cell_bg)
.add_modifier(Modifier::BOLD),
);
let r_clipped: String = r_text
.chars()
.skip(diff.scroll_x)
.take(r_text_w as usize)
.collect();
let mut r_padded = r_clipped.clone();
let r_pad = (r_text_w as usize).saturating_sub(r_padded.chars().count());
for _ in 0..r_pad {
r_padded.push(' ');
}
buf.set_string(
r_text_x,
y,
&r_padded,
Style::default()
.fg(if r_cell_bg == added_bg {
added_fg
} else {
equal_fg
})
.bg(r_cell_bg),
);
if let Some(needle) = find_needle.as_deref() {
use crate::widgets::diff::DiffSide;
if l_left_idx.is_some() && l_text_w > 0 {
let active = find_active
.filter(|a| a.row == row_idx && a.side == DiffSide::Left)
.map(|a| (a.col_chars, a.len_chars));
paint_search_highlight(
buf,
l_text_x,
y,
l_text_w,
&l_text,
needle,
find_opts,
diff.scroll_x,
active,
&[],
);
}
if r_right_idx.is_some() && r_text_w > 0 {
let active = find_active
.filter(|a| a.row == row_idx && a.side == DiffSide::Right)
.map(|a| (a.col_chars, a.len_chars));
paint_search_highlight(
buf,
r_text_x,
y,
r_text_w,
&r_text,
needle,
find_opts,
diff.scroll_x,
active,
&[],
);
}
}
if let Some(needle) = occ_needle.as_deref() {
if l_left_idx.is_some() && l_text_w > 0 {
paint_selection_occurrences(
buf,
l_text_x,
y,
l_text_w,
&l_text,
needle,
diff.scroll_x,
&[],
);
}
if r_right_idx.is_some() && r_text_w > 0 {
paint_selection_occurrences(
buf,
r_text_x,
y,
r_text_w,
&r_text,
needle,
diff.scroll_x,
&[],
);
}
}
}
paint_diff_selection_band(
diff,
body_top,
body_height,
l_text_x,
l_text_w,
r_text_x,
r_text_w,
end,
buf,
);
let visible_first = diff.scroll + 1;
let visible_last = end;
let status = format!(
" {visible_first}–{visible_last} of {total} · ↑/↓ PgUp/PgDn · ‹/› click arrows or F7 for next/prev change "
);
buf.set_string(
inner.x,
status_y,
&status,
Style::default()
.fg(Color::Gray)
.bg(Color::Rgb(0x14, 0x18, 0x22)),
);
(prev_arrow, next_arrow)
}
#[allow(clippy::too_many_arguments)]
fn paint_diff_selection_band(
diff: &crate::widgets::diff::DiffData,
body_top: u16,
body_height: u16,
l_text_x: u16,
l_text_w: u16,
r_text_x: u16,
r_text_w: u16,
end: usize,
buf: &mut Buffer,
) {
use crate::widgets::diff::DiffSide;
let Some(sel) = diff.selection else {
return;
};
if !sel.has_area() {
return;
}
let (start, stop) = sel.normalized();
let (text_x, text_w) = match sel.side {
DiffSide::Left => (l_text_x, l_text_w),
DiffSide::Right => (r_text_x, r_text_w),
};
if text_w == 0 {
return;
}
let first_visible = diff.scroll;
let last_visible = end;
let row_start = start.0.max(first_visible);
let row_end = stop.0.min(last_visible.saturating_sub(1));
if row_end < row_start {
return;
}
for row_idx in row_start..=row_end {
let y = body_top + (row_idx - first_visible) as u16;
if y >= body_top + body_height {
break;
}
let (cs, ce) = if start.0 == stop.0 {
(start.1, stop.1)
} else if row_idx == start.0 {
(start.1, usize::MAX)
} else if row_idx == stop.0 {
(0, stop.1)
} else {
(0, usize::MAX)
};
let cs_screen = cs.saturating_sub(diff.scroll_x);
let ce_screen = ce.saturating_sub(diff.scroll_x);
paint_selection_band(buf, text_x, y, text_w, cs_screen, ce_screen);
}
}
pub fn diff_hit_test(
diff: &crate::widgets::diff::DiffData,
last_inner: Rect,
col: u16,
row: u16,
) -> Option<(crate::widgets::diff::DiffSide, usize, usize)> {
use crate::widgets::diff::DiffSide;
if diff.unified {
return None;
}
if last_inner.width < 16 || last_inner.height < 3 {
return None;
}
let body_top = last_inner.y + 1;
let body_height = last_inner.height.saturating_sub(2);
if body_height == 0 {
return None;
}
if row < body_top || row >= body_top + body_height {
return None;
}
let half = last_inner.width / 2;
if half < 8 {
return None;
}
let l_gutter = (diff.left_lines.len() + 1).to_string().len() as u16 + 1;
let r_gutter = (diff.right_lines.len() + 1).to_string().len() as u16 + 1;
let l_x = last_inner.x;
let l_sign_x = l_x + l_gutter;
let l_text_x = l_sign_x + 2;
let l_text_w = half.saturating_sub(l_gutter + 2 + 1);
let r_x = last_inner.x + half + 1;
let r_sign_x = r_x + r_gutter;
let r_text_x = r_sign_x + 2;
let r_text_w = (last_inner.width - (half + 1)).saturating_sub(r_gutter + 2);
let seam_x = last_inner.x + half;
let vis_row = (row - body_top) as usize;
let row_idx = diff.scroll + vis_row;
if row_idx >= diff.rows.len() {
return None;
}
let (side, text_x, text_w) = if col < seam_x {
(DiffSide::Left, l_text_x, l_text_w)
} else if col > seam_x {
(DiffSide::Right, r_text_x, r_text_w)
} else {
return None;
};
let screen_col = if col >= text_x {
(col - text_x).min(text_w.saturating_sub(1)) as usize
} else {
0
};
let char_col = screen_col + diff.scroll_x;
Some((side, row_idx, char_col))
}
fn paint_diff_nav_arrows(inner: Rect, head_bg: Color, buf: &mut Buffer) -> (Rect, Rect) {
let strip_w: u16 = 7;
if inner.width < strip_w + 4 {
return (Rect::default(), Rect::default());
}
let strip_right = inner.x + inner.width;
let prev_x = strip_right - strip_w + 1;
let next_x = strip_right - 3;
let y = inner.y;
let arrow_style = Style::default()
.fg(Color::White)
.bg(head_bg)
.add_modifier(Modifier::BOLD);
buf.set_string(prev_x, y, "\u{2039}", arrow_style);
buf.set_string(next_x, y, "\u{203a}", arrow_style);
(
Rect {
x: prev_x,
y,
width: 1,
height: 1,
},
Rect {
x: next_x,
y,
width: 1,
height: 1,
},
)
}
fn render_unified_deletion(
diff: &mut crate::widgets::diff::DiffData,
inner: Rect,
buf: &mut Buffer,
bg: Color,
) -> (Rect, Rect) {
use crate::widgets::diff::DiffRow;
let name = diff
.left_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| diff.left_path.display().to_string());
let header = format!(" diff: {name} \u{2022} deleted (HEAD \u{2192} /dev/null) ");
let head_style = Style::default()
.fg(Color::White)
.bg(Color::Rgb(0x6b, 0x1f, 0x1f))
.add_modifier(Modifier::BOLD);
for x in inner.x..inner.x + inner.width {
buf[(x, inner.y)].set_style(head_style);
buf[(x, inner.y)].set_symbol(" ");
}
buf.set_string(inner.x, inner.y, &header, head_style);
let (prev_arrow, next_arrow) = paint_diff_nav_arrows(inner, Color::Rgb(0x6b, 0x1f, 0x1f), buf);
let body_top = inner.y + 1;
let body_height = inner.height.saturating_sub(2);
let status_y = inner.y + inner.height - 1;
if body_height == 0 {
return (prev_arrow, next_arrow);
}
let left_max = diff.left_lines.len();
let gutter = (left_max + 1).to_string().len() as u16 + 1;
let sign_x = inner.x + gutter;
let text_x = sign_x + 2;
let text_w = inner.width.saturating_sub(gutter + 2);
let total = diff.rows.len();
let viewport = body_height as usize;
let max_scroll = total.saturating_sub(viewport);
if diff.scroll > max_scroll {
diff.scroll = max_scroll;
}
let removed_bg = Color::Rgb(0x4a, 0x1f, 0x1f);
let removed_fg = Color::Rgb(0xff, 0xb3, 0xb3);
let gutter_fg = Color::Rgb(0x6c, 0x7d, 0x9c);
let end = (diff.scroll + viewport).min(total);
for (vis_row, row_idx) in (diff.scroll..end).enumerate() {
let y = body_top + vis_row as u16;
let row = diff.rows[row_idx];
let (left_idx, sign, cell_bg) = match row {
DiffRow::Removed { left } | DiffRow::Replaced { left, .. } => {
(Some(left), '-', removed_bg)
}
DiffRow::Equal { left, .. } => (Some(left), ' ', bg),
DiffRow::Added { .. } => (None, ' ', bg),
};
let label = left_idx
.map(|i| format!("{:>width$} ", i + 1, width = gutter as usize - 1))
.unwrap_or_else(|| " ".repeat(gutter as usize));
buf.set_string(
inner.x,
y,
&label,
Style::default().fg(gutter_fg).bg(cell_bg),
);
buf.set_string(
sign_x,
y,
format!("{sign} "),
Style::default()
.fg(if cell_bg == removed_bg {
removed_fg
} else {
gutter_fg
})
.bg(cell_bg)
.add_modifier(Modifier::BOLD),
);
let text = left_idx
.and_then(|i| diff.left_lines.get(i).cloned())
.unwrap_or_default();
let clipped: String = text
.chars()
.skip(diff.scroll_x)
.take(text_w as usize)
.collect();
let mut padded = clipped;
let pad = (text_w as usize).saturating_sub(padded.chars().count());
for _ in 0..pad {
padded.push(' ');
}
buf.set_string(
text_x,
y,
&padded,
Style::default()
.fg(if cell_bg == removed_bg {
removed_fg
} else {
Color::Rgb(0xc5, 0xcd, 0xd9)
})
.bg(cell_bg),
);
}
let visible_first = diff.scroll + 1;
let visible_last = end;
let status = format!(
" {visible_first}\u{2013}{visible_last} of {total} \u{00b7} every line removed at HEAD \u{00b7} \u{2191}/\u{2193} PgUp/PgDn to scroll "
);
buf.set_string(
inner.x,
status_y,
&status,
Style::default()
.fg(Color::Gray)
.bg(Color::Rgb(0x14, 0x18, 0x22)),
);
(prev_arrow, next_arrow)
}
fn write_cell(buf: &mut Buffer, x: u16, y: u16, w: u16, text: &str, style: Style) {
let max_chars = w as usize;
let content: String = text.chars().take(max_chars).collect();
let mut padded = content;
let pad_count = max_chars.saturating_sub(padded.chars().count());
for _ in 0..pad_count {
padded.push(' ');
}
buf.set_string(x, y, &padded, style);
}
fn format_bytes_human(n: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = KB * 1024;
if n >= MB {
format!("{:.1} MB", n as f64 / MB as f64)
} else if n >= KB {
format!("{:.1} KB", n as f64 / KB as f64)
} else {
format!("{n} B")
}
}
pub fn extension_is_image(ext: &str) -> bool {
let lc = ext.to_ascii_lowercase();
IMAGE_EXTENSIONS.iter().any(|e| *e == lc)
}
pub fn extension_is_pdf(ext: &str) -> bool {
ext.eq_ignore_ascii_case("pdf")
}
pub fn image_format_label_from_ext(ext: &str) -> String {
match ext.to_ascii_lowercase().as_str() {
"jpg" | "jpeg" => "JPEG".to_string(),
other => other.to_ascii_uppercase(),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EditorSelection {
pub anchor: (usize, usize),
pub head: (usize, usize),
}
impl EditorSelection {
pub fn new(row: usize, col: usize) -> Self {
Self {
anchor: (row, col),
head: (row, col),
}
}
pub fn normalised(&self) -> ((usize, usize), (usize, usize)) {
if self.anchor <= self.head {
(self.anchor, self.head)
} else {
(self.head, self.anchor)
}
}
pub fn has_area(&self) -> bool {
self.anchor != self.head
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextSpanEdit {
pub start: (usize, usize),
pub end: (usize, usize),
pub new_text: String,
}
pub fn apply_span_edits_to_lines(lines: &mut Vec<String>, edits: &[TextSpanEdit]) -> usize {
let mut order: Vec<&TextSpanEdit> = edits.iter().collect();
order.sort_by_key(|e| std::cmp::Reverse(e.start));
let mut applied = 0;
for e in order {
if replace_span(lines, e) {
applied += 1;
}
}
applied
}
fn replace_span(lines: &mut Vec<String>, e: &TextSpanEdit) -> bool {
let (sr, sc) = e.start;
let (er, ec) = e.end;
if sr >= lines.len() || er >= lines.len() || (er, ec) < (sr, sc) {
return false;
}
let from = char_byte(&lines[sr], sc);
let to = char_byte(&lines[er], ec);
let head = lines[sr][..from].to_string();
let tail = lines[er][to..].to_string();
let combined = format!("{head}{}{tail}", e.new_text);
let new_lines: Vec<String> = combined.split('\n').map(str::to_string).collect();
let _ = lines.splice(sr..=er, new_lines);
true
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EditKind {
InsertChar,
Newline,
Backspace,
DeleteForward,
Paste,
DeleteSelection,
DuplicateLines,
DeleteLines,
KillToEol,
KillToBol,
OpenLine,
Indent,
MultiEdit,
MoveLines,
ToggleComment,
JoinLines,
TransformCase,
SortLines,
TrimWhitespace,
Transpose,
IndentConvert,
TrimFinalNewlines,
Replace,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CaseTransform {
Upper,
Lower,
Title,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CaretEdit {
Insert(char),
Backspace,
DeleteForward,
}
#[derive(Clone, Debug)]
struct Snapshot {
lines: Vec<String>,
cursor_row: usize,
cursor_col: usize,
selection: Option<EditorSelection>,
carets: Vec<EditorSelection>,
dirty: bool,
save_seq: u64,
}
const UNDO_STACK_LIMIT: usize = 500;
const SELECTION_HIGHLIGHT_MAX_LEN: usize = 200;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExternalChange {
Unchanged,
Reloaded,
ReloadFailed,
Conflict,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SaveOutcome {
Saved,
DiskConflict,
EncodingLoss,
}
#[derive(Debug, Default)]
pub struct ExternalReloadReport {
pub reloaded: Vec<PathBuf>,
pub conflicts: Vec<PathBuf>,
pub failed: Vec<PathBuf>,
}
impl ExternalReloadReport {
pub fn is_empty(&self) -> bool {
self.reloaded.is_empty() && self.conflicts.is_empty() && self.failed.is_empty()
}
}
pub(crate) const NAVIGATOR_ACCENT: Color = Color::Rgb(0xff, 0x9d, 0x2f);
const IGNORE_TAIL_COLS: usize = 11;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommentBox {
pub id: u64,
pub line: usize,
pub author: String,
pub body: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommentHit {
Body,
Reply,
Ignore,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommentFocus {
pub id: u64,
pub reply: String,
pub cursor: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum VisRow {
Text {
line: usize,
start: usize,
end: usize,
},
Box { box_idx: usize, box_row: usize },
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum LineEnding {
#[default]
Lf,
Crlf,
}
impl LineEnding {
pub fn label(self) -> &'static str {
match self {
Self::Lf => "LF",
Self::Crlf => "CRLF",
}
}
pub fn sequence(self) -> &'static str {
match self {
Self::Lf => "\n",
Self::Crlf => "\r\n",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct IndentStyle {
pub width: u32,
pub use_spaces: bool,
}
impl IndentStyle {
pub fn unit(self) -> String {
if self.use_spaces {
" ".repeat(self.width as usize)
} else {
"\t".to_string()
}
}
pub fn label(self) -> String {
let kind = if self.use_spaces {
"Spaces"
} else {
"Tab Size"
};
format!("{kind}: {}", self.width)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum GitMark {
Added,
Modified,
Deleted,
}
#[derive(Debug, Clone)]
struct SnippetSession {
anchor: (usize, usize),
cur_len: usize,
stops: std::collections::VecDeque<(usize, usize, usize)>,
}
#[cfg(test)]
thread_local! {
static FOLD_RANGE_REBUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub struct Editor {
pub path: Option<PathBuf>,
pub lines: Vec<String>,
pub breakpoints: std::collections::HashMap<PathBuf, std::collections::BTreeSet<usize>>,
pub stop_line: Option<(PathBuf, usize)>,
pub unverified_breakpoints:
std::collections::HashMap<PathBuf, std::collections::BTreeSet<usize>>,
pub breakpoint_conditions:
std::collections::HashMap<PathBuf, std::collections::HashMap<usize, String>>,
pub breakpoint_logs:
std::collections::HashMap<PathBuf, std::collections::HashMap<usize, String>>,
pub edit_seq: u64,
pub collab_synced_seq: u64,
pub collab_doc_gen: u64,
pub git_head_lines: Option<Vec<String>>,
pub git_baseline_for: Option<PathBuf>,
git_marks: std::collections::HashMap<usize, GitMark>,
git_marks_seq: u64,
pub auto_close_pairs: bool,
auto_pair_at: Option<(usize, usize, u64)>,
conflicts: Vec<crate::merge::ConflictBlock>,
conflicts_seq: u64,
pub merge_action_spans: Vec<(u16, std::ops::Range<u16>, usize, crate::merge::Resolution)>,
pub blame_lines: Option<Vec<crate::git::BlameLine>>,
pub blame_for: Option<PathBuf>,
pub blame_enabled: bool,
pub scroll: usize,
scroll_sub: usize,
wrap_total_cache: Vec<(usize, usize)>,
pub scroll_col: usize,
pub cursor_row: usize,
pub cursor_col: usize,
pub focused: bool,
pub focus_gradient: bool,
pub theme: crate::theme::Theme,
pub pdf_viewer_enabled: bool,
pub csv_viewer_enabled: bool,
pub dirty: bool,
save_seq: u64,
pub status: String,
pub last_area: Rect,
pub last_inner: Rect,
pub last_scrollbar: Rect,
pub last_hscrollbar: Rect,
last_text_rows: u16,
hscroll_content_cols: Option<usize>,
last_wrap_rows: Vec<VisRow>,
pub last_gutter_width: u16,
pub selection: Option<EditorSelection>,
pub carets: Vec<EditorSelection>,
pub ghost_carets: Vec<(usize, usize, Color)>,
pub ghost_caret_labels: Vec<(usize, usize, String, Color)>,
pub stream_stop_line: Option<usize>,
pub comment_boxes: Vec<CommentBox>,
pub comment_focus: Option<CommentFocus>,
pub sticky_lines: Vec<u32>,
sticky_click_rows: Vec<(u16, u32)>,
box_anchor: Option<(usize, usize)>,
snippet: Option<SnippetSession>,
folded: std::collections::BTreeSet<usize>,
hidden_ranges: Vec<(usize, usize)>,
fold_epoch_lines: usize,
pub preview: bool,
pub pinned: bool,
undo_stack: Vec<Snapshot>,
redo_stack: Vec<Snapshot>,
last_edit_kind: Option<EditKind>,
lang: Option<LangKind>,
indent_override: Option<IndentStyle>,
pub eol: LineEnding,
pub encoding: &'static encoding_rs::Encoding,
bom: bool,
pub show_indent_guides: bool,
pub show_bracket_colors: bool,
bracket_colors: Vec<Vec<(usize, u8)>>,
pub whitespace_mode: WhitespaceMode,
pub inline_values: std::collections::BTreeMap<usize, String>,
wrap_override: Option<bool>,
highlights: Vec<Vec<HiSpan>>,
semantic_overlay: Vec<Vec<HiSpan>>,
semantic_data: Vec<u32>,
semantic_legend: Option<std::sync::Arc<Vec<String>>>,
semantic_path: Option<PathBuf>,
semantic_is_full: bool,
diagnostics: Vec<crate::lsp::manager::Diagnostic>,
diagnostics_path: Option<PathBuf>,
diagnostic_spans: Vec<Vec<(usize, usize, crate::lsp::manager::DiagnosticSeverity)>>,
inlay_hints: Vec<crate::lsp::manager::InlayHintItem>,
inlay_path: Option<PathBuf>,
occurrences: Vec<(usize, usize, usize, bool)>,
inlay_spans: Vec<Vec<(usize, String)>>,
registry: LangRegistry,
pub search_highlight: Option<String>,
pub search_highlight_opts: crate::widgets::search::SearchOpts,
pub active_search_match: Option<(usize, usize, usize)>,
pub markdown_preview: Option<crate::markdown::MarkdownPreview>,
pub image: Option<ImageView>,
pdf_restore_page: Option<u32>,
pub sheet: Option<crate::sheet::SheetView>,
pub diff: Option<crate::widgets::diff::DiffData>,
pub hex: Option<crate::hex::HexView>,
pub force_text: bool,
pub diff_prev_arrow: Rect,
pub diff_next_arrow: Rect,
disk_stamp: Option<(SystemTime, u64)>,
pub disk_conflict: bool,
pub encoding_loss: bool,
pub lossy_save_armed: bool,
pub last_edit_at: Option<std::time::Instant>,
}
impl Editor {
pub fn new() -> Self {
Self {
path: None,
lines: Vec::new(),
breakpoints: std::collections::HashMap::new(),
stop_line: None,
unverified_breakpoints: std::collections::HashMap::new(),
breakpoint_conditions: std::collections::HashMap::new(),
breakpoint_logs: std::collections::HashMap::new(),
edit_seq: 0,
collab_synced_seq: 0,
collab_doc_gen: 0,
git_head_lines: None,
git_baseline_for: None,
git_marks: std::collections::HashMap::new(),
git_marks_seq: u64::MAX,
auto_close_pairs: true,
auto_pair_at: None,
conflicts: Vec::new(),
merge_action_spans: Vec::new(),
conflicts_seq: u64::MAX,
blame_lines: None,
blame_for: None,
blame_enabled: true,
scroll: 0,
scroll_sub: 0,
wrap_total_cache: Vec::new(),
scroll_col: 0,
cursor_row: 0,
cursor_col: 0,
focused: false,
focus_gradient: false,
theme: crate::theme::Theme::default(),
pdf_viewer_enabled: true,
csv_viewer_enabled: true,
dirty: false,
save_seq: 0,
status: String::from("No file open"),
last_area: Rect::default(),
last_inner: Rect::default(),
last_scrollbar: Rect::default(),
last_hscrollbar: Rect::default(),
last_text_rows: 0,
hscroll_content_cols: None,
last_wrap_rows: Vec::new(),
last_gutter_width: 0,
selection: None,
carets: Vec::new(),
ghost_carets: Vec::new(),
ghost_caret_labels: Vec::new(),
stream_stop_line: None,
comment_boxes: Vec::new(),
comment_focus: None,
sticky_lines: Vec::new(),
sticky_click_rows: Vec::new(),
box_anchor: None,
snippet: None,
folded: std::collections::BTreeSet::new(),
hidden_ranges: Vec::new(),
fold_epoch_lines: 0,
preview: false,
pinned: false,
undo_stack: Vec::new(),
redo_stack: Vec::new(),
last_edit_kind: None,
lang: None,
indent_override: None,
eol: LineEnding::Lf,
encoding: encoding_rs::UTF_8,
bom: false,
show_indent_guides: true,
show_bracket_colors: true,
bracket_colors: Vec::new(),
whitespace_mode: WhitespaceMode::default(),
inline_values: std::collections::BTreeMap::new(),
wrap_override: None,
highlights: Vec::new(),
semantic_overlay: Vec::new(),
semantic_data: Vec::new(),
semantic_legend: None,
semantic_path: None,
semantic_is_full: false,
diagnostics: Vec::new(),
diagnostics_path: None,
diagnostic_spans: Vec::new(),
inlay_hints: Vec::new(),
inlay_path: None,
occurrences: Vec::new(),
inlay_spans: Vec::new(),
registry: LangRegistry::new(),
search_highlight: None,
search_highlight_opts: crate::widgets::search::SearchOpts::default(),
active_search_match: None,
markdown_preview: None,
image: None,
pdf_restore_page: None,
sheet: None,
diff: None,
hex: None,
force_text: false,
diff_prev_arrow: Rect::default(),
diff_next_arrow: Rect::default(),
disk_stamp: None,
disk_conflict: false,
encoding_loss: false,
lossy_save_armed: false,
last_edit_at: None,
}
}
pub fn set_search_highlight(&mut self, term: Option<String>) {
self.search_highlight = term.filter(|s| !s.is_empty());
}
pub fn toggle_breakpoint(&mut self) -> Option<(PathBuf, usize, bool)> {
self.toggle_breakpoint_line(self.cursor_row + 1) }
pub fn toggle_breakpoint_line(&mut self, line: usize) -> Option<(PathBuf, usize, bool)> {
let path = self.path.clone()?;
let set = self.breakpoints.entry(path.clone()).or_default();
let now_set = if set.remove(&line) {
if let Some(conds) = self.breakpoint_conditions.get_mut(&path) {
conds.remove(&line);
if conds.is_empty() {
self.breakpoint_conditions.remove(&path);
}
}
if let Some(logs) = self.breakpoint_logs.get_mut(&path) {
logs.remove(&line);
if logs.is_empty() {
self.breakpoint_logs.remove(&path);
}
}
false
} else {
set.insert(line);
true
};
if set.is_empty() {
self.breakpoints.remove(&path);
}
Some((path, line, now_set))
}
pub fn gutter_line_at(&self, col: u16, row: u16) -> Option<usize> {
if self.last_inner.height == 0 || self.lines.is_empty() {
return None;
}
if row < self.last_inner.y || row >= self.last_inner.y + self.last_inner.height {
return None;
}
let text_x = self.last_inner.x + self.last_gutter_width + 1;
if col < self.last_inner.x || col >= text_x {
return None;
}
let vis_row = (row - self.last_inner.y) as usize;
let line = if self.last_wrap_rows.is_empty() {
self.scroll + vis_row
} else {
self.text_row(vis_row)?.0
};
(line < self.lines.len()).then_some(line)
}
pub fn fold_chevron_at(&mut self, col: u16, row: u16) -> bool {
if col != self.last_inner.x + 1 || row < self.last_inner.y {
return false;
}
let Some((line, start, _)) = self.text_row((row - self.last_inner.y) as usize) else {
return false;
};
if self.wrap_enabled() && start != 0 {
return false;
}
if self.is_foldable(line) {
self.toggle_fold(line);
return true;
}
false
}
pub fn test_glyph_at(&self, col: u16, row: u16) -> Option<String> {
if col != self.last_inner.x || row < self.last_inner.y {
return None;
}
let (line, start, _) = self.text_row((row - self.last_inner.y) as usize)?;
if self.wrap_enabled() && start != 0 {
return None;
}
if self.sign_cell_taken(line) {
return None;
}
crate::testing::locate::test_fn_on_line(self.path.as_deref(), &self.lines, line)
}
fn sign_cell_taken(&self, line: usize) -> bool {
if self.stream_stop_line == Some(line) {
return true;
}
let Some(path) = self.path.as_deref() else {
return false;
};
let here = line + 1; self.stop_line
.as_ref()
.is_some_and(|(p, l)| p == path && *l == here)
|| self
.breakpoints
.get(path)
.is_some_and(|s| s.contains(&here))
}
pub fn stream_stop_at(&self, col: u16, row: u16) -> bool {
let Some(stop_line) = self.stream_stop_line else {
return false;
};
if col != self.last_inner.x || row < self.last_inner.y {
return false;
}
let Some((line, start, _)) = self.text_row((row - self.last_inner.y) as usize) else {
return false;
};
if self.wrap_enabled() && start != 0 {
return false;
}
line == stop_line
}
pub fn screen_row_of_line(&self, line: usize) -> Option<u16> {
self.last_wrap_rows
.iter()
.position(|r| matches!(r, VisRow::Text { line: l, .. } if *l == line))
.map(|idx| self.last_inner.y.saturating_add(idx as u16))
}
pub fn breakpoint_lines(&self, path: &Path) -> Vec<u32> {
self.breakpoints
.get(path)
.map(|s| s.iter().map(|&l| l as u32).collect())
.unwrap_or_default()
}
pub fn source_breakpoints(
&self,
path: &Path,
lines: &std::collections::BTreeSet<usize>,
) -> Vec<crate::dap::session::SourceBreakpoint> {
let conds = self.breakpoint_conditions.get(path);
let logs = self.breakpoint_logs.get(path);
lines
.iter()
.map(|&l| crate::dap::session::SourceBreakpoint {
line: l as u32,
condition: conds.and_then(|c| c.get(&l)).cloned(),
log_message: logs.and_then(|m| m.get(&l)).cloned(),
})
.collect()
}
fn mark_buffer_changed(&mut self) {
self.dirty = true;
self.last_edit_at = Some(std::time::Instant::now());
self.edit_seq = self.edit_seq.wrapping_add(1);
self.hscroll_content_cols = None;
self.wrap_total_cache.clear();
self.occurrences.clear();
self.encoding_loss = false;
self.lossy_save_armed = false;
}
pub fn set_git_head_lines(&mut self, path: PathBuf, head: Option<Vec<String>>) {
self.git_baseline_for = Some(path);
self.git_head_lines = head;
self.git_marks_seq = u64::MAX;
}
pub fn set_blame(&mut self, path: PathBuf, blame: Option<Vec<crate::git::BlameLine>>) {
self.blame_for = Some(path);
self.blame_lines = blame;
}
pub fn current_line_blame_annotation(&self) -> Option<String> {
if !self.blame_enabled {
return None;
}
if crate::merge::conflict_containing(&self.conflicts, self.cursor_row).is_some() {
return None;
}
if self.blame_for != self.path {
return None;
}
let blame = self.blame_lines.as_ref()?;
if matches!(
self.git_mark_at(self.cursor_row),
Some(GitMark::Added | GitMark::Modified)
) {
return Some("Uncommitted changes".to_string());
}
if blame.len() != self.lines.len() {
return None;
}
let line = blame.get(self.cursor_row)?;
if line.uncommitted {
return Some("Uncommitted changes".to_string());
}
Some(format!(
"{}, {} • {}",
line.author,
crate::git::humanize_age(line.age_secs),
line.summary
))
}
pub fn conflicts(&mut self) -> &[crate::merge::ConflictBlock] {
if self.conflicts_seq != self.edit_seq {
self.conflicts_seq = self.edit_seq;
self.conflicts = crate::merge::find_conflicts(&self.lines);
}
&self.conflicts
}
pub fn resolve_conflict_at(&mut self, row: usize, res: crate::merge::Resolution) -> bool {
let Some(block) = crate::merge::conflict_containing(self.conflicts(), row) else {
return false;
};
let replacement = crate::merge::resolution_lines(&self.lines, &block, res);
self.pin_on_edit();
self.push_undo(EditKind::Replace);
self.clear_selection();
self.lines
.splice(block.ours_start..=block.theirs_end, replacement);
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.cursor_row = block.ours_start.min(self.lines.len() - 1);
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.mark_buffer_changed();
self.recompute_highlights();
true
}
fn refresh_git_marks(&mut self) {
use crate::widgets::diff::DiffRow;
if self.git_marks_seq == self.edit_seq {
return;
}
self.git_marks_seq = self.edit_seq;
self.git_marks.clear();
let Some(head) = self.git_head_lines.as_ref() else {
return;
};
let rows = crate::widgets::diff::build_diff_rows(head, &self.lines);
let mut pending_delete = false;
for row in &rows {
match *row {
DiffRow::Added { right } => {
self.git_marks.insert(right, GitMark::Added);
pending_delete = false;
}
DiffRow::Replaced { right, .. } => {
self.git_marks.insert(right, GitMark::Modified);
pending_delete = false;
}
DiffRow::Removed { .. } => pending_delete = true,
DiffRow::Equal { right, .. } => {
if pending_delete {
self.git_marks.insert(right, GitMark::Deleted);
pending_delete = false;
}
}
}
}
if pending_delete && !self.lines.is_empty() {
self.git_marks
.entry(self.lines.len() - 1)
.or_insert(GitMark::Deleted);
}
}
pub fn git_mark_at(&self, line: usize) -> Option<GitMark> {
self.git_marks.get(&line).copied()
}
pub fn wrap_enabled(&self) -> bool {
self.wrap_override
.unwrap_or(matches!(self.lang, Some(LangKind::Markdown)))
}
fn content_cols(&mut self) -> usize {
if let Some(cols) = self.hscroll_content_cols {
return cols;
}
let cols = self
.lines
.iter()
.enumerate()
.map(|(i, l)| {
let extra: usize = self
.inlay_spans
.get(i)
.map(|hs| hs.iter().map(|(_, label)| label.chars().count()).sum())
.unwrap_or(0);
l.chars().count() + extra
})
.max()
.unwrap_or(0);
self.hscroll_content_cols = Some(cols);
cols
}
fn text_row(&self, i: usize) -> Option<(usize, usize, usize)> {
match self.last_wrap_rows.get(i)? {
VisRow::Text { line, start, end } => Some((*line, *start, *end)),
VisRow::Box { .. } => None,
}
}
fn comment_body_lines(body: &str, bw: usize) -> Vec<String> {
let bw = bw.max(8);
let mut out = Vec::new();
for line in body.split('\n') {
let chars: Vec<char> = line.chars().collect();
for &(s, e) in &wrap_segments(&chars, bw) {
out.push(chars[s..e].iter().collect());
}
}
if out.is_empty() {
out.push(String::new());
}
out
}
fn comment_box_height(&self, idx: usize, tw: usize) -> usize {
let body = &self.comment_boxes[idx].body;
2 + Self::comment_body_lines(body, tw.saturating_sub(4)).len()
}
fn box_rows_at_line(&self, line: usize, tw: usize) -> usize {
if self.comment_boxes.is_empty() {
return 0;
}
(0..self.comment_boxes.len())
.filter(|&i| self.comment_boxes[i].line == line)
.map(|i| self.comment_box_height(i, tw))
.sum()
}
fn box_rows_between(&self, from: usize, to: usize, tw: usize) -> usize {
if self.comment_boxes.is_empty() {
return 0;
}
(0..self.comment_boxes.len())
.filter(|&i| {
let l = self.comment_boxes[i].line;
l >= from && l < to && !self.is_line_hidden(l)
})
.map(|i| self.comment_box_height(i, tw))
.sum()
}
#[allow(clippy::too_many_arguments)]
fn paint_comment_box_row(
&self,
buf: &mut ratatui::buffer::Buffer,
inner: Rect,
y: u16,
gutter_width: u16,
text_x: u16,
text_width: u16,
box_idx: usize,
box_row: usize,
) {
buf.set_line(
inner.x,
y,
&Line::from(" ".repeat(gutter_width as usize + 1)),
gutter_width + 1,
);
let w = text_width as usize;
if w < 8 {
return;
}
let b = &self.comment_boxes[box_idx];
let accent = Style::default()
.fg(NAVIGATOR_ACCENT)
.bg(self.theme.sticky_scroll_bg());
let body_st = Style::default().bg(self.theme.sticky_scroll_bg());
let dim = Style::default()
.fg(Color::DarkGray)
.bg(self.theme.sticky_scroll_bg());
let height = self.comment_box_height(box_idx, w);
let pad = |s: &str, n: usize| -> String {
let mut out: String = s.chars().take(n).collect();
while out.chars().count() < n {
out.push(' ');
}
out
};
let line = if box_row == 0 {
let head = format!("\u{256d}\u{2500} \u{25c6} {} ", b.author);
let fill = w.saturating_sub(head.chars().count() + 1);
Line::from(Span::styled(
format!("{head}{}\u{256e}", "\u{2500}".repeat(fill)),
accent,
))
} else if box_row + 1 < height {
let body_lines = Self::comment_body_lines(&b.body, w.saturating_sub(4));
let text = body_lines.get(box_row - 1).cloned().unwrap_or_default();
Line::from(vec![
Span::styled("\u{2502} ", accent),
Span::styled(pad(&text, w - 4), body_st),
Span::styled(" \u{2502}", accent),
])
} else {
let focus = self.comment_focus.as_ref().filter(|f| f.id == b.id);
let field_w = w.saturating_sub(4 + IGNORE_TAIL_COLS);
let win = focus.map_or(0, |f| f.cursor.saturating_sub(field_w.saturating_sub(1)));
let (draft, style) = match focus {
Some(f) => {
let visible: String = f.reply.chars().skip(win).take(field_w).collect();
(pad(&visible, field_w), body_st)
}
None => (pad("Reply", field_w), dim),
};
let mut spans = vec![
Span::styled("\u{2570} ", accent),
Span::styled("\u{276f} ", accent),
];
match focus {
Some(f) if field_w > 0 && f.cursor - win < field_w => {
let cursor = f.cursor - win;
let chars: Vec<char> = draft.chars().collect();
let before: String = chars[..cursor].iter().collect();
let at: String = chars[cursor..=cursor].iter().collect();
let after: String = chars[cursor + 1..].iter().collect();
spans.push(Span::styled(before, style));
spans.push(Span::styled(
at,
style.add_modifier(ratatui::style::Modifier::REVERSED),
));
spans.push(Span::styled(after, style));
}
_ => spans.push(Span::styled(draft, style)),
}
spans.push(Span::styled(" \u{2715} Ignore ", accent));
spans.push(Span::styled("\u{256f}", accent));
Line::from(spans)
};
buf.set_line(text_x, y, &line, text_width);
for x in text_x..text_x + text_width {
if buf[(x, y)].symbol() == " " && buf[(x, y)].style().bg.is_none() {
buf[(x, y)].set_style(body_st);
}
}
}
pub fn comment_box_hit(&self, col: u16, row: u16) -> Option<(u64, CommentHit)> {
if self.comment_boxes.is_empty() {
return None;
}
let inner = self.last_inner;
if row < inner.y || col < inner.x {
return None;
}
let VisRow::Box { box_idx, box_row } =
*self.last_wrap_rows.get((row - inner.y) as usize)?
else {
return None;
};
let b = &self.comment_boxes[box_idx];
let text_x = inner.x + self.last_gutter_width + 1;
let w = self.visible_text_width();
if box_row + 1 == self.comment_box_height(box_idx, w) {
let rel = (col.saturating_sub(text_x)) as usize;
if rel + IGNORE_TAIL_COLS >= w && rel < w {
return Some((b.id, CommentHit::Ignore));
}
return Some((b.id, CommentHit::Reply));
}
Some((b.id, CommentHit::Body))
}
fn line_segments(&self, line: usize, width: usize) -> Vec<(usize, usize)> {
let chars: Vec<char> = self
.lines
.get(line)
.map(|l| l.chars().collect())
.unwrap_or_default();
wrap_segments(&chars, width)
}
fn line_visual_rows(&self, line: usize, width: usize) -> usize {
if width == 0 {
return 1;
}
let len = self.line_char_len(line);
if len <= width {
1
} else {
self.line_segments(line, width).len()
}
}
fn group_visual_rows(&self, line: usize, width: usize) -> usize {
self.line_visual_rows(line, width) + self.box_rows_at_line(line, width)
}
fn total_visual_rows(&mut self, width: usize) -> usize {
let text =
if let Some(&(_, total)) = self.wrap_total_cache.iter().find(|&&(w, _)| w == width) {
total
} else {
let total: usize = (0..self.lines.len())
.map(|l| self.line_visual_rows(l, width))
.sum();
self.wrap_total_cache.push((width, total));
total
};
text + self.box_rows_between(0, self.lines.len(), width)
}
fn top_visual_row(&self, width: usize) -> usize {
(0..self.scroll)
.map(|l| self.group_visual_rows(l, width))
.sum::<usize>()
+ self.scroll_sub
}
fn cursor_visual_row(&self, width: usize) -> usize {
let before: usize = (0..self.cursor_row)
.map(|l| self.group_visual_rows(l, width))
.sum();
before + self.segment_index_of_col(self.cursor_row, self.cursor_col, width)
}
fn segment_index_of_col(&self, line: usize, col: usize, width: usize) -> usize {
let segs = self.line_segments(line, width);
let line_len = self.line_char_len(line);
segs.iter()
.position(|&(s, e)| col >= s && (col < e || (col == e && e == line_len)))
.unwrap_or(segs.len().saturating_sub(1))
}
fn set_top_to_visual_row(&mut self, target: usize, width: usize) {
let mut acc = 0;
for line in 0..self.lines.len() {
let n = self.group_visual_rows(line, width);
if acc + n > target {
self.scroll = line;
self.scroll_sub = target - acc;
return;
}
acc += n;
}
self.scroll = self.lines.len().saturating_sub(1);
self.scroll_sub = self.group_visual_rows(self.scroll, width).saturating_sub(1);
}
fn logical_pos_at_visual_row(&self, target: usize, width: usize) -> (usize, usize) {
let mut acc = 0;
for line in 0..self.lines.len() {
let segs = self.line_segments(line, width);
let group = segs.len() + self.box_rows_at_line(line, width);
if acc + group > target {
let idx = (target - acc).min(segs.len().saturating_sub(1));
return (line, segs[idx].0);
}
acc += group;
}
(self.lines.len().saturating_sub(1), 0)
}
fn visual_row_is_box(&self, target: usize, width: usize) -> bool {
if self.comment_boxes.is_empty() {
return false;
}
let mut acc = 0;
for line in 0..self.lines.len() {
let segs = self.line_visual_rows(line, width);
let group = segs + self.box_rows_at_line(line, width);
if acc + group > target {
return target - acc >= segs;
}
acc += group;
}
false
}
fn wrap_set_top(&mut self, top_target: usize) {
let width = self.visible_text_width();
let viewport = self.text_rows();
if width == 0 || viewport == 0 {
return;
}
let total = self.total_visual_rows(width);
let new_top = top_target.min(total.saturating_sub(viewport));
self.set_top_to_visual_row(new_top, width);
let cursor_vrow = self.cursor_visual_row(width);
let target_row = if cursor_vrow < new_top {
Some(new_top)
} else if cursor_vrow >= new_top + viewport {
Some(new_top + viewport - 1)
} else {
None
};
if let Some(vrow) = target_row {
let (line, col) = self.logical_pos_at_visual_row(vrow, width);
self.cursor_row = line;
self.cursor_col = col.min(self.line_char_len(line));
}
self.last_edit_kind = None;
}
fn wrap_move_vertical(&mut self, dir: isize) {
let width = self.visible_text_width().max(1);
let segs = self.line_segments(self.cursor_row, width);
let seg_idx = self.segment_index_of_col(self.cursor_row, self.cursor_col, width);
let goal_col = self.cursor_col - segs[seg_idx].0;
let current = self.cursor_visual_row(width) as isize;
let total = self.total_visual_rows(width) as isize;
let mut target = current + dir;
while target >= 0 && target < total && self.visual_row_is_box(target as usize, width) {
target += dir;
}
if target < 0 || target >= total {
return;
}
let (line, seg_start) = self.logical_pos_at_visual_row(target as usize, width);
let (s, e) = self
.line_segments(line, width)
.into_iter()
.find(|&(s, _)| s == seg_start)
.unwrap_or((seg_start, seg_start));
self.cursor_row = line;
self.cursor_col = (s + goal_col).min(e).min(self.line_char_len(line));
}
pub fn word_before_cursor(&self) -> String {
let Some(line) = self.lines.get(self.cursor_row) else {
return String::new();
};
let chars: Vec<char> = line.chars().collect();
let end = self.cursor_col.min(chars.len());
let mut start = end;
while start > 0 && is_word_char(chars[start - 1]) {
start -= 1;
}
chars[start..end].iter().collect()
}
pub fn open(&mut self, path: &Path) -> Result<()> {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
if self.path.as_deref() != Some(path) {
self.force_text = false;
}
if !self.force_text {
if extension_is_image(ext) {
match self.open_image(path) {
Err(e) if e.to_string().starts_with("Could not decode image") => {}
other => return other,
}
}
if ext.eq_ignore_ascii_case("svg") && self.open_svg(path).is_ok() {
return Ok(());
}
if extension_is_pdf(ext) && self.pdf_viewer_enabled {
return self.open_pdf(path);
}
if crate::sheet::extension_is_sheet(ext) && self.csv_viewer_enabled {
match self.open_sheet(path) {
Err(e)
if e.to_string().starts_with("Spreadsheet open failed")
&& !e.to_string().contains("too large") => {}
other => return other,
}
}
}
let meta = std::fs::metadata(path)?;
if meta.len() > MAX_FILE_BYTES {
let head = read_file_head(path)?;
let head_bom_text = encoding_rs::Encoding::for_bom(&head).is_some();
if !head_bom_text && is_binary(&head) {
return self.open_hex(path);
}
anyhow::bail!("File too large ({} bytes)", meta.len());
}
let bytes = std::fs::read(path)?;
match (!self.force_text)
.then(|| crate::magic::sniff(&bytes))
.flatten()
{
Some(m) if m.is_image() && !extension_is_image(ext) => {
if self.open_image(path).is_ok() {
return Ok(());
}
}
Some(crate::magic::Magic::Pdf) if !extension_is_pdf(ext) && self.pdf_viewer_enabled => {
if self.open_pdf(path).is_ok() {
return Ok(());
}
}
Some(crate::magic::Magic::Zip)
if !ext.eq_ignore_ascii_case("xlsx") && self.csv_viewer_enabled =>
{
if let Ok(view) =
crate::sheet::open_sheet_with_kind(path, crate::sheet::SheetKind::Xlsx)
{
self.install_sheet_view(path, view);
return Ok(());
}
}
_ => {}
}
let sniffed = encoding_rs::Encoding::for_bom(&bytes);
let enc = sniffed.map(|(e, _)| e).unwrap_or(encoding_rs::UTF_8);
let bom_declares_text = enc == encoding_rs::UTF_16LE || enc == encoding_rs::UTF_16BE;
if !bom_declares_text && is_binary(&bytes) {
return self.open_hex(path);
}
let changed_file = self.path.as_deref() != Some(path);
let enc = if changed_file || sniffed.is_some() {
enc
} else {
self.encoding
};
self.encoding = enc;
self.bom = sniffed.is_some();
let text = enc.decode(&bytes).0.into_owned();
self.eol = if text.contains("\r\n") {
LineEnding::Crlf
} else {
LineEnding::Lf
};
self.lines = split_into_lines(&text);
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.hscroll_content_cols = None;
self.wrap_total_cache.clear();
self.scroll_sub = 0;
self.path = Some(path.to_path_buf());
self.disk_stamp = Self::disk_stamp_of(path);
self.disk_conflict = false;
self.encoding_loss = false;
self.lossy_save_armed = false;
self.lang = path
.extension()
.and_then(|e| e.to_str())
.and_then(lang_for_extension);
self.wrap_override = None;
if changed_file {
self.folded.clear();
self.hidden_ranges.clear();
self.fold_epoch_lines = 0;
self.inline_values.clear();
} else if !self.folded.is_empty() {
self.rebuild_hidden_ranges();
}
self.scroll = 0;
self.cursor_row = 0;
self.cursor_col = 0;
self.dirty = false;
self.selection = None;
self.undo_stack.clear();
self.redo_stack.clear();
self.last_edit_kind = None;
self.image = None;
self.sheet = None;
self.markdown_preview = None;
self.hex = None;
self.diff = None;
self.status = format!("Opened {}", path.display());
self.edit_seq = self.edit_seq.wrapping_add(1);
if changed_file {
self.collab_doc_gen = 0;
self.collab_synced_seq = self.edit_seq;
}
self.semantic_data = Vec::new();
self.semantic_overlay = Vec::new();
self.semantic_is_full = false;
self.inlay_hints = Vec::new();
self.inlay_path = None;
self.inlay_spans = Vec::new();
self.recompute_highlights();
Ok(())
}
fn open_image(&mut self, path: &Path) -> Result<()> {
let meta = std::fs::metadata(path)?;
if meta.len() > MAX_IMAGE_BYTES {
anyhow::bail!("Image too large ({} bytes)", meta.len());
}
let bytes = std::fs::read(path)?;
let (pixel_w, pixel_h) = image::load_from_memory(&bytes)
.map(|img| (img.width(), img.height()))
.map_err(|e| anyhow::anyhow!("Could not decode image: {e}"))?;
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
let format_label = image_format_label_from_ext(ext);
self.path = Some(path.to_path_buf());
self.disk_stamp = Self::disk_stamp_of(path);
self.disk_conflict = false;
self.encoding_loss = false;
self.lossy_save_armed = false;
self.lines = vec![String::new()];
self.edit_seq = self.edit_seq.wrapping_add(1);
self.lang = None;
self.scroll = 0;
self.cursor_row = 0;
self.cursor_col = 0;
self.dirty = false;
self.selection = None;
self.undo_stack.clear();
self.redo_stack.clear();
self.last_edit_kind = None;
self.highlights = vec![Vec::new()];
self.image = Some(ImageView {
bytes,
format_label,
pixel_w,
pixel_h,
byte_size: meta.len(),
generation: next_image_generation(),
pdf: None,
});
self.diff = None;
self.diff_prev_arrow = Rect::default();
self.diff_next_arrow = Rect::default();
self.sheet = None;
self.hex = None;
self.status = format!("Opened image {}", path.display());
Ok(())
}
fn open_sheet(&mut self, path: &Path) -> Result<()> {
let view = crate::sheet::open_sheet(path)
.map_err(|e| anyhow::anyhow!("Spreadsheet open failed: {e}"))?;
self.install_sheet_view(path, view);
Ok(())
}
fn open_svg(&mut self, path: &Path) -> Result<()> {
let meta = std::fs::metadata(path)?;
if meta.len() > crate::svg::MAX_SVG_BYTES {
anyhow::bail!("SVG too large ({} bytes)", meta.len());
}
let src = std::fs::read(path)?;
let (png, pixel_w, pixel_h) =
crate::svg::rasterize(&src).map_err(|e| anyhow::anyhow!("SVG render failed: {e}"))?;
self.path = Some(path.to_path_buf());
self.disk_stamp = Self::disk_stamp_of(path);
self.disk_conflict = false;
self.encoding_loss = false;
self.lossy_save_armed = false;
self.lines = vec![String::new()];
self.edit_seq = self.edit_seq.wrapping_add(1);
self.lang = None;
self.scroll = 0;
self.cursor_row = 0;
self.cursor_col = 0;
self.dirty = false;
self.selection = None;
self.undo_stack.clear();
self.redo_stack.clear();
self.last_edit_kind = None;
self.highlights = vec![Vec::new()];
self.diff = None;
self.diff_prev_arrow = Rect::default();
self.diff_next_arrow = Rect::default();
self.sheet = None;
self.hex = None;
self.markdown_preview = None;
self.image = Some(ImageView {
bytes: png,
format_label: String::from("SVG"),
pixel_w,
pixel_h,
byte_size: meta.len(),
generation: next_image_generation(),
pdf: None,
});
self.status = format!("Opened SVG {}", path.display());
Ok(())
}
fn install_sheet_view(&mut self, path: &Path, view: crate::sheet::SheetView) {
self.path = Some(path.to_path_buf());
self.disk_stamp = Self::disk_stamp_of(path);
self.disk_conflict = false;
self.encoding_loss = false;
self.lossy_save_armed = false;
self.lines = vec![String::new()];
self.edit_seq = self.edit_seq.wrapping_add(1);
self.lang = None;
self.scroll = 0;
self.cursor_row = 0;
self.cursor_col = 0;
self.dirty = false;
self.selection = None;
self.undo_stack.clear();
self.redo_stack.clear();
self.last_edit_kind = None;
self.highlights = vec![Vec::new()];
self.diff = None;
self.diff_prev_arrow = Rect::default();
self.diff_next_arrow = Rect::default();
self.image = None;
self.hex = None;
self.status = format!("Opened {} ({})", path.display(), view.kind.label());
self.sheet = Some(view);
}
fn open_pdf(&mut self, path: &Path) -> Result<()> {
let backend = crate::pdf::detect_backend()
.ok_or_else(|| anyhow::anyhow!("Install poppler (pdftoppm) to preview PDFs"))?;
let meta = std::fs::metadata(path)?;
let page_count = crate::pdf::detect_page_count(path);
let page = match self.pdf_restore_page.take() {
Some(p) => p.clamp(1, page_count.unwrap_or(p).max(1)),
None => 1,
};
let bytes = crate::pdf::rasterize_page(path, page, backend)
.map_err(|e| anyhow::anyhow!("PDF render failed: {e}"))?;
let (pixel_w, pixel_h) = image::load_from_memory(&bytes)
.map(|img| (img.width(), img.height()))
.map_err(|e| anyhow::anyhow!("Could not decode rasterised PDF: {e}"))?;
self.path = Some(path.to_path_buf());
self.disk_stamp = Self::disk_stamp_of(path);
self.disk_conflict = false;
self.encoding_loss = false;
self.lossy_save_armed = false;
self.lines = vec![String::new()];
self.edit_seq = self.edit_seq.wrapping_add(1);
self.lang = None;
self.scroll = 0;
self.cursor_row = 0;
self.cursor_col = 0;
self.dirty = false;
self.selection = None;
self.undo_stack.clear();
self.redo_stack.clear();
self.last_edit_kind = None;
self.highlights = vec![Vec::new()];
self.image = Some(ImageView {
bytes,
format_label: String::from("PDF"),
pixel_w,
pixel_h,
byte_size: meta.len(),
generation: next_image_generation(),
pdf: Some(PdfState {
source_path: path.to_path_buf(),
current_page: page,
page_count,
backend,
source_byte_size: meta.len(),
links: None,
}),
});
self.diff = None;
self.diff_prev_arrow = Rect::default();
self.diff_next_arrow = Rect::default();
self.sheet = None;
self.hex = None;
self.status = format!("Opened PDF {}", path.display());
Ok(())
}
pub fn has_non_text_view(&self) -> bool {
self.diff.is_some() || self.sheet.is_some() || self.image.is_some() || self.hex.is_some()
}
pub fn open_hex(&mut self, path: &Path) -> Result<()> {
if self.path.as_deref() == Some(path)
&& let Some(view) = self.hex.as_mut()
{
view.refresh_from_disk(path)
.map_err(|e| anyhow::anyhow!("Hex reload failed: {e}"))?;
self.disk_stamp = Self::disk_stamp_of(path);
self.disk_conflict = false;
return Ok(());
}
let view =
crate::hex::HexView::open(path).map_err(|e| anyhow::anyhow!("Hex open failed: {e}"))?;
self.path = Some(path.to_path_buf());
self.disk_stamp = Self::disk_stamp_of(path);
self.disk_conflict = false;
self.encoding_loss = false;
self.lossy_save_armed = false;
self.lines = vec![String::new()];
self.edit_seq = self.edit_seq.wrapping_add(1);
self.lang = None;
self.scroll = 0;
self.cursor_row = 0;
self.cursor_col = 0;
self.dirty = false;
self.selection = None;
self.undo_stack.clear();
self.redo_stack.clear();
self.last_edit_kind = None;
self.highlights = vec![Vec::new()];
self.diff = None;
self.diff_prev_arrow = Rect::default();
self.diff_next_arrow = Rect::default();
self.image = None;
self.sheet = None;
self.markdown_preview = None;
self.hex = Some(view);
self.status = format!("Opened {} in the hex viewer", path.display());
Ok(())
}
pub fn pdf_page(&self) -> Option<u32> {
self.image.as_ref()?.pdf.as_ref().map(|p| p.current_page)
}
pub fn change_pdf_page(&mut self, delta: i32) -> bool {
let Some(pdf) = self.image.as_ref().and_then(|i| i.pdf.clone()) else {
return false;
};
let new_page = if let Some(total) = pdf.page_count {
if total == 0 {
return false;
}
let cur = pdf.current_page as i64;
let next = ((cur - 1 + delta as i64).rem_euclid(total as i64)) + 1;
next as u32
} else if delta > 0 {
pdf.current_page.saturating_add(delta as u32)
} else {
pdf.current_page.saturating_sub((-delta) as u32).max(1)
};
self.render_pdf_page(new_page)
}
pub fn set_pdf_page(&mut self, page: u32) -> bool {
let Some(pdf) = self.image.as_ref().and_then(|i| i.pdf.clone()) else {
return false;
};
if page == u32::MAX && pdf.page_count.is_none() {
self.status = String::from("PDF page count unknown; cannot jump to the last page");
return false;
}
let last = pdf.page_count.unwrap_or(u32::MAX).max(1);
self.render_pdf_page(page.clamp(1, last))
}
fn render_pdf_page(&mut self, new_page: u32) -> bool {
let Some(image) = self.image.as_mut() else {
return false;
};
let Some(pdf) = image.pdf.clone() else {
return false;
};
if new_page == pdf.current_page {
return false;
}
let bytes = match crate::pdf::rasterize_page(&pdf.source_path, new_page, pdf.backend) {
Ok(b) => b,
Err(e) => {
self.status = format!("PDF page {new_page} failed: {e}");
return false;
}
};
let (pixel_w, pixel_h) = match image::load_from_memory(&bytes) {
Ok(img) => (img.width(), img.height()),
Err(_) => return false,
};
image.bytes = bytes;
image.generation = next_image_generation();
image.pixel_w = pixel_w;
image.pixel_h = pixel_h;
if let Some(state) = image.pdf.as_mut() {
state.current_page = new_page;
state.links = None;
}
true
}
pub fn rehighlight_for_theme(&mut self) {
self.recompute_highlights();
if self.markdown_preview.is_some() {
let text = self.lines.join("\n");
let lines = crate::markdown::render_markdown(&text, self.theme, &mut self.registry);
if let Some(md) = self.markdown_preview.as_mut() {
md.lines = lines;
md.built_seq = self.edit_seq;
}
}
}
fn recompute_highlights(&mut self) {
match self.lang {
Some(kind) => {
let text = self.lines.join("\n");
let bytes = text.as_bytes();
let line_starts = compute_line_starts(bytes);
let (spans, protected) = crate::highlight::highlight_text_with_protected(
&mut self.registry,
kind,
bytes,
&line_starts,
);
self.highlights = spans;
self.bracket_colors = scan_bracket_colors(&self.lines, &protected);
}
None => {
self.highlights = vec![Vec::new(); self.lines.len()];
let bytes: usize = self.lines.iter().map(String::len).sum();
self.bracket_colors = if bytes > BRACKET_SCAN_MAX_BYTES {
Vec::new()
} else {
scan_bracket_colors(&self.lines, &[])
};
}
}
self.recompute_semantic_overlay();
self.recompute_diagnostic_spans();
self.recompute_inlay_spans();
}
pub fn apply_semantic_tokens(
&mut self,
path: PathBuf,
data: Vec<u32>,
legend: std::sync::Arc<Vec<String>>,
is_full: bool,
) {
let same_file = self.semantic_path.as_deref() == Some(path.as_path());
if !is_full && same_file && self.semantic_is_full {
return;
}
self.semantic_path = Some(path);
self.semantic_data = data;
self.semantic_legend = Some(legend);
self.semantic_is_full = is_full;
self.recompute_semantic_overlay();
}
pub fn apply_inlay_hints(
&mut self,
path: PathBuf,
hints: Vec<crate::lsp::manager::InlayHintItem>,
) {
self.inlay_path = Some(path);
self.inlay_hints = hints;
self.recompute_inlay_spans();
}
pub fn apply_occurrences(&mut self, items: Vec<crate::lsp::manager::OccurrenceItem>) {
self.occurrences.clear();
for item in items {
for row in item.start_line..=item.end_line {
let row = row as usize;
let Some(text) = self.lines.get(row) else {
continue;
};
let cols = text.chars().count();
let start = if row as u32 == item.start_line {
utf16_to_char_col(text, item.start_char).min(cols)
} else {
0
};
let end = if row as u32 == item.end_line {
utf16_to_char_col(text, item.end_char).min(cols)
} else {
cols
};
if end > start {
self.occurrences.push((row, start, end, item.write));
}
}
}
}
pub fn clear_occurrences(&mut self) -> bool {
let had = !self.occurrences.is_empty();
self.occurrences.clear();
had
}
pub fn clear_inlay_hints(&mut self) {
self.inlay_hints = Vec::new();
self.inlay_path = None;
self.recompute_inlay_spans();
}
fn recompute_inlay_spans(&mut self) {
self.hscroll_content_cols = None;
let same_file = self.inlay_path.as_deref() == self.path.as_deref();
if !same_file || self.inlay_hints.is_empty() {
self.inlay_spans = Vec::new();
return;
}
let mut spans: Vec<Vec<(usize, String)>> = vec![Vec::new(); self.lines.len()];
for h in &self.inlay_hints {
let Some(text) = self.lines.get(h.line as usize) else {
continue;
};
let col = utf16_to_char_col(text, h.character).min(text.chars().count());
spans[h.line as usize].push((col, h.label.clone()));
}
for line in &mut spans {
line.sort_by_key(|(c, _)| *c);
}
self.inlay_spans = spans;
}
fn row_inlay_spans(&self, line: usize) -> &[(usize, String)] {
if self.wrap_enabled() {
return &[];
}
self.inlay_spans.get(line).map(Vec::as_slice).unwrap_or(&[])
}
pub fn clean_cache_text(&self) -> Option<String> {
(!self.dirty).then(|| self.lines.join("\n"))
}
#[cfg(test)]
pub(crate) fn semantic_overlay_for_test(&self) -> &[Vec<HiSpan>] {
&self.semantic_overlay
}
#[cfg(test)]
pub(crate) fn occurrence_count_for_test(&self) -> usize {
self.occurrences.len()
}
#[cfg(test)]
pub(crate) fn lines_for_test(&self) -> &[String] {
&self.lines
}
pub fn apply_diagnostics(
&mut self,
path: PathBuf,
diagnostics: Vec<crate::lsp::manager::Diagnostic>,
) {
self.diagnostics_path = Some(path);
self.diagnostics = diagnostics;
self.recompute_diagnostic_spans();
}
pub fn diagnostics_path(&self) -> Option<&Path> {
self.diagnostics_path.as_deref()
}
pub fn diagnostics_in_line_range(
&self,
start_line: u32,
end_line: u32,
) -> Vec<crate::lsp::manager::Diagnostic> {
self.diagnostics
.iter()
.filter(|d| d.start_line <= end_line && d.end_line >= start_line)
.cloned()
.collect()
}
#[cfg(test)]
pub(crate) fn diagnostic_spans_for_test(
&self,
) -> &[Vec<(usize, usize, crate::lsp::manager::DiagnosticSeverity)>] {
&self.diagnostic_spans
}
fn recompute_diagnostic_spans(&mut self) {
let same_file = self.diagnostics_path.as_deref() == self.path.as_deref();
if !same_file || self.diagnostics.is_empty() {
self.diagnostic_spans = Vec::new();
return;
}
let mut spans: Vec<Vec<(usize, usize, crate::lsp::manager::DiagnosticSeverity)>> =
vec![Vec::new(); self.lines.len()];
for d in &self.diagnostics {
let start_line = d.start_line as usize;
let end_line = d.end_line as usize;
for (line, (text, line_spans)) in self
.lines
.iter()
.zip(spans.iter_mut())
.enumerate()
.take(end_line + 1)
.skip(start_line)
{
let line_chars = text.chars().count();
let from = if line == start_line {
utf16_to_char_col(text, d.start_char)
} else {
0
};
let to = if line == end_line {
utf16_to_char_col(text, d.end_char)
} else {
line_chars
};
let to = to.max(from + 1);
line_spans.push((from, to, d.severity));
}
}
self.diagnostic_spans = spans;
}
fn recompute_semantic_overlay(&mut self) {
let same_file = self.semantic_path.as_deref() == self.path.as_deref();
let Some(legend) = self.semantic_legend.as_ref().filter(|_| same_file) else {
self.semantic_overlay = Vec::new();
return;
};
if self.semantic_data.is_empty() {
self.semantic_overlay = Vec::new();
return;
}
let text = self.lines.join("\n");
let bytes = text.as_bytes();
let line_starts = compute_line_starts(bytes);
self.semantic_overlay =
decode_semantic_tokens(&self.semantic_data, legend, bytes, &line_starts);
}
pub fn line_count(&self) -> usize {
self.lines.len()
}
pub fn toggle_markdown_preview(&mut self) -> bool {
if self.markdown_preview.take().is_some() {
return true;
}
let is_md_text = matches!(self.lang, Some(LangKind::Markdown))
&& self.image.is_none()
&& self.sheet.is_none()
&& self.diff.is_none();
if !is_md_text {
return false;
}
let text = self.lines.join("\n");
let lines = crate::markdown::render_markdown(&text, self.theme, &mut self.registry);
self.markdown_preview = Some(crate::markdown::MarkdownPreview {
lines,
scroll: 0,
built_seq: self.edit_seq,
});
true
}
pub fn scroll_markdown_preview(&mut self, delta: i32) -> bool {
let Some(md) = self.markdown_preview.as_mut() else {
return false;
};
md.scroll = md.scroll.saturating_add_signed(delta as i16);
true
}
fn line_char_len(&self, row: usize) -> usize {
self.lines.get(row).map(|s| s.chars().count()).unwrap_or(0)
}
fn byte_index(&self, row: usize, col: usize) -> usize {
let line = &self.lines[row];
line.char_indices()
.nth(col)
.map(|(i, _)| i)
.unwrap_or(line.len())
}
fn pin_on_edit(&mut self) {
self.preview = false;
self.reveal_cursor_fold();
}
pub fn insert_char(&mut self, c: char) {
if self.auto_close_pairs && self.insert_char_with_pairs(c) {
return;
}
self.pin_on_edit();
let had_selection = self.selection.map(|s| s.has_area()).unwrap_or(false);
let kind = if had_selection {
EditKind::DeleteSelection
} else {
EditKind::InsertChar
};
self.push_undo(kind);
self.delete_selection_inner();
if self.lines.is_empty() {
self.lines.push(String::new());
}
let row = self.cursor_row;
let col = self.cursor_col;
let byte = self.byte_index(row, col);
self.lines[row].insert(byte, c);
self.cursor_col += 1;
self.mark_buffer_changed();
self.recompute_highlights();
}
fn insert_char_with_pairs(&mut self, c: char) -> bool {
if self.lines.is_empty() {
self.lines.push(String::new());
}
let close = auto_close_partner(c);
let has_sel = self.selection.map(|s| s.has_area()).unwrap_or(false);
if has_sel {
let Some(close) = close else {
return false;
};
if is_pair_closer(c) {
return false;
}
self.pin_on_edit();
self.push_undo(EditKind::Paste);
let ((sr, sc), (er, ec)) = self.selection.unwrap().normalised();
let close_byte = self.byte_index(er, ec);
self.lines[er].insert(close_byte, close);
let open_byte = self.byte_index(sr, sc);
self.lines[sr].insert(open_byte, c);
let inner_end = if sr == er { ec + 1 } else { ec };
self.selection = Some(EditorSelection {
anchor: (sr, sc + 1),
head: (er, inner_end),
});
self.cursor_row = er;
self.cursor_col = inner_end;
self.mark_buffer_changed();
self.recompute_highlights();
return true;
}
let next = self
.lines
.get(self.cursor_row)
.and_then(|l| l.chars().nth(self.cursor_col));
if (is_pair_closer(c) || is_pair_quote(c)) && next == Some(c) {
self.cursor_col += 1;
self.ensure_cursor_col_visible();
return true;
}
let Some(close) = close else {
return false;
};
if is_pair_closer(c) {
return false;
}
let next_ok = next.is_none_or(|n| !n.is_alphanumeric() && n != '_' && n != c);
let prev = if self.cursor_col == 0 {
None
} else {
self.lines
.get(self.cursor_row)
.and_then(|l| l.chars().nth(self.cursor_col - 1))
};
let prev_ok =
!is_pair_quote(c) || prev.is_none_or(|p| !p.is_alphanumeric() && p != '_' && p != c);
if !next_ok || !prev_ok {
return false;
}
self.pin_on_edit();
self.push_undo(EditKind::InsertChar);
let row = self.cursor_row;
let byte = self.byte_index(row, self.cursor_col);
self.lines[row].insert(byte, close);
self.lines[row].insert(byte, c);
self.cursor_col += 1;
self.mark_buffer_changed();
self.recompute_highlights();
self.auto_pair_at = Some((self.cursor_row, self.cursor_col, self.edit_seq));
true
}
pub fn apply_span_edits(&mut self, edits: &[TextSpanEdit]) -> usize {
if edits.is_empty() {
return 0;
}
self.pin_on_edit();
self.push_undo(EditKind::Paste);
let n = apply_span_edits_to_lines(&mut self.lines, edits);
if n > 0 {
self.mark_buffer_changed();
self.recompute_highlights();
}
n
}
pub fn indent_style(&self) -> IndentStyle {
self.indent_override.unwrap_or(IndentStyle {
width: indent_unit_for(self.lang).chars().count() as u32,
use_spaces: true,
})
}
pub fn set_indent_style(&mut self, style: IndentStyle) {
self.indent_override = Some(style);
}
fn indent_unit(&self) -> String {
self.indent_style().unit()
}
pub fn indent_preference(&self) -> (u32, bool) {
let s = self.indent_style();
(s.width, s.use_spaces)
}
pub fn language_label(&self) -> &'static str {
language_label(self.lang)
}
pub fn language(&self) -> Option<LangKind> {
self.lang
}
pub fn set_language(&mut self, lang: Option<LangKind>) {
self.lang = lang;
self.recompute_highlights();
}
pub fn reopen_with_encoding(&mut self, enc: &'static encoding_rs::Encoding) -> Result<()> {
let path = self
.path
.clone()
.ok_or_else(|| anyhow::anyhow!("No file open"))?;
let bytes = std::fs::read(&path)?;
let (decoded, used, _) = enc.decode(&bytes);
let text = decoded.into_owned();
self.encoding = used;
self.bom = encoding_rs::Encoding::for_bom(&bytes).is_some();
self.eol = if text.contains("\r\n") {
LineEnding::Crlf
} else {
LineEnding::Lf
};
self.lines = split_into_lines(&text);
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.undo_stack.clear();
self.redo_stack.clear();
self.hscroll_content_cols = None;
self.wrap_total_cache.clear();
self.scroll = 0;
self.scroll_sub = 0;
self.cursor_row = 0;
self.cursor_col = 0;
self.selection = None;
self.dirty = false;
self.encoding_loss = false;
self.lossy_save_armed = false;
self.edit_seq = self.edit_seq.wrapping_add(1);
self.recompute_highlights();
Ok(())
}
pub fn clamp_cursor(&mut self) {
if self.lines.is_empty() {
self.cursor_row = 0;
self.cursor_col = 0;
return;
}
self.cursor_row = self.cursor_row.min(self.lines.len() - 1);
let max_col = self.lines[self.cursor_row].chars().count();
self.cursor_col = self.cursor_col.min(max_col);
}
pub fn insert_str(&mut self, s: &str) {
self.pin_on_edit();
self.push_undo(EditKind::Paste);
if self.selection.is_some() {
self.delete_selection_inner();
}
for c in s.chars() {
if c == '\n' {
self.insert_newline_raw();
} else {
self.insert_char_raw(c);
}
}
self.recompute_highlights();
}
fn insert_char_raw(&mut self, c: char) {
if self.lines.is_empty() {
self.lines.push(String::new());
}
let row = self.cursor_row;
let col = self.cursor_col;
let byte = self.byte_index(row, col);
self.lines[row].insert(byte, c);
self.cursor_col += 1;
self.mark_buffer_changed();
}
pub fn scope_id(&self) -> &'static str {
language_scope_id(self.lang)
}
pub fn snippet_active(&self) -> bool {
self.snippet.is_some()
}
pub fn cancel_snippet(&mut self) {
self.snippet = None;
}
pub fn expand_snippet(&mut self, body: &str, prefix_len: usize) {
self.snippet = None;
for _ in 0..prefix_len {
self.backspace();
}
let start = (self.cursor_row, self.cursor_col);
let indent: String = self
.lines
.get(start.0)
.map(|l| {
l.chars()
.take(start.1)
.take_while(|c| *c == ' ' || *c == '\t')
.collect()
})
.unwrap_or_default();
let indent_len = indent.chars().count();
let parsed = crate::snippets::parse_body(body);
let inserted = if indent.is_empty() {
parsed.text.clone()
} else {
parsed.text.replace('\n', &format!("\n{indent}"))
};
self.insert_str(&inserted);
let mut abs: std::collections::VecDeque<(usize, usize, usize)> = parsed
.stops
.iter()
.map(|s| {
let (ld, col) = crate::snippets::offset_to_line_col(&parsed.text, s.offset);
let row = start.0 + ld;
let c = if ld == 0 {
start.1 + col
} else {
indent_len + col
};
(row, c, s.len)
})
.collect();
let Some(first) = abs.pop_front() else {
return; };
self.place_at_snippet_stop(first);
if !abs.is_empty() {
self.snippet = Some(SnippetSession {
anchor: (first.0, first.1),
cur_len: first.2,
stops: abs,
});
}
}
pub fn snippet_next(&mut self) -> bool {
let Some(mut sess) = self.snippet.take() else {
return false;
};
if self.cursor_row == sess.anchor.0 {
let typed = self.cursor_col as isize - sess.anchor.1 as isize;
let shift = typed - sess.cur_len as isize;
if shift != 0 {
let after = sess.anchor.1 + sess.cur_len;
for s in sess.stops.iter_mut() {
if s.0 == sess.anchor.0 && s.1 >= after {
s.1 = (s.1 as isize + shift).max(0) as usize;
}
}
}
}
let Some(next) = sess.stops.pop_front() else {
return false;
};
self.place_at_snippet_stop(next);
if !sess.stops.is_empty() {
sess.anchor = (next.0, next.1);
sess.cur_len = next.2;
self.snippet = Some(sess);
}
true
}
fn place_at_snippet_stop(&mut self, stop: (usize, usize, usize)) {
let (row, col, len) = stop;
let row = row.min(self.lines.len().saturating_sub(1));
let line_len = self.line_char_len(row);
let col = col.min(line_len);
let end = (col + len).min(line_len);
self.cursor_row = row;
self.cursor_col = end;
self.selection = (end > col).then_some(EditorSelection {
anchor: (row, col),
head: (row, end),
});
}
fn insert_newline_raw(&mut self) {
if self.lines.is_empty() {
self.lines.push(String::new());
}
let row = self.cursor_row;
let col = self.cursor_col;
let byte = self.byte_index(row, col);
let right = self.lines[row].split_off(byte);
self.lines.insert(row + 1, right);
self.cursor_row += 1;
self.cursor_col = 0;
self.mark_buffer_changed();
}
pub fn insert_newline(&mut self) {
self.pin_on_edit();
self.push_undo(EditKind::Newline);
self.delete_selection_inner();
self.smart_insert_newline_inner();
self.recompute_highlights();
}
fn smart_insert_newline_inner(&mut self) {
if self.lines.is_empty() {
self.lines.push(String::new());
}
let row = self.cursor_row;
let col = self.cursor_col;
let line = self.lines[row].clone();
let leading: String = line
.chars()
.take(col)
.take_while(|c| *c == ' ' || *c == '\t')
.collect();
let prefix_chars: Vec<char> = line.chars().take(col).collect();
let last_non_ws = prefix_chars
.iter()
.rev()
.find(|c| !c.is_whitespace())
.copied();
let next_char = line.chars().nth(col);
let unit = self.indent_unit();
let extra = if extra_indent_triggered(self.lang, last_non_ws) {
unit.as_str()
} else {
""
};
let pair_split = is_bracket_pair_split(self.lang, last_non_ws, next_char);
self.insert_newline_raw();
let new_indent = format!("{leading}{extra}");
for c in new_indent.chars() {
self.insert_char_raw(c);
}
if pair_split {
self.insert_newline_raw();
for c in leading.chars() {
self.insert_char_raw(c);
}
self.cursor_row -= 1;
self.cursor_col = new_indent.chars().count();
}
}
pub fn backspace(&mut self) {
self.pin_on_edit();
self.push_undo(EditKind::Backspace);
if self.auto_close_pairs
&& !self.selection.map(|s| s.has_area()).unwrap_or(false)
&& self.cursor_col > 0
&& self.auto_pair_at == Some((self.cursor_row, self.cursor_col, self.edit_seq))
{
let line = self.lines.get(self.cursor_row).cloned().unwrap_or_default();
let prev = line.chars().nth(self.cursor_col - 1);
let next = line.chars().nth(self.cursor_col);
if let (Some(p), Some(n)) = (prev, next)
&& auto_close_partner(p) == Some(n)
&& !is_pair_closer(p)
{
let byte = self.byte_index(self.cursor_row, self.cursor_col);
self.lines[self.cursor_row].remove(byte);
}
}
self.backspace_raw();
self.recompute_highlights();
}
fn backspace_raw(&mut self) {
if self.delete_selection_inner() {
return;
}
if self.cursor_col > 0 {
let row = self.cursor_row;
let col = self.cursor_col - 1;
let from = self.byte_index(row, col);
let to = self.byte_index(row, col + 1);
self.lines[row].replace_range(from..to, "");
self.cursor_col -= 1;
self.mark_buffer_changed();
} else if self.cursor_row > 0 {
let cur = self.lines.remove(self.cursor_row);
self.cursor_row -= 1;
self.cursor_col = self.line_char_len(self.cursor_row);
self.lines[self.cursor_row].push_str(&cur);
self.mark_buffer_changed();
}
}
pub fn delete_forward(&mut self) {
self.pin_on_edit();
self.push_undo(EditKind::DeleteForward);
self.delete_forward_raw();
self.recompute_highlights();
}
fn delete_forward_raw(&mut self) {
if self.delete_selection_inner() {
return;
}
let row = self.cursor_row;
let len = self.line_char_len(row);
if self.cursor_col < len {
let from = self.byte_index(row, self.cursor_col);
let to = self.byte_index(row, self.cursor_col + 1);
self.lines[row].replace_range(from..to, "");
self.mark_buffer_changed();
} else if row + 1 < self.lines.len() {
let next = self.lines.remove(row + 1);
self.lines[row].push_str(&next);
self.mark_buffer_changed();
}
}
pub fn has_multi_cursor(&self) -> bool {
!self.carets.is_empty()
}
pub fn collapse_carets(&mut self) {
self.carets.clear();
}
pub fn select_all_occurrences_of_word_at_cursor(&mut self) -> usize {
let Some((start, end)) = self.word_at(self.cursor_row, self.cursor_col) else {
return 0;
};
let word: Vec<char> = self.lines[self.cursor_row]
.chars()
.skip(start)
.take(end - start)
.collect();
if word.is_empty() {
return 0;
}
let mut occ: Vec<EditorSelection> = Vec::new();
for (row, line) in self.lines.iter().enumerate() {
let chars: Vec<char> = line.chars().collect();
for col in find_word_occurrences(&chars, &word) {
occ.push(EditorSelection {
anchor: (row, col),
head: (row, col + word.len()),
});
}
}
if occ.is_empty() {
return 0;
}
let primary_idx = occ
.iter()
.position(|s| {
s.anchor.0 == self.cursor_row
&& self.cursor_col >= s.anchor.1
&& self.cursor_col <= s.head.1
})
.unwrap_or(0);
let primary = occ[primary_idx];
self.selection = Some(primary);
self.cursor_row = primary.head.0;
self.cursor_col = primary.head.1;
self.carets = occ
.into_iter()
.enumerate()
.filter(|(i, _)| *i != primary_idx)
.map(|(_, s)| s)
.collect();
self.carets.len() + 1
}
pub fn select_next_occurrence(&mut self) -> usize {
let Some(sel) = self.selection else {
let Some((s, e)) = self.word_at(self.cursor_row, self.cursor_col) else {
return 0;
};
self.selection = Some(EditorSelection {
anchor: (self.cursor_row, s),
head: (self.cursor_row, e),
});
self.cursor_col = e;
self.ensure_cursor_col_visible();
return 1;
};
let (start, end) = sel.normalised();
if start.0 != end.0 {
return self.carets.len() + 1;
}
let word: Vec<char> = self.lines[start.0]
.chars()
.skip(start.1)
.take(end.1 - start.1)
.collect();
if word.is_empty() {
return self.carets.len() + 1;
}
let mut occ: Vec<(usize, usize)> = Vec::new();
for (row, line) in self.lines.iter().enumerate() {
let chars: Vec<char> = line.chars().collect();
for col in find_word_occurrences(&chars, &word) {
occ.push((row, col));
}
}
let mut taken: Vec<(usize, usize)> = self.carets.iter().map(|c| c.normalised().0).collect();
taken.push(start);
let from = occ.iter().position(|&o| o == start).unwrap_or(0);
let n = occ.len();
let next = (1..=n)
.map(|k| occ[(from + k) % n])
.find(|o| !taken.contains(o));
let Some((row, col)) = next else {
return self.carets.len() + 1;
};
self.carets.push(sel);
let head = (row, col + word.len());
self.selection = Some(EditorSelection {
anchor: (row, col),
head,
});
self.cursor_row = head.0;
self.cursor_col = head.1;
self.ensure_cursor_col_visible();
self.carets.len() + 1
}
pub fn multi_insert_char(&mut self, c: char) {
self.multi_apply(CaretEdit::Insert(c));
}
pub fn multi_backspace(&mut self) {
self.multi_apply(CaretEdit::Backspace);
}
pub fn multi_delete_forward(&mut self) {
self.multi_apply(CaretEdit::DeleteForward);
}
fn multi_apply(&mut self, edit: CaretEdit) {
self.pin_on_edit();
self.push_undo(EditKind::MultiEdit);
let primary = self
.selection
.unwrap_or_else(|| EditorSelection::new(self.cursor_row, self.cursor_col));
let mut items: Vec<(bool, EditorSelection)> = Vec::with_capacity(self.carets.len() + 1);
items.push((true, primary));
for s in &self.carets {
items.push((false, *s));
}
items.sort_by_key(|item| std::cmp::Reverse(item.1.normalised().0));
self.carets.clear();
let mut new_primary = (self.cursor_row, self.cursor_col);
let mut new_secondary: Vec<(usize, usize)> = Vec::new();
for (is_primary, sel) in items {
if sel.has_area() {
self.selection = Some(sel);
} else {
self.selection = None;
}
let last = self.lines.len().saturating_sub(1);
self.cursor_row = sel.head.0.min(last);
self.cursor_col = sel.head.1.min(self.line_char_len(self.cursor_row));
self.apply_caret_edit_raw(edit);
let pos = (self.cursor_row, self.cursor_col);
if is_primary {
new_primary = pos;
} else {
new_secondary.push(pos);
}
}
self.selection = None;
let last = self.lines.len().saturating_sub(1);
self.cursor_row = new_primary.0.min(last);
self.cursor_col = new_primary.1.min(self.line_char_len(self.cursor_row));
new_secondary.sort_unstable();
self.carets = new_secondary
.into_iter()
.map(|(r, c)| EditorSelection::new(r, c))
.collect();
self.recompute_highlights();
}
fn apply_caret_edit_raw(&mut self, edit: CaretEdit) {
match edit {
CaretEdit::Insert(c) => {
self.delete_selection_inner();
self.insert_char_raw(c);
}
CaretEdit::Backspace => self.backspace_raw(),
CaretEdit::DeleteForward => self.delete_forward_raw(),
}
}
pub fn start_selection_at_cursor(&mut self) {
self.selection = Some(EditorSelection::new(self.cursor_row, self.cursor_col));
}
pub fn extend_selection_to_cursor(&mut self) {
if let Some(sel) = self.selection.as_mut() {
sel.head = (self.cursor_row, self.cursor_col);
} else {
self.start_selection_at_cursor();
}
}
pub fn clear_selection(&mut self) {
self.selection = None;
}
pub fn select_all(&mut self) {
if self.lines.is_empty() {
self.selection = None;
return;
}
let last_row = self.lines.len() - 1;
let last_col = self.line_char_len(last_row);
self.selection = Some(EditorSelection {
anchor: (0, 0),
head: (last_row, last_col),
});
self.cursor_row = last_row;
self.cursor_col = last_col;
}
pub fn selection_text(&self) -> String {
let Some(sel) = self.selection else {
return String::new();
};
if !sel.has_area() {
return String::new();
}
let ((sr, sc), (er, ec)) = sel.normalised();
if sr == er {
let line = &self.lines[sr];
let from = char_byte(line, sc);
let to = char_byte(line, ec);
return line[from..to].to_string();
}
let mut out = String::new();
let first = &self.lines[sr];
let from = char_byte(first, sc);
out.push_str(&first[from..]);
out.push('\n');
for r in (sr + 1)..er {
out.push_str(&self.lines[r]);
out.push('\n');
}
let last = &self.lines[er];
let to = char_byte(last, ec);
out.push_str(&last[..to]);
out
}
fn selection_occurrence_needle(&self) -> Option<String> {
let sel = self.selection?;
if !sel.has_area() {
return None;
}
let ((sr, sc), (er, ec)) = sel.normalised();
if sr != er {
return None;
}
let line = &self.lines[sr];
let text = &line[char_byte(line, sc)..char_byte(line, ec)];
if text.trim().is_empty() || text.chars().count() > SELECTION_HIGHLIGHT_MAX_LEN {
return None;
}
Some(text.to_string())
}
pub fn delete_selection(&mut self) -> bool {
if !self.selection.map(|s| s.has_area()).unwrap_or(false) {
self.selection = None;
return false;
}
self.push_undo(EditKind::DeleteSelection);
let removed = self.delete_selection_inner();
if removed {
self.recompute_highlights();
}
removed
}
fn delete_selection_inner(&mut self) -> bool {
let Some(sel) = self.selection else {
return false;
};
if !sel.has_area() {
self.selection = None;
return false;
}
let ((sr, sc), (er, ec)) = sel.normalised();
if sr == er {
let line = &mut self.lines[sr];
let from = char_byte(line, sc);
let to = char_byte(line, ec);
line.replace_range(from..to, "");
} else {
let last = self.lines.remove(er);
for _ in (sr + 1)..er {
self.lines.remove(sr + 1);
}
let first = &mut self.lines[sr];
let from = char_byte(first, sc);
first.truncate(from);
let to = char_byte(&last, ec);
first.push_str(&last[to..]);
}
self.cursor_row = sr;
self.cursor_col = sc;
self.selection = None;
self.mark_buffer_changed();
true
}
fn indent_width(&self, line: usize) -> Option<usize> {
let s = self.lines.get(line)?;
(!s.trim().is_empty()).then(|| s.chars().take_while(|c| *c == ' ' || *c == '\t').count())
}
pub fn fold_range(&self, line: usize) -> Option<(usize, usize)> {
let base = self.indent_width(line)?;
let mut end = line;
let mut i = line + 1;
while i < self.lines.len() {
match self.indent_width(i) {
None => {} Some(w) if w > base => end = i,
Some(_) => break, }
i += 1;
}
(end > line).then_some((line, end))
}
pub fn is_foldable(&self, line: usize) -> bool {
self.fold_range(line).is_some()
}
fn outermost_enclosing_header(&self, line: usize) -> Option<usize> {
let mut head = self.enclosing_fold_header(line)?;
loop {
let above = (0..head)
.rev()
.find(|&h| matches!(self.fold_range(h), Some((_, end)) if head <= end));
match above {
Some(a) => head = a,
None => return Some(head),
}
}
}
pub fn set_inline_values_from_locals(&mut self, stop_line: usize, locals: &[(String, String)]) {
const MAX_ENTRIES_PER_LINE: usize = 4;
const MAX_VALUE_CHARS: usize = 40;
const MAX_SPAN_LINES: usize = 200;
self.inline_values.clear();
if locals.is_empty() || stop_line == 0 || self.lines.is_empty() {
return;
}
let stop = (stop_line - 1).min(self.lines.len() - 1);
let from = self
.outermost_enclosing_header(stop)
.unwrap_or(stop)
.max(stop.saturating_sub(MAX_SPAN_LINES));
for li in from..=stop {
let line = self.lines[li].clone();
let mut parts: Vec<String> = Vec::new();
for token in identifier_tokens(&line) {
if parts.len() >= MAX_ENTRIES_PER_LINE {
break;
}
let Some((name, value)) = locals.iter().find(|(n, _)| n == token) else {
continue;
};
if parts
.iter()
.any(|p| p.starts_with(name.as_str()) && p[name.len()..].starts_with(" = "))
{
continue;
}
let shown: String = if value.chars().count() > MAX_VALUE_CHARS {
let head: String = value.chars().take(MAX_VALUE_CHARS / 2).collect();
let tail: String = value
.chars()
.rev()
.take(MAX_VALUE_CHARS / 2 - 1)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
format!("{head}\u{2026}{tail}")
} else {
value.clone()
};
parts.push(format!("{name} = {shown}"));
}
if !parts.is_empty() {
self.inline_values.insert(li, parts.join(", "));
}
}
}
fn guide_step(&self) -> usize {
let s = self.indent_style();
if s.use_spaces {
s.width.max(1) as usize
} else {
1
}
}
fn guide_indent_width(&self, line: usize) -> usize {
const BLANK_SCAN_CAP: usize = 200;
if let Some(w) = self.indent_width(line) {
return w;
}
let above = (0..line)
.rev()
.take(BLANK_SCAN_CAP)
.find_map(|i| self.indent_width(i))
.unwrap_or(0);
let below = (line + 1..self.lines.len())
.take(BLANK_SCAN_CAP)
.find_map(|i| self.indent_width(i))
.unwrap_or(0);
above.min(below)
}
fn active_indent_guide(&self) -> Option<(usize, usize, usize)> {
const BLOCK_WALK_CAP: usize = 5_000;
let step = self.guide_step();
let cr = self.cursor_row.min(self.lines.len().saturating_sub(1));
let own = self
.indent_width(cr)
.unwrap_or_else(|| self.guide_indent_width(cr));
let below = (cr + 1..self.lines.len())
.take(BLOCK_WALK_CAP)
.find_map(|i| self.indent_width(i))
.unwrap_or(0);
let target = own.max(below);
if target == 0 {
return None;
}
let col = (target - 1) / step * step;
let anchor = if own > col { cr } else { cr + 1 };
if anchor >= self.lines.len() || self.guide_indent_width(anchor) <= col {
return None;
}
let mut lo = anchor;
while lo > 0 && anchor - (lo - 1) <= BLOCK_WALK_CAP && self.guide_indent_width(lo - 1) > col
{
lo -= 1;
}
let mut hi = anchor;
while hi + 1 < self.lines.len()
&& (hi + 1) - anchor <= BLOCK_WALK_CAP
&& self.guide_indent_width(hi + 1) > col
{
hi += 1;
}
Some((col, lo, hi))
}
fn enclosing_fold_header(&self, line: usize) -> Option<usize> {
if self.is_foldable(line) {
return Some(line);
}
(0..line)
.rev()
.find(|&h| matches!(self.fold_range(h), Some((_, end)) if line <= end))
}
pub fn is_line_hidden(&self, line: usize) -> bool {
self.hidden_ranges
.binary_search_by(|&(header, end)| {
if line <= header {
std::cmp::Ordering::Greater
} else if line > end {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Equal
}
})
.is_ok()
}
fn rebuild_hidden_ranges(&mut self) {
#[cfg(test)]
FOLD_RANGE_REBUILDS.with(|c| c.set(c.get() + 1));
let mut out: Vec<(usize, usize)> = Vec::new();
for &h in &self.folded {
if let Some(&(_, end)) = out.last()
&& h <= end
{
continue;
}
if let Some(span) = self.fold_range(h) {
out.push(span);
}
}
self.hidden_ranges = out;
}
pub fn reveal_cursor_fold(&mut self) {
if self.folded.is_empty() {
return;
}
let row = self.cursor_row;
let covering: Vec<usize> = self
.folded
.iter()
.copied()
.filter(|&h| matches!(self.fold_range(h), Some((_, end)) if h < row && row <= end))
.collect();
if covering.is_empty() {
return;
}
for h in covering {
self.folded.remove(&h);
}
self.rebuild_hidden_ranges();
}
fn next_visible_line(&self, line: usize) -> Option<usize> {
let mut l = line;
while l < self.lines.len() {
if !self.is_line_hidden(l) {
return Some(l);
}
l += 1;
}
None
}
fn prev_visible_line(&self, line: usize) -> usize {
let mut l = line;
while l > 0 && self.is_line_hidden(l) {
l -= 1;
}
l
}
pub fn toggle_fold(&mut self, line: usize) {
let Some(header) = self.enclosing_fold_header(line) else {
return;
};
let collapsing = !self.folded.remove(&header);
if collapsing {
self.folded.insert(header);
}
self.rebuild_hidden_ranges();
if collapsing && self.is_line_hidden(self.cursor_row) {
let len = self
.lines
.get(header)
.map(|s| s.chars().count())
.unwrap_or(0);
self.cursor_row = header;
self.cursor_col = self.cursor_col.min(len);
}
self.fold_epoch_lines = self.lines.len();
}
pub fn fold_all(&mut self) {
self.folded = (0..self.lines.len())
.filter(|&l| self.is_foldable(l))
.collect();
self.fold_epoch_lines = self.lines.len();
self.rebuild_hidden_ranges();
while self.cursor_row > 0 && self.is_line_hidden(self.cursor_row) {
self.cursor_row -= 1;
}
}
pub fn unfold_all(&mut self) {
self.folded.clear();
self.hidden_ranges.clear();
}
fn snapshot(&self) -> Snapshot {
Snapshot {
lines: self.lines.clone(),
cursor_row: self.cursor_row,
cursor_col: self.cursor_col,
selection: self.selection,
carets: self.carets.clone(),
dirty: self.dirty,
save_seq: self.save_seq,
}
}
fn push_undo(&mut self, kind: EditKind) {
let coalesce =
kind == EditKind::InsertChar && self.last_edit_kind == Some(EditKind::InsertChar);
if !coalesce {
self.undo_stack.push(self.snapshot());
if self.undo_stack.len() > UNDO_STACK_LIMIT {
self.undo_stack.remove(0);
}
}
self.redo_stack.clear();
self.last_edit_kind = Some(kind);
}
pub fn undo(&mut self) -> bool {
let Some(snap) = self.undo_stack.pop() else {
return false;
};
self.redo_stack.push(self.snapshot());
self.restore_snapshot(snap);
true
}
pub fn redo(&mut self) -> bool {
let Some(snap) = self.redo_stack.pop() else {
return false;
};
self.undo_stack.push(self.snapshot());
self.restore_snapshot(snap);
true
}
fn restore_snapshot(&mut self, snap: Snapshot) {
self.lines = snap.lines;
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.cursor_row = snap.cursor_row.min(self.lines.len().saturating_sub(1));
self.cursor_col = snap.cursor_col.min(self.line_char_len(self.cursor_row));
self.selection = snap.selection;
self.carets = snap.carets;
self.dirty = snap.dirty || self.save_seq != snap.save_seq;
self.last_edit_kind = None;
self.edit_seq = self.edit_seq.wrapping_add(1);
self.hscroll_content_cols = None;
self.wrap_total_cache.clear();
self.recompute_highlights();
}
pub fn break_undo_coalescing(&mut self) {
self.last_edit_kind = None;
}
pub fn mouse_down(&mut self, col: u16, row: u16) {
self.click(col, row);
self.start_selection_at_cursor();
}
pub fn mouse_drag(&mut self, col: u16, row: u16) {
if self.selection.is_none() {
self.start_selection_at_cursor();
}
self.click(col, row);
self.extend_selection_to_cursor();
}
pub fn matches_open_path(&self, event_path: &Path) -> bool {
let Some(open) = self.path.as_ref() else {
return false;
};
if open == event_path {
return true;
}
if let (Ok(a), Ok(b)) = (open.canonicalize(), event_path.canonicalize()) {
return a == b;
}
false
}
fn disk_stamp_of(path: &Path) -> Option<(SystemTime, u64)> {
let meta = std::fs::metadata(path).ok()?;
Some((meta.modified().ok()?, meta.len()))
}
fn mark_synced_with_disk(&mut self) {
self.disk_stamp = self.path.as_deref().and_then(Self::disk_stamp_of);
self.disk_conflict = false;
self.save_seq = self.save_seq.wrapping_add(1);
}
pub fn disk_changed_externally(&self) -> bool {
let Some(path) = self.path.as_deref() else {
return false;
};
match self.disk_stamp {
Some(known) => Self::disk_stamp_of(path) != Some(known),
None => false,
}
}
pub fn reload_if_clean(&mut self) -> Option<Result<()>> {
if self.dirty {
return None;
}
Some(self.reload_from_disk())
}
fn reload_from_disk(&mut self) -> Result<()> {
let Some(path) = self.path.as_ref().cloned() else {
return Ok(());
};
let prev_row = self.cursor_row;
let prev_col = self.cursor_col;
let prev_scroll = self.scroll;
self.pdf_restore_page = self.pdf_page().filter(|&p| p > 1);
let result = self.open(&path);
self.pdf_restore_page = None;
self.cursor_row = prev_row.min(self.lines.len().saturating_sub(1));
self.cursor_col = prev_col.min(self.line_char_len(self.cursor_row));
self.scroll = prev_scroll.min(self.lines.len().saturating_sub(1));
result
}
pub fn revert_to_disk(&mut self) -> Result<()> {
self.reload_from_disk()?;
self.dirty = false;
Ok(())
}
pub fn reload_or_flag_conflict(&mut self) -> ExternalChange {
if !self.disk_changed_externally() {
return ExternalChange::Unchanged;
}
if self.dirty {
let newly_conflicted = !self.disk_conflict;
self.disk_conflict = true;
return if newly_conflicted {
ExternalChange::Conflict
} else {
ExternalChange::Unchanged
};
}
match self.reload_from_disk() {
Ok(()) => ExternalChange::Reloaded,
Err(_) => ExternalChange::ReloadFailed,
}
}
pub fn save_to_disk(&mut self) -> Result<SaveOutcome> {
if self.disk_changed_externally() {
self.disk_conflict = true;
return Ok(SaveOutcome::DiskConflict);
}
self.write_buffer_to_disk()
}
pub fn save_to_disk_force(&mut self) -> Result<SaveOutcome> {
self.write_buffer_to_disk()
}
fn encode_for_disk(&self, content: &str) -> (Vec<u8>, bool) {
let enc = self.encoding;
if enc == encoding_rs::UTF_16LE || enc == encoding_rs::UTF_16BE {
let le = enc == encoding_rs::UTF_16LE;
let mut out = Vec::with_capacity(content.len() * 2 + 2);
out.extend_from_slice(if le { &[0xFF, 0xFE] } else { &[0xFE, 0xFF] });
for unit in content.encode_utf16() {
out.extend_from_slice(&if le {
unit.to_le_bytes()
} else {
unit.to_be_bytes()
});
}
return (out, false);
}
let (encoded, _, had_errors) = enc.encode(content);
if self.bom && enc == encoding_rs::UTF_8 {
let mut out = Vec::with_capacity(encoded.len() + 3);
out.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
out.extend_from_slice(&encoded);
return (out, had_errors);
}
(encoded.into_owned(), had_errors)
}
pub fn unmappable_chars(&self) -> Vec<char> {
const MAX: usize = 8;
let enc = self.encoding;
if enc == encoding_rs::UTF_8 || enc == encoding_rs::UTF_16LE || enc == encoding_rs::UTF_16BE
{
return Vec::new();
}
let mut out: Vec<char> = Vec::new();
let mut buf = [0u8; 4];
for line in &self.lines {
for ch in line.chars().filter(|c| !c.is_ascii()) {
if out.contains(&ch) {
continue;
}
let (_, _, had_errors) = enc.encode(ch.encode_utf8(&mut buf));
if had_errors {
out.push(ch);
if out.len() == MAX {
return out;
}
}
}
}
out
}
fn write_buffer_to_disk(&mut self) -> Result<SaveOutcome> {
if self.has_non_text_view() {
anyhow::bail!("This tab is a read-only preview; nothing to save");
}
let path = self
.path
.as_ref()
.ok_or_else(|| anyhow::anyhow!("No file open"))?
.clone();
let content = self.lines.join(self.eol.sequence());
let (encoded, had_errors) = self.encode_for_disk(&content);
if had_errors && !self.lossy_save_armed {
self.encoding_loss = true;
return Ok(SaveOutcome::EncodingLoss);
}
std::fs::write(&path, encoded)?;
self.encoding_loss = false;
self.lossy_save_armed = false;
self.dirty = false;
self.last_edit_kind = None;
self.status = format!("Saved {}", path.display());
self.mark_synced_with_disk();
Ok(SaveOutcome::Saved)
}
pub fn move_up(&mut self) {
if self.wrap_enabled() {
self.wrap_move_vertical(-1);
} else if self.cursor_row > 0 {
self.cursor_row = self.prev_visible_line(self.cursor_row - 1);
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
}
self.last_edit_kind = None;
}
pub fn move_down(&mut self) {
if self.wrap_enabled() {
self.wrap_move_vertical(1);
} else if self.cursor_row + 1 < self.lines.len() {
if let Some(next) = self.next_visible_line(self.cursor_row + 1) {
self.cursor_row = next;
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
}
}
self.last_edit_kind = None;
}
pub fn goto_top(&mut self) {
self.clear_selection();
self.cursor_row = 0;
self.cursor_col = 0;
self.last_edit_kind = None;
}
pub fn goto_bottom(&mut self) {
self.clear_selection();
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.cursor_row = self.lines.len() - 1;
self.cursor_col = 0;
self.last_edit_kind = None;
}
pub fn copy_view_position_from(&mut self, src: &Editor) {
let max_row = self.lines.len().saturating_sub(1);
self.cursor_row = src.cursor_row.min(max_row);
let max_col = self
.lines
.get(self.cursor_row)
.map_or(0, |l| l.chars().count());
self.cursor_col = src.cursor_col.min(max_col);
self.scroll = src.scroll.min(max_row);
self.scroll_sub = src.scroll_sub;
self.scroll_col = src.scroll_col;
}
pub fn goto_line(&mut self, one_based: usize) {
self.clear_selection();
if self.lines.is_empty() {
self.lines.push(String::new());
}
let max = self.lines.len() - 1;
let target = one_based.saturating_sub(1).min(max);
self.cursor_row = target;
self.cursor_col = 0;
self.last_edit_kind = None;
}
pub fn yank_lines(&self, count: usize) -> String {
let n = count.max(1);
let start = self.cursor_row;
self.lines_slice_text(start, n)
}
pub fn delete_lines(&mut self, count: usize) -> String {
self.pin_on_edit();
if self.lines.is_empty() {
return String::new();
}
self.push_undo(EditKind::DeleteLines);
self.clear_selection();
let n = count.max(1);
let start = self.cursor_row;
let end = (start + n).min(self.lines.len());
let yanked = self.lines_slice_text(start, end - start);
self.lines.drain(start..end);
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.cursor_row = start.min(self.lines.len() - 1);
self.cursor_col = 0;
self.mark_buffer_changed();
self.recompute_highlights();
yanked
}
pub fn delete_caret_lines(&mut self) -> String {
self.pin_on_edit();
if self.lines.is_empty() {
return String::new();
}
self.push_undo(EditKind::DeleteLines);
let last = self.lines.len() - 1;
let primary = self
.selection
.unwrap_or_else(|| EditorSelection::new(self.cursor_row, self.cursor_col));
let mut doomed = vec![false; self.lines.len()];
for sel in std::iter::once(primary).chain(self.carets.iter().copied()) {
let (a, h) = sel.normalised();
for slot in &mut doomed[a.0.min(last)..=h.0.min(last)] {
*slot = true;
}
}
let rows: Vec<usize> = doomed
.iter()
.enumerate()
.filter_map(|(r, &drop)| drop.then_some(r))
.collect();
let yanked = rows
.iter()
.map(|&r| self.lines[r].as_str())
.collect::<Vec<_>>()
.join("\n")
+ "\n";
let mut i = 0;
self.lines.retain(|_| {
let keep = !doomed[i];
i += 1;
keep
});
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.selection = None;
self.carets.clear();
self.cursor_row = rows[0].min(self.lines.len() - 1);
self.cursor_col = 0;
self.mark_buffer_changed();
self.recompute_highlights();
yanked
}
pub fn kill_to_bol(&mut self) -> String {
self.pin_on_edit();
if self.lines.is_empty() {
return String::new();
}
self.clear_selection();
let row = self.cursor_row;
if self.cursor_col == 0 {
return String::new();
}
self.push_undo(EditKind::KillToBol);
let from = self.byte_index(row, 0);
let to = self.byte_index(row, self.cursor_col);
let killed = self.lines[row][from..to].to_string();
self.lines[row].replace_range(from..to, "");
self.cursor_col = 0;
self.mark_buffer_changed();
self.recompute_highlights();
killed
}
pub fn open_line_below(&mut self) {
self.pin_on_edit();
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.push_undo(EditKind::OpenLine);
self.clear_selection();
let row = self.cursor_row;
let indent: String = self.lines[row]
.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.collect();
self.lines.insert(row + 1, indent.clone());
self.cursor_row = row + 1;
self.cursor_col = indent.chars().count();
self.mark_buffer_changed();
self.recompute_highlights();
}
pub fn open_line_above(&mut self) {
self.pin_on_edit();
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.push_undo(EditKind::OpenLine);
self.clear_selection();
let row = self.cursor_row;
let indent: String = self.lines[row]
.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.collect();
self.lines.insert(row, indent.clone());
self.cursor_col = indent.chars().count();
self.mark_buffer_changed();
self.recompute_highlights();
}
pub fn kill_to_eol(&mut self) -> String {
self.pin_on_edit();
if self.lines.is_empty() {
return String::new();
}
self.clear_selection();
let row = self.cursor_row;
let line_len = self.line_char_len(row);
if self.cursor_col >= line_len {
return String::new();
}
self.push_undo(EditKind::KillToEol);
let from = self.byte_index(row, self.cursor_col);
let to = self.byte_index(row, line_len);
let killed = self.lines[row][from..to].to_string();
self.lines[row].replace_range(from..to, "");
self.mark_buffer_changed();
self.recompute_highlights();
killed
}
pub fn replace_find_match(
&mut self,
row: usize,
col_chars: usize,
len_chars: usize,
text: &str,
) {
if row >= self.lines.len() {
return;
}
let line_len = self.line_char_len(row);
if col_chars.saturating_add(len_chars) > line_len {
return;
}
self.pin_on_edit();
self.push_undo(EditKind::Replace);
self.clear_selection();
let from = self.byte_index(row, col_chars);
let to = self.byte_index(row, col_chars + len_chars);
let text = &normalize_newlines(text);
let breaks = text.matches('\n').count();
if breaks == 0 {
self.lines[row].replace_range(from..to, text);
self.cursor_row = row;
self.cursor_col = col_chars + text.chars().count();
} else {
let line = std::mem::take(&mut self.lines[row]);
let merged = format!("{}{}{}", &line[..from], text, &line[to..]);
self.lines
.splice(row..=row, merged.split('\n').map(str::to_string));
self.cursor_row = row + breaks;
self.cursor_col = text
.rsplit('\n')
.next()
.map_or(0, |tail| tail.chars().count());
}
self.mark_buffer_changed();
self.recompute_highlights();
}
pub fn replace_all_lines(&mut self, new_lines: Vec<String>) {
self.pin_on_edit();
self.push_undo(EditKind::Replace);
self.clear_selection();
self.lines = new_lines;
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.cursor_row = self.cursor_row.min(self.lines.len() - 1);
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.mark_buffer_changed();
self.recompute_highlights();
}
fn lines_slice_text(&self, start: usize, count: usize) -> String {
if count == 0 || start >= self.lines.len() {
return String::new();
}
let end = (start + count).min(self.lines.len());
let mut out = self.lines[start..end].join("\n");
out.push('\n');
out
}
pub fn move_left(&mut self) {
if self.cursor_col > 0 {
self.cursor_col -= 1;
} else if self.cursor_row > 0 {
self.cursor_row -= 1;
self.cursor_col = self.line_char_len(self.cursor_row);
}
self.ensure_cursor_col_visible();
self.last_edit_kind = None;
}
pub fn move_right(&mut self) {
if self.cursor_col < self.line_char_len(self.cursor_row) {
self.cursor_col += 1;
} else if self.cursor_row + 1 < self.lines.len() {
self.cursor_row += 1;
self.cursor_col = 0;
}
self.ensure_cursor_col_visible();
self.last_edit_kind = None;
}
pub fn move_word_right(&mut self) {
loop {
let chars: Vec<char> = self.lines[self.cursor_row].chars().collect();
while self.cursor_col < chars.len() && !is_word_char(chars[self.cursor_col]) {
self.cursor_col += 1;
}
if self.cursor_col < chars.len() {
break;
}
if self.cursor_row + 1 < self.lines.len() {
self.cursor_row += 1;
self.cursor_col = 0;
} else {
self.ensure_cursor_col_visible();
self.last_edit_kind = None;
return;
}
}
let chars: Vec<char> = self.lines[self.cursor_row].chars().collect();
while self.cursor_col < chars.len() && is_word_char(chars[self.cursor_col]) {
self.cursor_col += 1;
}
self.ensure_cursor_col_visible();
self.last_edit_kind = None;
}
pub fn duplicate_lines_down(&mut self) {
self.push_undo(EditKind::DuplicateLines);
let (start_row, end_row) = self.selected_or_cursor_row_range();
let block: Vec<String> = self.lines[start_row..=end_row].to_vec();
let block_len = block.len();
let insert_at = end_row + 1;
for (i, line) in block.into_iter().enumerate() {
self.lines.insert(insert_at + i, line);
}
self.cursor_row += block_len;
if let Some(sel) = self.selection.as_mut() {
sel.anchor.0 += block_len;
sel.head.0 += block_len;
}
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn duplicate_lines_up(&mut self) {
self.push_undo(EditKind::DuplicateLines);
let (start_row, end_row) = self.selected_or_cursor_row_range();
let block: Vec<String> = self.lines[start_row..=end_row].to_vec();
for (i, line) in block.into_iter().enumerate() {
self.lines.insert(start_row + i, line);
}
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
fn selected_or_cursor_row_range(&self) -> (usize, usize) {
match &self.selection {
Some(sel) => {
let (start, end) = sel.normalised();
(start.0, end.0)
}
None => (self.cursor_row, self.cursor_row),
}
}
fn char_range_text(&self, start: (usize, usize), end: (usize, usize)) -> String {
if start.0 == end.0 {
return self.lines[start.0]
.chars()
.skip(start.1)
.take(end.1.saturating_sub(start.1))
.collect();
}
let mut out: String = self.lines[start.0].chars().skip(start.1).collect();
for line in &self.lines[start.0 + 1..end.0] {
out.push('\n');
out.push_str(line);
}
out.push('\n');
let last: String = self.lines[end.0].chars().take(end.1).collect();
out.push_str(&last);
out
}
fn replace_char_range(&mut self, start: (usize, usize), end: (usize, usize), new: &str) {
let prefix: String = self.lines[start.0].chars().take(start.1).collect();
let suffix: String = self.lines[end.0].chars().skip(end.1).collect();
let combined = format!("{prefix}{new}{suffix}");
let replacement: Vec<String> = combined.split('\n').map(str::to_string).collect();
self.lines.splice(start.0..=end.0, replacement);
}
pub fn move_lines_down(&mut self) {
let (start, end) = self.selected_or_cursor_row_range();
if end + 1 >= self.lines.len() {
return;
}
self.push_undo(EditKind::MoveLines);
self.lines[start..=end + 1].rotate_right(1);
self.cursor_row += 1;
if let Some(sel) = self.selection.as_mut() {
sel.anchor.0 += 1;
sel.head.0 += 1;
}
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn move_lines_up(&mut self) {
let (start, end) = self.selected_or_cursor_row_range();
if start == 0 {
return;
}
self.push_undo(EditKind::MoveLines);
self.lines[start - 1..=end].rotate_left(1);
self.cursor_row -= 1;
if let Some(sel) = self.selection.as_mut() {
sel.anchor.0 -= 1;
sel.head.0 -= 1;
}
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn toggle_line_comment(&mut self) -> bool {
let Some(token) = line_comment_token(self.lang) else {
return false;
};
let (start, end) = self.selected_or_cursor_row_range();
let non_blank: Vec<usize> = (start..=end)
.filter(|&r| !self.lines[r].trim().is_empty())
.collect();
if non_blank.is_empty() {
return false;
}
self.push_undo(EditKind::ToggleComment);
let all_commented = non_blank
.iter()
.all(|&r| self.lines[r].trim_start().starts_with(token));
if all_commented {
for &r in &non_blank {
let line = self.lines[r].clone();
let off = line.len() - line.trim_start().len();
let mut rest = line[off..].to_string();
rest.drain(..token.len());
if rest.starts_with(' ') {
rest.drain(..1);
}
self.lines[r] = format!("{}{}", &line[..off], rest);
}
} else {
let min_indent = non_blank
.iter()
.map(|&r| {
let l = &self.lines[r];
l.len() - l.trim_start().len()
})
.min()
.unwrap_or(0);
for &r in &non_blank {
self.lines[r].insert_str(min_indent, &format!("{token} "));
}
}
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
true
}
pub fn toggle_block_comment(&mut self) -> bool {
let Some((open, close)) = block_comment_tokens(self.lang) else {
return false;
};
let (start, end) = match &self.selection {
Some(sel) => sel.normalised(),
None => {
let len = self.line_char_len(self.cursor_row);
((self.cursor_row, 0), (self.cursor_row, len))
}
};
let text = self.char_range_text(start, end);
let trimmed = text.trim();
if trimmed.is_empty() {
return false;
}
self.push_undo(EditKind::ToggleComment);
let wrapped = trimmed.starts_with(open)
&& trimmed.ends_with(close)
&& trimmed.len() >= open.len() + close.len();
let new = if wrapped {
trimmed[open.len()..trimmed.len() - close.len()]
.trim()
.to_string()
} else {
format!("{open} {trimmed} {close}")
};
self.replace_char_range(start, end, &new);
self.selection = None;
self.cursor_row = start.0;
self.cursor_col = self.line_char_len(start.0);
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
true
}
pub fn join_lines(&mut self) {
let (start, end) = self.selected_or_cursor_row_range();
let last = if start == end { start + 1 } else { end };
if last >= self.lines.len() {
return;
}
self.push_undo(EditKind::JoinLines);
let mut result = self.lines[start].trim_end().to_string();
let cursor_col = result.chars().count();
for line in &self.lines[start + 1..=last] {
let piece = line.trim_start();
if !result.is_empty() && !result.ends_with(char::is_whitespace) && !piece.is_empty() {
result.push(' ');
}
result.push_str(piece);
}
self.lines.splice(start..=last, std::iter::once(result));
self.cursor_row = start;
self.cursor_col = cursor_col;
self.selection = None;
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn transform_selection_case(&mut self, kind: CaseTransform) {
let range = match &self.selection {
Some(sel) => Some(sel.normalised()),
None => self
.word_at(self.cursor_row, self.cursor_col)
.map(|(s, e)| ((self.cursor_row, s), (self.cursor_row, e))),
};
let Some((start, end)) = range else {
return;
};
let text = self.char_range_text(start, end);
if text.is_empty() {
return;
}
self.push_undo(EditKind::TransformCase);
let new = match kind {
CaseTransform::Upper => text.to_uppercase(),
CaseTransform::Lower => text.to_lowercase(),
CaseTransform::Title => title_case(&text),
};
self.replace_char_range(start, end, &new);
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn sort_lines(&mut self, ascending: bool) {
let (start, end) = match &self.selection {
Some(sel) => {
let (s, e) = sel.normalised();
(s.0, e.0)
}
None => (0, self.lines.len().saturating_sub(1)),
};
if start >= end {
return;
}
self.push_undo(EditKind::SortLines);
let mut block: Vec<String> = self.lines[start..=end].to_vec();
block.sort();
if !ascending {
block.reverse();
}
self.lines.splice(start..=end, block);
self.mark_buffer_changed();
self.recompute_highlights();
}
pub fn trim_trailing_whitespace(&mut self) -> bool {
let any = self
.lines
.iter()
.any(|l| l.trim_end_matches([' ', '\t']).len() != l.len());
if !any {
return false;
}
self.push_undo(EditKind::TrimWhitespace);
for line in &mut self.lines {
let trimmed_len = line.trim_end_matches([' ', '\t']).len();
line.truncate(trimmed_len);
}
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.mark_buffer_changed();
self.recompute_highlights();
true
}
fn char_at(&self, row: usize, col: usize) -> Option<char> {
self.lines.get(row)?.chars().nth(col)
}
fn match_bracket_forward(&self, open: BPos) -> Option<BPos> {
let oc = self.char_at(open.0, open.1)?;
let cc = matching_close(oc)?;
let mut depth = 0i32;
let (mut row, mut col) = open;
loop {
match self.char_at(row, col) {
Some(ch) => {
if ch == oc {
depth += 1;
} else if ch == cc {
depth -= 1;
if depth == 0 {
return Some((row, col));
}
}
col += 1;
}
None => {
row += 1;
col = 0;
if row >= self.lines.len() {
return None;
}
}
}
}
}
fn match_bracket_backward(&self, close: BPos) -> Option<BPos> {
let cc = self.char_at(close.0, close.1)?;
let oc = matching_open(cc)?;
let mut depth = 0i32;
let mut row = close.0;
let mut col = close.1 as isize;
loop {
if col < 0 {
if row == 0 {
return None;
}
row -= 1;
col = self.line_char_len(row) as isize - 1;
continue;
}
let ch = self.char_at(row, col as usize)?;
if ch == cc {
depth += 1;
} else if ch == oc {
depth -= 1;
if depth == 0 {
return Some((row, col as usize));
}
}
col -= 1;
}
}
fn enclosing_brackets(&self) -> Option<(BPos, BPos)> {
let mut row = self.cursor_row;
let mut col = self.cursor_col as isize - 1;
let mut expected: Vec<char> = Vec::new();
loop {
if col < 0 {
if row == 0 {
return None;
}
row -= 1;
col = self.line_char_len(row) as isize - 1;
continue;
}
let ch = self.char_at(row, col as usize)?;
if is_close_bracket(ch) {
expected.push(matching_open(ch)?);
} else if is_open_bracket(ch) {
match expected.last() {
Some(&want) if want == ch => {
expected.pop();
}
_ => {
let open = (row, col as usize);
let close = self.match_bracket_forward(open)?;
return Some((open, close));
}
}
}
col -= 1;
}
}
fn next_bracket_pair(&self) -> Option<(BPos, BPos)> {
let mut row = self.cursor_row;
let mut col = self.cursor_col;
loop {
match self.char_at(row, col) {
Some(ch) if is_open_bracket(ch) => {
let open = (row, col);
return self.match_bracket_forward(open).map(|c| (open, c));
}
Some(ch) if is_close_bracket(ch) => {
let close = (row, col);
return self.match_bracket_backward(close).map(|o| (o, close));
}
Some(_) => col += 1,
None => {
row += 1;
col = 0;
if row >= self.lines.len() {
return None;
}
}
}
}
}
fn find_bracket_pair(&self) -> Option<(BPos, BPos, bool)> {
if let Some(pair) = self.adjacent_bracket_pair() {
return Some(pair);
}
if let Some((open, close)) = self.enclosing_brackets() {
return Some((open, close, false));
}
self.next_bracket_pair().map(|(o, c)| (o, c, false))
}
fn adjacent_bracket_pair(&self) -> Option<(BPos, BPos, bool)> {
let row = self.cursor_row;
let col = self.cursor_col;
let left = col.checked_sub(1).and_then(|c| self.char_at(row, c));
let right = self.char_at(row, col);
if left.is_some_and(is_close_bracket) {
let close = (row, col - 1);
return self.match_bracket_backward(close).map(|o| (o, close, true));
}
if right.is_some_and(is_open_bracket) {
let open = (row, col);
return self.match_bracket_forward(open).map(|c| (open, c, false));
}
if left.is_some_and(is_open_bracket) {
let open = (row, col - 1);
return self.match_bracket_forward(open).map(|c| (open, c, false));
}
if right.is_some_and(is_close_bracket) {
let close = (row, col);
return self.match_bracket_backward(close).map(|o| (o, close, true));
}
None
}
pub fn bracket_match_pair(&self) -> Option<(BPos, BPos)> {
self.adjacent_bracket_pair().map(|(o, c, _)| (o, c))
}
pub fn jump_to_matching_bracket(&mut self) -> bool {
let Some((open, close, anchored_on_close)) = self.find_bracket_pair() else {
return false;
};
let target = if anchored_on_close { open } else { close };
self.clear_selection();
self.cursor_row = target.0;
self.cursor_col = target.1;
self.last_edit_kind = None;
self.ensure_cursor_col_visible();
true
}
pub fn select_to_matching_bracket(&mut self) -> bool {
let Some((open, close, _)) = self.find_bracket_pair() else {
return false;
};
let head = (close.0, close.1 + 1);
self.selection = Some(EditorSelection { anchor: open, head });
self.cursor_row = head.0;
self.cursor_col = head.1;
self.last_edit_kind = None;
self.ensure_cursor_col_visible();
true
}
pub fn transpose_chars(&mut self) {
let row = self.cursor_row;
let col = self.cursor_col;
let len = self.line_char_len(row);
if col >= len {
if row + 1 >= self.lines.len() {
return;
}
self.push_undo(EditKind::Transpose);
if len > 0 {
let mut chars: Vec<char> = self.lines[row].chars().collect();
let moved = chars.pop().unwrap();
self.lines[row] = chars.into_iter().collect();
self.lines[row + 1].insert(0, moved);
self.cursor_col = 1;
} else {
self.cursor_col = 0;
}
self.cursor_row = row + 1;
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
return;
}
if col == 0 {
self.cursor_col = 1;
self.ensure_cursor_col_visible();
return;
}
self.push_undo(EditKind::Transpose);
let mut chars: Vec<char> = self.lines[row].chars().collect();
chars.swap(col - 1, col);
self.lines[row] = chars.into_iter().collect();
self.cursor_col = col + 1;
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn indentation_to_spaces(&mut self) {
self.convert_indentation(true);
}
pub fn indentation_to_tabs(&mut self) {
self.convert_indentation(false);
}
fn convert_indentation(&mut self, to_spaces: bool) {
let tab_w = (self.indent_style().width as usize).max(1);
let spaces = " ".repeat(tab_w);
let mut new_lines = self.lines.clone();
let mut changed = false;
for line in new_lines.iter_mut() {
let indent_len = line.chars().take_while(|c| *c == ' ' || *c == '\t').count();
let indent: String = line.chars().take(indent_len).collect();
let converted = if to_spaces {
indent.replace('\t', &spaces)
} else {
indent.replace(&spaces, "\t")
};
if converted != indent {
let rest: String = line.chars().skip(indent_len).collect();
*line = format!("{converted}{rest}");
changed = true;
}
}
if !changed {
return;
}
self.push_undo(EditKind::IndentConvert);
self.lines = new_lines;
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn trim_final_newlines(&mut self) -> bool {
let mut end = self.lines.len();
while end > 1 && self.lines[end - 1].is_empty() {
end -= 1;
}
if end == self.lines.len() {
return false;
}
self.push_undo(EditKind::TrimFinalNewlines);
self.lines.truncate(end);
if self.cursor_row >= self.lines.len() {
self.cursor_row = self.lines.len() - 1;
}
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.mark_buffer_changed();
self.recompute_highlights();
true
}
pub fn add_cursor_below(&mut self) {
let max_row = self
.carets
.iter()
.map(|c| c.head.0)
.chain(std::iter::once(self.cursor_row))
.max()
.unwrap_or(self.cursor_row);
let target = max_row + 1;
if target >= self.lines.len() {
return;
}
let col = self.cursor_col.min(self.line_char_len(target));
self.carets.push(EditorSelection {
anchor: (target, col),
head: (target, col),
});
}
pub fn add_caret_at_screen(&mut self, col: u16, row: u16) -> bool {
let Some((r, c)) = self.buffer_pos_at(col, row) else {
return false;
};
if (r, c) == (self.cursor_row, self.cursor_col) {
return true;
}
if let Some(idx) = self
.carets
.iter()
.position(|s| !s.has_area() && s.head == (r, c))
{
self.carets.remove(idx);
return true;
}
let primary = self.selection.unwrap_or(EditorSelection {
anchor: (self.cursor_row, self.cursor_col),
head: (self.cursor_row, self.cursor_col),
});
self.carets.push(primary);
self.selection = None;
self.cursor_row = r;
self.cursor_col = c;
self.ensure_cursor_col_visible();
true
}
pub fn begin_box_select(&mut self, col: u16, row: u16) -> bool {
let Some((r, c)) = self.buffer_pos_at(col, row) else {
return false;
};
self.box_anchor = Some((r, c));
self.carets.clear();
self.selection = None;
self.cursor_row = r;
self.cursor_col = c;
true
}
pub fn box_selecting(&self) -> bool {
self.box_anchor.is_some()
}
pub fn box_drag_to_screen(&mut self, col: u16, row: u16) {
if self.box_anchor.is_none() {
return;
}
if let Some((r, c)) = self.buffer_pos_at(col, row) {
self.box_select_to(r, c);
}
}
fn box_select_to(&mut self, head_row: usize, head_col: usize) {
let Some((ar, ac)) = self.box_anchor else {
return;
};
let (r0, r1) = (ar.min(head_row), ar.max(head_row));
let (c0, c1) = (ac.min(head_col), ac.max(head_col));
self.carets.clear();
self.selection = None;
for r in r0..=r1 {
let len = self.line_char_len(r);
let s = c0.min(len);
let e = c1.min(len);
let sel = EditorSelection {
anchor: (r, s),
head: (r, e),
};
if r == head_row {
self.selection = (e > s).then_some(sel);
self.cursor_row = r;
self.cursor_col = e;
} else {
self.carets.push(sel);
}
}
self.ensure_cursor_col_visible();
}
pub fn end_box_select(&mut self) {
self.box_anchor = None;
}
pub fn add_cursor_above(&mut self) {
let min_row = self
.carets
.iter()
.map(|c| c.head.0)
.chain(std::iter::once(self.cursor_row))
.min()
.unwrap_or(self.cursor_row);
if min_row == 0 {
return;
}
let target = min_row - 1;
let col = self.cursor_col.min(self.line_char_len(target));
self.carets.push(EditorSelection {
anchor: (target, col),
head: (target, col),
});
}
pub fn toggle_wrap(&mut self) {
let now = self.wrap_enabled();
self.wrap_override = Some(!now);
}
pub fn selection_is_multiline(&self) -> bool {
match &self.selection {
Some(sel) => {
let (start, end) = sel.normalised();
start.0 != end.0
}
None => false,
}
}
pub fn indent_at_cursor(&mut self) {
self.pin_on_edit();
self.push_undo(EditKind::Indent);
if self.selection.is_some() {
self.delete_selection_inner();
}
if self.lines.is_empty() {
self.lines.push(String::new());
}
let style = self.indent_style();
let row = self.cursor_row;
let byte = self.byte_index(row, self.cursor_col);
let (ins, advance): (String, usize) = if style.use_spaces {
let unit_w = (style.width as usize).max(1);
let pad = unit_w - (self.cursor_col % unit_w);
(" ".repeat(pad), pad)
} else {
("\t".to_string(), 1)
};
self.lines[row].insert_str(byte, &ins);
self.cursor_col += advance;
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn indent_lines(&mut self) {
self.pin_on_edit();
self.push_undo(EditKind::Indent);
let unit = self.indent_unit();
let unit_w = unit.chars().count();
let (start_row, end_row) = self.selected_or_cursor_row_range();
for row in start_row..=end_row {
if !self.lines[row].is_empty() {
self.lines[row].insert_str(0, &unit);
}
}
let shift = |row: usize, col: usize, lines: &[String]| -> usize {
if row >= start_row && row <= end_row && !lines[row].is_empty() {
col + unit_w
} else {
col
}
};
self.cursor_col = shift(self.cursor_row, self.cursor_col, &self.lines);
if let Some(mut sel) = self.selection {
sel.anchor.1 = shift(sel.anchor.0, sel.anchor.1, &self.lines);
sel.head.1 = shift(sel.head.0, sel.head.1, &self.lines);
self.selection = Some(sel);
}
self.mark_buffer_changed();
self.recompute_highlights();
self.ensure_cursor_col_visible();
}
pub fn dedent_lines(&mut self) {
self.pin_on_edit();
self.push_undo(EditKind::Indent);
let unit_w = (self.indent_style().width as usize).max(1);
let (start_row, end_row) = self.selected_or_cursor_row_range();
let mut removed = vec![0usize; self.lines.len()];
let mut any = false;
for (row, slot) in removed
.iter_mut()
.enumerate()
.take(end_row + 1)
.skip(start_row)
{
let n = leading_outdent_chars(&self.lines[row], unit_w);
if n > 0 {
self.lines[row].replace_range(0..n, "");
*slot = n;
any = true;
}
}
let pull = |row: usize, col: usize, removed: &[usize]| -> usize {
if row < removed.len() {
col.saturating_sub(removed[row])
} else {
col
}
};
self.cursor_col = pull(self.cursor_row, self.cursor_col, &removed);
if let Some(mut sel) = self.selection {
sel.anchor.1 = pull(sel.anchor.0, sel.anchor.1, &removed);
sel.head.1 = pull(sel.head.0, sel.head.1, &removed);
self.selection = Some(sel);
}
if any {
self.mark_buffer_changed();
self.recompute_highlights();
}
self.ensure_cursor_col_visible();
}
pub fn move_word_left(&mut self) {
loop {
let chars: Vec<char> = self.lines[self.cursor_row].chars().collect();
while self.cursor_col > 0 && !is_word_char(chars[self.cursor_col - 1]) {
self.cursor_col -= 1;
}
if self.cursor_col > 0 {
break;
}
if self.cursor_row > 0 {
self.cursor_row -= 1;
self.cursor_col = self.line_char_len(self.cursor_row);
} else {
self.ensure_cursor_col_visible();
self.last_edit_kind = None;
return;
}
}
let chars: Vec<char> = self.lines[self.cursor_row].chars().collect();
while self.cursor_col > 0 && is_word_char(chars[self.cursor_col - 1]) {
self.cursor_col -= 1;
}
self.ensure_cursor_col_visible();
self.last_edit_kind = None;
}
pub fn scroll_left_by(&mut self, n: usize) {
self.scroll_col = self.scroll_col.saturating_sub(n);
}
pub fn scroll_right_by(&mut self, n: usize) {
self.scroll_col = self.scroll_col.saturating_add(n);
}
fn visible_text_width(&self) -> usize {
let scrollbar_w = u16::from(self.last_scrollbar.width > 0);
self.last_inner
.width
.saturating_sub(self.last_gutter_width + 2 + scrollbar_w) as usize
}
pub(crate) fn ensure_cursor_col_visible(&mut self) {
if self.wrap_enabled() {
return;
}
let width = self.visible_text_width();
if width == 0 {
return;
}
if self.cursor_col < self.scroll_col {
self.scroll_col = self.cursor_col;
} else {
loop {
let extra = self.inlay_cells_before_cursor(self.cursor_row, self.scroll_col);
if self.cursor_col + extra < self.scroll_col + width {
break;
}
let target = (self.cursor_col + extra + 1).saturating_sub(width);
if target <= self.scroll_col {
break;
}
self.scroll_col = target.min(self.cursor_col);
}
}
}
pub fn page_size(&self) -> usize {
let from_rows = self.text_rows();
if from_rows > 0 { from_rows } else { 20 }
}
pub fn page_down_one_screen(&mut self) {
let page = self.page_size();
if self.wrap_enabled() {
let top = self.top_visual_row(self.visible_text_width());
self.wrap_set_top(top + page);
return;
}
let max_row = self.lines.len().saturating_sub(1);
let new_top = (self.scroll + page).min(max_row);
self.scroll = new_top;
self.cursor_row = new_top;
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.last_edit_kind = None;
}
pub fn page_up_one_screen(&mut self) {
let page = self.page_size();
if self.wrap_enabled() {
let top = self.top_visual_row(self.visible_text_width());
self.wrap_set_top(top.saturating_sub(page));
return;
}
let new_top = self.scroll.saturating_sub(page);
self.scroll = new_top;
self.cursor_row = new_top;
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.last_edit_kind = None;
}
pub fn home_line(&mut self) {
self.cursor_col = 0;
self.last_edit_kind = None;
}
pub fn end_line(&mut self) {
self.cursor_col = self.line_char_len(self.cursor_row);
self.last_edit_kind = None;
}
pub fn scroll_sheet_rows(&mut self, rows: isize) -> bool {
let Some(sheet) = self.sheet.as_mut() else {
return false;
};
let Some(data) = sheet.sheets.get_mut(sheet.current_sheet) else {
return false;
};
let last = data.rows.len().saturating_sub(1);
data.scroll_row = data.scroll_row.saturating_add_signed(rows).min(last);
true
}
pub fn scroll_up(&mut self, n: usize) {
if self.scroll_markdown_preview(-(n as i32)) {
return;
}
if self.scroll_sheet_rows(-(n as isize)) {
return;
}
if self.wrap_enabled() {
let top = self.top_visual_row(self.visible_text_width());
self.wrap_set_top(top.saturating_sub(n));
} else if self.comment_boxes.is_empty() {
self.scroll_view_to(self.scroll.saturating_sub(n));
} else {
self.nonwrap_set_top(self.nonwrap_top_content_row().saturating_sub(n));
}
}
pub fn scroll_down(&mut self, n: usize) {
if self.scroll_markdown_preview(n as i32) {
return;
}
if self.scroll_sheet_rows(n as isize) {
return;
}
if self.wrap_enabled() {
let top = self.top_visual_row(self.visible_text_width());
self.wrap_set_top(top.saturating_add(n));
} else if self.comment_boxes.is_empty() {
self.scroll_view_to(self.scroll.saturating_add(n));
} else {
self.nonwrap_set_top(self.nonwrap_top_content_row().saturating_add(n));
}
}
pub fn scroll_to_bar_y(&mut self, y: u16) -> bool {
let viewport = self.text_rows();
if self.wrap_enabled() {
let width = self.visible_text_width();
let total = self.total_visual_rows(width);
let Some(metrics) = scrollbar::vertical_metrics(
self.last_scrollbar,
total,
viewport,
self.top_visual_row(width),
) else {
return false;
};
self.wrap_set_top(scrollbar::scroll_for_y(metrics, y));
return true;
}
let bw = self.visible_text_width();
let content = self.lines.len() + self.box_rows_between(0, self.lines.len(), bw);
let Some(metrics) = scrollbar::vertical_metrics(
self.last_scrollbar,
content,
viewport,
self.nonwrap_top_content_row(),
) else {
return false;
};
self.nonwrap_set_top(scrollbar::scroll_for_y(metrics, y));
true
}
pub fn scroll_to_bar_x(&mut self, x: u16) -> bool {
let width = self.visible_text_width();
let Some(metrics) = scrollbar::horizontal_metrics(
self.last_hscrollbar,
self.content_cols(),
width,
self.scroll_col,
) else {
return false;
};
self.scroll_col = scrollbar::scroll_for_x(metrics, x);
true
}
pub(crate) fn text_rows(&self) -> usize {
let rows = self.last_text_rows as usize;
if rows > 0 {
rows
} else {
self.last_inner.height as usize
}
}
pub fn visible_rows(&self) -> usize {
self.text_rows()
}
pub fn selection_rows(&self) -> Option<(usize, usize)> {
let sel = self.selection?;
if !sel.has_area() {
return None;
}
let (start, end) = sel.normalised();
Some((start.0, end.0))
}
pub fn goto_line_centered(&mut self, line: usize) {
if self.lines.is_empty() {
return;
}
let line = line.min(self.lines.len() - 1);
self.cursor_row = line;
self.cursor_col = self.cursor_col.min(self.line_char_len(line));
let viewport = self.text_rows();
self.scroll = line
.saturating_sub(viewport / 2)
.min(self.lines.len().saturating_sub(viewport));
self.last_edit_kind = None;
}
pub fn minimap_rgba(
&self,
w: u32,
h: u32,
content_h: u32,
bg: (u8, u8, u8),
fg: (u8, u8, u8),
) -> Vec<u8> {
let mut buf = vec![0u8; (w * h * 4) as usize];
for px in buf.chunks_exact_mut(4) {
px[0] = bg.0;
px[1] = bg.1;
px[2] = bg.2;
px[3] = 0xff;
}
let total = self.lines.len().max(1) as u64;
for (i, line) in self.lines.iter().enumerate() {
let y0 = (i as u64 * content_h as u64 / total) as u32;
if y0 >= h {
break;
}
let y1 = (((i as u64 + 1) * content_h as u64 / total) as u32).clamp(y0 + 1, h);
let merged = merge_overlay(
self.highlights.get(i).map(Vec::as_slice).unwrap_or(&[]),
self.semantic_overlay
.get(i)
.map(Vec::as_slice)
.unwrap_or(&[]),
);
let mut si = 0usize;
for (col, (byte, ch)) in (0_u32..).zip(line.char_indices()) {
if col >= w {
break;
}
while si < merged.len() && merged[si].end <= byte {
si += 1;
}
if !ch.is_whitespace() {
let (r, g, b) = if si < merged.len() && merged[si].start <= byte {
span_rgb(merged[si].style, fg)
} else {
fg
};
for y in y0..y1 {
let idx = ((y * w + col) * 4) as usize;
buf[idx] = r;
buf[idx + 1] = g;
buf[idx + 2] = b;
}
}
}
}
buf
}
fn nonwrap_top_content_row(&self) -> usize {
let bw = self.visible_text_width();
self.scroll + self.box_rows_between(0, self.scroll, bw) + self.scroll_sub
}
fn nonwrap_set_top(&mut self, row: usize) {
let viewport = self.text_rows();
if viewport == 0 || self.lines.is_empty() {
self.scroll = 0;
self.scroll_sub = 0;
return;
}
if self.comment_boxes.is_empty() {
self.scroll_sub = 0;
self.scroll_view_to(row);
return;
}
let bw = self.visible_text_width();
let total = self.lines.len() + self.box_rows_between(0, self.lines.len(), bw);
let row = row.min(total.saturating_sub(viewport));
let mut acc = 0usize;
let mut line = 0usize;
while line < self.lines.len() {
let group = 1 + self.box_rows_between(line, line + 1, bw);
if acc + group > row {
break;
}
acc += group;
line += 1;
}
self.scroll = line.min(self.lines.len().saturating_sub(1));
self.scroll_sub = row.saturating_sub(acc);
let last_visible = (self.scroll + viewport - 1).min(self.lines.len().saturating_sub(1));
let floor = self.caret_floor_row().min(last_visible);
if self.cursor_row < floor {
self.cursor_row = floor;
} else if self.cursor_row > last_visible {
self.cursor_row = last_visible;
}
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.last_edit_kind = None;
}
fn scroll_view_to(&mut self, top: usize) {
let viewport = self.last_inner.height as usize;
if viewport == 0 || self.lines.is_empty() {
self.scroll = 0;
self.cursor_row = 0;
self.cursor_col = 0;
self.last_edit_kind = None;
return;
}
self.scroll = top.min(self.lines.len().saturating_sub(viewport));
let last_visible = (self.scroll + viewport - 1).min(self.lines.len().saturating_sub(1));
let floor = self.caret_floor_row().min(last_visible);
if self.cursor_row < floor {
self.cursor_row = floor;
} else if self.cursor_row > last_visible {
self.cursor_row = last_visible;
}
self.cursor_col = self.cursor_col.min(self.line_char_len(self.cursor_row));
self.last_edit_kind = None;
}
fn caret_floor_row(&self) -> usize {
if self.wrap_enabled() || self.sticky_lines.is_empty() {
return self.scroll;
}
let rows_avail = (self.last_inner.height as usize).saturating_sub(1);
self.scroll + self.sticky_lines.len().min(rows_avail)
}
pub fn select_word_at(&mut self, col: u16, row: u16) {
self.click(col, row);
if self.lines.is_empty() {
self.selection = None;
return;
}
let r = self.cursor_row;
let chars: Vec<char> = self.lines[r].chars().collect();
let c = self.cursor_col;
let pivot = if c < chars.len() && is_word_char(chars[c]) {
Some(c)
} else if c == chars.len() && c > 0 && is_word_char(chars[c - 1]) {
Some(c - 1)
} else {
None
};
let Some(p) = pivot else {
self.selection = None;
return;
};
let mut start = p;
while start > 0 && is_word_char(chars[start - 1]) {
start -= 1;
}
let mut end = p + 1;
while end < chars.len() && is_word_char(chars[end]) {
end += 1;
}
self.cursor_col = end;
self.selection = Some(EditorSelection {
anchor: (r, start),
head: (r, end),
});
self.last_edit_kind = None;
}
pub fn click(&mut self, col: u16, row: u16) {
if self.lines.is_empty() || self.last_inner.height == 0 {
return;
}
if row < self.last_inner.y || row >= self.last_inner.y + self.last_inner.height {
return;
}
let row_idx = (row - self.last_inner.y) as usize;
let text_x = self.last_inner.x + self.last_gutter_width + 1;
let visible = col.saturating_sub(text_x) as usize;
let clamped = row_idx.min(self.last_wrap_rows.len().saturating_sub(1));
let nearest_text = (0..=clamped)
.rev()
.find_map(|i| self.text_row(i).map(|t| (i, t)));
if !self.last_wrap_rows.is_empty()
&& row_idx < self.last_wrap_rows.len()
&& self.text_row(row_idx).is_none()
{
return;
}
let (target_line, target_col) = match nearest_text {
Some((_, (line, start, end))) => {
let cap = if self.wrap_enabled() { end } else { usize::MAX };
(
line,
self.buffer_col_at_display(line, start + visible).min(cap),
)
}
None => {
let line = (self.scroll + row_idx).min(self.lines.len().saturating_sub(1));
(
line,
self.buffer_col_at_display(line, visible + self.scroll_col),
)
}
};
self.cursor_row = target_line;
self.cursor_col = target_col.min(self.line_char_len(target_line));
self.last_edit_kind = None;
self.carets.clear();
}
pub fn buffer_pos_at(&self, col: u16, row: u16) -> Option<(usize, usize)> {
if self.last_inner.height == 0 || self.lines.is_empty() || row < self.last_inner.y {
return None;
}
let text_x = self.last_inner.x + self.last_gutter_width + 1;
if self.wrap_enabled() {
let (line, start, end) = self.text_row((row - self.last_inner.y) as usize)?;
if col < text_x {
return None;
}
let visible_col = (col - text_x) as usize;
let char_col = (start + visible_col).min(end).min(self.line_char_len(line));
return Some((line, char_col));
}
if row >= self.last_inner.y + self.last_inner.height {
return None;
}
let line = if self.last_wrap_rows.is_empty() {
self.scroll + (row - self.last_inner.y) as usize
} else {
self.text_row((row - self.last_inner.y) as usize)?.0
};
if line >= self.lines.len() || col < text_x {
return None;
}
let text_width = self
.last_inner
.width
.saturating_sub(self.last_gutter_width + 2 + u16::from(self.last_scrollbar.width > 0));
let visible_col = (col - text_x) as usize;
if visible_col >= text_width as usize {
return None;
}
Some((
line,
self.buffer_col_at_display(line, self.scroll_col + visible_col),
))
}
fn buffer_col_at_display(&self, line: usize, display_col: usize) -> usize {
let line_len = self.line_char_len(line);
let hints = self.row_inlay_spans(line);
if hints.is_empty() {
return display_col.min(line_len);
}
let mut c = self.scroll_col;
while c < line_len {
let extra: usize = hints
.iter()
.filter(|(hc, _)| *hc >= self.scroll_col && *hc <= c)
.map(|(_, l)| l.chars().count())
.sum();
if c + extra >= display_col {
break;
}
c += 1;
}
c.min(line_len)
}
pub fn word_at(&self, line: usize, col: usize) -> Option<(usize, usize)> {
let chars: Vec<char> = self.lines.get(line)?.chars().collect();
if col >= chars.len() || !is_word_char(chars[col]) {
return None;
}
let mut start = col;
while start > 0 && is_word_char(chars[start - 1]) {
start -= 1;
}
let mut end = col + 1;
while end < chars.len() && is_word_char(chars[end]) {
end += 1;
}
Some((start, end))
}
pub fn word_string_at(&self, line: usize, col: usize) -> Option<String> {
let (start, end) = self.word_at(line, col)?;
let chars: Vec<char> = self.lines.get(line)?.chars().collect();
Some(chars[start..end].iter().collect())
}
pub fn diagnostics_at(
&self,
line: usize,
ch: usize,
) -> Vec<(crate::lsp::manager::DiagnosticSeverity, String)> {
if self.diagnostics_path.as_deref() != self.path.as_deref() {
return Vec::new();
}
let mut out = Vec::new();
for d in &self.diagnostics {
let start_line = d.start_line as usize;
let end_line = d.end_line as usize;
if line < start_line || line > end_line {
continue;
}
let Some(text) = self.lines.get(line) else {
continue;
};
let from = if line == start_line {
utf16_to_char_col(text, d.start_char)
} else {
0
};
let to = if line == end_line {
utf16_to_char_col(text, d.end_char)
} else {
text.chars().count()
};
let to = to.max(from + 1);
if ch >= from && ch < to {
out.push((d.severity, d.message.clone()));
}
}
out
}
pub fn hover_region_at(&self, line: usize, ch: usize) -> Option<(usize, usize, usize)> {
if let Some((start, end)) = self.word_at(line, ch) {
return Some((line, start, end));
}
if self.diagnostics_path.as_deref() != self.path.as_deref() {
return None;
}
for d in &self.diagnostics {
let start_line = d.start_line as usize;
let end_line = d.end_line as usize;
if line < start_line || line > end_line {
continue;
}
let text = self.lines.get(line)?;
let from = if line == start_line {
utf16_to_char_col(text, d.start_char)
} else {
0
};
let to = if line == end_line {
utf16_to_char_col(text, d.end_char)
} else {
text.chars().count()
};
let to = to.max(from + 1);
if ch >= from && ch < to {
return Some((line, from, to));
}
}
None
}
}
fn char_byte(s: &str, char_idx: usize) -> usize {
s.char_indices()
.nth(char_idx)
.map(|(i, _)| i)
.unwrap_or(s.len())
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
type BPos = (usize, usize);
const BRACKET_PAIRS: [(char, char); 3] = [('(', ')'), ('[', ']'), ('{', '}')];
fn is_open_bracket(c: char) -> bool {
BRACKET_PAIRS.iter().any(|&(o, _)| o == c)
}
fn is_close_bracket(c: char) -> bool {
BRACKET_PAIRS.iter().any(|&(_, cl)| cl == c)
}
fn matching_close(c: char) -> Option<char> {
BRACKET_PAIRS
.iter()
.find(|&&(o, _)| o == c)
.map(|&(_, cl)| cl)
}
fn matching_open(c: char) -> Option<char> {
BRACKET_PAIRS
.iter()
.find(|&&(_, cl)| cl == c)
.map(|&(o, _)| o)
}
fn find_word_occurrences(chars: &[char], word: &[char]) -> Vec<usize> {
let mut out = Vec::new();
if word.is_empty() || word.len() > chars.len() {
return out;
}
let last_start = chars.len() - word.len();
let mut i = 0;
while i <= last_start {
if chars[i..i + word.len()] == *word {
let before_ok = i == 0 || !is_word_char(chars[i - 1]);
let after_idx = i + word.len();
let after_ok = after_idx >= chars.len() || !is_word_char(chars[after_idx]);
if before_ok && after_ok {
out.push(i);
i += word.len();
continue;
}
}
i += 1;
}
out
}
fn line_comment_token(lang: Option<LangKind>) -> Option<&'static str> {
match lang {
Some(LangKind::Rust)
| Some(LangKind::JavaScript)
| Some(LangKind::TypeScript)
| Some(LangKind::Tsx)
| Some(LangKind::Go)
| Some(LangKind::C)
| Some(LangKind::Cpp) => Some("//"),
Some(LangKind::Python)
| Some(LangKind::Yaml)
| Some(LangKind::Toml)
| Some(LangKind::Bash) => Some("#"),
_ => None,
}
}
fn block_comment_tokens(lang: Option<LangKind>) -> Option<(&'static str, &'static str)> {
match lang {
Some(LangKind::Rust)
| Some(LangKind::JavaScript)
| Some(LangKind::TypeScript)
| Some(LangKind::Tsx)
| Some(LangKind::Go)
| Some(LangKind::C)
| Some(LangKind::Cpp)
| Some(LangKind::Css) => Some(("/*", "*/")),
Some(LangKind::Html) | Some(LangKind::Markdown) => Some(("<!--", "-->")),
Some(LangKind::Python) => Some(("\"\"\"", "\"\"\"")),
_ => None,
}
}
fn title_case(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut prev_alnum = false;
for c in s.chars() {
if c.is_alphanumeric() {
if prev_alnum {
out.extend(c.to_lowercase());
} else {
out.extend(c.to_uppercase());
}
prev_alnum = true;
} else {
out.push(c);
prev_alnum = false;
}
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WhitespaceMode {
None,
#[default]
Selection,
All,
}
impl WhitespaceMode {
pub fn pref_id(self) -> &'static str {
match self {
Self::None => "none",
Self::Selection => "selection",
Self::All => "all",
}
}
pub fn from_pref(id: &str) -> Self {
match id {
"none" => Self::None,
"all" => Self::All,
_ => Self::Selection,
}
}
pub fn label(self) -> &'static str {
match self {
Self::None => "none",
Self::Selection => "selection",
Self::All => "all",
}
}
pub fn next(self) -> Self {
match self {
Self::Selection => Self::All,
Self::All => Self::None,
Self::None => Self::Selection,
}
}
}
fn identifier_tokens(line: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut start: Option<usize> = None;
for (i, ch) in line.char_indices() {
let is_ident = ch == '_' || ch.is_ascii_alphanumeric();
match (start, is_ident) {
(None, true) if ch == '_' || ch.is_ascii_alphabetic() => start = Some(i),
(Some(s), false) => {
out.push(&line[s..i]);
start = None;
}
_ => {}
}
}
if let Some(s) = start {
out.push(&line[s..]);
}
out
}
const UNEXPECTED_BRACKET: u8 = u8::MAX;
const BRACKET_SCAN_MAX_BYTES: usize = 1_000_000;
const BRACKET_COLOR_CYCLE: usize = 3;
fn scan_bracket_colors(lines: &[String], protected: &[(usize, usize)]) -> Vec<Vec<(usize, u8)>> {
let mut out = vec![Vec::new(); lines.len()];
let mut stack: Vec<char> = Vec::new();
let mut abs = 0usize;
let mut pi = 0usize;
for (li, line) in lines.iter().enumerate() {
for (ci, ch) in line.chars().enumerate() {
let b = abs;
abs += ch.len_utf8();
while pi < protected.len() && protected[pi].1 <= b {
pi += 1;
}
if pi < protected.len() && protected[pi].0 <= b {
continue;
}
match ch {
'(' | '[' | '{' => {
out[li].push((ci, (stack.len() % BRACKET_COLOR_CYCLE) as u8));
stack.push(ch);
}
')' | ']' | '}' => {
let want = match ch {
')' => '(',
']' => '[',
_ => '{',
};
if stack.last() == Some(&want) {
stack.pop();
out[li].push((ci, (stack.len() % BRACKET_COLOR_CYCLE) as u8));
} else {
out[li].push((ci, UNEXPECTED_BRACKET));
}
}
_ => {}
}
}
abs += 1; }
out
}
fn indent_unit_for(lang: Option<LangKind>) -> &'static str {
match lang {
Some(LangKind::Yaml) => " ",
_ => " ",
}
}
pub fn language_label(lang: Option<LangKind>) -> &'static str {
match lang {
None => "Plain Text",
Some(LangKind::Rust) => "Rust",
Some(LangKind::Python) => "Python",
Some(LangKind::JavaScript) => "JavaScript",
Some(LangKind::TypeScript) => "TypeScript",
Some(LangKind::Tsx) => "TypeScript JSX",
Some(LangKind::Json) => "JSON",
Some(LangKind::Toml) => "TOML",
Some(LangKind::Yaml) => "YAML",
Some(LangKind::Markdown) => "Markdown",
Some(LangKind::Go) => "Go",
Some(LangKind::Html) => "HTML",
Some(LangKind::Css) => "CSS",
Some(LangKind::Bash) => "Shell Script",
Some(LangKind::C) => "C",
Some(LangKind::Cpp) => "C++",
}
}
pub fn language_scope_id(lang: Option<LangKind>) -> &'static str {
match lang {
None => "plaintext",
Some(LangKind::Rust) => "rust",
Some(LangKind::Python) => "python",
Some(LangKind::JavaScript) => "javascript",
Some(LangKind::TypeScript) => "typescript",
Some(LangKind::Tsx) => "typescriptreact",
Some(LangKind::Json) => "json",
Some(LangKind::Toml) => "toml",
Some(LangKind::Yaml) => "yaml",
Some(LangKind::Markdown) => "markdown",
Some(LangKind::Go) => "go",
Some(LangKind::Html) => "html",
Some(LangKind::Css) => "css",
Some(LangKind::Bash) => "shellscript",
Some(LangKind::C) => "c",
Some(LangKind::Cpp) => "cpp",
}
}
pub const SELECTABLE_LANGUAGES: &[LangKind] = &[
LangKind::Rust,
LangKind::Python,
LangKind::JavaScript,
LangKind::TypeScript,
LangKind::Tsx,
LangKind::Json,
LangKind::Toml,
LangKind::Yaml,
LangKind::Markdown,
LangKind::Go,
LangKind::Html,
LangKind::Css,
LangKind::Bash,
LangKind::C,
LangKind::Cpp,
];
fn leading_outdent_chars(line: &str, unit_w: usize) -> usize {
if unit_w == 0 {
return 0;
}
if line.starts_with('\t') {
return 1;
}
let spaces = line.chars().take_while(|c| *c == ' ').count();
if spaces == 0 {
0
} else {
((spaces - 1) % unit_w) + 1
}
}
fn extra_indent_triggered(lang: Option<LangKind>, last_non_ws: Option<char>) -> bool {
let last = match last_non_ws {
Some(c) => c,
None => return false,
};
match lang {
Some(LangKind::Python) => matches!(last, ':' | '(' | '[' | '{'),
Some(LangKind::Rust)
| Some(LangKind::JavaScript)
| Some(LangKind::TypeScript)
| Some(LangKind::Tsx)
| Some(LangKind::Json)
| Some(LangKind::Go)
| Some(LangKind::Css) => matches!(last, '(' | '[' | '{'),
_ => false,
}
}
fn is_bracket_pair_split(lang: Option<LangKind>, prev: Option<char>, next: Option<char>) -> bool {
let bracket_aware = matches!(
lang,
Some(LangKind::Rust)
| Some(LangKind::Python)
| Some(LangKind::JavaScript)
| Some(LangKind::TypeScript)
| Some(LangKind::Tsx)
| Some(LangKind::Json)
| Some(LangKind::Go)
| Some(LangKind::Css)
);
if !bracket_aware {
return false;
}
matches!(
(prev, next),
(Some('{'), Some('}')) | (Some('['), Some(']')) | (Some('('), Some(')'))
)
}
fn read_file_head(path: &Path) -> std::io::Result<Vec<u8>> {
use std::io::Read as _;
let mut head = vec![0u8; 4096];
let mut f = std::fs::File::open(path)?;
let mut filled = 0;
while filled < head.len() {
let n = f.read(&mut head[filled..])?;
if n == 0 {
break;
}
filled += n;
}
head.truncate(filled);
Ok(head)
}
fn is_binary(data: &[u8]) -> bool {
let sample = &data[..data.len().min(4096)];
if sample.contains(&0) {
return true;
}
if sample.is_empty() {
return false;
}
let nontext = sample
.iter()
.filter(|&&b| !(b >= 0x20 || matches!(b, b'\n' | b'\r' | b'\t' | 0x0c | 0x08)))
.count();
(nontext as f32 / sample.len() as f32) > 0.30
}
fn byte_index_of_char(line: &str, chars_in: usize) -> usize {
line.char_indices()
.nth(chars_in)
.map(|(b, _)| b)
.unwrap_or(line.len())
}
fn utf16_to_char_col(line: &str, u16_off: u32) -> usize {
let mut units: u32 = 0;
for (char_idx, ch) in line.chars().enumerate() {
if units >= u16_off {
return char_idx;
}
units += ch.len_utf16() as u32;
}
line.chars().count()
}
fn is_wrap_break_after(c: char) -> bool {
c.is_whitespace()
|| matches!(
c,
')' | ']' | '}' | '-' | '/' | ',' | '.' | ';' | ':' | '?' | '!'
)
}
fn wrap_segments(chars: &[char], width: usize) -> Vec<(usize, usize)> {
if width == 0 || chars.len() <= width {
return vec![(0, chars.len())];
}
let mut segs = Vec::new();
let mut start = 0;
while start < chars.len() {
if chars.len() - start <= width {
segs.push((start, chars.len()));
break;
}
let limit = start + width;
let mut brk = limit;
let mut i = limit;
while i > start + 1 {
if is_wrap_break_after(chars[i - 1]) {
brk = i;
break;
}
i -= 1;
}
segs.push((start, brk));
start = brk;
}
segs
}
fn split_into_lines(text: &str) -> Vec<String> {
normalize_newlines(text)
.lines()
.map(|s| s.to_string())
.collect()
}
pub(crate) fn normalize_newlines(text: &str) -> String {
text.replace("\r\n", "\n").replace('\r', "\n")
}
fn shift_spans_for_view(spans: &[HiSpan], byte_start: usize) -> Vec<HiSpan> {
let mut out = Vec::with_capacity(spans.len());
for sp in spans {
if sp.end <= byte_start {
continue;
}
let new_start = sp.start.saturating_sub(byte_start);
let new_end = sp.end - byte_start;
out.push(HiSpan {
start: new_start,
end: new_end,
style: sp.style,
});
}
out
}
fn span_rgb(style: ratatui::style::Style, default: (u8, u8, u8)) -> (u8, u8, u8) {
match style.fg {
Some(ratatui::style::Color::Rgb(r, g, b)) => (r, g, b),
_ => default,
}
}
fn merge_overlay(base: &[HiSpan], over: &[HiSpan]) -> Vec<HiSpan> {
if over.is_empty() {
return base.to_vec();
}
let mut out: Vec<HiSpan> = Vec::with_capacity(base.len() + over.len());
for b in base {
let mut cur = b.start;
for o in over.iter().filter(|o| o.end > b.start && o.start < b.end) {
if o.start > cur {
out.push(HiSpan {
start: cur,
end: o.start,
style: b.style,
});
}
cur = cur.max(o.end);
if cur >= b.end {
break;
}
}
if cur < b.end {
out.push(HiSpan {
start: cur,
end: b.end,
style: b.style,
});
}
}
out.extend_from_slice(over);
out.sort_by_key(|s| s.start);
out
}
fn build_line_spans<'a>(line: &'a str, spans: &[HiSpan]) -> Vec<Span<'a>> {
if spans.is_empty() {
return vec![Span::raw(line)];
}
let mut out: Vec<Span> = Vec::with_capacity(spans.len() * 2);
let mut cursor = 0usize;
for sp in spans {
if sp.start > cursor && sp.start <= line.len() {
let slice = &line[cursor..sp.start];
if !slice.is_empty() {
out.push(Span::raw(slice));
}
}
let s = sp.start.min(line.len());
let e = sp.end.min(line.len());
if e > s {
out.push(Span::styled(&line[s..e], sp.style));
cursor = e;
}
}
if cursor < line.len() {
out.push(Span::raw(&line[cursor..]));
}
out
}
impl Widget for &mut Editor {
fn render(self, area: Rect, buf: &mut Buffer) {
let block_style = if self.focused {
Style::default().fg(Color::Rgb(0x4e, 0x9a, 0xff))
} else {
Style::default().fg(Color::DarkGray)
};
let block = Block::default()
.borders(Borders::ALL)
.border_style(block_style);
let inner = block.inner(area);
block.render(area, buf);
if self.focused && self.focus_gradient {
crate::gradient::paint_gradient_box(buf, area);
}
self.last_area = area;
self.last_inner = inner;
self.last_scrollbar = Rect::default();
self.last_hscrollbar = Rect::default();
self.merge_action_spans.clear();
let height = inner.height as usize;
if height == 0 {
return;
}
let cbg = canvas_bg(
crate::iterm2_inline::detect_iterm2_inline_support(),
self.theme,
);
if let Some(image) = self.image.as_ref() {
let ibg = image_canvas_bg(
crate::iterm2_inline::detect_inline_image_protocol(),
self.theme,
);
render_image_placeholder(image, self.path.as_deref(), inner, buf, ibg);
return;
}
if let Some(view) = self.sheet.as_ref() {
render_sheet(view, self.path.as_deref(), inner, buf, cbg);
return;
}
if let Some(view) = self.hex.as_mut() {
render_hex(view, self.path.as_deref(), inner, buf, cbg, self.theme);
return;
}
if self.markdown_preview.is_some() {
self.render_markdown_preview(inner, buf);
return;
}
if let Some(diff) = self.diff.as_mut() {
let (prev_arrow, next_arrow) = render_diff(diff, inner, buf, cbg);
self.diff_prev_arrow = prev_arrow;
self.diff_next_arrow = next_arrow;
return;
}
self.diff_prev_arrow = Rect::default();
self.diff_next_arrow = Rect::default();
const SIGN_MARGIN: u16 = 2;
let gutter_width = (self.lines.len() + 1).to_string().len() as u16 + 1 + SIGN_MARGIN;
self.last_gutter_width = gutter_width;
self.refresh_git_marks();
self.conflicts();
if !self.folded.is_empty() && self.lines.len() != self.fold_epoch_lines {
self.folded.clear();
self.hidden_ranges.clear();
}
if !self.folded.is_empty() && self.is_line_hidden(self.cursor_row) {
self.reveal_cursor_fold();
}
let wrap = self.wrap_enabled();
if wrap {
self.scroll_col = 0;
}
let text_x = inner.x + gutter_width + 1;
let content_cols = self.content_cols();
let provisional_text_width = inner
.width
.saturating_sub(gutter_width + 2 + u16::from(self.lines.len() > height))
as usize;
let hbar_present =
!wrap && provisional_text_width > 0 && content_cols > provisional_text_width;
let text_height = height - usize::from(hbar_present);
self.last_text_rows = text_height as u16;
let scrollbar_area = Rect {
x: inner.x + inner.width.saturating_sub(1),
y: inner.y,
width: u16::from(inner.width > 0),
height: text_height as u16,
};
let (text_width, scrollbar_metrics) = if wrap {
let wide = inner.width.saturating_sub(gutter_width + 2) as usize;
let vbar = self.total_visual_rows(wide) > text_height;
let tw = if vbar { wide.saturating_sub(1) } else { wide };
let content_rows = self.total_visual_rows(tw);
if text_height > 0 {
let cursor_vrow = self.cursor_visual_row(tw);
let mut top = self.top_visual_row(tw);
if cursor_vrow < top {
top = cursor_vrow;
} else if cursor_vrow >= top + text_height {
top = cursor_vrow + 1 - text_height;
}
top = top.min(content_rows.saturating_sub(text_height));
self.set_top_to_visual_row(top, tw);
}
let metrics = scrollbar::vertical_metrics(
scrollbar_area,
content_rows,
text_height,
self.top_visual_row(tw),
);
(tw as u16, metrics)
} else {
if self.comment_boxes.is_empty() {
self.scroll_sub = 0;
} else {
let bw = inner.width.saturating_sub(gutter_width + 3) as usize;
let group = 1 + self.box_rows_between(self.scroll, self.scroll + 1, bw);
self.scroll_sub = self.scroll_sub.min(group - 1);
}
let scroll_before = self.scroll;
if text_height > 0 {
if self.cursor_row < self.scroll {
self.scroll = self.cursor_row;
} else if self.cursor_row >= self.scroll + text_height {
self.scroll = self.cursor_row + 1 - text_height;
}
if !self.comment_boxes.is_empty() {
let bw = inner.width.saturating_sub(gutter_width + 3) as usize;
while self.cursor_row + self.box_rows_between(self.scroll, self.cursor_row, bw)
>= self.scroll + text_height
{
self.scroll += 1;
}
}
}
if self.scroll != scroll_before {
self.scroll_sub = 0;
}
let bw = inner.width.saturating_sub(gutter_width + 3) as usize;
let box_rows = self.box_rows_between(0, self.lines.len(), bw);
let metrics = scrollbar::vertical_metrics(
scrollbar_area,
self.lines.len() + box_rows,
text_height,
self.scroll + self.box_rows_between(0, self.scroll, bw) + self.scroll_sub,
);
let sw = u16::from(metrics.is_some());
let tw = inner.width.saturating_sub(gutter_width + 2 + sw);
(tw, metrics)
};
if let Some(metrics) = scrollbar_metrics {
self.last_scrollbar = metrics.area;
}
let max_scroll_col = content_cols.saturating_sub(text_width as usize);
self.scroll_col = self.scroll_col.min(max_scroll_col);
let hbar_metrics = scrollbar::horizontal_metrics(
Rect {
x: text_x,
y: inner.y + text_height as u16,
width: text_width,
height: u16::from(hbar_present),
},
content_cols,
text_width as usize,
self.scroll_col,
);
self.last_hscrollbar = hbar_metrics.map(|m| m.area).unwrap_or_default();
let mut visual_rows: Vec<VisRow> = Vec::with_capacity(text_height);
let push_box_rows = |rows: &mut Vec<VisRow>,
ed: &Editor,
line: usize,
skip: usize,
seg_count: usize,
tw: usize| {
if ed.comment_boxes.is_empty() {
return;
}
let mut group_pos = seg_count;
for idx in 0..ed.comment_boxes.len() {
if ed.comment_boxes[idx].line != line {
continue;
}
for box_row in 0..ed.comment_box_height(idx, tw) {
if group_pos >= skip && rows.len() < text_height {
rows.push(VisRow::Box {
box_idx: idx,
box_row,
});
}
group_pos += 1;
}
}
};
if wrap {
let tw = text_width as usize;
let mut line = self.scroll;
let mut skip = self.scroll_sub;
while line < self.lines.len() && visual_rows.len() < text_height {
if self.is_line_hidden(line) {
line += 1;
continue;
}
let segs = self.line_segments(line, tw);
for (i, &(s, e)) in segs.iter().enumerate() {
if i < skip {
continue;
}
if visual_rows.len() >= text_height {
break;
}
visual_rows.push(VisRow::Text {
line,
start: s,
end: e,
});
}
push_box_rows(&mut visual_rows, self, line, skip, segs.len(), tw);
skip = 0;
line += 1;
}
} else {
let tw = text_width as usize;
let mut line = self.scroll;
let mut skip = self.scroll_sub;
while line < self.lines.len() && visual_rows.len() < text_height {
if !self.is_line_hidden(line) {
if skip == 0 && visual_rows.len() < text_height {
visual_rows.push(VisRow::Text {
line,
start: self.scroll_col,
end: self.scroll_col + text_width as usize,
});
}
push_box_rows(&mut visual_rows, self, line, skip, 1, tw);
skip = 0;
}
line += 1;
}
}
self.last_wrap_rows = visual_rows.clone();
let sel_norm = self
.selection
.filter(|s| s.has_area())
.map(|s| s.normalised());
let occ_needle = self.selection_occurrence_needle();
let bracket_pair = if self.focused {
self.bracket_match_pair()
} else {
None
};
let guide_step = self.guide_step();
let active_guide = (self.show_indent_guides && self.focused)
.then(|| self.active_indent_guide())
.flatten();
let guide_fg = self.theme.indent_guide();
let guide_active_fg = self.theme.indent_guide_active();
for (row_idx, vis_row) in visual_rows.iter().enumerate() {
let y = inner.y + row_idx as u16;
let (line_idx, row_start, row_end) = match *vis_row {
VisRow::Box { box_idx, box_row } => {
self.paint_comment_box_row(
buf,
inner,
y,
gutter_width,
text_x,
text_width,
box_idx,
box_row,
);
continue;
}
VisRow::Text { line, start, end } => (line, start, end),
};
if !wrap || row_start == 0 {
let line_no = format!(
"{:>width$} ",
line_idx + 1,
width = gutter_width as usize - 1
);
let gutter =
Line::from(Span::styled(line_no, Style::default().fg(Color::DarkGray)));
buf.set_line(inner.x, y, &gutter, gutter_width);
} else {
buf.set_line(
inner.x,
y,
&Line::from(" ".repeat(gutter_width as usize)),
gutter_width,
);
}
let sign_x = inner.x;
let mut sign_taken = false;
if (!wrap || row_start == 0)
&& let Some(path) = self.path.as_deref()
{
let here = line_idx + 1; let is_stop = self
.stop_line
.as_ref()
.is_some_and(|(p, l)| p == path && *l == here);
let is_bp = self
.breakpoints
.get(path)
.is_some_and(|s| s.contains(&here));
let is_unverified = self
.unverified_breakpoints
.get(path)
.is_some_and(|s| s.contains(&here));
let is_conditional = self
.breakpoint_conditions
.get(path)
.is_some_and(|c| c.contains_key(&here));
let is_logpoint = self
.breakpoint_logs
.get(path)
.is_some_and(|m| m.contains_key(&here));
if is_stop {
buf.set_string(
sign_x,
y,
"▶",
Style::default().fg(Color::Rgb(0xff, 0xcc, 0x00)),
);
sign_taken = true;
} else if is_bp {
let (glyph, color) = if is_unverified {
("○", Color::Rgb(0x99, 0x99, 0x99))
} else if is_conditional {
("◆", Color::Rgb(0xe5, 0x1c, 0x23))
} else if is_logpoint {
("◆", Color::Rgb(0xe5, 0xc0, 0x7b))
} else {
("●", Color::Rgb(0xe5, 0x1c, 0x23))
};
buf.set_string(sign_x, y, glyph, Style::default().fg(color));
sign_taken = true;
}
}
if (!wrap || row_start == 0) && !sign_taken && self.stream_stop_line == Some(line_idx) {
buf.set_string(
sign_x,
y,
"■",
Style::default().fg(Color::Rgb(0xff, 0x9d, 0x2f)),
);
sign_taken = true;
}
if (!wrap || row_start == 0)
&& !sign_taken
&& crate::testing::locate::test_fn_on_line(
self.path.as_deref(),
&self.lines,
line_idx,
)
.is_some()
{
buf.set_string(
sign_x,
y,
"\u{eb2c}", Style::default().fg(Color::Rgb(0x73, 0xc9, 0x91)),
);
}
if (!wrap || row_start == 0) && self.is_foldable(line_idx) {
let collapsed = self.folded.contains(&line_idx);
let (glyph, color) = if collapsed {
("▸", Color::Gray)
} else {
("▾", Color::DarkGray)
};
buf.set_string(sign_x + 1, y, glyph, Style::default().fg(color));
}
if (!wrap || row_start == 0)
&& let Some(mark) = self.git_marks.get(&line_idx)
{
let color = match mark {
GitMark::Added => self.theme.git_added(),
GitMark::Modified => self.theme.git_modified(),
GitMark::Deleted => self.theme.git_deleted(),
};
buf.set_string(
inner.x + gutter_width,
y,
"\u{2503}", Style::default().fg(color),
);
}
let raw = &self.lines[line_idx];
let line_len = self.line_char_len(line_idx);
let row_width = (row_end - row_start) as u16;
let byte_start = byte_index_of_char(raw, row_start);
let byte_end = byte_index_of_char(raw, row_end);
let visible_raw = &raw[byte_start..byte_end];
let seg_bytes = byte_end - byte_start;
let empty: Vec<HiSpan> = Vec::new();
let line_spans = self.highlights.get(line_idx).unwrap_or(&empty);
let sem_spans = self.semantic_overlay.get(line_idx).unwrap_or(&empty);
let merged = merge_overlay(line_spans, sem_spans);
let hint_cap = row_end.min(line_len);
let hint_cells: Vec<(usize, usize)> = self
.row_inlay_spans(line_idx)
.iter()
.filter(|(hc, _)| *hc >= row_start && *hc <= hint_cap)
.map(|(hc, l)| (*hc, l.chars().count()))
.collect();
let ex = |c: usize| inlay_cells_before(&hint_cells, c);
let ex_caret = |c: usize| inlay_cells_strictly_before(&hint_cells, c);
if hint_cells.is_empty() {
let shifted: Vec<HiSpan> = shift_spans_for_view(&merged, byte_start)
.into_iter()
.filter_map(|mut sp| {
if sp.start >= seg_bytes {
return None;
}
sp.end = sp.end.min(seg_bytes);
Some(sp)
})
.collect();
let spans = build_line_spans(visible_raw, &shifted);
buf.set_line(text_x, y, &Line::from(spans), row_width);
} else {
let hint_style = Style::default()
.fg(self.theme.ignored_fg())
.add_modifier(Modifier::ITALIC);
let mut out: Vec<Span> = Vec::new();
let mut from = row_start;
for (hcol, label) in self
.row_inlay_spans(line_idx)
.iter()
.filter(|(hc, _)| *hc >= row_start && *hc <= hint_cap)
{
if *hcol > from {
out.extend(inlay_text_segment(raw, &merged, from, *hcol));
}
out.push(Span::styled(label.clone(), hint_style));
from = from.max(*hcol);
}
if row_end > from {
out.extend(inlay_text_segment(raw, &merged, from, row_end));
}
buf.set_line(text_x, y, &Line::from(out), row_width);
}
if self.show_bracket_colors
&& let Some(cols) = self.bracket_colors.get(line_idx)
{
for &(c, ci) in cols {
if c < row_start {
continue;
}
let col = (c + ex(c) - row_start) as u16;
if col >= row_width {
break;
}
let fg = if ci == UNEXPECTED_BRACKET {
self.theme.bracket_unexpected_fg()
} else {
self.theme.bracket_pair_color(usize::from(ci))
};
let cell = &mut buf[(text_x + col, y)];
let style = cell.style().fg(fg);
cell.set_style(style);
}
}
if self.show_indent_guides && (!wrap || row_start == 0) {
for c in (0..self.guide_indent_width(line_idx)).step_by(guide_step) {
if c < row_start {
continue;
}
let col = (c + ex(c) - row_start) as u16;
if col >= row_width {
break;
}
let cell = &mut buf[(text_x + col, y)];
if cell.symbol() != " " {
continue;
}
let fg = match active_guide {
Some((ac, lo, hi)) if ac == c && (lo..=hi).contains(&line_idx) => {
guide_active_fg
}
_ => guide_fg,
};
cell.set_symbol("\u{2502}");
let style = cell.style().fg(fg);
cell.set_style(style);
}
}
if self.whitespace_mode != WhitespaceMode::None {
let ws_fg = self.theme.whitespace_fg();
let mut ws_spans: Vec<(usize, usize)> = Vec::new();
match self.whitespace_mode {
WhitespaceMode::All => ws_spans.push((0, line_len)),
WhitespaceMode::Selection => {
if let Some(((sr, sc), (er, ec))) = sel_norm
&& line_idx >= sr
&& line_idx <= er
{
let s = if line_idx == sr { sc } else { 0 };
let e = if line_idx == er { ec } else { line_len };
if e > s {
ws_spans.push((s, e));
}
}
for caret in &self.carets {
let ((cr0, cc0), (cr1, cc1)) = caret.normalised();
if line_idx >= cr0 && line_idx <= cr1 {
let s = if line_idx == cr0 { cc0 } else { 0 };
let e = if line_idx == cr1 { cc1 } else { line_len };
if e > s {
ws_spans.push((s, e));
}
}
}
}
WhitespaceMode::None => {}
}
for (s, e) in ws_spans {
let from = s.max(row_start);
let to = e.min(row_end).min(line_len);
if to <= from {
continue;
}
for (ci, ch) in raw.chars().enumerate().skip(from).take(to - from) {
let glyph = match ch {
' ' => "\u{b7}",
'\t' => "\u{2192}",
_ => continue,
};
let col = (ci + ex(ci) - row_start) as u16;
if col >= row_width {
break;
}
let cell = &mut buf[(text_x + col, y)];
cell.set_symbol(glyph);
let style = cell.style().fg(ws_fg);
cell.set_style(style);
}
}
}
if let Some(tint) = conflict_row_tint(&self.conflicts, line_idx) {
paint_full_row_bg(buf, text_x, y, row_width, tint);
}
if let Some(block_idx) = self.conflicts.iter().position(|b| b.ours_start == line_idx) {
let block = self.conflicts[block_idx];
let marker_len = self
.lines
.get(line_idx)
.map(|l| l.chars().count() as u16)
.unwrap_or(0)
.saturating_sub(row_start as u16);
let mut x = text_x + marker_len.min(row_width) + 2;
let actions: [(&str, crate::merge::Resolution); 3] = [
("[Accept Current]", crate::merge::Resolution::Current),
("[Accept Incoming]", crate::merge::Resolution::Incoming),
("[Accept Both]", crate::merge::Resolution::Both),
];
for (label, res) in actions {
let w = label.len() as u16;
if x + w > text_x + row_width {
break;
}
buf.set_string(
x,
y,
label,
Style::default()
.fg(Color::Rgb(0x8a, 0xb4, 0xf8))
.add_modifier(Modifier::UNDERLINED),
);
self.merge_action_spans
.push((y, x..x + w, block.ours_start, res));
x += w + 2;
}
}
let empty_diag: Vec<(usize, usize, crate::lsp::manager::DiagnosticSeverity)> =
Vec::new();
for &(sc, ec, severity) in self.diagnostic_spans.get(line_idx).unwrap_or(&empty_diag) {
let vs = (sc + ex(sc)).saturating_sub(row_start);
let ve = (ec + ex(ec.saturating_sub(1))).saturating_sub(row_start);
if ve > vs {
paint_diagnostic_underline(buf, text_x, y, row_width, vs, ve, severity);
}
}
for &(occ_row, occ_start, occ_end, occ_write) in &self.occurrences {
if occ_row != line_idx {
continue;
}
let bg = if occ_write {
self.theme.occurrence_write_bg()
} else {
self.theme.occurrence_bg()
};
for c in occ_start..occ_end {
if c < row_start {
continue;
}
let col = (c + inlay_cells_before(&hint_cells, c) - row_start) as u16;
if col >= row_width {
break;
}
let cell = &mut buf[(text_x + col, y)];
cell.set_style(cell.style().bg(bg));
}
}
if let Some(term) = self.search_highlight.as_deref() {
let active_on_line = self
.active_search_match
.filter(|(r, _, _)| *r == line_idx)
.map(|(_, c, l)| (c, l));
paint_search_highlight(
buf,
text_x,
y,
row_width,
raw,
term,
self.search_highlight_opts,
row_start,
active_on_line,
&hint_cells,
);
}
if let Some(needle) = occ_needle.as_deref() {
paint_selection_occurrences(
buf,
text_x,
y,
row_width,
raw,
needle,
row_start,
&hint_cells,
);
}
if let Some(((sr, sc), (er, ec))) = sel_norm
&& line_idx >= sr
&& line_idx <= er
{
let sel_start = if line_idx == sr { sc } else { 0 };
let sel_end = if line_idx == er { ec } else { line_len + 1 };
let visible_start = (sel_start + ex(sel_start)).saturating_sub(row_start);
let visible_end =
(sel_end + ex(sel_end.saturating_sub(1))).saturating_sub(row_start);
if visible_end > visible_start {
paint_selection_band(buf, text_x, y, row_width, visible_start, visible_end);
}
}
if let Some((open, close)) = bracket_pair {
for pos in [open, close] {
if pos.0 == line_idx {
paint_bracket_match(
buf,
text_x,
y,
row_width,
pos.1 + ex(pos.1),
row_start,
self.theme,
);
}
}
}
for caret in &self.carets {
let ((cr0, cc0), (cr1, cc1)) = caret.normalised();
if line_idx >= cr0 && line_idx <= cr1 {
let cs = if line_idx == cr0 { cc0 } else { 0 };
let ce = if line_idx == cr1 { cc1 } else { line_len + 1 };
let vs = (cs + ex(cs)).saturating_sub(row_start);
let ve = (ce + ex(ce.saturating_sub(1))).saturating_sub(row_start);
if ve > vs {
paint_selection_band(buf, text_x, y, row_width, vs, ve);
}
}
let c = caret.head.1;
let on_row = caret.head.0 == line_idx
&& c >= row_start
&& (c < row_end || (c == row_end && row_end == line_len));
if on_row {
paint_block_cursor(buf, text_x, y, row_width, c + ex_caret(c), row_start);
}
}
for &(gr, gc, color) in &self.ghost_carets {
let on_row = gr == line_idx
&& gc >= row_start
&& (gc < row_end || (gc == row_end && row_end == line_len));
if on_row {
paint_ghost_caret(
buf,
text_x,
y,
row_width,
gc + ex_caret(gc),
row_start,
color,
);
}
}
if self.focused
&& line_idx == self.cursor_row
&& row_end >= line_len
&& !self.inline_values.contains_key(&line_idx)
&& let Some(note) = self.current_line_blame_annotation()
{
let text_cols = (line_len + ex(line_len)).saturating_sub(row_start);
let start_x = text_x + text_cols as u16 + 2;
let right = inner.x + inner.width;
if start_x < right {
let avail = (right - start_x) as usize;
let shown: String = note.chars().take(avail).collect();
buf.set_string(
start_x,
y,
&shown,
Style::default()
.fg(self.theme.ignored_fg())
.add_modifier(Modifier::ITALIC),
);
}
}
if row_end >= line_len
&& let Some(note) = self.inline_values.get(&line_idx)
{
let text_cols = (line_len + ex(line_len)).saturating_sub(row_start);
let start_x = text_x + text_cols as u16 + 2;
let right = inner.x + inner.width;
if start_x < right {
let avail = (right - start_x) as usize;
let shown: String = note.chars().take(avail).collect();
buf.set_string(
start_x,
y,
&shown,
Style::default()
.fg(self.theme.ignored_fg())
.add_modifier(Modifier::ITALIC),
);
}
}
}
for (cl, cc, name, color) in &self.ghost_caret_labels {
let Some(caret_vidx) = visual_rows.iter().position(|r| {
matches!(r, VisRow::Text { line: li, start: s, end: e }
if *li == *cl && *cc >= *s
&& (*cc < *e || (*cc == *e && *e == self.line_char_len(*li))))
}) else {
continue;
};
let label_vidx = if caret_vidx > 0 {
caret_vidx - 1
} else {
caret_vidx + 1
};
if label_vidx >= visual_rows.len() {
continue;
}
let VisRow::Text {
start: caret_start,
end: caret_end,
..
} = visual_rows[caret_vidx]
else {
continue;
};
let hint_cap = caret_end.min(self.line_char_len(*cl));
let hint_cells: Vec<(usize, usize)> = self
.row_inlay_spans(*cl)
.iter()
.filter(|(hc, _)| *hc >= caret_start && *hc <= hint_cap)
.map(|(hc, l)| (*hc, l.chars().count()))
.collect();
let col_cells = cc + inlay_cells_before(&hint_cells, *cc);
if col_cells < caret_start {
continue;
}
let x0 = (col_cells - caret_start) as u16;
let y = inner.y + label_vidx as u16;
let style = Style::default()
.fg(Color::Black)
.bg(*color)
.add_modifier(Modifier::BOLD);
for (i, ch) in name.chars().enumerate() {
let x = x0 + i as u16;
if x >= text_width {
break;
}
buf[(text_x + x, y)].set_char(ch).set_style(style);
}
}
self.sticky_click_rows.clear();
if !wrap && !self.sticky_lines.is_empty() && inner.height > 1 {
let bg = self.theme.sticky_scroll_bg();
let text_w = (inner.x + inner.width).saturating_sub(text_x);
let rows_avail = (inner.height - 1) as usize;
let caret_row = self
.last_wrap_rows
.iter()
.position(|r| matches!(r, VisRow::Text { line, .. } if *line == self.cursor_row));
let max_rows = match caret_row {
Some(row) => rows_avail.min(row),
None => rows_avail,
};
let sticky = self.sticky_lines.clone();
for (i, &line) in sticky.iter().take(max_rows).enumerate() {
let y = inner.y + i as u16;
for x in inner.x..inner.x + inner.width {
buf[(x, y)].set_symbol(" ");
buf[(x, y)].set_style(Style::default().bg(bg));
}
let line_no = format!(
"{:>width$} ",
line + 1,
width = gutter_width.saturating_sub(1) as usize
);
buf.set_string(
inner.x,
y,
&line_no,
Style::default().fg(Color::DarkGray).bg(bg),
);
self.paint_highlighted_line(buf, text_x, y, text_w, line as usize);
self.sticky_click_rows.push((y, line));
}
let band_end = inner.y + sticky.len().min(max_rows) as u16;
self.merge_action_spans
.retain(|(y, _, _, _)| *y >= band_end);
}
if let Some(metrics) = scrollbar_metrics {
scrollbar::render_vertical(buf, metrics, self.focused, self.theme);
}
if let Some(metrics) = hbar_metrics {
scrollbar::render_horizontal(buf, metrics, self.focused, self.theme);
}
}
}
impl Editor {
fn render_markdown_preview(&mut self, inner: Rect, buf: &mut Buffer) {
let stale = self
.markdown_preview
.as_ref()
.is_some_and(|md| md.built_seq != self.edit_seq);
if stale {
let text = self.lines.join("\n");
let lines = crate::markdown::render_markdown(&text, self.theme, &mut self.registry);
if let Some(md) = self.markdown_preview.as_mut() {
md.lines = lines;
md.built_seq = self.edit_seq;
}
}
let Some(md) = self.markdown_preview.as_mut() else {
return;
};
let text_area = Rect {
x: inner.x + 1,
width: inner.width.saturating_sub(3),
..inner
};
if text_area.width == 0 {
return;
}
let para = Paragraph::new(Text::from(md.lines.clone())).wrap(Wrap { trim: false });
let total = para.line_count(text_area.width);
let max_scroll = total.saturating_sub(inner.height as usize) as u16;
md.scroll = md.scroll.min(max_scroll);
para.scroll((md.scroll, 0)).render(text_area, buf);
if let Some(metrics) = scrollbar::vertical_metrics(
Rect {
x: inner.x + inner.width.saturating_sub(1),
y: inner.y,
width: 1,
height: inner.height,
},
total,
inner.height as usize,
md.scroll as usize,
) {
self.last_scrollbar = metrics.area;
scrollbar::render_vertical(buf, metrics, self.focused, self.theme);
}
}
fn paint_highlighted_line(
&self,
buf: &mut Buffer,
text_x: u16,
y: u16,
width: u16,
line_idx: usize,
) {
let Some(raw) = self.lines.get(line_idx) else {
return;
};
let empty: Vec<HiSpan> = Vec::new();
let line_spans = self.highlights.get(line_idx).unwrap_or(&empty);
let sem_spans = self.semantic_overlay.get(line_idx).unwrap_or(&empty);
let merged = merge_overlay(line_spans, sem_spans);
let raw_bytes = raw.len();
let clamped: Vec<HiSpan> = merged
.into_iter()
.filter_map(|mut sp| {
if sp.start >= raw_bytes {
return None;
}
sp.end = sp.end.min(raw_bytes);
Some(sp)
})
.collect();
let spans = build_line_spans(raw, &clamped);
buf.set_line(text_x, y, &Line::from(spans), width);
}
pub fn sticky_line_at(&self, col: u16, row: u16) -> Option<u32> {
if col < self.last_inner.x || col >= self.last_inner.x + self.last_inner.width {
return None;
}
self.sticky_click_rows
.iter()
.find(|&&(y, _)| y == row)
.map(|&(_, line)| line)
}
pub fn cursor_screen_pos(&self) -> Option<(u16, u16)> {
if self.last_inner.height == 0 {
return None;
}
let text_x = self.last_inner.x + self.last_gutter_width + 1;
if self.wrap_enabled() {
let idx = self.last_wrap_rows.iter().position(|r| {
matches!(r, VisRow::Text { line, start, end }
if *line == self.cursor_row
&& self.cursor_col >= *start
&& (self.cursor_col < *end
|| (self.cursor_col == *end
&& *end == self.line_char_len(*line))))
})?;
let (_, start, _) = self.text_row(idx)?;
let visible_col = self.cursor_col - start;
let x = text_x as usize + visible_col;
let right = (self.last_inner.x + self.last_inner.width)
.saturating_sub(u16::from(self.last_scrollbar.width > 0))
as usize;
if x >= right {
return None;
}
return Some((x as u16, self.last_inner.y + idx as u16));
}
if self.cursor_row < self.scroll {
return None;
}
let row_in_view = if self.last_wrap_rows.is_empty() {
self.cursor_row - self.scroll
} else {
self.last_wrap_rows
.iter()
.position(|r| matches!(r, VisRow::Text { line, .. } if *line == self.cursor_row))?
};
if (row_in_view as u16) >= self.last_inner.height {
return None;
}
let text_width = self
.last_inner
.width
.saturating_sub(self.last_gutter_width + 2 + u16::from(self.last_scrollbar.width > 0));
if text_width == 0 || self.cursor_col < self.scroll_col {
return None;
}
let extra = self.inlay_cells_before_cursor(self.cursor_row, self.scroll_col);
let visible_col = self.cursor_col - self.scroll_col + extra;
if (visible_col as u16) >= text_width {
return None;
}
Some((
text_x + visible_col as u16,
self.last_inner.y + row_in_view as u16,
))
}
fn inlay_cells_before_cursor(&self, line: usize, scroll_col: usize) -> usize {
self.row_inlay_spans(line)
.iter()
.filter(|(hc, _)| *hc >= scroll_col && *hc < self.cursor_col)
.map(|(_, l)| l.chars().count())
.sum()
}
pub fn diff_caret_screen_pos(&self) -> Option<(u16, u16)> {
use crate::widgets::diff::DiffSide;
let diff = self.diff.as_ref()?;
if diff.unified {
return None;
}
let (side, row_idx, char_col) = diff.caret()?;
let inner = self.last_inner;
if inner.width < 16 || inner.height < 3 {
return None;
}
let body_top = inner.y + 1;
let body_height = inner.height.saturating_sub(2);
if body_height == 0 || row_idx < diff.scroll {
return None;
}
let vis_row = row_idx - diff.scroll;
if vis_row as u16 >= body_height {
return None;
}
let half = inner.width / 2;
if half < 8 {
return None;
}
let l_gutter = (diff.left_lines.len() + 1).to_string().len() as u16 + 1;
let r_gutter = (diff.right_lines.len() + 1).to_string().len() as u16 + 1;
let (text_x, text_w) = match side {
DiffSide::Left => (
inner.x + l_gutter + 2,
half.saturating_sub(l_gutter + 2 + 1),
),
DiffSide::Right => (
inner.x + half + 1 + r_gutter + 2,
(inner.width - (half + 1)).saturating_sub(r_gutter + 2),
),
};
if text_w == 0 || char_col < diff.scroll_x {
return None;
}
let vis_col = char_col - diff.scroll_x;
if vis_col as u16 >= text_w {
return None;
}
Some((text_x + vis_col as u16, body_top + vis_row as u16))
}
}
fn inlay_cells_before(hints: &[(usize, usize)], c: usize) -> usize {
hints
.iter()
.filter(|(hc, _)| *hc <= c)
.map(|(_, n)| n)
.sum()
}
fn inlay_cells_strictly_before(hints: &[(usize, usize)], c: usize) -> usize {
hints.iter().filter(|(hc, _)| *hc < c).map(|(_, n)| n).sum()
}
fn inlay_text_segment<'a>(
raw: &'a str,
merged: &[HiSpan],
from: usize,
to: usize,
) -> Vec<Span<'a>> {
let byte_from = byte_index_of_char(raw, from);
let byte_to = byte_index_of_char(raw, to);
let seg = &raw[byte_from..byte_to];
let seg_bytes = byte_to - byte_from;
let shifted: Vec<HiSpan> = shift_spans_for_view(merged, byte_from)
.into_iter()
.filter_map(|mut sp| {
if sp.start >= seg_bytes {
return None;
}
sp.end = sp.end.min(seg_bytes);
Some(sp)
})
.collect();
build_line_spans(seg, &shifted)
}
#[allow(clippy::too_many_arguments)]
fn paint_search_highlight(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
raw_line: &str,
needle: &str,
opts: crate::widgets::search::SearchOpts,
scroll_col: usize,
active_match_on_line: Option<(usize, usize)>,
hints: &[(usize, usize)],
) {
if needle.is_empty() {
return;
}
let inactive_style = Style::default()
.fg(Color::Black)
.bg(Color::Rgb(0xff, 0xd7, 0x4a))
.add_modifier(Modifier::BOLD);
let active_style = Style::default()
.fg(Color::Black)
.bg(Color::Rgb(0xff, 0x8c, 0x2a))
.add_modifier(Modifier::BOLD);
let segments = crate::widgets::search::split_for_highlight(raw_line, needle, opts);
let mut abs_col: usize = 0;
for (chunk, is_match) in segments {
let chunk_cols = chunk.chars().count();
if is_match {
let is_active =
active_match_on_line.is_some_and(|(c, l)| c == abs_col && l == chunk_cols);
let style = if is_active {
active_style
} else {
inactive_style
};
for c in 0..chunk_cols {
let absolute = abs_col + c;
if absolute < scroll_col {
continue;
}
let col = (absolute + inlay_cells_before(hints, absolute) - scroll_col) as u16;
if col >= text_width {
break;
}
buf[(text_x + col, y)].set_style(style);
}
}
abs_col = abs_col.saturating_add(chunk_cols);
if abs_col >= scroll_col + text_width as usize {
break;
}
}
}
#[allow(clippy::too_many_arguments)]
fn paint_selection_occurrences(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
raw_line: &str,
needle: &str,
scroll_col: usize,
hints: &[(usize, usize)],
) {
if needle.is_empty() {
return;
}
let bg = Color::Rgb(0x37, 0x61, 0x8e);
let needle_cols = needle.chars().count();
let mut search_from = 0usize;
while let Some(rel) = raw_line[search_from..].find(needle) {
let byte_start = search_from + rel;
let char_start = raw_line[..byte_start].chars().count();
for c in 0..needle_cols {
let absolute = char_start + c;
if absolute < scroll_col {
continue;
}
let col = (absolute + inlay_cells_before(hints, absolute) - scroll_col) as u16;
if col >= text_width {
break;
}
let cell = &mut buf[(text_x + col, y)];
cell.set_style(cell.style().bg(bg));
}
search_from = byte_start + needle.len();
}
}
fn paint_block_cursor(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
col_char: usize,
scroll_col: usize,
) {
if col_char < scroll_col {
return;
}
let col = col_char - scroll_col;
if col as u16 >= text_width {
return;
}
let cell = &mut buf[(text_x + col as u16, y)];
cell.set_style(
Style::default()
.fg(Color::Black)
.bg(Color::Rgb(0xae, 0xc6, 0xff))
.add_modifier(Modifier::BOLD),
);
}
fn paint_ghost_caret(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
col_char: usize,
scroll_col: usize,
color: Color,
) {
if col_char < scroll_col {
return;
}
let col = col_char - scroll_col;
if col as u16 >= text_width {
return;
}
let cell = &mut buf[(text_x + col as u16, y)];
cell.set_style(
Style::default()
.fg(Color::Black)
.bg(color)
.add_modifier(Modifier::BOLD),
);
}
fn paint_bracket_match(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
col_char: usize,
scroll_col: usize,
theme: crate::theme::Theme,
) {
if col_char < scroll_col {
return;
}
let col = (col_char - scroll_col) as u16;
if col >= text_width {
return;
}
let cell = &mut buf[(text_x + col, y)];
cell.set_style(cell.style().bg(theme.bracket_match_bg()));
}
fn auto_close_partner(c: char) -> Option<char> {
match c {
'(' => Some(')'),
'[' => Some(']'),
'{' => Some('}'),
'"' => Some('"'),
'\'' => Some('\''),
'`' => Some('`'),
_ => None,
}
}
fn is_pair_closer(c: char) -> bool {
matches!(c, ')' | ']' | '}')
}
fn is_pair_quote(c: char) -> bool {
matches!(c, '"' | '\'' | '`')
}
fn conflict_row_tint(blocks: &[crate::merge::ConflictBlock], row: usize) -> Option<Color> {
let block = blocks.iter().find(|b| b.contains(row))?;
let ours_end = block.base_start.unwrap_or(block.sep);
Some(if row == block.ours_start {
Color::Rgb(0x2a, 0x4f, 0x33)
} else if row < ours_end {
Color::Rgb(0x1b, 0x33, 0x22)
} else if row < block.sep {
Color::Rgb(0x2a, 0x2a, 0x2a)
} else if row == block.sep {
Color::Rgb(0x28, 0x28, 0x28)
} else if row == block.theirs_end {
Color::Rgb(0x1f, 0x41, 0x66)
} else {
Color::Rgb(0x16, 0x2b, 0x44)
})
}
fn paint_full_row_bg(buf: &mut Buffer, text_x: u16, y: u16, text_width: u16, bg: Color) {
for col in 0..text_width {
let x = text_x + col;
let cell = &mut buf[(x, y)];
cell.set_style(cell.style().bg(bg));
}
}
fn paint_selection_band(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
start_char: usize,
end_char: usize,
) {
let bg = Color::Rgb(0x26, 0x4f, 0x78);
let s = start_char.min(text_width as usize);
let e = end_char.min(text_width as usize);
if e <= s {
return;
}
for col in s..e {
let x = text_x + col as u16;
let cell = &mut buf[(x, y)];
cell.set_style(cell.style().bg(bg));
}
}
fn paint_diagnostic_underline(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
start_char: usize,
end_char: usize,
severity: crate::lsp::manager::DiagnosticSeverity,
) {
use crate::lsp::manager::DiagnosticSeverity;
let color = match severity {
DiagnosticSeverity::Error => Color::Rgb(0xf1, 0x4c, 0x4c),
DiagnosticSeverity::Warning => Color::Rgb(0xcc, 0xa7, 0x00),
DiagnosticSeverity::Information | DiagnosticSeverity::Hint => Color::Rgb(0x3b, 0x9e, 0xff),
};
let s = start_char.min(text_width as usize);
let e = end_char.min(text_width as usize);
if e <= s {
return;
}
for col in s..e {
let x = text_x + col as u16;
let cell = &mut buf[(x, y)];
cell.set_style(
cell.style()
.add_modifier(Modifier::UNDERLINED)
.underline_color(color),
);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Crumb {
pub label: String,
pub target: Option<(u32, u32)>,
}
type BreadcrumbRange = (u16, u16, Option<(u32, u32)>);
pub struct EditorTabs {
pub editors: Vec<Editor>,
active: usize,
pub breadcrumbs: Vec<Crumb>,
breadcrumb_ranges: Vec<BreadcrumbRange>,
breadcrumb_y: Option<u16>,
tab_screen_ranges: Vec<(u16, u16)>,
tab_close_x: Vec<u16>,
tab_strip_y: u16,
pub last_full_area: Rect,
search_highlight_term: Option<String>,
search_highlight_opts: crate::widgets::search::SearchOpts,
pub hover_pointer: Option<(u16, u16)>,
}
impl EditorTabs {
pub fn new() -> Self {
Self {
editors: vec![Editor::new()],
active: 0,
breadcrumbs: Vec::new(),
breadcrumb_ranges: Vec::new(),
breadcrumb_y: None,
tab_screen_ranges: Vec::new(),
tab_close_x: Vec::new(),
tab_strip_y: 0,
last_full_area: Rect::default(),
search_highlight_term: None,
search_highlight_opts: crate::widgets::search::SearchOpts::default(),
hover_pointer: None,
}
}
pub fn tab_count(&self) -> usize {
self.editors.len()
}
pub fn set_search_highlight(
&mut self,
term: Option<String>,
opts: crate::widgets::search::SearchOpts,
) {
let normalised = term.filter(|s| !s.is_empty());
let cleared = normalised.is_none();
self.search_highlight_term = normalised.clone();
self.search_highlight_opts = opts;
for ed in &mut self.editors {
ed.search_highlight = normalised.clone();
ed.search_highlight_opts = opts;
if cleared {
ed.active_search_match = None;
}
}
}
pub fn active_index(&self) -> usize {
self.active
}
pub fn tab_display_label(&self, idx: usize) -> String {
self.editors.get(idx).map(tab_label).unwrap_or_default()
}
pub fn tab_path(&self, idx: usize) -> Option<PathBuf> {
self.editors.get(idx).and_then(|e| e.path.clone())
}
pub fn tab_display_labels(&self) -> Vec<String> {
disambiguated_tab_labels(&self.editors)
}
#[cfg(test)]
pub fn tab_strip_y_for_test(&self) -> u16 {
self.tab_strip_y
}
pub fn iter_tabs(&self) -> impl Iterator<Item = &Editor> {
self.editors.iter()
}
pub fn select(&mut self, idx: usize) -> bool {
if idx >= self.editors.len() {
return false;
}
self.editors[self.active].focused = false;
self.active = idx;
self.editors[self.active].focused = true;
true
}
pub fn reload_externally_changed_tabs(
&mut self,
skip: &dyn Fn(&Path) -> bool,
) -> ExternalReloadReport {
let mut report = ExternalReloadReport::default();
for ed in &mut self.editors {
if ed.path.is_none() || ed.diff.is_some() {
continue;
}
if ed.path.as_deref().is_some_and(skip) {
continue;
}
let path = ed.path.clone();
match ed.reload_or_flag_conflict() {
ExternalChange::Reloaded => {
if let Some(p) = path {
report.reloaded.push(p);
}
}
ExternalChange::Conflict => {
if let Some(p) = path {
report.conflicts.push(p);
}
}
ExternalChange::ReloadFailed => {
if let Some(p) = path {
report.failed.push(p);
}
}
ExternalChange::Unchanged => {}
}
}
report
}
pub fn revert_paths_to_disk(&mut self, paths: &[PathBuf]) -> Vec<PathBuf> {
let mut reverted = Vec::new();
for ed in &mut self.editors {
let Some(p) = ed.path.clone() else { continue };
if paths.iter().any(|q| q == &p) && ed.revert_to_disk().is_ok() {
reverted.push(p);
}
}
reverted
}
pub fn rename_open_path(&mut self, old: &Path, new: &Path) {
for e in &mut self.editors {
if e.path.as_deref() == Some(old) {
e.path = Some(new.to_path_buf());
e.mark_synced_with_disk();
}
}
}
pub fn open_in_new_tab(&mut self, path: &Path) -> Result<()> {
let mut e = Editor::new();
e.focused = self.editors[self.active].focused;
e.open(path)?;
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
Ok(())
}
pub fn add_tab_with_path(&mut self, path: PathBuf) {
let mut e = Editor::new();
e.path = Some(path);
e.focused = self.editors[self.active].focused;
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
}
pub fn close_active(&mut self) -> bool {
self.close_tab(self.active)
}
pub fn close_tab(&mut self, idx: usize) -> bool {
if idx >= self.editors.len() {
return false;
}
if self.editors.len() == 1 {
let was_focused = self.editors[0].focused;
let mut fresh = Editor::new();
fresh.focused = was_focused;
self.editors[0] = fresh;
self.active = 0;
return true;
}
self.editors.remove(idx);
if self.active > idx {
self.active -= 1;
} else if self.active >= self.editors.len() {
self.active = self.editors.len() - 1;
}
for (i, ed) in self.editors.iter_mut().enumerate() {
ed.focused = i == self.active;
}
true
}
pub fn close_others(&mut self, keep_idx: usize) -> usize {
if keep_idx >= self.editors.len() || self.editors.len() <= 1 {
return 0;
}
let before = self.editors.len();
let mut new_active = 0;
let mut kept: Vec<Editor> = Vec::with_capacity(before);
for (i, ed) in std::mem::take(&mut self.editors).into_iter().enumerate() {
if i == keep_idx {
new_active = kept.len();
kept.push(ed);
} else if ed.pinned {
kept.push(ed);
}
}
let removed = before - kept.len();
self.editors = kept;
self.active = new_active;
for (i, ed) in self.editors.iter_mut().enumerate() {
ed.focused = i == self.active;
}
removed
}
pub fn close_to_right(&mut self, from_idx: usize) -> usize {
if from_idx >= self.editors.len() {
return 0;
}
let before = self.editors.len();
let old_active = self.active;
let mut new_active: Option<usize> = None;
let mut pivot_pos = 0;
let mut kept: Vec<Editor> = Vec::with_capacity(before);
for (i, ed) in std::mem::take(&mut self.editors).into_iter().enumerate() {
if i <= from_idx || ed.pinned {
if i == from_idx {
pivot_pos = kept.len();
}
if i == old_active {
new_active = Some(kept.len());
}
kept.push(ed);
}
}
let removed = before - kept.len();
self.editors = kept;
self.active = new_active.unwrap_or(pivot_pos);
for (i, ed) in self.editors.iter_mut().enumerate() {
ed.focused = i == self.active;
}
removed
}
pub fn close_all(&mut self) -> usize {
let n = self.editors.len();
let was_focused = self.editors[self.active].focused;
let mut fresh = Editor::new();
fresh.focused = was_focused;
self.editors = vec![fresh];
self.active = 0;
n
}
pub fn close_saved(&mut self) -> usize {
let before = self.editors.len();
let was_focused = self.editors[self.active].focused;
let mut kept: Vec<Editor> = std::mem::take(&mut self.editors)
.into_iter()
.filter(|e| e.dirty)
.collect();
let removed = before - kept.len();
if kept.is_empty() {
let mut fresh = Editor::new();
fresh.focused = was_focused;
kept.push(fresh);
}
self.editors = kept;
self.active = 0;
for (i, ed) in self.editors.iter_mut().enumerate() {
ed.focused = i == 0;
}
removed
}
pub fn tab_at(&self, col: u16, row: u16) -> Option<usize> {
if row != self.tab_strip_y {
return None;
}
for (i, &(x, w)) in self.tab_screen_ranges.iter().enumerate() {
if col >= x && col < x.saturating_add(w) {
return Some(i);
}
}
None
}
pub fn tab_full_path(&self, idx: usize) -> Option<String> {
let e = self.editors.get(idx)?;
if let Some(diff) = e.diff.as_ref() {
let l = diff.left_path.to_string_lossy().into_owned();
let r_is_real = diff.right_path != Path::new("/dev/null")
&& !diff.right_path.as_os_str().is_empty();
if r_is_real {
let r = diff.right_path.to_string_lossy().into_owned();
return Some(format!("{l} \u{2194} {r}"));
}
return Some(l);
}
e.path.as_ref().map(|p| p.to_string_lossy().into_owned())
}
pub fn tab_screen_x(&self, idx: usize) -> Option<(u16, u16)> {
self.tab_screen_ranges.get(idx).copied()
}
pub fn close_screen_x(&self, idx: usize) -> Option<u16> {
self.tab_close_x.get(idx).copied().filter(|&x| x != 0)
}
pub fn close_at(&self, col: u16, row: u16) -> Option<usize> {
if row != self.tab_strip_y {
return None;
}
self.tab_close_x.iter().position(|&x| x != 0 && x == col)
}
pub fn find_tab_with_path(&self, target: &Path) -> Option<usize> {
self.find_tab_matching(target, |_| true)
}
pub fn apply_rename_to_open_tab(
&mut self,
path: &Path,
edits: &[TextSpanEdit],
) -> Option<usize> {
let idx = self.find_tab_with_path(path)?;
Some(self.editors[idx].apply_span_edits(edits))
}
fn find_tab_matching(&self, target: &Path, extra: impl Fn(&Editor) -> bool) -> Option<usize> {
let canon_target = target.canonicalize().ok();
self.editors.iter().position(|e| {
if !extra(e) {
return false;
}
let Some(p) = e.path.as_ref() else {
return false;
};
if p == target {
return true;
}
match (canon_target.as_ref(), p.canonicalize().ok()) {
(Some(a), Some(b)) => *a == b,
_ => false,
}
})
}
pub fn preview_index(&self) -> Option<usize> {
self.editors.iter().position(|e| e.preview)
}
pub fn pin_active(&mut self) {
self.editors[self.active].preview = false;
}
pub fn is_preview(&self, idx: usize) -> bool {
self.editors.get(idx).is_some_and(|e| e.preview)
}
pub fn keep_open(&mut self, idx: usize) -> bool {
match self.editors.get_mut(idx) {
Some(e) if e.preview => {
e.preview = false;
true
}
_ => false,
}
}
pub fn is_pinned(&self, idx: usize) -> bool {
self.editors.get(idx).is_some_and(|e| e.pinned)
}
pub fn toggle_pin(&mut self, idx: usize) -> bool {
if idx >= self.editors.len() {
return false;
}
let now_pinned = !self.editors[idx].pinned;
self.editors[idx].pinned = now_pinned;
if now_pinned {
self.editors[idx].preview = false;
}
let n = self.editors.len();
let mut order: Vec<usize> = (0..n).collect();
order.sort_by_key(|&i| !self.editors[i].pinned);
let new_active = order.iter().position(|&i| i == self.active).unwrap_or(0);
let mut slots: Vec<Option<Editor>> = self.editors.drain(..).map(Some).collect();
self.editors = order.iter().map(|&i| slots[i].take().unwrap()).collect();
self.active = new_active;
for (i, ed) in self.editors.iter_mut().enumerate() {
ed.focused = i == self.active;
}
now_pinned
}
pub fn take_active_editor(&mut self) -> Editor {
let ed = self.editors.remove(self.active);
if self.editors.is_empty() {
self.editors.push(Editor::new());
self.active = 0;
} else if self.active >= self.editors.len() {
self.active = self.editors.len() - 1;
}
for (i, e) in self.editors.iter_mut().enumerate() {
e.focused = i == self.active;
}
ed
}
pub fn push_editor(&mut self, mut ed: Editor) {
if self.is_blank_initial() {
ed.focused = true;
self.editors[0] = ed;
self.active = 0;
return;
}
self.editors.push(ed);
self.active = self.editors.len() - 1;
for (i, e) in self.editors.iter_mut().enumerate() {
e.focused = i == self.active;
}
}
pub fn open_preview(&mut self, path: &Path) -> Result<()> {
if let Some(idx) = self.find_tab_with_path(path) {
if let Some(prev) = self.preview_index()
&& prev != idx
{
self.editors.remove(prev);
let new_idx = if idx > prev { idx - 1 } else { idx };
self.active = new_idx;
for (i, ed) in self.editors.iter_mut().enumerate() {
ed.focused = i == new_idx;
}
return Ok(());
}
self.select(idx);
return Ok(());
}
if let Some(idx) = self.preview_index() {
self.select(idx);
self.editors[idx].open(path)?;
self.editors[idx].preview = true;
return Ok(());
}
if self.is_blank_initial() {
let active = self.active;
self.editors[active].open(path)?;
self.editors[active].preview = true;
self.editors[active].search_highlight = self.search_highlight_term.clone();
self.editors[active].search_highlight_opts = self.search_highlight_opts;
return Ok(());
}
let mut e = Editor::new();
e.focused = self.editors[self.active].focused;
e.open(path)?;
e.preview = true;
e.search_highlight = self.search_highlight_term.clone();
e.search_highlight_opts = self.search_highlight_opts;
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
Ok(())
}
pub fn open_diff(&mut self, left: &Path, right: &Path) -> Result<()> {
let left_text =
std::fs::read_to_string(left).with_context(|| format!("reading {}", left.display()))?;
let right_text = std::fs::read_to_string(right)
.with_context(|| format!("reading {}", right.display()))?;
let left_lines: Vec<String> = left_text.lines().map(str::to_string).collect();
let right_lines: Vec<String> = right_text.lines().map(str::to_string).collect();
let mut data = crate::widgets::diff::DiffData::build(
left.to_path_buf(),
right.to_path_buf(),
left_lines,
right_lines,
);
data.left_is_real_file = true;
let mut e = Editor::new();
e.focused = self.editors[self.active].focused;
e.preview = false;
e.path = Some(left.to_path_buf());
e.diff = Some(data);
if self.is_blank_initial() {
self.editors[self.active] = e;
return Ok(());
}
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
Ok(())
}
pub fn open_head_diff_with_text(
&mut self,
left_label: PathBuf,
left_text: &str,
right: &Path,
left_is_git_head: bool,
) -> Result<()> {
let right_text = std::fs::read_to_string(right)
.with_context(|| format!("reading {}", right.display()))?;
let left_lines: Vec<String> = left_text.lines().map(str::to_string).collect();
let right_lines: Vec<String> = right_text.lines().map(str::to_string).collect();
let mut data = crate::widgets::diff::DiffData::build_with_byte_check(
left_label,
right.to_path_buf(),
left_lines,
right_lines,
Some(left_text),
Some(&right_text),
);
if let Some(row) = data.first_change_row() {
data.scroll_to_row(row);
}
data.left_is_git_head = left_is_git_head;
let mut e = Editor::new();
e.focused = self.editors[self.active].focused;
e.preview = false;
e.path = Some(right.to_path_buf());
e.diff = Some(data);
if self.is_blank_initial() {
self.editors[self.active] = e;
return Ok(());
}
if let Some(idx) = self.find_tab_with_path(right)
&& !self.editors[idx].dirty
{
self.editors[idx] = e;
self.select(idx);
return Ok(());
}
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
Ok(())
}
pub fn open_deleted_diff_with_text(&mut self, path: &Path, head_text: &str) -> Result<()> {
let data =
crate::widgets::diff::DiffData::build_unified_deletion(path.to_path_buf(), head_text);
let mut e = Editor::new();
e.focused = self.editors[self.active].focused;
e.preview = false;
e.path = Some(path.to_path_buf());
e.diff = Some(data);
if self.is_blank_initial() {
self.editors[self.active] = e;
return Ok(());
}
if let Some(idx) = self.find_tab_with_path(path)
&& !self.editors[idx].dirty
{
self.editors[idx] = e;
self.select(idx);
return Ok(());
}
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
Ok(())
}
pub fn open_git_diff_side_by_side(&mut self, label: &Path, raw_diff: &str) -> Result<()> {
let data = crate::widgets::diff::DiffData::build_side_by_side_from_git_text(
label.to_path_buf(),
raw_diff,
);
let mut e = Editor::new();
e.focused = self.editors[self.active].focused;
e.preview = false;
e.path = Some(label.to_path_buf());
e.diff = Some(data);
if self.is_blank_initial() {
self.editors[self.active] = e;
return Ok(());
}
if let Some(idx) = self.find_tab_with_path(label) {
self.editors[idx] = e;
self.select(idx);
return Ok(());
}
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
Ok(())
}
pub fn open_text_buffer(&mut self, label: &Path, text: &str) -> Result<()> {
let mut e = Editor::new();
e.focused = self.editors[self.active].focused;
e.preview = false;
e.path = Some(label.to_path_buf());
e.lines = split_into_lines(text);
if e.lines.is_empty() {
e.lines.push(String::new());
}
if self.is_blank_initial() {
self.editors[self.active] = e;
return Ok(());
}
if let Some(idx) = self.find_tab_with_path(label) {
self.editors[idx] = e;
self.select(idx);
return Ok(());
}
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
Ok(())
}
pub fn open_pinned(&mut self, path: &Path) -> Result<()> {
if let Some(idx) = self.find_tab_matching(path, |e| e.diff.is_none()) {
self.editors[idx].preview = false;
self.select(idx);
return Ok(());
}
if self.is_blank_initial() {
let active = self.active;
self.editors[active].open(path)?;
self.editors[active].preview = false;
self.editors[active].search_highlight = self.search_highlight_term.clone();
self.editors[active].search_highlight_opts = self.search_highlight_opts;
return Ok(());
}
let mut e = Editor::new();
e.focused = self.editors[self.active].focused;
e.open(path)?;
e.preview = false;
e.search_highlight = self.search_highlight_term.clone();
e.search_highlight_opts = self.search_highlight_opts;
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
Ok(())
}
pub fn is_blank_initial(&self) -> bool {
self.editors.len() == 1
&& self.editors[0].path.is_none()
&& !self.editors[0].dirty
&& self.editors[0].lines.iter().all(|l| l.is_empty())
}
pub fn add_preview_tab_with_path(&mut self, path: PathBuf) {
let mut e = Editor::new();
e.path = Some(path);
e.preview = true;
e.focused = self.editors[self.active].focused;
let pos = self.active + 1;
self.editors.insert(pos, e);
self.editors[self.active].focused = false;
self.active = pos;
}
pub fn repoint_preview_to(&mut self, path: PathBuf) {
if let Some(idx) = self.preview_index() {
self.editors[idx].path = Some(path);
}
}
}
impl Default for EditorTabs {
fn default() -> Self {
Self::new()
}
}
impl Deref for EditorTabs {
type Target = Editor;
fn deref(&self) -> &Editor {
&self.editors[self.active]
}
}
impl DerefMut for EditorTabs {
fn deref_mut(&mut self) -> &mut Editor {
&mut self.editors[self.active]
}
}
const TAB_INACTIVE_FG: Color = Color::Rgb(0x9d, 0xa5, 0xb4);
const TAB_ACTIVE_FG: Color = Color::White;
impl Widget for &mut EditorTabs {
fn render(self, area: Rect, buf: &mut Buffer) {
self.last_full_area = area;
if area.height == 0 || area.width == 0 {
for ed in self.editors.iter_mut() {
ed.last_area = Rect {
x: area.x,
y: area.y,
width: area.width,
height: 0,
};
ed.last_inner = ed.last_area;
ed.last_scrollbar = Rect::default();
}
return;
}
let strip_h: u16 = 1;
let strip = Rect {
x: area.x,
y: area.y,
width: area.width,
height: strip_h,
};
let mut body = Rect {
x: area.x,
y: area.y + strip_h,
width: area.width,
height: area.height - strip_h,
};
let theme = self
.editors
.iter()
.map(|e| e.theme)
.find(|t| *t != crate::theme::Theme::default())
.unwrap_or_default();
let strip_bg_style = Style::default().bg(theme.tab_strip_bg());
for x in strip.x..strip.x + strip.width {
buf[(x, strip.y)].set_style(strip_bg_style);
buf[(x, strip.y)].set_symbol(" ");
}
self.tab_strip_y = strip.y;
self.tab_screen_ranges.clear();
self.tab_close_x.clear();
let mut cursor_x = strip.x;
let active = self.active;
let brand = self.editors.iter().any(|e| e.focus_gradient);
if brand {
for ed in self.editors.iter_mut() {
ed.focus_gradient = true;
}
}
let active_tab_bg = theme.tab_active_bg();
let pointer = self.hover_pointer;
let display_labels = disambiguated_tab_labels(&self.editors);
for (i, ed) in self.editors.iter().enumerate() {
let label_text = display_labels[i].clone();
let label_chars = Span::raw(label_text.as_str()).width() as u16;
let pad: u16 = 1;
let close_pad: u16 = 2;
let width = label_chars
.saturating_add(pad * 2)
.saturating_add(close_pad);
if cursor_x.saturating_add(width) > strip.x + strip.width {
self.tab_screen_ranges.push((cursor_x, 0));
self.tab_close_x.push(0);
continue;
}
let is_active = i == active;
let close_x = cursor_x + 1 + label_chars + 1;
let tab_hovered = pointer.is_some_and(|(px, py)| {
py == strip.y && px >= cursor_x && px < cursor_x.saturating_add(width)
});
let on_close = pointer == Some((close_x, strip.y));
let hover_lift = tab_hovered && !is_active;
let bg = if hover_lift {
theme.tab_hover_bg()
} else if is_active {
active_tab_bg
} else {
theme.tab_inactive_bg()
};
let fg = if is_active || hover_lift {
TAB_ACTIVE_FG
} else {
TAB_INACTIVE_FG
};
let mut modifiers = Modifier::empty();
if is_active {
modifiers |= Modifier::BOLD;
}
if ed.preview {
modifiers |= Modifier::ITALIC;
}
let style = Style::default().fg(fg).bg(bg).add_modifier(modifiers);
let close_glyph = if ed.pinned { "\u{f08d}" } else { "\u{2715}" };
let padded = format!(" {label_text} {close_glyph} ");
buf.set_string(cursor_x, strip.y, &padded, style);
if on_close {
let pill_bg = theme.tab_close_pill_bg();
buf.set_string(
close_x,
strip.y,
close_glyph,
Style::default()
.fg(Color::White)
.bg(pill_bg)
.add_modifier(Modifier::BOLD),
);
}
self.tab_screen_ranges.push((cursor_x, width));
self.tab_close_x.push(close_x);
cursor_x = cursor_x.saturating_add(width);
}
self.breadcrumb_ranges.clear();
self.breadcrumb_y = None;
if !self.breadcrumbs.is_empty() && body.height > 1 {
let crumb_y = body.y;
self.breadcrumb_y = Some(crumb_y);
let theme = self.editors[active].theme;
let bg = theme.editor_bg();
for x in area.x..area.x + area.width {
buf[(x, crumb_y)].set_symbol(" ");
buf[(x, crumb_y)].set_style(Style::default().bg(bg));
}
let max_x = area.x + area.width;
let mut x = area.x + 1;
for (i, crumb) in self.breadcrumbs.iter().enumerate() {
if i > 0 {
let sep = " \u{203A} "; let sw = sep.chars().count() as u16;
if x + sw >= max_x {
break;
}
buf.set_string(x, crumb_y, sep, Style::default().fg(Color::DarkGray).bg(bg));
x += sw;
}
if x >= max_x {
break;
}
let avail = (max_x - x) as usize;
let fg = if crumb.target.is_some() {
Color::Gray
} else {
Color::DarkGray
};
let (end_x, _) = buf.set_stringn(
x,
crumb_y,
&crumb.label,
avail,
Style::default().fg(fg).bg(bg),
);
let sw = end_x.saturating_sub(x);
self.breadcrumb_ranges.push((x, sw, crumb.target));
x = end_x;
}
body = Rect {
y: body.y + 1,
height: body.height - 1,
..body
};
}
let active_editor = &mut self.editors[active];
Widget::render(active_editor, body, buf);
}
}
impl EditorTabs {
pub fn breadcrumb_target_at(&self, col: u16, row: u16) -> Option<(u32, u32)> {
if self.breadcrumb_y != Some(row) {
return None;
}
self.breadcrumb_ranges
.iter()
.find(|&&(x, w, _)| col >= x && col < x + w)
.and_then(|&(_, _, target)| target)
}
}
pub(crate) fn disambiguated_tab_labels(editors: &[Editor]) -> Vec<String> {
let base: Vec<String> = editors.iter().map(tab_label).collect();
let mut out = base.clone();
let mut groups: std::collections::HashMap<String, Vec<usize>> =
std::collections::HashMap::new();
for (i, e) in editors.iter().enumerate() {
if e.diff.is_none()
&& let Some(name) = e.path.as_deref().and_then(|p| p.file_name())
{
groups
.entry(name.to_string_lossy().into_owned())
.or_default()
.push(i);
}
}
for idxs in groups.into_values() {
if idxs.len() < 2 {
continue;
}
let max_depth = idxs
.iter()
.filter_map(|&i| editors[i].path.as_deref())
.filter_map(|p| p.parent())
.map(|p| p.components().count())
.max()
.unwrap_or(1)
.max(1);
for depth in 1..=max_depth {
let sufs: Vec<String> = idxs
.iter()
.map(|&i| {
dir_suffix(
editors[i]
.path
.as_deref()
.unwrap_or(std::path::Path::new("")),
depth,
)
})
.collect();
let mut seen = std::collections::HashSet::new();
let all_unique = sufs.iter().all(|s| seen.insert(s.clone()));
if all_unique || depth == max_depth {
for (k, &i) in idxs.iter().enumerate() {
if !sufs[k].is_empty() {
out[i] = format!("{} — {}", base[i], sufs[k]);
}
}
break;
}
}
}
out
}
fn dir_suffix(path: &std::path::Path, depth: usize) -> String {
let Some(parent) = path.parent() else {
return String::new();
};
let comps: Vec<String> = parent
.components()
.rev()
.take(depth)
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
comps.into_iter().rev().collect::<Vec<_>>().join("/")
}
fn tab_label(e: &Editor) -> String {
if let Some(diff) = e.diff.as_ref() {
let l = diff
.left_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| diff.left_path.to_string_lossy().into_owned());
let r_is_real = diff.right_path != std::path::Path::new("/dev/null")
&& !diff.right_path.as_os_str().is_empty();
if r_is_real {
let r = diff
.right_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| diff.right_path.to_string_lossy().into_owned());
return format!("{l} \u{2194} {r}");
}
return l;
}
let name = match &e.path {
Some(p) => p
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| String::from("untitled")),
None => String::from("untitled"),
};
if e.dirty {
format!("\u{25cf} {name}")
} else {
name
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;
fn blame_line(
author: &str,
summary: &str,
age: i64,
uncommitted: bool,
) -> crate::git::BlameLine {
crate::git::BlameLine {
short_hash: "abc12345".into(),
summary: summary.into(),
author: author.into(),
age_secs: age,
uncommitted,
}
}
#[test]
fn snippet_expansion_places_caret_and_tab_advances_with_drift() {
let mut e = editor_with("");
e.insert_str("for");
e.expand_snippet("for ${1:i} in ${2:xs}:", 3);
assert_eq!(e.lines[0], "for i in xs:");
assert_eq!((e.cursor_row, e.cursor_col), (0, 5));
assert!(e.snippet_active());
assert_eq!(e.selection_text(), "i");
e.insert_str("idx");
assert_eq!(e.lines[0], "for idx in xs:");
assert!(e.snippet_next());
assert_eq!(
e.selection_text(),
"xs",
"$2 must track the drift from the longer $1"
);
assert!(!e.snippet_active());
}
#[test]
fn a_failed_revert_keeps_the_buffer_dirty() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("gone.txt");
std::fs::write(&path, "disk\n").unwrap();
let mut e = Editor::new();
e.open(&path).unwrap();
e.insert_char('x');
assert!(e.dirty, "staging: unsaved edits");
std::fs::remove_file(&path).unwrap();
assert!(e.revert_to_disk().is_err(), "staging: the reload fails");
assert!(
e.dirty,
"a failed reload must keep the unsaved edits marked dirty"
);
}
#[test]
fn a_snippet_stop_on_a_deleted_row_cannot_plant_a_selection_out_of_bounds() {
let mut e = editor_with("");
e.insert_str("try");
e.expand_snippet(
"try:\n ${1:pass}\nexcept ${2:Exception}:\n ${3:raise}",
3,
);
assert!(e.snippet_active());
assert_eq!(e.selection_text(), "pass");
for _ in 0..6 {
e.backspace();
}
assert!(e.lines.len() < 4, "staging: a row was joined away");
e.snippet_next();
e.snippet_next();
e.insert_char('x');
}
#[test]
fn open_resets_collab_attachment_only_on_a_path_change() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
let b = tmp.path().join("b.txt");
std::fs::write(&a, "aaa").unwrap();
std::fs::write(&b, "bbb").unwrap();
let mut e = Editor::new();
e.open(&a).unwrap();
e.collab_doc_gen = 7;
e.collab_synced_seq = 3;
e.open(&b).unwrap();
assert_eq!(
e.collab_doc_gen, 0,
"opening another path must detach the buffer from the old doc"
);
assert_eq!(
e.collab_synced_seq, e.edit_seq,
"a fresh open has nothing pending to extract"
);
e.collab_doc_gen = 7;
e.open(&b).unwrap();
assert_eq!(
e.collab_doc_gen, 7,
"a same-path reload must keep its attachment so the reload broadcasts as edits"
);
}
#[test]
fn snippet_indents_continuation_lines_to_the_caret() {
let mut e = editor_with(" ");
e.cursor_row = 0;
e.cursor_col = 4;
e.expand_snippet("if x:\n $0", 0);
assert_eq!(e.lines[0], " if x:");
assert_eq!(
e.lines[1], " ",
"continuation line keeps the 4-space block indent plus its own"
);
}
#[test]
fn current_line_blame_annotation_reads_author_age_and_summary() {
let mut e = editor_with("one\ntwo\n");
e.path = Some(PathBuf::from("f.rs"));
e.set_blame(
PathBuf::from("f.rs"),
Some(vec![
blame_line("Vitali", "fix: the thing", 90, false),
blame_line("Alice", "feat: two", 7200, false),
]),
);
e.cursor_row = 0;
assert_eq!(
e.current_line_blame_annotation().as_deref(),
Some("Vitali, 1 minute ago • fix: the thing")
);
e.cursor_row = 1;
assert_eq!(
e.current_line_blame_annotation().as_deref(),
Some("Alice, 2 hours ago • feat: two")
);
}
#[test]
fn current_line_blame_annotation_marks_uncommitted_lines() {
let mut e = editor_with("edited\n");
e.path = Some(PathBuf::from("f.rs"));
e.set_blame(
PathBuf::from("f.rs"),
Some(vec![blame_line("Not Committed Yet", "x", 0, true)]),
);
e.cursor_row = 0;
assert_eq!(
e.current_line_blame_annotation().as_deref(),
Some("Uncommitted changes")
);
}
#[test]
fn current_line_blame_annotation_is_none_when_disabled_or_unavailable() {
let mut e = editor_with("one\n");
e.path = Some(PathBuf::from("f.rs"));
assert!(e.current_line_blame_annotation().is_none());
e.set_blame(
PathBuf::from("f.rs"),
Some(vec![blame_line("V", "s", 5, false)]),
);
e.blame_enabled = false;
assert!(
e.current_line_blame_annotation().is_none(),
"the toggle suppresses the annotation without dropping the data"
);
e.blame_enabled = true;
e.cursor_row = 9;
assert!(e.current_line_blame_annotation().is_none());
}
#[test]
fn blame_for_another_file_never_paints_on_this_one() {
let mut e = editor_with("one\ntwo\n");
e.path = Some(PathBuf::from("a.rs"));
e.set_blame(
PathBuf::from("a.rs"),
Some(vec![
blame_line("Alice", "s", 5, false),
blame_line("Alice", "s", 5, false),
]),
);
e.path = Some(PathBuf::from("b.rs"));
assert!(
e.current_line_blame_annotation().is_none(),
"a.rs blame painted on b.rs while its own fetch was still in flight"
);
}
#[test]
fn opening_a_real_file_clears_a_stale_diff_view() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
std::fs::write(&path, "disk\n").unwrap();
let mut e = Editor::new();
e.diff = Some(crate::widgets::diff::DiffData::build_unified_deletion(
path.clone(),
"old\n",
));
e.open(&path).unwrap();
assert!(
e.diff.is_none(),
"the stale diff kept rendering over the freshly opened file"
);
}
#[test]
fn a_head_diff_never_replaces_a_dirty_tab_in_place() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
std::fs::write(&path, "disk\n").unwrap();
let mut tabs = EditorTabs::new();
tabs.open(&path).unwrap();
tabs.lines[0].push('x');
tabs.dirty = true;
tabs.open_head_diff_with_text(
PathBuf::from("a.txt (local snapshot)"),
"old\n",
&path,
false,
)
.unwrap();
assert!(
tabs.editors
.iter()
.any(|e| e.dirty && e.diff.is_none() && e.lines[0] == "diskx"),
"the dirty buffer was destroyed by the snapshot diff"
);
assert!(
tabs.editors.iter().any(|e| e.diff.is_some()),
"staging: the diff itself still opened in some tab"
);
}
#[test]
fn disabling_the_csv_viewer_opens_the_file_as_plain_text() {
let f = tempfile::Builder::new()
.suffix(".csv")
.tempfile()
.expect("temp csv");
std::fs::write(f.path(), "a,b\n1,2\n").expect("write csv");
let mut on = Editor::new();
on.open(f.path()).expect("open with viewer enabled");
assert!(on.sheet.is_some(), "enabled CSV viewer renders the sheet");
let mut off = Editor::new();
off.csv_viewer_enabled = false;
off.open(f.path()).expect("open with viewer disabled");
assert!(
off.sheet.is_none(),
"disabled CSV viewer must not build a sheet"
);
assert_eq!(
off.lines,
vec!["a,b".to_string(), "1,2".to_string()],
"disabled CSV viewer opens the raw rows as text lines"
);
}
#[test]
fn toggle_breakpoint_adds_then_removes_on_cursor_line() {
let mut e = Editor::new();
e.path = Some(PathBuf::from("/x/a.py"));
e.lines = vec!["a".into(), "b".into(), "c".into()];
e.cursor_row = 1; assert_eq!(
e.toggle_breakpoint(),
Some((PathBuf::from("/x/a.py"), 2, true))
);
assert_eq!(e.breakpoint_lines(Path::new("/x/a.py")), vec![2u32]);
assert_eq!(
e.toggle_breakpoint(),
Some((PathBuf::from("/x/a.py"), 2, false))
);
assert!(e.breakpoint_lines(Path::new("/x/a.py")).is_empty());
}
#[test]
fn toggle_breakpoint_without_open_file_is_noop() {
let mut e = Editor::new();
assert_eq!(e.toggle_breakpoint(), None);
}
#[test]
fn removing_a_breakpoint_discards_its_logpoint_and_condition() {
let path = PathBuf::from("/x/a.py");
let mut e = Editor::new();
e.path = Some(path.clone());
e.lines = vec!["a".into(), "b".into(), "c".into()];
e.toggle_breakpoint_line(2);
e.breakpoint_logs
.entry(path.clone())
.or_default()
.insert(2, String::from("x is {x}"));
e.breakpoint_conditions
.entry(path.clone())
.or_default()
.insert(2, String::from("x > 1"));
e.toggle_breakpoint_line(2); e.toggle_breakpoint_line(2); let lines = e.breakpoints.get(&path).cloned().unwrap();
let specs = e.source_breakpoints(&path, &lines);
assert_eq!(specs.len(), 1);
assert_eq!(
specs[0].log_message, None,
"a re-added breakpoint must pause, not print"
);
assert_eq!(
specs[0].condition, None,
"a re-added breakpoint must be unconditional"
);
}
#[test]
fn toggle_breakpoint_line_targets_an_explicit_line_not_the_cursor() {
let mut e = Editor::new();
e.path = Some(PathBuf::from("/x/a.py"));
e.lines = vec!["a".into(), "b".into(), "c".into()];
e.cursor_row = 0; assert_eq!(
e.toggle_breakpoint_line(3),
Some((PathBuf::from("/x/a.py"), 3, true))
);
assert_eq!(e.breakpoint_lines(Path::new("/x/a.py")), vec![3u32]);
assert_eq!(e.cursor_row, 0);
assert_eq!(
e.toggle_breakpoint_line(3),
Some((PathBuf::from("/x/a.py"), 3, false))
);
assert!(e.breakpoint_lines(Path::new("/x/a.py")).is_empty());
}
#[test]
fn gutter_line_at_maps_gutter_clicks_and_ignores_the_body() {
let mut e = editor_with("a\nbb\nccc\ndddd\neeeee");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2; assert_eq!(e.gutter_line_at(0, 0), Some(0), "col 0 is the glyph margin");
assert_eq!(e.gutter_line_at(2, 2), Some(2), "col 2 is the line number");
assert_eq!(e.gutter_line_at(3, 0), None, "col 3 is the text body");
assert_eq!(e.gutter_line_at(10, 1), None, "deep in the body");
assert_eq!(e.gutter_line_at(0, 20), None, "row past content");
}
#[test]
fn gutter_line_at_follows_vertical_scroll() {
let mut e = editor_with("a\nbb\nccc\ndddd\neeeee");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
e.scroll = 2;
assert_eq!(
e.gutter_line_at(1, 0),
Some(2),
"the top visible gutter row is buffer line scroll = 2"
);
}
#[test]
fn breakpoint_glyph_sits_in_left_margin_not_over_the_line_number() {
let f = NamedTempFile::new().unwrap();
std::fs::write(f.path(), "aaa\nbbb\nccc\n").unwrap();
let mut ed = Editor::new();
ed.open(f.path()).unwrap();
ed.breakpoints
.entry(f.path().to_path_buf())
.or_default()
.insert(2); let area = Rect {
x: 0,
y: 0,
width: 30,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
let inner_x = ed.last_inner.x;
let gutter = ed.last_gutter_width;
let row = ed.last_inner.y + 1; let mut line = String::new();
for x in 0..area.width {
line.push_str(buf[(x, row)].symbol());
}
assert_eq!(
buf[(inner_x, row)].symbol(),
"●",
"breakpoint dot must be in the left glyph margin; row was {line:?}"
);
assert_eq!(
buf[(inner_x + gutter - 2, row)].symbol(),
"2",
"line number must survive after the margin; row was {line:?}"
);
assert_eq!(
buf[(inner_x + 1, row)].symbol(),
" ",
"a space separates the dot from the line number; row was {line:?}"
);
}
#[test]
fn source_breakpoints_attach_conditions() {
let mut e = Editor::new();
let p = PathBuf::from("/x/a.py");
let mut lines = std::collections::BTreeSet::new();
lines.insert(3usize);
lines.insert(5usize);
e.breakpoint_conditions
.entry(p.clone())
.or_default()
.insert(5, String::from("i == 10"));
let specs = e.source_breakpoints(&p, &lines);
assert_eq!(specs.len(), 2);
assert_eq!(specs[0].line, 3);
assert_eq!(specs[0].condition, None);
assert_eq!(specs[1].line, 5);
assert_eq!(specs[1].condition.as_deref(), Some("i == 10"));
}
#[test]
fn source_breakpoints_attach_log_messages() {
let mut e = Editor::new();
let p = PathBuf::from("/x/a.py");
let mut lines = std::collections::BTreeSet::new();
lines.insert(3usize);
lines.insert(5usize);
e.breakpoint_logs
.entry(p.clone())
.or_default()
.insert(5, String::from("value is {v}"));
let specs = e.source_breakpoints(&p, &lines);
assert_eq!(specs[0].log_message, None);
assert_eq!(specs[1].log_message.as_deref(), Some("value is {v}"));
}
#[test]
fn logpoint_wears_an_amber_diamond_in_the_gutter() {
let mut e = editor_with("a\nb\nc");
let p = PathBuf::from("/x/lp.py");
e.path = Some(p.clone());
e.breakpoints.entry(p.clone()).or_default().insert(2);
e.breakpoint_logs
.entry(p)
.or_default()
.insert(2, String::from("hit {x}"));
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let cell = &buf[(e.last_inner.x, e.last_inner.y + 1)];
assert_eq!(
cell.symbol(),
"◆",
"a logpoint paints the diamond in the glyph margin"
);
assert_eq!(
cell.fg,
Color::Rgb(0xe5, 0xc0, 0x7b),
"the logpoint diamond is amber, distinct from the conditional's red"
);
}
#[test]
fn word_string_at_reads_identifier_under_cursor() {
let mut e = Editor::new();
e.lines = vec![" total = count + 1".into()];
assert_eq!(e.word_string_at(0, 6).as_deref(), Some("total"));
assert_eq!(e.word_string_at(0, 13).as_deref(), Some("count"));
assert_eq!(e.word_string_at(0, 10), None);
}
fn editor_with(text: &str) -> Editor {
let mut e = Editor::new();
e.lines = if text.is_empty() {
vec![String::new()]
} else {
text.lines().map(|s| s.to_string()).collect()
};
if e.lines.is_empty() {
e.lines.push(String::new());
}
e
}
fn head(lines: &[&str]) -> Option<Vec<String>> {
Some(lines.iter().map(|s| s.to_string()).collect())
}
#[test]
fn git_gutter_marks_added_modified_and_deleted_lines() {
let mut e = editor_with("a\nB2\nINSERTED\nc");
e.set_git_head_lines(PathBuf::from("f.rs"), head(&["a", "b", "c", "d"]));
e.refresh_git_marks();
assert_eq!(e.git_mark_at(0), None, "unchanged line carries no mark");
assert_eq!(e.git_mark_at(1), Some(GitMark::Modified));
assert_eq!(e.git_mark_at(2), Some(GitMark::Added));
assert_eq!(e.git_mark_at(3), Some(GitMark::Deleted));
}
#[test]
fn git_gutter_no_baseline_means_no_marks() {
let mut e = editor_with("a\nb\nc");
e.refresh_git_marks();
assert_eq!(e.git_mark_at(0), None);
assert_eq!(e.git_mark_at(1), None);
}
#[test]
fn git_gutter_recomputes_after_an_edit() {
let mut e = editor_with("a\nb");
e.set_git_head_lines(PathBuf::from("f.rs"), head(&["a", "b"]));
e.refresh_git_marks();
assert_eq!(e.git_mark_at(1), None, "buffer matches HEAD: clean");
e.cursor_row = 1;
e.cursor_col = 1;
e.insert_char('X');
e.refresh_git_marks();
assert_eq!(e.git_mark_at(1), Some(GitMark::Modified));
}
#[test]
fn git_gutter_render_paints_bar_in_the_spacer_cell() {
use ratatui::buffer::Buffer;
let mut e = editor_with("a\nb");
e.set_git_head_lines(PathBuf::from("f.rs"), head(&["a", "DIFFERENT"]));
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 5,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let bar_x = e.last_inner.x + e.last_gutter_width;
let cell = &buf[(bar_x, e.last_inner.y + 1)];
assert_eq!(
cell.symbol(),
"\u{2503}",
"modified line shows a gutter bar"
);
}
#[test]
fn save_on_a_preview_tab_never_touches_the_file() {
let tmp = tempfile::tempdir().unwrap();
let png = tmp.path().join("pic.png");
image::RgbaImage::new(2, 2).save(&png).unwrap();
let png_bytes = std::fs::read(&png).unwrap();
let mut e = Editor::new();
e.open(&png).unwrap();
assert!(e.image.is_some());
assert!(e.save_to_disk().is_err(), "image tab save must refuse");
assert!(e.save_to_disk_force().is_err(), "force save too");
assert_eq!(std::fs::read(&png).unwrap(), png_bytes, "file intact");
let bin = tmp.path().join("blob.bin");
std::fs::write(&bin, b"\x00\x01\x02\x03").unwrap();
let mut e = Editor::new();
e.open(&bin).unwrap();
assert!(e.hex.is_some());
assert!(e.save_to_disk().is_err(), "hex tab save must refuse");
assert_eq!(std::fs::read(&bin).unwrap(), b"\x00\x01\x02\x03");
let csv = tmp.path().join("t.csv");
std::fs::write(&csv, "a,b\n1,2\n").unwrap();
let mut e = Editor::new();
e.open(&csv).unwrap();
assert!(e.sheet.is_some());
assert!(e.save_to_disk().is_err(), "sheet tab save must refuse");
assert_eq!(std::fs::read(&csv).unwrap(), b"a,b\n1,2\n");
}
#[test]
fn is_binary_detects_nul() {
assert!(is_binary(b"hello\0world"));
assert!(!is_binary(b"hello world"));
assert!(!is_binary(b""));
}
#[test]
fn binary_file_opens_in_the_hex_viewer_instead_of_erroring() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("blob.bin");
std::fs::write(&p, b"\x00\x01\x02payload\xff\xfe").unwrap();
let mut e = Editor::new();
e.open(&p).unwrap();
assert!(e.hex.is_some(), "binary files land in the hex viewer");
assert_eq!(
e.lines,
vec![String::new()],
"the whole-buffer-swap convention: one empty line, like image/sheet tabs"
);
assert_eq!(e.path.as_deref(), Some(p.as_path()));
assert!(!e.dirty, "hex tabs are read-only");
}
#[test]
fn oversized_binary_opens_in_hex_but_oversized_text_still_errors() {
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("huge.bin");
let f = std::fs::File::create(&bin).unwrap();
f.set_len(MAX_FILE_BYTES + 5).unwrap(); drop(f);
let mut e = Editor::new();
e.open(&bin).unwrap();
assert!(e.hex.is_some(), "an over-limit binary opens in hex");
let txt = tmp.path().join("huge.log");
let f = std::fs::File::create(&txt).unwrap();
use std::io::Write as _;
let mut w = std::io::BufWriter::new(f);
w.write_all(&vec![b'a'; 8192]).unwrap();
drop(w);
std::fs::OpenOptions::new()
.append(true)
.open(&txt)
.unwrap()
.set_len(MAX_FILE_BYTES + 5)
.unwrap();
let mut e2 = Editor::new();
let err = e2.open(&txt).unwrap_err().to_string();
assert!(
err.contains("too large"),
"text keeps the size guard: {err}"
);
}
#[test]
fn hex_tab_renders_offsets_hex_bytes_ascii_and_status() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("blob.bin");
let mut data = b"MZ\x90\x00".to_vec();
data.extend_from_slice(b"Hello!\x00\xde\xad\xbe\xef");
std::fs::write(&p, &data).unwrap();
let mut ed = Editor::new();
ed.open(&p).unwrap();
assert!(ed.hex.is_some());
let area = Rect {
x: 0,
y: 0,
width: 92,
height: 12,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
let mut rows = Vec::new();
for y in 0..area.height {
let mut line = String::new();
for x in 0..area.width {
line.push_str(buf[(x, y)].symbol());
}
rows.push(line);
}
let all = rows.join("\n");
assert!(all.contains("blob.bin"), "header names the file: {all}");
assert!(all.contains("00000000"), "offset column paints: {all}");
assert!(
all.contains("4D 5A 90 00"),
"hex bytes paint uppercase: {all}"
);
assert!(
all.contains("MZ·"),
"ascii gutter: printables verbatim, non-printables as ·: {all}"
);
assert!(
all.contains("0x00000000"),
"status row shows the cursor offset: {all}"
);
let view = ed.hex.as_ref().unwrap();
assert_eq!(view.bytes_per_row, 16, "a 92-col pane fits 16 bytes/row");
assert!(
view.layout.data_rows > 0,
"layout written back for mouse hit-testing"
);
}
#[test]
fn hex_mouse_hit_test_round_trips_through_the_painted_layout() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("blob.bin");
std::fs::write(&p, (0u8..60).collect::<Vec<_>>()).unwrap();
let mut ed = Editor::new();
ed.open(&p).unwrap();
let area = Rect {
x: 0,
y: 0,
width: 92,
height: 12,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
let view = ed.hex.as_ref().unwrap();
let l = view.layout;
let y = l.data_top + 1;
assert_eq!(view.hit_test(l.hex_x + 3 * 3, y), Some(19), "hex cell");
assert_eq!(view.hit_test(l.ascii_x + 3, y), Some(19), "ascii cell");
assert_eq!(
view.hit_test(l.hex_x + 10 * 3 + 1, y),
Some(26),
"post-gap hex cell accounts for the group divider"
);
let last_row_y = l.data_top + 3;
assert_eq!(
view.hit_test(l.ascii_x + 15, last_row_y),
None,
"past EOF misses"
);
assert_eq!(view.hit_test(area.x + 1, y), None, "offset gutter misses");
assert_eq!(
view.hit_test(l.hex_x, l.data_top - 1),
None,
"header misses"
);
}
fn write_minimal_xlsx(p: &Path) {
use std::io::Write as _;
let f = std::fs::File::create(p).unwrap();
let mut z = zip::ZipWriter::new(f);
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored);
let parts: &[(&str, &str)] = &[
(
"[Content_Types].xml",
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
</Types>"#,
),
(
"_rels/.rels",
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
</Relationships>"#,
),
(
"xl/workbook.xml",
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets><sheet name="Data" sheetId="1" r:id="rId1"/></sheets>
</workbook>"#,
),
(
"xl/_rels/workbook.xml.rels",
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
</Relationships>"#,
),
(
"xl/worksheets/sheet1.xml",
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>hello</t></is></c><c r="B1"><v>42</v></c></row></sheetData>
</worksheet>"#,
),
];
for (name, body) in parts {
z.start_file(*name, opts).unwrap();
z.write_all(body.as_bytes()).unwrap();
}
z.finish().unwrap();
}
#[test]
fn svg_opens_as_a_rendered_preview_and_reopen_as_text_edits_the_source() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("logo.svg");
std::fs::write(
&p,
r##"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50">
<rect width="100" height="50" fill="#3366ff"/></svg>"##,
)
.unwrap();
let mut e = Editor::new();
e.open(&p).unwrap();
let img = e.image.as_ref().expect("svg opens rendered");
assert_eq!(img.format_label, "SVG");
assert!(img.pixel_w > 0 && img.pixel_h > 0);
assert!(
image::load_from_memory(&img.bytes).is_ok(),
"the overlay pipeline gets a decodable raster"
);
e.force_text = true;
e.open(&p).unwrap();
assert!(e.image.is_none());
assert!(e.lines[0].contains("<svg"), "editing the source");
e.open(&p).unwrap();
assert!(
e.image.is_none(),
"the override survives a same-path reload (FS sync)"
);
e.force_text = false;
e.open(&p).unwrap();
assert!(
e.image.is_some(),
"clearing the override restores the render"
);
e.force_text = true;
e.open(&p).unwrap();
let q = tmp.path().join("other.svg");
std::fs::copy(&p, &q).unwrap();
e.open(&q).unwrap();
assert!(e.image.is_some(), "a path change resets force_text");
}
#[test]
fn broken_svg_falls_through_to_the_text_editor() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("broken.svg");
std::fs::write(&p, "this is not xml").unwrap();
let mut e = Editor::new();
e.open(&p).unwrap();
assert!(e.image.is_none());
assert_eq!(e.lines, vec!["this is not xml".to_string()]);
}
#[test]
fn extensionless_png_routes_to_the_image_preview_by_content() {
let tmp = tempfile::tempdir().unwrap();
let png = tmp.path().join("pic.png");
image::RgbaImage::new(2, 2).save(&png).unwrap();
let bare = tmp.path().join("logo");
std::fs::copy(&png, &bare).unwrap();
let mut e = Editor::new();
e.open(&bare).unwrap();
assert!(
e.image.is_some(),
"content routing must recognise the PNG without an extension"
);
assert!(e.hex.is_none());
}
#[test]
fn misnamed_image_extension_falls_through_to_the_real_content() {
let tmp = tempfile::tempdir().unwrap();
let fake = tmp.path().join("notes.png");
std::fs::write(&fake, "just words\n").unwrap();
let mut e = Editor::new();
e.open(&fake).unwrap();
assert!(e.image.is_none());
assert_eq!(e.lines, vec!["just words".to_string()]);
let junk = tmp.path().join("junk.png");
std::fs::write(&junk, b"\x00\x01\x02\x03garbage").unwrap();
let mut e = Editor::new();
e.open(&junk).unwrap();
assert!(e.hex.is_some(), "misnamed binary lands in hex");
}
#[test]
fn extensionless_workbook_routes_to_the_sheet_viewer_by_content() {
let tmp = tempfile::tempdir().unwrap();
let bare = tmp.path().join("report");
write_minimal_xlsx(&bare);
let mut e = Editor::new();
e.open(&bare).unwrap();
let sheet = e
.sheet
.as_ref()
.expect("zip content routed to the sheet viewer");
assert_eq!(sheet.kind, crate::sheet::SheetKind::Xlsx);
let data = &sheet.sheets[0];
let all: String = data
.headers
.iter()
.chain(data.rows.iter().flatten())
.cloned()
.collect::<Vec<_>>()
.join(",");
assert!(all.contains("hello") && all.contains("42"), "cells: {all}");
}
#[test]
fn oversized_csv_keeps_its_size_refusal_instead_of_silently_opening() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("big.csv");
let f = std::fs::File::create(&p).unwrap();
f.set_len(26 * 1024 * 1024).unwrap(); drop(f);
let mut e = Editor::new();
let err = e.open(&p).unwrap_err().to_string();
assert!(
err.contains("too large"),
"size refusal must surface: {err}"
);
assert!(e.sheet.is_none() && e.hex.is_none());
}
#[test]
fn workbook_misnamed_as_csv_still_reaches_the_sheet_viewer() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("data.csv");
write_minimal_xlsx(&p);
let mut e = Editor::new();
e.open(&p).unwrap();
let sheet = e.sheet.as_ref().expect("zip content retried as xlsx");
assert_eq!(sheet.kind, crate::sheet::SheetKind::Xlsx);
}
#[test]
fn extensionless_pdf_and_plain_zip_never_dead_end() {
let tmp = tempfile::tempdir().unwrap();
let pdf = tmp.path().join("doc");
std::fs::write(
&pdf,
b"%PDF-1.4\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF\n\x00",
)
.unwrap();
let mut e = Editor::new();
e.open(&pdf).unwrap();
assert!(
e.image.as_ref().is_some_and(|i| i.pdf.is_some()) || e.hex.is_some(),
"a sniffed PDF opens in the reader or falls to hex, never errors"
);
let plain = tmp.path().join("bundle");
let f = std::fs::File::create(&plain).unwrap();
let mut z = zip::ZipWriter::new(f);
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored);
use std::io::Write as _;
z.start_file("readme.txt", opts).unwrap();
z.write_all(b"inside").unwrap();
z.finish().unwrap();
let mut e = Editor::new();
e.open(&plain).unwrap();
assert!(e.hex.is_some(), "non-workbook zip lands in hex");
assert!(e.sheet.is_none());
}
#[test]
fn preview_openers_supersede_a_diff_view_and_its_arrow_rects() {
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("blob.bin");
std::fs::write(&bin, b"\x00\x01\x02").unwrap();
let mut e = Editor::new();
e.diff = Some(crate::widgets::diff::DiffData::build(
std::path::PathBuf::from("left.txt"),
std::path::PathBuf::from("right.txt"),
vec![String::from("a")],
vec![String::from("b")],
));
e.diff_prev_arrow = Rect {
x: 1,
y: 1,
width: 3,
height: 1,
};
e.diff_next_arrow = e.diff_prev_arrow;
e.open(&bin).unwrap();
assert!(e.hex.is_some());
assert!(e.diff.is_none(), "the diff view is superseded");
assert_eq!(e.diff_prev_arrow, Rect::default(), "stale hit rect cleared");
assert_eq!(e.diff_next_arrow, Rect::default());
let png = tmp.path().join("pic.png");
image::RgbaImage::new(2, 2).save(&png).unwrap();
let mut e = Editor::new();
e.diff = Some(crate::widgets::diff::DiffData::build(
std::path::PathBuf::from("left.txt"),
std::path::PathBuf::from("right.txt"),
vec![String::from("a")],
vec![String::from("b")],
));
e.open(&png).unwrap();
assert!(e.image.is_some());
assert!(e.diff.is_none(), "image opener supersedes the diff too");
}
#[test]
fn hex_render_narrower_than_the_8_byte_layout_paints_no_half_grid() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("blob.bin");
std::fs::write(&p, vec![0u8; 64]).unwrap();
let mut ed = Editor::new();
ed.open(&p).unwrap();
let area = Rect {
x: 0,
y: 0,
width: 34, height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
let mut all = String::new();
for y in 0..area.height {
for x in 0..area.width {
all.push_str(buf[(x, y)].symbol());
}
all.push('\n');
}
assert!(all.contains("HEX"), "header still names the tab: {all}");
assert!(
!all.contains("00000000"),
"no offset column without bytes to go with it: {all}"
);
assert!(!all.contains("00 "), "no lone byte cells: {all}");
let view = ed.hex.as_ref().unwrap();
assert_eq!(
view.layout.data_rows, 0,
"empty state publishes no hit-test rows"
);
}
#[test]
fn hex_render_drops_to_8_bytes_per_row_in_a_narrow_pane() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("blob.bin");
std::fs::write(&p, vec![0x00u8; 64]).unwrap();
let mut ed = Editor::new();
ed.open(&p).unwrap();
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
assert_eq!(ed.hex.as_ref().unwrap().bytes_per_row, 8);
}
#[test]
fn hex_view_swaps_away_cleanly_when_a_text_file_reopens() {
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("blob.bin");
std::fs::write(&bin, b"\x00\x01\x02").unwrap();
let txt = tmp.path().join("notes.txt");
std::fs::write(&txt, "hello\n").unwrap();
let mut e = Editor::new();
e.open(&bin).unwrap();
assert!(e.hex.is_some());
e.open(&txt).unwrap();
assert!(e.hex.is_none(), "text reopen drops the hex state");
assert_eq!(e.lines, vec!["hello".to_string()]);
e.open(&bin).unwrap();
assert!(e.hex.is_some(), "and back again");
assert_eq!(e.lines, vec![String::new()]);
}
fn diag(
start_line: u32,
start_char: u32,
end_line: u32,
end_char: u32,
severity: crate::lsp::manager::DiagnosticSeverity,
) -> crate::lsp::manager::Diagnostic {
crate::lsp::manager::Diagnostic {
start_line,
start_char,
end_line,
end_char,
severity,
message: String::from("test diagnostic"),
}
}
#[test]
fn apply_diagnostics_decodes_into_per_line_char_spans() {
use crate::lsp::manager::DiagnosticSeverity;
let mut e = editor_with("const x = 1;");
let p = std::path::PathBuf::from("/tmp/diag.ts");
e.path = Some(p.clone());
e.apply_diagnostics(p, vec![diag(0, 6, 0, 7, DiagnosticSeverity::Error)]);
let spans = e.diagnostic_spans_for_test();
assert_eq!(
spans[0],
vec![(6, 7, DiagnosticSeverity::Error)],
"the diagnostic must decode to a single-char run over `x`"
);
}
#[test]
fn zero_width_diagnostic_is_widened_to_one_cell() {
use crate::lsp::manager::DiagnosticSeverity;
let mut e = editor_with("const x = 1;");
let p = std::path::PathBuf::from("/tmp/diag.ts");
e.path = Some(p.clone());
e.apply_diagnostics(p, vec![diag(0, 6, 0, 6, DiagnosticSeverity::Warning)]);
assert_eq!(
e.diagnostic_spans_for_test()[0],
vec![(6, 7, DiagnosticSeverity::Warning)],
"a zero-width diagnostic must widen to one cell so it stays visible"
);
}
#[test]
fn diagnostics_for_another_file_do_not_decode() {
use crate::lsp::manager::DiagnosticSeverity;
let mut e = editor_with("const x = 1;");
e.path = Some(std::path::PathBuf::from("/tmp/open.ts"));
e.apply_diagnostics(
std::path::PathBuf::from("/tmp/other.ts"),
vec![diag(0, 0, 0, 5, DiagnosticSeverity::Error)],
);
assert!(
e.diagnostic_spans_for_test().iter().all(|l| l.is_empty()),
"a batch for a different file must not underline the loaded one"
);
}
#[test]
fn empty_diagnostics_batch_clears_the_underlines() {
use crate::lsp::manager::DiagnosticSeverity;
let mut e = editor_with("const x = 1;");
let p = std::path::PathBuf::from("/tmp/diag.ts");
e.path = Some(p.clone());
e.apply_diagnostics(p.clone(), vec![diag(0, 6, 0, 7, DiagnosticSeverity::Error)]);
assert!(!e.diagnostic_spans_for_test()[0].is_empty());
e.apply_diagnostics(p, Vec::new());
assert!(
e.diagnostic_spans_for_test().iter().all(|l| l.is_empty()),
"an empty batch must erase the squiggles"
);
}
#[test]
fn diagnostics_at_returns_messages_covering_the_point() {
use crate::lsp::manager::{Diagnostic, DiagnosticSeverity};
let mut e = editor_with("const x = 1;");
let p = std::path::PathBuf::from("/tmp/diag.ts");
e.path = Some(p.clone());
e.apply_diagnostics(
p,
vec![Diagnostic {
start_line: 0,
start_char: 6,
end_line: 0,
end_char: 7,
severity: DiagnosticSeverity::Error,
message: String::from("Type 'number' is not assignable to type 'string'."),
}],
);
assert_eq!(
e.diagnostics_at(0, 6),
vec![(
DiagnosticSeverity::Error,
String::from("Type 'number' is not assignable to type 'string'.")
)],
"a point inside the diagnostic range must surface its message"
);
assert!(
e.diagnostics_at(0, 0).is_empty(),
"a point outside every diagnostic range must surface nothing"
);
}
#[test]
fn diagnostics_at_widens_a_zero_width_diagnostic_to_one_cell() {
use crate::lsp::manager::{Diagnostic, DiagnosticSeverity};
let mut e = editor_with("const x = 1;");
let p = std::path::PathBuf::from("/tmp/diag.ts");
e.path = Some(p.clone());
e.apply_diagnostics(
p,
vec![Diagnostic {
start_line: 0,
start_char: 6,
end_line: 0,
end_char: 6,
severity: DiagnosticSeverity::Warning,
message: String::from("missing semicolon"),
}],
);
assert_eq!(
e.diagnostics_at(0, 6),
vec![(
DiagnosticSeverity::Warning,
String::from("missing semicolon")
)],
"a zero-width diagnostic must still be hoverable over its one widened cell"
);
}
#[test]
fn hover_region_at_prefers_the_word_then_falls_back_to_the_diagnostic_span() {
use crate::lsp::manager::{Diagnostic, DiagnosticSeverity};
let mut e = editor_with("a.b");
let p = std::path::PathBuf::from("/tmp/dot.ts");
e.path = Some(p.clone());
e.apply_diagnostics(
p,
vec![Diagnostic {
start_line: 0,
start_char: 1,
end_line: 0,
end_char: 2,
severity: DiagnosticSeverity::Error,
message: String::from("unexpected token"),
}],
);
assert_eq!(
e.hover_region_at(0, 0),
Some((0, 0, 1)),
"over the `a` identifier the region is the word range"
);
assert_eq!(
e.hover_region_at(0, 1),
Some((0, 1, 2)),
"over the punctuation `.` the region falls back to the covering diagnostic span"
);
}
#[test]
fn render_paints_severity_coloured_underline_over_the_diagnostic_span() {
use crate::lsp::manager::DiagnosticSeverity;
let mut e = editor_with("const x = 1;");
let p = std::path::PathBuf::from("/tmp/diag.ts");
e.path = Some(p.clone());
e.apply_diagnostics(p, vec![diag(0, 6, 0, 7, DiagnosticSeverity::Error)]);
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let red = Color::Rgb(0xf1, 0x4c, 0x4c);
let mut underlined: Vec<(u16, u16, String)> = Vec::new();
for y in 0..area.height {
for x in 0..area.width {
let cell = &buf[(x, y)];
if cell.modifier.contains(Modifier::UNDERLINED) && cell.underline_color == red {
underlined.push((x, y, cell.symbol().to_string()));
}
}
}
assert_eq!(
underlined.len(),
1,
"exactly one cell (the `x`) must carry a red error underline; got {underlined:?}"
);
assert_eq!(
underlined[0].2, "x",
"the underline must sit under the offending `x` glyph"
);
}
#[test]
fn focused_editor_gradient_border_is_gated_on_focus_gradient() {
use crate::gradient::{GRAD_TL, rgb_color};
let mut e = editor_with("hi");
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 5,
};
e.focus_gradient = true;
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
assert_eq!(buf[(0, 0)].symbol(), "\u{256d}");
assert_eq!(buf[(0, 0)].fg, rgb_color(GRAD_TL));
e.focus_gradient = false;
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
assert_eq!(buf[(0, 0)].symbol(), "\u{250c}");
assert_eq!(buf[(0, 0)].fg, Color::Rgb(0x4e, 0x9a, 0xff));
}
fn inlay(line: u32, character: u32, label: &str) -> crate::lsp::manager::InlayHintItem {
crate::lsp::manager::InlayHintItem {
line,
character,
label: label.to_string(),
}
}
fn first_row_text(e: &mut Editor) -> String {
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(e as &mut Editor).render(area, &mut buf);
(0..area.width)
.map(|x| buf[(x, 1)].symbol().to_string())
.collect()
}
#[test]
fn inlay_hint_splices_dim_italic_label_into_the_row() {
let mut e = editor_with("let x = f(y);");
let p = std::path::PathBuf::from("/tmp/hints.rs");
e.path = Some(p.clone());
e.apply_inlay_hints(p, vec![inlay(0, 5, ": i32"), inlay(0, 10, "n: ")]);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let row: String = (0..area.width)
.map(|x| buf[(x, 1)].symbol().to_string())
.collect();
assert!(
row.contains("let x: i32 = f(n: y);"),
"hints must splice into the rendered row; got {row:?}"
);
let hint_fg = e.theme.ignored_fg();
let hint_x = (0..area.width)
.find(|&x| {
buf[(x, 1)].symbol() == "i"
&& buf[(x + 1, 1)].symbol() == "3"
&& buf[(x + 2, 1)].symbol() == "2"
})
.expect("the i32 hint must be on the row");
for dx in 0..3 {
let cell = &buf[(hint_x + dx, 1)];
assert!(
cell.modifier.contains(Modifier::ITALIC),
"hint cells must be italic"
);
assert_eq!(cell.fg, hint_fg, "hint cells must use the muted grey");
}
let code_x = (0..area.width)
.find(|&x| buf[(x, 1)].symbol() == "x")
.expect("the x binding must be on the row");
assert!(
!buf[(code_x, 1)].modifier.contains(Modifier::ITALIC),
"real code cells must stay non-italic"
);
}
#[test]
fn gutter_play_glyph_marks_test_fns_and_maps_clicks_to_the_name() {
let mut e = editor_with("#[test]\nfn my_case() {}\nfn helper() {}");
e.path = Some(PathBuf::from("/x/a.rs"));
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let sign_x = e.last_inner.x;
assert_eq!(
buf[(sign_x, 2)].symbol(),
"\u{eb2c}",
"a test fn's first row must wear the play glyph in the sign margin"
);
assert_ne!(
buf[(sign_x, 3)].symbol(),
"\u{eb2c}",
"a plain fn must not wear the glyph"
);
assert_eq!(
e.test_glyph_at(sign_x, 2).as_deref(),
Some("my_case"),
"clicking the glyph must resolve the test's name"
);
assert_eq!(
e.test_glyph_at(sign_x, 3),
None,
"clicking the sign margin of a non-test line resolves nothing"
);
assert_eq!(
e.test_glyph_at(sign_x + 1, 2),
None,
"the fold-chevron column is not the play glyph"
);
}
#[test]
fn gutter_stream_stop_glyph_renders_maps_clicks_and_outranks_the_play_glyph() {
let mut e = editor_with("#[test]\nfn my_case() {}\nfn helper() {}");
e.path = Some(PathBuf::from("/x/a.rs")); e.stream_stop_line = Some(1); let area = Rect {
x: 0,
y: 0,
width: 60,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let sign_x = e.last_inner.x;
assert_eq!(
buf[(sign_x, 2)].symbol(),
"■",
"the streamed row's sign cell wears the stop square, not the play glyph"
);
assert!(e.stream_stop_at(sign_x, 2), "the stop cell is clickable");
assert!(
!e.stream_stop_at(sign_x + 1, 2),
"the fold-chevron column is not the button"
);
assert!(
!e.stream_stop_at(sign_x, 3),
"other rows are not the button"
);
e.stream_stop_line = None;
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
assert_eq!(
buf[(sign_x, 2)].symbol(),
"\u{eb2c}",
"without a stream the test play glyph owns the cell again"
);
assert!(!e.stream_stop_at(sign_x, 2));
}
#[test]
fn comment_box_renders_unnumbered_rows_between_lines() {
let mut e = editor_with("first\nsecond\nthird");
e.comment_boxes = vec![CommentBox {
id: 7,
line: 0,
author: "navigator".into(),
body: "tighten this".into(),
}];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let row_text = |y: u16| -> String {
(0..area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect()
};
assert!(row_text(1).contains("first"));
assert!(row_text(1).contains('1'), "line 0 keeps its number");
assert!(row_text(2).contains("navigator"), "title names the author");
assert!(row_text(3).contains("tighten this"), "body renders");
assert!(row_text(4).contains("Ignore"), "footer has the button");
let gutter = e.last_gutter_width;
for y in 2..=4u16 {
let g: String = (0..gutter)
.map(|x| buf[(x, y)].symbol().to_string())
.collect();
assert!(
g.chars().all(|c| !c.is_ascii_digit()),
"box rows are unnumbered, got gutter {g:?} at y={y}"
);
}
assert!(row_text(5).contains("second"));
assert!(row_text(5).contains('2'));
assert_eq!(
e.screen_row_of_line(1),
Some(5),
"screen row mapping shifts by the box height"
);
}
#[test]
fn clicks_map_through_comment_box_rows() {
let mut e = editor_with("first\nsecond\nthird");
e.comment_boxes = vec![CommentBox {
id: 7,
line: 0,
author: "navigator".into(),
body: "tighten this".into(),
}];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_eq!(
e.buffer_pos_at(text_x, 3),
None,
"a box row is not a buffer cell"
);
assert_eq!(
e.buffer_pos_at(text_x, 5),
Some((1, 0)),
"the line below the box maps at its shifted row"
);
}
#[test]
fn comment_box_hit_finds_reply_ignore_and_body() {
let mut e = editor_with("first\nsecond\nthird");
e.comment_boxes = vec![CommentBox {
id: 7,
line: 0,
author: "navigator".into(),
body: "tighten this".into(),
}];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let ignore_x = (0..area.width)
.find(|&x| buf[(x, 4)].symbol() == "\u{2715}")
.expect("the footer renders the ✕ Ignore button");
assert_eq!(
e.comment_box_hit(ignore_x, 4),
Some((7, CommentHit::Ignore))
);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_eq!(
e.comment_box_hit(text_x + 2, 4),
Some((7, CommentHit::Reply)),
"the rest of the footer is the reply field"
);
assert_eq!(
e.comment_box_hit(text_x + 2, 3),
Some((7, CommentHit::Body))
);
assert_eq!(e.comment_box_hit(text_x + 2, 1), None, "text rows miss");
assert_eq!(e.comment_box_hit(text_x + 2, 5), None);
}
#[test]
fn cursor_skips_comment_box_rows_in_wrap_mode() {
let mut e = editor_with("first\nsecond\nthird");
e.wrap_override = Some(true);
e.comment_boxes = vec![CommentBox {
id: 7,
line: 0,
author: "navigator".into(),
body: "tighten this".into(),
}];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
e.cursor_row = 0;
e.cursor_col = 0;
e.move_down();
assert_eq!(e.cursor_row, 1, "the caret skips the box");
e.move_up();
assert_eq!(e.cursor_row, 0);
}
#[test]
fn a_box_hidden_by_a_fold_does_not_extend_the_scroll_geometry() {
let mut e = editor_with("fn a() {\n body();\n}\nlast");
e.comment_boxes = vec![CommentBox {
id: 1,
line: 1,
author: "navigator".into(),
body: (0..20)
.map(|i| format!("p{i}"))
.collect::<Vec<_>>()
.join("\n"),
}];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
e.toggle_fold(0);
assert!(e.is_line_hidden(1), "the box's line folds away");
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
assert_eq!(
e.last_scrollbar.width, 0,
"4 lines minus a fold fit the viewport; nothing left to scroll"
);
e.scroll_down(3);
assert_eq!(
(e.scroll, e.scroll_sub),
(0, 0),
"scrolling must not walk into folded-away box rows"
);
}
#[test]
fn nonwrap_scrolling_reaches_a_tall_comment_boxes_footer() {
let mut e = editor_with("first\nsecond\nthird");
e.comment_boxes = vec![CommentBox {
id: 1,
line: 0,
author: "navigator".into(),
body: (0..30)
.map(|i| format!("point {i}"))
.collect::<Vec<_>>()
.join("\n"),
}];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let screen = |buf: &ratatui::buffer::Buffer| -> String {
(0..area.height)
.map(|y| {
(0..area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
};
assert!(
!screen(&buf).contains("Ignore"),
"the tall box overflows: its footer starts off-screen"
);
for _ in 0..12 {
e.scroll_down(3);
}
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
assert!(
screen(&buf).contains("Ignore"),
"scrolling must reach the box footer; got:\n{}",
screen(&buf)
);
}
#[test]
fn a_long_reply_windows_so_the_caret_and_tail_stay_visible() {
let mut e = editor_with("first\nsecond\nthird");
e.comment_boxes = vec![CommentBox {
id: 7,
line: 0,
author: "navigator".into(),
body: "tighten this".into(),
}];
let reply = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_TAIL";
e.comment_focus = Some(CommentFocus {
id: 7,
reply: reply.into(),
cursor: reply.chars().count(),
});
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let footer: String = (0..area.width)
.map(|x| buf[(x, 4)].symbol().to_string())
.collect();
assert!(
footer.contains("_TAIL"),
"the field must window to keep the tail under the caret visible: {footer:?}"
);
let caret_cells = (0..area.width)
.filter(|&x| {
buf[(x, 4)]
.style()
.add_modifier
.contains(ratatui::style::Modifier::REVERSED)
})
.count();
assert_eq!(caret_cells, 1, "exactly one caret cell renders: {footer:?}");
}
#[test]
fn focused_comment_box_renders_the_reply_draft() {
let mut e = editor_with("first\nsecond\nthird");
e.comment_boxes = vec![CommentBox {
id: 7,
line: 0,
author: "navigator".into(),
body: "tighten this".into(),
}];
e.comment_focus = Some(CommentFocus {
id: 7,
reply: String::from("why here?"),
cursor: 9,
});
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let footer: String = (0..area.width)
.map(|x| buf[(x, 4)].symbol().to_string())
.collect();
assert!(
footer.contains("why here?"),
"the reply draft renders in the footer: {footer:?}"
);
}
#[test]
fn find_highlights_stay_readable_over_occurrence_tints() {
let mut e = editor_with("config here");
e.path = Some(PathBuf::from("/x/a.rs"));
e.set_search_highlight(Some(String::from("config")));
e.occurrences = vec![(0, 0, 6, false)];
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let gold = Color::Rgb(0xff, 0xd7, 0x4a);
let occ = crate::theme::Theme::BLACK.occurrence_bg();
let mut gold_cells = 0;
for y in 0..area.height {
for x in 0..area.width {
let cell = &buf[(x, y)];
if cell.bg == gold {
gold_cells += 1;
}
assert!(
!(cell.fg == Color::Black && cell.bg == occ),
"cell ({x},{y}) '{}' wears the find layer's black fg on the occurrence bg — unreadable",
cell.symbol()
);
}
}
assert!(
gold_cells >= 6,
"the find highlight must survive the occurrence pass (got {gold_cells} gold cells)"
);
}
#[test]
fn a_claimed_sign_cell_does_not_hit_test_as_the_play_bead() {
let mut e = editor_with("#[test]\nfn my_case() {}");
e.path = Some(PathBuf::from("/x/a.rs"));
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let sign_x = e.last_inner.x;
assert_eq!(e.test_glyph_at(sign_x, 2).as_deref(), Some("my_case"));
e.toggle_breakpoint_line(2);
assert_eq!(
e.test_glyph_at(sign_x, 2),
None,
"the breakpoint dot's cell must not run tests on click"
);
e.toggle_breakpoint_line(2);
assert_eq!(
e.test_glyph_at(sign_x, 2).as_deref(),
Some("my_case"),
"removing the dot hands the cell back to the bead"
);
e.stop_line = Some((e.path.clone().unwrap(), 2));
assert_eq!(
e.test_glyph_at(sign_x, 2),
None,
"the paused stop arrow owns its cell"
);
e.stop_line = None;
e.stream_stop_line = Some(1);
assert_eq!(
e.test_glyph_at(sign_x, 2),
None,
"the AI-stream stop square owns its cell"
);
}
#[test]
fn gutter_play_glyph_yields_to_a_breakpoint_dot() {
let mut e = editor_with("#[test]\nfn my_case() {}");
let p = std::path::PathBuf::from("/tmp/bp.rs");
e.path = Some(p.clone());
e.breakpoints.entry(p).or_default().insert(2); let area = Rect {
x: 0,
y: 0,
width: 60,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
assert_eq!(
buf[(e.last_inner.x, 2)].symbol(),
"●",
"a breakpoint on the fn line owns the shared sign cell"
);
}
fn occ(
start_line: u32,
start_char: u32,
end_line: u32,
end_char: u32,
write: bool,
) -> crate::lsp::manager::OccurrenceItem {
crate::lsp::manager::OccurrenceItem {
start_line,
start_char,
end_line,
end_char,
write,
}
}
#[test]
fn lsp_occurrences_paint_theme_tints_with_utf16_columns_and_clear_on_edit() {
let mut e = editor_with("a𐐀x = x;");
let p = std::path::PathBuf::from("/tmp/occ.rs");
e.path = Some(p.clone());
e.apply_occurrences(vec![occ(0, 0, 0, 4, true), occ(0, 7, 0, 8, false)]);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let write_bg = e.theme.occurrence_write_bg();
let read_bg = e.theme.occurrence_bg();
let a_x = (0..area.width)
.find(|&x| buf[(x, 1)].symbol() == "a")
.expect("the identifier must be on the row");
for dx in 0..3 {
assert_eq!(
buf[(a_x + dx, 1)].bg,
write_bg,
"the write occurrence must tint all three identifier chars (dx={dx})"
);
}
let second_x = (a_x + 3..area.width)
.find(|&x| buf[(x, 1)].symbol() == "x")
.expect("the second x must be on the row");
assert_eq!(
buf[(second_x, 1)].bg,
read_bg,
"the read occurrence must tint exactly the second x"
);
assert_ne!(
buf[(second_x - 1, 1)].bg,
read_bg,
"the cell before the second x must stay untinted"
);
e.mark_buffer_changed();
let mut buf2 = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf2);
assert_ne!(
buf2[(second_x, 1)].bg,
read_bg,
"an edit must clear the occurrence tints"
);
}
#[test]
fn inlay_hints_for_another_file_do_not_paint() {
let mut e = editor_with("let x = f(y);");
e.path = Some(std::path::PathBuf::from("/tmp/current.rs"));
e.apply_inlay_hints(
std::path::PathBuf::from("/tmp/other.rs"),
vec![inlay(0, 5, ": i32")],
);
let row = first_row_text(&mut e);
assert!(
row.contains("let x = f(y);") && !row.contains("i32"),
"hints for a different file must not paint; got {row:?}"
);
}
#[test]
fn wrap_mode_suppresses_inlay_hints() {
let mut e = editor_with("let x = f(y);");
let p = std::path::PathBuf::from("/tmp/hints.rs");
e.path = Some(p.clone());
e.apply_inlay_hints(p, vec![inlay(0, 5, ": i32")]);
e.wrap_override = Some(true);
let row = first_row_text(&mut e);
assert!(
row.contains("let x = f(y);") && !row.contains("i32"),
"wrap mode must render the raw text unshifted; got {row:?}"
);
}
#[test]
fn cursor_screen_pos_shifts_past_inlay_hints() {
let mut e = editor_with("let x = f(y);");
let p = std::path::PathBuf::from("/tmp/hints.rs");
e.path = Some(p.clone());
e.apply_inlay_hints(p, vec![inlay(0, 5, ": i32")]);
e.focused = true;
let _ = first_row_text(&mut e);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
e.cursor_row = 0;
e.cursor_col = 6;
assert_eq!(
e.cursor_screen_pos(),
Some((text_x + 11, e.last_inner.y)),
"the caret must account for hint cells before it"
);
e.cursor_col = 5;
assert_eq!(
e.cursor_screen_pos(),
Some((text_x + 5, e.last_inner.y)),
"the caret at the anchor must sit before the hint"
);
}
#[test]
fn secondary_and_ghost_carets_sit_left_of_an_inlay_hint_like_the_primary() {
let mut e = editor_with("let x = f(y);");
let p = std::path::PathBuf::from("/tmp/hints.rs");
e.path = Some(p.clone());
e.apply_inlay_hints(p, vec![inlay(0, 5, ": i32")]);
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 5,
};
e.carets = vec![EditorSelection::new(0, 5)];
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let block_x = (0..area.width).find(|&x| buf[(x, 1)].bg == Color::Rgb(0xae, 0xc6, 0xff));
assert_eq!(
block_x,
Some(text_x + 5),
"the secondary caret's block must sit where the primary would"
);
e.carets.clear();
e.ghost_carets = vec![(0, 5, Color::Red)];
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
let ghost_x = (0..area.width).find(|&x| buf[(x, 1)].bg == Color::Red);
assert_eq!(
ghost_x,
Some(text_x + 5),
"a collaborator's ghost caret must sit where the primary would"
);
}
#[test]
fn click_and_word_select_map_through_inlay_hints() {
let mut e = editor_with("let x = f(y);");
let p = std::path::PathBuf::from("/tmp/hints.rs");
e.path = Some(p.clone());
e.apply_inlay_hints(p, vec![inlay(0, 5, ": i32")]);
let _ = first_row_text(&mut e);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y = e.last_inner.y;
e.click(text_x + 13, y);
assert_eq!(
(e.cursor_row, e.cursor_col),
(0, 8),
"the caret must land where the pointer is, not past the hint"
);
e.select_word_at(text_x + 15, y);
assert_eq!(
e.selection.map(|s| (s.anchor, s.head)),
Some(((0, 10), (0, 11))),
"word select must resolve the word under the pointer"
);
}
#[test]
fn buffer_pos_at_maps_clicks_through_inlay_hints() {
let mut e = editor_with("let x = f(y);");
let p = std::path::PathBuf::from("/tmp/hints.rs");
e.path = Some(p.clone());
e.apply_inlay_hints(p, vec![inlay(0, 5, ": i32")]);
let _ = first_row_text(&mut e);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y = e.last_inner.y;
assert_eq!(e.buffer_pos_at(text_x + 11, y), Some((0, 6)));
assert_eq!(e.buffer_pos_at(text_x + 7, y), Some((0, 5)));
assert_eq!(e.buffer_pos_at(text_x + 2, y), Some((0, 2)));
}
#[test]
fn opening_a_file_drops_the_previous_files_inlay_hints() {
let mut e = editor_with("let x = f(y);");
let p = std::path::PathBuf::from("/tmp/hints.rs");
e.path = Some(p.clone());
e.apply_inlay_hints(p, vec![inlay(0, 5, ": i32")]);
let dir = std::env::temp_dir().join("croft_inlay_open_test");
std::fs::create_dir_all(&dir).unwrap();
let other = dir.join("other.rs");
std::fs::write(&other, "fn g() {}\n").unwrap();
e.open(&other).unwrap();
let row = first_row_text(&mut e);
assert!(
!row.contains("i32"),
"a newly opened file must not inherit stale hints; got {row:?}"
);
}
#[test]
fn markdown_preview_toggles_renders_and_returns_to_source() {
let mut e = editor_with("# Title\n\nSome body text.");
e.lang = Some(LangKind::Markdown);
assert!(e.toggle_markdown_preview(), "a Markdown tab must toggle");
let text = first_row_screen(&mut e, 60, 8);
assert!(
text.contains("Title") && !text.contains("# Title"),
"the preview must render the heading without its # marker; got:\n{text}"
);
assert!(text.contains("Some body text."), "got:\n{text}");
assert!(e.toggle_markdown_preview(), "toggling again returns");
assert!(e.markdown_preview.is_none());
let text = first_row_screen(&mut e, 60, 8);
assert!(
text.contains("# Title"),
"the source view must show the raw markdown again; got:\n{text}"
);
}
#[test]
fn markdown_preview_refuses_non_markdown_tabs() {
let mut e = editor_with("fn main() {}");
e.lang = Some(LangKind::Rust);
assert!(!e.toggle_markdown_preview());
assert!(e.markdown_preview.is_none());
}
#[test]
fn markdown_preview_rebuilds_when_the_buffer_moves() {
let mut e = editor_with("# Old heading");
e.lang = Some(LangKind::Markdown);
assert!(e.toggle_markdown_preview());
e.lines[0] = String::from("# New heading");
e.edit_seq = e.edit_seq.wrapping_add(1);
let text = first_row_screen(&mut e, 60, 8);
assert!(
text.contains("New heading") && !text.contains("Old heading"),
"a stale preview must rebuild against the edited buffer; got:\n{text}"
);
}
fn first_row_screen(e: &mut Editor, width: u16, height: u16) -> String {
let area = Rect {
x: 0,
y: 0,
width,
height,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(e as &mut Editor).render(area, &mut buf);
let mut out = String::new();
for y in 0..height {
for x in 0..width {
out.push_str(buf[(x, y)].symbol());
}
out.push('\n');
}
out
}
#[test]
fn range_batch_does_not_overwrite_a_full_batch_for_the_same_file() {
let mut e = editor_with("def f(x):\n return x\n");
let p = std::path::PathBuf::from("/tmp/sem_guard.py");
e.path = Some(p.clone());
let legend = std::sync::Arc::new(vec!["parameter".to_string()]);
let full = vec![0, 6, 1, 0, 0, 1, 11, 1, 0, 0];
e.apply_semantic_tokens(p.clone(), full, legend.clone(), true);
let body_spans = e.semantic_overlay_for_test()[1].len();
assert!(body_spans > 0, "full batch must colour the body reference");
let range_only_line0 = vec![0, 6, 1, 0, 0];
e.apply_semantic_tokens(p.clone(), range_only_line0, legend, false);
assert_eq!(
e.semantic_overlay_for_test()[1].len(),
body_spans,
"a range batch must not erase off-screen colour from the full batch"
);
}
#[test]
fn range_batch_paints_first_then_full_replaces() {
let mut e = editor_with("def f(x):\n return x\n");
let p = std::path::PathBuf::from("/tmp/sem_first.py");
e.path = Some(p.clone());
let legend = std::sync::Arc::new(vec!["parameter".to_string()]);
e.apply_semantic_tokens(p.clone(), vec![0, 6, 1, 0, 0], legend.clone(), false);
let line1_before = e
.semantic_overlay_for_test()
.get(1)
.map(|s| s.len())
.unwrap_or(0);
assert_eq!(
line1_before, 0,
"range batch leaves the off-screen line bare"
);
e.apply_semantic_tokens(p.clone(), vec![0, 6, 1, 0, 0, 1, 11, 1, 0, 0], legend, true);
assert!(
!e.semantic_overlay_for_test()[1].is_empty(),
"full reply must colour the previously-bare off-screen line"
);
}
#[test]
fn find_word_occurrences_matches_whole_words_only() {
let chars: Vec<char> = "foo foobar foo_ foo".chars().collect();
let word: Vec<char> = "foo".chars().collect();
assert_eq!(find_word_occurrences(&chars, &word), vec![0, 16]);
}
#[test]
fn select_all_occurrences_picks_cursor_match_as_primary() {
let mut e = editor_with("foo bar foo\nfoo");
e.cursor_row = 0;
e.cursor_col = 8; let n = e.select_all_occurrences_of_word_at_cursor();
assert_eq!(n, 3);
assert_eq!(e.selection.unwrap().normalised(), ((0, 8), (0, 11)));
assert_eq!(e.carets.len(), 2);
assert!(e.has_multi_cursor());
}
#[test]
fn multi_insert_replaces_every_occurrence_in_one_undo_step() {
let mut e = editor_with("foo bar foo\nfoo");
e.cursor_row = 0;
e.cursor_col = 0;
assert_eq!(e.select_all_occurrences_of_word_at_cursor(), 3);
e.multi_insert_char('X');
assert_eq!(e.lines, vec!["X bar X".to_string(), "X".to_string()]);
assert!(e.undo());
assert_eq!(e.lines, vec!["foo bar foo".to_string(), "foo".to_string()]);
}
#[test]
fn multi_backspace_deletes_at_every_caret() {
let mut e = editor_with("ab ab ab");
e.cursor_row = 0;
e.cursor_col = 0;
assert_eq!(e.select_all_occurrences_of_word_at_cursor(), 3);
e.multi_backspace();
assert_eq!(e.lines, vec![" ".to_string()]);
}
#[test]
fn collapse_carets_drops_secondary_cursors() {
let mut e = editor_with("x x x");
e.cursor_col = 0;
e.select_all_occurrences_of_word_at_cursor();
assert!(e.has_multi_cursor());
e.collapse_carets();
assert!(!e.has_multi_cursor());
assert!(e.carets.is_empty());
}
#[test]
fn apply_span_edits_applies_bottom_to_top() {
let mut lines = vec!["foo bar foo".to_string()];
let edits = vec![
TextSpanEdit {
start: (0, 0),
end: (0, 3),
new_text: "baz".to_string(),
},
TextSpanEdit {
start: (0, 8),
end: (0, 11),
new_text: "baz".to_string(),
},
];
assert_eq!(apply_span_edits_to_lines(&mut lines, &edits), 2);
assert_eq!(lines, vec!["baz bar baz".to_string()]);
}
#[test]
fn apply_span_edits_splits_multiline_new_text_into_separate_lines() {
let mut lines = vec![
"import typing".to_string(),
"import pandas".to_string(),
"import logging".to_string(),
"import re".to_string(),
];
let edits = vec![TextSpanEdit {
start: (0, 0),
end: (3, 9),
new_text: "import logging\nimport re\nimport typing\n\nimport pandas".to_string(),
}];
assert_eq!(apply_span_edits_to_lines(&mut lines, &edits), 1);
assert_eq!(
lines,
vec![
"import logging".to_string(),
"import re".to_string(),
"import typing".to_string(),
String::new(),
"import pandas".to_string(),
]
);
}
#[test]
fn apply_span_edits_single_line_range_with_multiline_new_text() {
let mut lines = vec!["abXYef".to_string()];
let edits = vec![TextSpanEdit {
start: (0, 2),
end: (0, 4),
new_text: "C\nD".to_string(),
}];
assert_eq!(apply_span_edits_to_lines(&mut lines, &edits), 1);
assert_eq!(lines, vec!["abC".to_string(), "Def".to_string()]);
}
#[test]
fn editor_apply_span_edits_marks_dirty_and_one_undo() {
let mut e = editor_with("name = 1\nprint(name)");
let edits = vec![
TextSpanEdit {
start: (0, 0),
end: (0, 4),
new_text: "label".to_string(),
},
TextSpanEdit {
start: (1, 6),
end: (1, 10),
new_text: "label".to_string(),
},
];
assert_eq!(e.apply_span_edits(&edits), 2);
assert!(e.dirty);
assert_eq!(
e.lines,
vec!["label = 1".to_string(), "print(label)".to_string()]
);
assert!(e.undo());
assert_eq!(
e.lines,
vec!["name = 1".to_string(), "print(name)".to_string()]
);
}
#[test]
fn is_binary_detects_high_nontext_ratio() {
let mut data = vec![0x01u8; 100];
data.extend_from_slice(b"abc");
assert!(is_binary(&data));
}
#[test]
fn is_binary_accepts_normal_text() {
let txt = "fn main() { println!(\"hello\"); }\n// this is fine\n";
assert!(!is_binary(txt.as_bytes()));
}
#[test]
fn open_loads_a_real_world_sized_log_file_above_the_old_5mb_cap() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("big.log");
let line =
"1778548312.915 lsp[ruff] stderr: 2026-05-12 02:11:52 INFO some workspace setting\n";
let line_bytes = line.len();
let target_bytes = 8 * 1024 * 1024;
let line_count = target_bytes / line_bytes + 1;
let mut buf = String::with_capacity(line_count * line_bytes);
for _ in 0..line_count {
buf.push_str(line);
}
std::fs::write(&path, &buf).unwrap();
assert!(
std::fs::metadata(&path).unwrap().len() > 5 * 1024 * 1024,
"test setup must produce a file larger than the historical 5MB cap"
);
let mut e = Editor::new();
e.open(&path)
.expect("editor.open must accept an 8MB plain-text log; the user reported lsp.log (7.4MB) being unopenable");
assert_eq!(e.lines.len(), line_count);
}
#[test]
fn line_char_len_counts_chars_not_bytes() {
let mut e = editor_with("héllo");
assert_eq!(e.line_char_len(0), 5);
e.lines[0] = String::from("日本語");
assert_eq!(e.line_char_len(0), 3);
}
#[test]
fn byte_index_ascii() {
let e = editor_with("abcdef");
assert_eq!(e.byte_index(0, 0), 0);
assert_eq!(e.byte_index(0, 3), 3);
assert_eq!(e.byte_index(0, 6), 6);
assert_eq!(e.byte_index(0, 99), 6); }
#[test]
fn byte_index_multibyte() {
let e = editor_with("héllo");
assert_eq!(e.byte_index(0, 0), 0);
assert_eq!(e.byte_index(0, 1), 1); assert_eq!(e.byte_index(0, 2), 3); assert_eq!(e.byte_index(0, 3), 4);
}
#[test]
fn insert_char_at_end() {
let mut e = editor_with("abc");
e.cursor_col = 3;
e.insert_char('d');
assert_eq!(e.lines[0], "abcd");
assert_eq!(e.cursor_col, 4);
assert!(e.dirty);
}
#[test]
fn insert_char_at_start() {
let mut e = editor_with("bc");
e.cursor_col = 0;
e.insert_char('a');
assert_eq!(e.lines[0], "abc");
assert_eq!(e.cursor_col, 1);
}
#[test]
fn insert_char_in_middle() {
let mut e = editor_with("ac");
e.cursor_col = 1;
e.insert_char('b');
assert_eq!(e.lines[0], "abc");
assert_eq!(e.cursor_col, 2);
}
#[test]
fn insert_char_multibyte_position() {
let mut e = editor_with("aé");
e.cursor_col = 2; e.insert_char('z');
assert_eq!(e.lines[0], "aéz");
}
#[test]
fn insert_newline_splits_line() {
let mut e = editor_with("hello world");
e.cursor_col = 5;
e.insert_newline();
assert_eq!(e.lines, vec!["hello".to_string(), " world".to_string()]);
assert_eq!(e.cursor_row, 1);
assert_eq!(e.cursor_col, 0);
}
#[test]
fn insert_newline_at_end_creates_blank_line() {
let mut e = editor_with("abc");
e.cursor_col = 3;
e.insert_newline();
assert_eq!(e.lines, vec!["abc".to_string(), String::new()]);
assert_eq!(e.cursor_row, 1);
}
#[test]
fn insert_newline_copies_previous_indent_for_unknown_language() {
let mut e = editor_with(" abc");
e.cursor_col = 7;
e.insert_newline();
assert_eq!(e.lines, vec![" abc".to_string(), " ".to_string()]);
assert_eq!(e.cursor_row, 1);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn insert_newline_python_indents_one_step_after_colon() {
let mut e = editor_with("def hello():");
e.lang = Some(LangKind::Python);
e.cursor_col = e.line_char_len(0);
e.insert_newline();
assert_eq!(
e.lines,
vec!["def hello():".to_string(), " ".to_string()]
);
assert_eq!(e.cursor_row, 1);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn insert_newline_python_no_extra_indent_without_colon() {
let mut e = editor_with(" print(x)");
e.lang = Some(LangKind::Python);
e.cursor_col = e.line_char_len(0);
e.insert_newline();
assert_eq!(
e.lines,
vec![" print(x)".to_string(), " ".to_string()]
);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn insert_newline_python_stacks_indent_on_nested_colon() {
let mut e = editor_with(" if x:");
e.lang = Some(LangKind::Python);
e.cursor_col = e.line_char_len(0);
e.insert_newline();
assert_eq!(
e.lines,
vec![" if x:".to_string(), " ".to_string()]
);
assert_eq!(e.cursor_col, 8);
}
#[test]
fn shift_tab_dedents_current_line_when_no_selection() {
let mut e = editor_with(" pass");
e.lang = Some(LangKind::Python);
e.cursor_row = 0;
e.cursor_col = 8;
e.dedent_lines();
assert_eq!(e.lines, vec![" pass".to_string()]);
assert_eq!(e.cursor_col, 4, "cursor follows the four stripped spaces");
}
#[test]
fn shift_tab_dedent_aligns_to_previous_tab_stop() {
let mut e = editor_with(" x = 1");
e.lang = Some(LangKind::Python);
e.cursor_col = 6;
e.dedent_lines();
assert_eq!(e.lines, vec![" x = 1".to_string()]);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn shift_tab_dedent_partial_indent_removes_all_leading_spaces() {
let mut e = editor_with(" y");
e.lang = Some(LangKind::Python);
e.cursor_col = 3;
e.dedent_lines();
assert_eq!(e.lines, vec!["y".to_string()]);
assert_eq!(e.cursor_col, 0);
}
#[test]
fn shift_tab_dedent_on_flush_left_line_is_a_noop() {
let mut e = editor_with("x");
e.lang = Some(LangKind::Python);
e.cursor_col = 1;
e.dedent_lines();
assert_eq!(e.lines, vec!["x".to_string()]);
assert_eq!(e.cursor_col, 1);
}
#[test]
fn shift_tab_dedent_strips_a_single_leading_tab() {
let mut e = editor_with("\tpass");
e.lang = Some(LangKind::Python);
e.cursor_col = 1;
e.dedent_lines();
assert_eq!(e.lines, vec!["pass".to_string()]);
assert_eq!(e.cursor_col, 0);
}
#[test]
fn shift_tab_dedents_every_line_a_selection_touches() {
let mut e = editor_with(" a\n b\n c");
e.lang = Some(LangKind::Python);
e.cursor_row = 2;
e.cursor_col = 5;
e.selection = Some(EditorSelection {
anchor: (0, 4),
head: (2, 5),
});
e.dedent_lines();
assert_eq!(
e.lines,
vec!["a".to_string(), "b".to_string(), "c".to_string()]
);
assert_eq!(
e.selection.unwrap(),
EditorSelection {
anchor: (0, 0),
head: (2, 1),
}
);
}
#[test]
fn tab_indents_every_line_a_multiline_selection_touches() {
let mut e = editor_with("a\nb");
e.lang = Some(LangKind::Python);
e.cursor_row = 1;
e.cursor_col = 1;
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (1, 1),
});
e.indent_lines();
assert_eq!(e.lines, vec![" a".to_string(), " b".to_string()]);
assert_eq!(
e.selection.unwrap(),
EditorSelection {
anchor: (0, 4),
head: (1, 5),
}
);
}
#[test]
fn tab_indent_block_leaves_empty_lines_untouched() {
let mut e = editor_with("a\n\nb");
e.lang = Some(LangKind::Python);
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (2, 1),
});
e.indent_lines();
assert_eq!(
e.lines,
vec![" a".to_string(), String::new(), " b".to_string()]
);
}
#[test]
fn tab_at_cursor_pads_to_the_next_tab_stop() {
let mut e = editor_with("ab");
e.lang = Some(LangKind::Python);
e.cursor_col = 2;
e.indent_at_cursor();
assert_eq!(e.lines, vec!["ab ".to_string()]);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn dedent_then_undo_restores_the_buffer_in_one_step() {
let mut e = editor_with(" pass");
e.lang = Some(LangKind::Python);
e.cursor_col = 8;
e.dedent_lines();
assert_eq!(e.lines, vec![" pass".to_string()]);
assert!(e.undo());
assert_eq!(e.lines, vec![" pass".to_string()]);
}
#[test]
fn redo_reapplies_an_undone_edit() {
let mut e = editor_with("");
e.insert_char('a');
e.insert_char('b');
assert_eq!(e.lines, vec!["ab".to_string()]);
assert!(e.undo());
assert_eq!(e.lines, vec![String::new()]);
assert!(e.redo());
assert_eq!(e.lines, vec!["ab".to_string()]);
assert_eq!(e.cursor_col, 2);
}
#[test]
fn redo_is_a_noop_on_an_empty_redo_stack() {
let mut e = editor_with("x");
assert!(!e.redo());
}
#[test]
fn undo_and_redo_bump_edit_seq_so_the_app_resyncs() {
let mut e = editor_with("");
e.insert_char('a');
let after_edit = e.edit_seq;
assert!(e.undo());
assert!(e.edit_seq > after_edit, "undo must bump edit_seq");
let after_undo = e.edit_seq;
assert!(e.redo());
assert!(e.edit_seq > after_undo, "redo must bump edit_seq");
}
#[test]
fn reopening_with_an_encoding_clears_both_history_stacks() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("enc.txt");
std::fs::write(&path, [0xC2_u8, 0xA2, b'\n']).unwrap();
let mut e = Editor::new();
e.open(&path).unwrap();
assert_eq!(e.lines, vec!["\u{a2}".to_string()], "staging: UTF-8 decode");
e.insert_char('x');
assert!(e.undo());
assert_eq!(e.lines, vec!["\u{a2}".to_string()], "staging: edit undone");
e.reopen_with_encoding(encoding_rs::WINDOWS_1252).unwrap();
assert_eq!(
e.lines,
vec!["\u{c2}\u{a2}".to_string()],
"the buffer holds the Windows-1252 decode"
);
assert!(
!e.redo(),
"redo must not resurrect the buffer decoded under the old encoding"
);
assert!(
!e.undo(),
"undo history from before the re-decode is equally stale"
);
assert_eq!(e.lines, vec!["\u{c2}\u{a2}".to_string()]);
}
#[test]
fn a_new_edit_after_undo_discards_the_redo_branch() {
let mut e = editor_with("");
e.insert_char('a');
assert!(e.undo());
assert_eq!(e.lines, vec![String::new()]);
e.insert_char('b');
assert!(!e.redo(), "a fresh edit must clear the redo stack");
assert_eq!(e.lines, vec!["b".to_string()]);
}
#[test]
fn insert_newline_rust_indents_after_open_brace() {
let mut e = editor_with("fn main() {");
e.lang = Some(LangKind::Rust);
e.cursor_col = e.line_char_len(0);
e.insert_newline();
assert_eq!(e.lines, vec!["fn main() {".to_string(), " ".to_string()]);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn insert_newline_typescript_indents_after_open_paren() {
let mut e = editor_with("foo(");
e.lang = Some(LangKind::TypeScript);
e.cursor_col = e.line_char_len(0);
e.insert_newline();
assert_eq!(e.lines, vec!["foo(".to_string(), " ".to_string()]);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn insert_newline_rust_bracket_pair_split_places_close_on_own_line() {
let mut e = editor_with("fn main() {}");
e.lang = Some(LangKind::Rust);
e.cursor_col = 11;
e.insert_newline();
assert_eq!(
e.lines,
vec![
"fn main() {".to_string(),
" ".to_string(),
"}".to_string()
]
);
assert_eq!(e.cursor_row, 1);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn insert_newline_rust_bracket_pair_split_preserves_outer_indent() {
let mut e = editor_with(" let v = vec![];");
e.lang = Some(LangKind::Rust);
e.cursor_col = 17;
e.insert_newline();
assert_eq!(
e.lines,
vec![
" let v = vec![".to_string(),
" ".to_string(),
" ];".to_string(),
]
);
assert_eq!(e.cursor_row, 1);
assert_eq!(e.cursor_col, 8);
}
#[test]
fn insert_newline_python_bracket_pair_split_places_close_on_own_line() {
let mut e = editor_with("foo()");
e.lang = Some(LangKind::Python);
e.cursor_col = 4;
e.insert_newline();
assert_eq!(
e.lines,
vec!["foo(".to_string(), " ".to_string(), ")".to_string()]
);
assert_eq!(e.cursor_row, 1);
assert_eq!(e.cursor_col, 4);
}
#[test]
fn insert_newline_yaml_uses_two_space_indent() {
let mut e = editor_with(" key:");
e.lang = Some(LangKind::Yaml);
e.cursor_col = e.line_char_len(0);
e.insert_newline();
assert_eq!(e.lines, vec![" key:".to_string(), " ".to_string()]);
assert_eq!(e.cursor_col, 2);
}
#[test]
fn backspace_mid_line() {
let mut e = editor_with("abcd");
e.cursor_col = 3;
e.backspace();
assert_eq!(e.lines[0], "abd");
assert_eq!(e.cursor_col, 2);
}
#[test]
fn backspace_at_col_zero_joins_with_previous_line() {
let mut e = editor_with("hello\nworld");
e.cursor_row = 1;
e.cursor_col = 0;
e.backspace();
assert_eq!(e.lines, vec!["helloworld".to_string()]);
assert_eq!(e.cursor_row, 0);
assert_eq!(e.cursor_col, 5);
}
#[test]
fn backspace_at_origin_does_nothing_destructive() {
let mut e = editor_with("abc");
e.cursor_row = 0;
e.cursor_col = 0;
e.backspace();
assert_eq!(e.lines, vec!["abc".to_string()]);
}
#[test]
fn delete_forward_mid_line() {
let mut e = editor_with("abcd");
e.cursor_col = 1;
e.delete_forward();
assert_eq!(e.lines[0], "acd");
assert_eq!(e.cursor_col, 1);
}
#[test]
fn delete_forward_at_end_joins_with_next_line() {
let mut e = editor_with("hello\nworld");
e.cursor_row = 0;
e.cursor_col = 5;
e.delete_forward();
assert_eq!(e.lines, vec!["helloworld".to_string()]);
assert_eq!(e.cursor_row, 0);
assert_eq!(e.cursor_col, 5);
}
#[test]
fn buffer_pos_at_maps_cells_to_line_and_char() {
let mut e = editor_with("fn main() {}\nlet x = 1;");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
assert_eq!(
e.buffer_pos_at(3, 0),
Some((0, 0)),
"first text cell (text_x = x + gutter + 1 = 3) is char 0 of line 0"
);
assert_eq!(
e.buffer_pos_at(6, 0),
Some((0, 3)),
"three cells into the text is char 3"
);
assert_eq!(
e.buffer_pos_at(3, 1),
Some((1, 0)),
"the second screen row is the second buffer line"
);
}
#[test]
fn buffer_pos_at_returns_none_over_the_gutter() {
let mut e = editor_with("hello");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
assert_eq!(e.buffer_pos_at(0, 0), None, "column 0 is in the gutter");
assert_eq!(e.buffer_pos_at(2, 0), None, "still left of text_x");
}
#[test]
fn buffer_pos_at_accounts_for_vertical_scroll() {
let mut e = editor_with("a\nbb\nccc\ndddd\neeeee");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
e.scroll = 2;
assert_eq!(
e.buffer_pos_at(3, 0),
Some((2, 0)),
"the top visible row is buffer line scroll = 2"
);
}
#[test]
fn buffer_pos_at_accounts_for_horizontal_scroll() {
let mut e = editor_with("abcdefghijklmnop");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
e.scroll_col = 5;
assert_eq!(
e.buffer_pos_at(3, 0),
Some((0, 5)),
"the leftmost text cell maps to char scroll_col, not char 0"
);
assert_eq!(
e.buffer_pos_at(5, 0),
Some((0, 7)),
"two cells right of the left edge is char scroll_col + 2"
);
}
#[test]
fn buffer_pos_at_honours_pane_offset() {
let mut e = editor_with("hello");
e.last_inner = Rect {
x: 10,
y: 4,
width: 40,
height: 10,
};
e.last_gutter_width = 3;
assert_eq!(e.buffer_pos_at(14, 4), Some((0, 0)), "text_x = 10 + 3 + 1");
assert_eq!(e.buffer_pos_at(16, 4), Some((0, 2)));
assert_eq!(e.buffer_pos_at(13, 4), None, "one cell left of text_x");
}
#[test]
fn buffer_pos_at_returns_none_outside_viewport_and_past_content() {
let mut e = editor_with("one\ntwo");
e.last_inner = Rect {
x: 0,
y: 2,
width: 80,
height: 4,
};
e.last_gutter_width = 2;
assert_eq!(e.buffer_pos_at(3, 1), None, "row above the pane");
assert_eq!(e.buffer_pos_at(3, 6), None, "row below the pane");
assert_eq!(
e.buffer_pos_at(3, 4),
None,
"row maps past the last line of content"
);
}
#[test]
fn buffer_pos_at_clamps_past_end_of_line() {
let mut e = editor_with("hi");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
assert_eq!(
e.buffer_pos_at(40, 0),
Some((0, 2)),
"a cell past the line's text clamps to the line length"
);
}
#[test]
fn word_at_returns_identifier_bounds() {
let e = editor_with("fn main() {}");
assert_eq!(e.word_at(0, 0), Some((0, 2)), "fn");
assert_eq!(e.word_at(0, 1), Some((0, 2)), "still within fn");
assert_eq!(e.word_at(0, 3), Some((3, 7)), "main starts at char 3");
assert_eq!(e.word_at(0, 6), Some((3, 7)), "last char of main");
}
#[test]
fn word_at_returns_none_off_a_word() {
let e = editor_with("fn main() {}");
assert_eq!(e.word_at(0, 2), None, "the space between fn and main");
assert_eq!(e.word_at(0, 7), None, "the open paren");
assert_eq!(e.word_at(0, 99), None, "past the end of the line");
}
#[test]
fn word_at_includes_underscores_and_digits() {
let e = editor_with("let foo_bar2 = 1");
assert_eq!(
e.word_at(0, 4),
Some((4, 12)),
"foo_bar2 is a single identifier"
);
assert_eq!(
e.word_at(0, 11),
Some((4, 12)),
"a trailing digit is part of the identifier"
);
}
#[test]
fn word_at_handles_missing_line() {
let e = editor_with("only one line");
assert_eq!(e.word_at(5, 0), None, "no such line");
}
#[test]
fn page_down_advances_one_full_viewport_and_puts_first_unseen_line_at_top() {
let mut e = editor_with_lines(100);
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
assert_eq!(e.scroll, 0);
assert_eq!(e.cursor_row, 0);
e.page_down_one_screen();
assert_eq!(
e.cursor_row, 25,
"cursor should jump to first previously-unseen row"
);
assert_eq!(
e.scroll, 25,
"scroll should align with new cursor at top of viewport"
);
}
#[test]
fn page_down_repeats_advance_one_viewport_at_a_time() {
let mut e = editor_with_lines(100);
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 20,
};
e.page_down_one_screen();
e.page_down_one_screen();
assert_eq!(e.cursor_row, 40);
assert_eq!(e.scroll, 40);
}
#[test]
fn page_down_clamps_at_end_of_file() {
let mut e = editor_with_lines(30);
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.scroll = 4;
e.cursor_row = 28;
e.page_down_one_screen();
assert_eq!(e.cursor_row, 29);
assert_eq!(e.scroll, 29);
}
#[test]
fn page_up_rewinds_one_full_viewport() {
let mut e = editor_with_lines(200);
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.scroll = 100;
e.cursor_row = 100;
e.page_up_one_screen();
assert_eq!(e.cursor_row, 75);
assert_eq!(e.scroll, 75);
}
#[test]
fn page_up_clamps_at_top_of_file() {
let mut e = editor_with_lines(50);
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.scroll = 5;
e.cursor_row = 5;
e.page_up_one_screen();
assert_eq!(e.cursor_row, 0);
assert_eq!(e.scroll, 0);
}
#[test]
fn page_size_falls_back_when_viewport_is_unknown() {
let mut e = editor_with_lines(100);
e.last_inner = Rect::default();
e.page_down_one_screen();
assert!(e.cursor_row > 0, "should advance even with zero last_inner");
}
fn editor_with_lines(n: usize) -> Editor {
let mut e = Editor::new();
e.lines = (0..n).map(|i| format!("line {i}")).collect();
e
}
#[test]
fn move_word_right_jumps_to_end_of_current_word() {
let mut e = editor_with("hello world");
e.cursor_row = 0;
e.cursor_col = 0;
e.move_word_right();
assert_eq!((e.cursor_row, e.cursor_col), (0, 5));
}
#[test]
fn move_word_right_skips_intervening_whitespace_and_lands_at_end_of_next_word() {
let mut e = editor_with("hello world!!!end");
e.cursor_row = 0;
e.cursor_col = 5;
e.move_word_right();
assert_eq!(
(e.cursor_row, e.cursor_col),
(0, 13),
"from end of 'hello' the next forward-word skips the spaces and stops at end of 'world'"
);
e.move_word_right();
assert_eq!(
(e.cursor_row, e.cursor_col),
(0, 19),
"second forward-word skips '!!!' and lands at end of 'end'"
);
}
#[test]
fn move_word_right_at_eol_advances_to_first_word_boundary_on_next_line() {
let mut e = editor_with("foo\n bar baz");
e.cursor_row = 0;
e.cursor_col = 3;
e.move_word_right();
assert_eq!((e.cursor_row, e.cursor_col), (1, 5));
}
#[test]
fn move_word_right_at_eof_is_a_noop() {
let mut e = editor_with("hi");
e.cursor_row = 0;
e.cursor_col = 2;
e.move_word_right();
assert_eq!((e.cursor_row, e.cursor_col), (0, 2));
}
#[test]
fn move_word_right_treats_underscore_as_part_of_the_word() {
let mut e = editor_with("snake_case rest");
e.cursor_row = 0;
e.cursor_col = 0;
e.move_word_right();
assert_eq!(
(e.cursor_row, e.cursor_col),
(0, 10),
"underscore is a word char so the whole identifier is one word"
);
}
#[test]
fn move_word_left_jumps_to_start_of_current_word() {
let mut e = editor_with("hello world");
e.cursor_row = 0;
e.cursor_col = 11;
e.move_word_left();
assert_eq!((e.cursor_row, e.cursor_col), (0, 6));
}
#[test]
fn move_word_left_skips_back_over_whitespace_and_punctuation() {
let mut e = editor_with("hello world!!!end");
e.cursor_row = 0;
e.cursor_col = 19;
e.move_word_left();
assert_eq!(
(e.cursor_row, e.cursor_col),
(0, 16),
"from end of 'end' the backward-word lands at start of 'end'"
);
e.move_word_left();
assert_eq!(
(e.cursor_row, e.cursor_col),
(0, 8),
"next backward-word skips '!!!' and lands at start of 'world'"
);
}
#[test]
fn move_word_left_at_bol_jumps_to_end_of_previous_line() {
let mut e = editor_with("foo bar\nbaz");
e.cursor_row = 1;
e.cursor_col = 0;
e.move_word_left();
assert_eq!(
(e.cursor_row, e.cursor_col),
(0, 4),
"backward-word from start of line 1 should cross the boundary and land at start of 'bar' on line 0"
);
}
#[test]
fn move_word_left_at_bof_is_a_noop() {
let mut e = editor_with("hi");
e.cursor_row = 0;
e.cursor_col = 0;
e.move_word_left();
assert_eq!((e.cursor_row, e.cursor_col), (0, 0));
}
#[test]
fn duplicate_lines_down_with_no_selection_copies_the_current_line_below_and_moves_cursor_to_it()
{
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 1;
e.cursor_col = 2;
e.duplicate_lines_down();
assert_eq!(e.lines, vec!["alpha", "beta", "beta", "gamma"]);
assert_eq!((e.cursor_row, e.cursor_col), (2, 2));
assert!(e.dirty);
}
#[test]
fn duplicate_lines_up_with_no_selection_copies_the_current_line_above_and_keeps_cursor_on_the_copy()
{
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 1;
e.cursor_col = 3;
e.duplicate_lines_up();
assert_eq!(e.lines, vec!["alpha", "beta", "beta", "gamma"]);
assert_eq!(
(e.cursor_row, e.cursor_col),
(1, 3),
"cursor stays at the same row index — that row is now the upper copy, the original was pushed to row 2"
);
}
#[test]
fn duplicate_lines_down_with_multiline_selection_duplicates_the_whole_block() {
let mut e = editor_with("a\nb\nc\nd");
e.cursor_row = 2;
e.cursor_col = 1;
e.selection = Some(EditorSelection {
anchor: (1, 0),
head: (2, 1),
});
e.duplicate_lines_down();
assert_eq!(e.lines, vec!["a", "b", "c", "b", "c", "d"]);
assert_eq!(
(e.cursor_row, e.cursor_col),
(4, 1),
"cursor follows the duplicated block — it was at (2,1) over the original 'c', now it's at (4,1) over the duplicate"
);
assert_eq!(
e.selection.unwrap(),
EditorSelection {
anchor: (3, 0),
head: (4, 1),
},
"the selection migrates onto the duplicated block too so the next gesture acts on the copy"
);
}
#[test]
fn duplicate_lines_up_with_multiline_selection_keeps_the_cursor_on_the_upper_copy() {
let mut e = editor_with("a\nb\nc\nd");
e.cursor_row = 2;
e.cursor_col = 0;
e.selection = Some(EditorSelection {
anchor: (1, 0),
head: (2, 1),
});
e.duplicate_lines_up();
assert_eq!(e.lines, vec!["a", "b", "c", "b", "c", "d"]);
assert_eq!(
(e.cursor_row, e.cursor_col),
(2, 0),
"the duplicate sits at rows 1-2 and the original was pushed down to rows 3-4; cursor at (2,0) is on the upper copy"
);
}
#[test]
fn duplicate_lines_down_then_undo_restores_the_buffer_in_one_step() {
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 1;
e.cursor_col = 0;
e.duplicate_lines_down();
assert_eq!(e.lines.len(), 4);
assert!(e.undo());
assert_eq!(e.lines, vec!["alpha", "beta", "gamma"]);
assert_eq!((e.cursor_row, e.cursor_col), (1, 0));
}
#[test]
fn duplicate_lines_up_at_first_row_inserts_the_copy_at_row_zero() {
let mut e = editor_with("alpha\nbeta");
e.cursor_row = 0;
e.cursor_col = 4;
e.duplicate_lines_up();
assert_eq!(e.lines, vec!["alpha", "alpha", "beta"]);
assert_eq!((e.cursor_row, e.cursor_col), (0, 4));
}
#[test]
fn goto_top_lands_on_row_zero_col_zero() {
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 2;
e.cursor_col = 4;
e.goto_top();
assert_eq!((e.cursor_row, e.cursor_col), (0, 0));
}
#[test]
fn goto_bottom_lands_on_last_row_col_zero() {
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 0;
e.cursor_col = 3;
e.goto_bottom();
assert_eq!((e.cursor_row, e.cursor_col), (2, 0));
}
#[test]
fn goto_line_uses_one_based_indexing_and_clamps_to_last_row() {
let mut e = editor_with("alpha\nbeta\ngamma");
e.goto_line(2);
assert_eq!((e.cursor_row, e.cursor_col), (1, 0));
e.goto_line(999);
assert_eq!((e.cursor_row, e.cursor_col), (2, 0));
e.goto_line(0);
assert_eq!((e.cursor_row, e.cursor_col), (0, 0));
}
#[test]
fn yank_lines_one_returns_current_line_with_trailing_newline() {
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 1;
let yanked = e.yank_lines(1);
assert_eq!(yanked, "beta\n");
assert_eq!(e.lines, vec!["alpha", "beta", "gamma"]);
}
#[test]
fn yank_lines_n_grabs_current_plus_below() {
let mut e = editor_with("alpha\nbeta\ngamma\ndelta");
e.cursor_row = 1;
let yanked = e.yank_lines(3);
assert_eq!(yanked, "beta\ngamma\ndelta\n");
}
#[test]
fn delete_lines_one_drops_current_row() {
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 1;
let yanked = e.delete_lines(1);
assert_eq!(yanked, "beta\n");
assert_eq!(e.lines, vec!["alpha", "gamma"]);
assert_eq!((e.cursor_row, e.cursor_col), (1, 0));
}
#[test]
fn delete_lines_n_clamps_at_end_of_buffer() {
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 1;
let yanked = e.delete_lines(99);
assert_eq!(yanked, "beta\ngamma\n");
assert_eq!(e.lines, vec!["alpha"]);
assert_eq!((e.cursor_row, e.cursor_col), (0, 0));
}
#[test]
fn delete_lines_leaves_an_empty_line_when_buffer_emptied() {
let mut e = editor_with("alpha\nbeta");
e.cursor_row = 0;
e.delete_lines(2);
assert_eq!(e.lines, vec![""]);
assert_eq!((e.cursor_row, e.cursor_col), (0, 0));
}
#[test]
fn delete_lines_is_undoable_in_one_step() {
let mut e = editor_with("alpha\nbeta\ngamma");
e.cursor_row = 1;
e.delete_lines(1);
assert!(e.undo());
assert_eq!(e.lines, vec!["alpha", "beta", "gamma"]);
assert_eq!((e.cursor_row, e.cursor_col), (1, 0));
}
#[test]
fn kill_to_bol_removes_head_of_current_line() {
let mut e = editor_with("hello world\nnext");
e.cursor_row = 0;
e.cursor_col = 6;
let killed = e.kill_to_bol();
assert_eq!(killed, "hello ");
assert_eq!(e.lines, vec!["world", "next"]);
assert_eq!((e.cursor_row, e.cursor_col), (0, 0));
}
#[test]
fn kill_to_bol_at_col_zero_is_noop() {
let mut e = editor_with("hello\nnext");
e.cursor_row = 0;
e.cursor_col = 0;
let killed = e.kill_to_bol();
assert_eq!(killed, "");
assert_eq!(e.lines, vec!["hello", "next"]);
}
#[test]
fn open_line_below_inserts_empty_line_after_current() {
let mut e = editor_with("alpha\nbeta");
e.cursor_row = 0;
e.cursor_col = 3;
e.open_line_below();
assert_eq!(e.lines, vec!["alpha", "", "beta"]);
assert_eq!((e.cursor_row, e.cursor_col), (1, 0));
}
#[test]
fn open_line_below_inherits_indent_from_current_row() {
let mut e = editor_with(" alpha\nbeta");
e.cursor_row = 0;
e.cursor_col = 6;
e.open_line_below();
assert_eq!(e.lines, vec![" alpha", " ", "beta"]);
assert_eq!((e.cursor_row, e.cursor_col), (1, 4));
}
#[test]
fn open_line_above_inserts_empty_line_before_current() {
let mut e = editor_with("alpha\nbeta");
e.cursor_row = 1;
e.cursor_col = 2;
e.open_line_above();
assert_eq!(e.lines, vec!["alpha", "", "beta"]);
assert_eq!((e.cursor_row, e.cursor_col), (1, 0));
}
#[test]
fn open_line_above_inherits_indent_from_current_row() {
let mut e = editor_with("alpha\n beta");
e.cursor_row = 1;
e.cursor_col = 10;
e.open_line_above();
assert_eq!(e.lines, vec!["alpha", " ", " beta"]);
assert_eq!((e.cursor_row, e.cursor_col), (1, 8));
}
#[test]
fn kill_to_eol_removes_tail_of_current_line() {
let mut e = editor_with("hello world\nnext");
e.cursor_row = 0;
e.cursor_col = 5;
let killed = e.kill_to_eol();
assert_eq!(killed, " world");
assert_eq!(e.lines, vec!["hello", "next"]);
assert_eq!((e.cursor_row, e.cursor_col), (0, 5));
}
#[test]
fn kill_to_eol_at_eol_is_noop() {
let mut e = editor_with("hello\nnext");
e.cursor_row = 0;
e.cursor_col = 5;
let killed = e.kill_to_eol();
assert_eq!(killed, "");
assert_eq!(e.lines, vec!["hello", "next"]);
}
#[test]
fn move_left_crosses_line_boundary() {
let mut e = editor_with("abc\ndef");
e.cursor_row = 1;
e.cursor_col = 0;
e.move_left();
assert_eq!(e.cursor_row, 0);
assert_eq!(e.cursor_col, 3);
}
#[test]
fn move_right_crosses_line_boundary() {
let mut e = editor_with("abc\ndef");
e.cursor_row = 0;
e.cursor_col = 3;
e.move_right();
assert_eq!(e.cursor_row, 1);
assert_eq!(e.cursor_col, 0);
}
#[test]
fn move_up_clamps_column() {
let mut e = editor_with("ab\nlongline");
e.cursor_row = 1;
e.cursor_col = 7;
e.move_up();
assert_eq!(e.cursor_row, 0);
assert_eq!(e.cursor_col, 2);
}
#[test]
fn home_and_end() {
let mut e = editor_with("hello world");
e.cursor_col = 5;
e.home_line();
assert_eq!(e.cursor_col, 0);
e.end_line();
assert_eq!(e.cursor_col, 11);
}
#[test]
fn open_reads_file_and_splits_lines() {
let mut tmp = NamedTempFile::new().unwrap();
writeln!(tmp, "alpha").unwrap();
writeln!(tmp, "beta").unwrap();
write!(tmp, "gamma").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert_eq!(
e.lines,
vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()]
);
assert_eq!(e.cursor_row, 0);
assert_eq!(e.cursor_col, 0);
assert!(!e.dirty);
}
#[test]
fn open_detects_crlf_and_save_preserves_it() {
use std::io::Read;
let mut tmp = NamedTempFile::new().unwrap();
tmp.write_all(b"alpha\r\nbeta\r\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert_eq!(e.eol, LineEnding::Crlf, "CRLF file detected");
assert_eq!(e.lines, vec!["alpha".to_string(), "beta".to_string()]);
e.save_to_disk().unwrap();
let mut raw = Vec::new();
std::fs::File::open(tmp.path())
.unwrap()
.read_to_end(&mut raw)
.unwrap();
assert_eq!(
raw, b"alpha\r\nbeta",
"save re-applies CRLF, no trailing EOL"
);
}
#[test]
fn open_defaults_to_lf_for_unix_files() {
let mut tmp = NamedTempFile::new().unwrap();
tmp.write_all(b"a\nb\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert_eq!(e.eol, LineEnding::Lf);
}
#[test]
fn reopen_with_encoding_decodes_windows_1252() {
use std::io::Write as _;
let mut tmp = NamedTempFile::new().unwrap();
tmp.write_all(&[b'c', b'a', b'f', 0xE9]).unwrap();
tmp.flush().unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert_ne!(e.lines[0], "café", "UTF-8 decode mangles the 0xE9 byte");
e.reopen_with_encoding(encoding_rs::WINDOWS_1252).unwrap();
assert_eq!(e.lines[0], "café", "Windows-1252 decodes 0xE9 as é");
assert_eq!(e.encoding, encoding_rs::WINDOWS_1252);
}
#[test]
fn a_reload_keeps_the_encoding_the_user_reopened_with() {
use std::io::Write as _;
let mut tmp = NamedTempFile::new().unwrap();
tmp.write_all(&[b'c', b'a', b'f', 0xE9]).unwrap();
tmp.flush().unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.reopen_with_encoding(encoding_rs::WINDOWS_1252).unwrap();
std::fs::write(tmp.path(), [b't', b'h', 0xE9]).unwrap();
e.reload_if_clean().unwrap().unwrap();
assert_eq!(
e.encoding,
encoding_rs::WINDOWS_1252,
"a same-path reload must keep the encoding the user chose"
);
assert_eq!(e.lines[0], "thé", "and decode the new bytes with it");
}
#[test]
fn a_utf16_file_survives_open_edit_save_open() {
let tmp = NamedTempFile::new().unwrap();
let mut bytes = vec![0xFF, 0xFE]; for u in "hi\nthere\n".encode_utf16() {
bytes.extend_from_slice(&u.to_le_bytes());
}
std::fs::write(tmp.path(), &bytes).unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert_eq!(e.encoding, encoding_rs::UTF_16LE, "opened as UTF-16LE");
assert_eq!(e.lines[0], "hi");
assert_eq!(e.lines[1], "there");
e.cursor_col = 2;
e.insert_char('!');
e.save_to_disk().unwrap();
let out = std::fs::read(tmp.path()).unwrap();
assert_eq!(&out[..2], &[0xFF, 0xFE], "the BOM must survive");
let mut e2 = Editor::new();
e2.open(tmp.path())
.expect("croft must be able to reopen what it just wrote");
assert_eq!(e2.encoding, encoding_rs::UTF_16LE);
assert_eq!(e2.lines[0], "hi!", "the edit round-tripped");
assert_eq!(e2.lines[1], "there");
}
#[test]
fn saving_as_utf16_always_writes_a_bom() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "plain\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert!(!e.bom, "the source file had no BOM");
e.encoding = encoding_rs::UTF_16BE;
e.dirty = true;
e.save_to_disk().unwrap();
let out = std::fs::read(tmp.path()).unwrap();
assert_eq!(&out[..2], &[0xFE, 0xFF], "UTF-16BE BOM written anyway");
let mut e2 = Editor::new();
e2.open(tmp.path()).expect("and it reopens");
assert_eq!(e2.lines[0], "plain");
}
#[test]
fn saving_keeps_a_utf8_bom() {
let tmp = NamedTempFile::new().unwrap();
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(b"hi\n");
std::fs::write(tmp.path(), &bytes).unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert_eq!(e.lines[0], "hi");
e.cursor_col = 2;
e.insert_char('!');
e.save_to_disk().unwrap();
let out = std::fs::read(tmp.path()).unwrap();
assert_eq!(&out[..3], &[0xEF, 0xBB, 0xBF], "the UTF-8 BOM must survive");
assert_eq!(&out[3..6], b"hi!");
}
#[test]
fn set_language_updates_the_label() {
let mut e = editor_with("x = 1");
e.set_language(Some(crate::highlight::LangKind::Python));
assert_eq!(e.language_label(), "Python");
e.set_language(None);
assert_eq!(e.language_label(), "Plain Text");
}
#[test]
fn open_splits_on_lone_cr_to_match_lsp_line_numbering() {
let mut tmp = NamedTempFile::new().unwrap();
write!(tmp, "a\n\rb\r\nc").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert_eq!(
e.lines,
vec![
"a".to_string(),
String::new(),
"b".to_string(),
"c".to_string()
],
"lone CR and CRLF must each split a line, matching the LSP"
);
}
#[test]
fn open_png_populates_image_view_and_skips_text_buffer() {
let img: image::RgbaImage = image::ImageBuffer::from_pixel(1, 1, image::Rgba([0, 0, 0, 0]));
let mut buf: Vec<u8> = Vec::new();
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("pic.png");
std::fs::write(&path, &buf).unwrap();
let mut e = Editor::new();
e.open(&path).unwrap();
let img = e.image.as_ref().expect("image-mode tab");
assert_eq!(img.pixel_w, 1);
assert_eq!(img.pixel_h, 1);
assert_eq!(img.format_label, "PNG");
assert_eq!(e.lines, vec![String::new()]);
assert!(e.path.is_some());
assert!(e.lang.is_none());
assert!(!e.dirty);
}
#[test]
fn a_reloaded_image_carries_a_fresh_generation() {
let img: image::RgbaImage = image::ImageBuffer::from_pixel(1, 1, image::Rgba([0, 0, 0, 0]));
let mut buf: Vec<u8> = Vec::new();
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("pic.png");
std::fs::write(&path, &buf).unwrap();
let mut e = Editor::new();
e.open(&path).unwrap();
let first = e.image.as_ref().unwrap().generation;
e.open(&path).unwrap();
let second = e.image.as_ref().unwrap().generation;
assert_ne!(
first, second,
"a reload must stamp fresh content, or the baked overlay stays stale"
);
}
#[test]
fn dragging_the_scrollbar_of_a_file_with_a_comment_box_scrolls() {
let mut e = editor_with("a\nb\nc\nd\ne");
e.comment_boxes.push(CommentBox {
id: 1,
line: 1,
author: String::from("navigator"),
body: (0..20)
.map(|i| format!("line {i}"))
.collect::<Vec<_>>()
.join("\n"),
});
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e as &mut Editor).render(area, &mut buf);
assert!(
e.last_scrollbar.width > 0,
"the box overflows the viewport, so a bar must be drawn"
);
assert!(
e.scroll_to_bar_y(e.last_scrollbar.y + e.last_scrollbar.height / 2),
"a drag on the drawn bar must scroll, not be refused as no-overflow"
);
}
#[test]
fn end_with_an_unknown_page_count_reports_instead_of_rendering_the_sentinel() {
let mut e = Editor::new();
e.image = Some(ImageView {
bytes: Vec::new(),
format_label: String::from("PDF"),
pixel_w: 1,
pixel_h: 1,
byte_size: 0,
generation: 0,
pdf: Some(PdfState {
source_path: PathBuf::from("/nonexistent/doc.pdf"),
current_page: 1,
page_count: None,
backend: crate::pdf::PdfBackend::SipsCli,
source_byte_size: 0,
links: None,
}),
});
assert!(!e.set_pdf_page(u32::MAX));
assert!(
!e.status.contains("4294967295"),
"the sentinel page must not leak into the status: {}",
e.status
);
assert_eq!(e.pdf_page(), Some(1), "the page must not move");
}
#[test]
fn extension_is_image_recognises_common_formats() {
for ext in ["png", "PNG", "jpg", "jpeg", "JPEG", "gif", "bmp", "webp"] {
assert!(extension_is_image(ext), "should recognise: {ext}");
}
for ext in ["txt", "rs", "md", "py", ""] {
assert!(!extension_is_image(ext), "should not recognise: {ext}");
}
}
#[test]
fn open_unrecognised_file_after_image_clears_image_view() {
let img: image::RgbaImage = image::ImageBuffer::from_pixel(1, 1, image::Rgba([0, 0, 0, 0]));
let mut buf: Vec<u8> = Vec::new();
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
let dir = tempfile::tempdir().unwrap();
let img_path = dir.path().join("pic.png");
std::fs::write(&img_path, &buf).unwrap();
let txt_path = dir.path().join("hi.txt");
std::fs::write(&txt_path, "hi\n").unwrap();
let mut e = Editor::new();
e.open(&img_path).unwrap();
assert!(e.image.is_some());
e.open(&txt_path).unwrap();
assert!(e.image.is_none());
assert_eq!(e.lines, vec!["hi".to_string()]);
}
#[test]
fn open_routes_binary_files_to_hex_not_text() {
let mut tmp = NamedTempFile::new().unwrap();
tmp.write_all(b"\x00\x01\x02binary garbage").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert!(e.hex.is_some(), "binary routes to hex");
assert!(!e.dirty);
assert_eq!(e.lines, vec![String::new()], "text path untouched");
}
#[test]
fn matches_open_path_handles_canonical_difference() {
let mut tmp = NamedTempFile::new().unwrap();
writeln!(tmp, "x").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert!(e.matches_open_path(tmp.path()));
let bogus = std::path::Path::new("/definitely/not/the/same/path.txt");
assert!(!e.matches_open_path(bogus));
}
#[test]
fn reload_if_clean_picks_up_external_changes() {
let mut tmp = NamedTempFile::new().unwrap();
writeln!(tmp, "def hello():").unwrap();
writeln!(tmp, " print(\"hi\")").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert!(e.lines[0].contains("hello"));
std::fs::write(tmp.path(), "def hi():\n print(\"hi\")\n").unwrap();
let outcome = e.reload_if_clean();
assert!(matches!(outcome, Some(Ok(()))));
assert_eq!(e.lines[0], "def hi():");
assert!(!e.dirty);
}
#[test]
fn external_reload_bumps_edit_seq_and_drops_stale_semantic_overlay() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "def hello():\n pass\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
let seq_before = e.edit_seq;
let legend = std::sync::Arc::new(vec![String::from("function")]);
e.apply_semantic_tokens(tmp.path().to_path_buf(), vec![0, 4, 5, 0, 0], legend, true);
assert!(e.semantic_overlay_for_test().iter().any(|l| !l.is_empty()));
std::fs::write(tmp.path(), "x = 1\n").unwrap();
assert!(matches!(
e.reload_or_flag_conflict(),
ExternalChange::Reloaded
));
assert_ne!(e.edit_seq, seq_before);
assert!(e.semantic_overlay_for_test().iter().all(|l| l.is_empty()));
}
#[test]
fn reload_if_clean_refuses_when_dirty() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "original\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.insert_str("local edit");
assert!(e.dirty);
std::fs::write(tmp.path(), "external change\n").unwrap();
let outcome = e.reload_if_clean();
assert!(
outcome.is_none(),
"should refuse to reload over dirty buffer"
);
assert!(e.lines[0].contains("local edit"));
}
#[test]
fn save_round_trips_content() {
let tmp = NamedTempFile::new().unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.insert_str("hello\nworld");
assert!(e.dirty);
e.save_to_disk().unwrap();
assert!(!e.dirty);
let written = std::fs::read_to_string(tmp.path()).unwrap();
assert_eq!(written, "hello\nworld");
}
#[test]
fn dirty_flag_lifecycle() {
let mut e = editor_with("abc");
assert!(!e.dirty);
e.insert_char('z');
assert!(e.dirty);
}
#[test]
fn switching_a_preview_tab_to_an_image_drops_the_stale_conflict_cache() {
let tmp = tempfile::tempdir().unwrap();
let mut e = Editor::new();
e.lines = vec![
"<<<<<<< HEAD".to_string(),
"ours".to_string(),
"=======".to_string(),
"theirs".to_string(),
">>>>>>> branch".to_string(),
];
e.mark_buffer_changed();
assert_eq!(e.conflicts().len(), 1, "the conflict parses");
let png = tmp.path().join("p.png");
image::RgbaImage::new(1, 1).save(&png).unwrap();
e.open_image(&png).unwrap();
assert!(
e.conflicts().is_empty(),
"an image tab has no merge conflicts; a stale cache here is a panic waiting in resolution_lines"
);
}
#[test]
fn undo_past_a_save_re_dirties_the_buffer() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "hello\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.insert_char('x');
assert!(matches!(e.save_to_disk(), Ok(SaveOutcome::Saved)));
assert!(!e.dirty);
assert!(e.undo());
assert!(
e.dirty,
"the undone buffer no longer matches disk and must say so"
);
}
#[test]
fn a_save_breaks_insert_coalescing() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.insert_char('x');
assert!(matches!(e.save_to_disk(), Ok(SaveOutcome::Saved)));
e.insert_char('y');
assert!(e.undo());
assert_eq!(
e.lines[0], "x",
"undo steps back to the save point, not past it"
);
}
#[test]
fn a_replacement_carriage_return_does_not_survive_in_a_line() {
let mut e = Editor::new();
e.lines = vec!["abc".to_string()];
e.replace_find_match(0, 1, 1, "x\r\ny");
assert_eq!(e.lines, vec!["ax".to_string(), "yc".to_string()]);
assert!(e.lines.iter().all(|l| !l.contains('\r')));
}
#[test]
fn a_multi_line_replacement_splices_into_separate_lines() {
let mut e = Editor::new();
e.lines = vec!["abc".to_string()];
e.replace_find_match(0, 1, 1, "x\ny");
assert_eq!(e.lines, vec!["ax".to_string(), "yc".to_string()]);
assert_eq!(
(e.cursor_row, e.cursor_col),
(1, 1),
"caret after the inserted text"
);
}
#[test]
fn an_external_reload_moves_the_edit_seq_past_an_in_flight_token_request() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "fn a() {}\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.apply_semantic_tokens(
tmp.path().to_path_buf(),
vec![0, 0, 2, 0, 0],
std::sync::Arc::new(vec!["keyword".to_string()]),
true,
);
let in_flight = e.edit_seq;
std::fs::write(tmp.path(), "fn bbbb() {}\nfn c() {}\n").unwrap();
e.reload_from_disk().unwrap();
assert_ne!(
e.edit_seq, in_flight,
"a reload must invalidate every in-flight token request"
);
assert!(
e.semantic_data.is_empty(),
"and drop the batch measured against the old text"
);
}
#[test]
fn an_external_reload_of_the_same_file_keeps_its_folds() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "def f():\n a\n b\ntail\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.toggle_fold(0);
assert!(e.is_line_hidden(1), "the block starts collapsed");
std::fs::write(tmp.path(), "def f():\n A\n B\ntail\n").unwrap();
let newer = std::time::SystemTime::now() + std::time::Duration::from_secs(2);
std::fs::OpenOptions::new()
.write(true)
.open(tmp.path())
.unwrap()
.set_modified(newer)
.unwrap();
assert_eq!(e.reload_or_flag_conflict(), ExternalChange::Reloaded);
assert_eq!(e.lines[1], " A", "the reload landed");
assert!(
e.is_line_hidden(1),
"the fold must survive a reload of the file it was set on"
);
}
#[test]
fn a_same_path_reload_remeasures_the_fold_spans() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "def f():\n a\n b\ntail\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.toggle_fold(0);
assert!(e.is_line_hidden(1), "the block starts collapsed");
std::fs::write(tmp.path(), "def f():\na \nb \ntail\n").unwrap();
let newer = std::time::SystemTime::now() + std::time::Duration::from_secs(2);
std::fs::OpenOptions::new()
.write(true)
.open(tmp.path())
.unwrap()
.set_modified(newer)
.unwrap();
assert_eq!(e.reload_or_flag_conflict(), ExternalChange::Reloaded);
assert_eq!(e.lines[1], "a ", "the reload landed");
assert!(
!e.is_line_hidden(1),
"a line the fold no longer covers must not stay hidden"
);
}
#[test]
fn reload_or_flag_conflict_reloads_clean_buffer() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "old\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
std::fs::write(tmp.path(), "new content here\n").unwrap();
assert_eq!(e.reload_or_flag_conflict(), ExternalChange::Reloaded);
assert_eq!(e.lines[0], "new content here");
assert!(!e.disk_conflict);
assert_eq!(e.reload_or_flag_conflict(), ExternalChange::Unchanged);
}
#[test]
fn reload_or_flag_conflict_flags_dirty_buffer_without_clobbering() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "original\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.insert_str("my unsaved edit");
std::fs::write(tmp.path(), "external change\n").unwrap();
assert_eq!(e.reload_or_flag_conflict(), ExternalChange::Conflict);
assert!(
e.lines[0].contains("my unsaved edit"),
"dirty buffer must NOT be reloaded over"
);
assert!(e.disk_conflict);
}
#[test]
fn reload_or_flag_conflict_fires_once_then_stays_quiet() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "original\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.insert_str("my unsaved edit");
std::fs::write(tmp.path(), "external change\n").unwrap();
assert_eq!(e.reload_or_flag_conflict(), ExternalChange::Conflict);
assert_eq!(e.reload_or_flag_conflict(), ExternalChange::Unchanged);
assert!(e.disk_conflict);
}
#[test]
fn revert_paths_to_disk_discards_edits_and_reloads() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "original\n").unwrap();
let mut tabs = EditorTabs::new();
tabs.open_pinned(tmp.path()).unwrap();
tabs.insert_str("my unsaved edit"); std::fs::write(tmp.path(), "external change\n").unwrap();
let reverted = tabs.revert_paths_to_disk(&[tmp.path().to_path_buf()]);
assert_eq!(reverted, vec![tmp.path().to_path_buf()]);
assert_eq!(tabs.lines[0], "external change");
assert!(!tabs.dirty);
assert!(!tabs.disk_conflict);
}
#[test]
fn reload_or_flag_conflict_unchanged_when_disk_matches() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "stable\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
assert_eq!(e.reload_or_flag_conflict(), ExternalChange::Unchanged);
}
#[test]
fn save_refuses_to_clobber_external_change_then_force_overwrites() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "original\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.insert_str("local");
std::fs::write(tmp.path(), "theirs\n").unwrap();
assert_eq!(e.save_to_disk().unwrap(), SaveOutcome::DiskConflict);
assert_eq!(
std::fs::read_to_string(tmp.path()).unwrap(),
"theirs\n",
"a guarded save must NOT clobber the external change"
);
assert!(e.disk_conflict);
e.save_to_disk_force().unwrap();
assert!(
std::fs::read_to_string(tmp.path())
.unwrap()
.contains("local")
);
assert!(!e.disk_conflict);
}
#[test]
fn saving_text_the_encoding_cannot_represent_is_refused_not_silently_mangled() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "cafe\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.reopen_with_encoding(encoding_rs::WINDOWS_1252).unwrap();
e.lines = vec![String::from("日本語 costs 5€")];
e.dirty = true;
assert_eq!(e.save_to_disk().unwrap(), SaveOutcome::EncodingLoss);
assert_eq!(
std::fs::read_to_string(tmp.path()).unwrap(),
"cafe\n",
"a refused save must leave the file untouched"
);
assert!(e.encoding_loss, "the refusal latches so auto save skips it");
assert_eq!(e.unmappable_chars(), vec!['日', '本', '語']);
e.lossy_save_armed = true;
assert_eq!(e.save_to_disk().unwrap(), SaveOutcome::Saved);
assert_eq!(
std::fs::read(tmp.path()).unwrap(),
b"日本語 costs 5\x80",
"consent writes encoding_rs' references, and € as the 0x80 byte"
);
assert!(!e.encoding_loss);
assert!(!e.lossy_save_armed, "consent is one-shot");
}
#[test]
fn a_representable_buffer_saves_without_a_prompt() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "cafe\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.reopen_with_encoding(encoding_rs::WINDOWS_1252).unwrap();
e.lines = vec![String::from("café")];
assert_eq!(e.save_to_disk().unwrap(), SaveOutcome::Saved);
assert_eq!(std::fs::read(tmp.path()).unwrap(), b"caf\xE9");
assert!(e.unmappable_chars().is_empty());
let mut u = Editor::new();
u.open(tmp.path()).unwrap();
u.lines = vec![String::from("日本語")];
assert_eq!(u.encoding, encoding_rs::UTF_8);
assert_eq!(u.save_to_disk().unwrap(), SaveOutcome::Saved);
assert!(u.unmappable_chars().is_empty());
}
#[test]
fn reopening_with_another_encoding_clears_the_encoding_loss_latch() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "日本語").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.encoding = encoding_rs::WINDOWS_1252;
assert_eq!(e.save_to_disk().unwrap(), SaveOutcome::EncodingLoss);
assert!(e.encoding_loss);
e.reopen_with_encoding(encoding_rs::UTF_8).unwrap();
assert!(!e.encoding_loss);
assert_eq!(e.save_to_disk().unwrap(), SaveOutcome::Saved);
}
#[test]
fn an_edit_after_a_lossy_refusal_revokes_the_armed_consent() {
let tmp = NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "cafe\n").unwrap();
let mut e = Editor::new();
e.open(tmp.path()).unwrap();
e.reopen_with_encoding(encoding_rs::WINDOWS_1252).unwrap();
e.lines = vec![String::from("日")];
e.dirty = true;
assert_eq!(e.save_to_disk().unwrap(), SaveOutcome::EncodingLoss);
e.lossy_save_armed = true; e.insert_char('本'); assert!(!e.lossy_save_armed, "an edit revokes the stale consent");
assert!(
!e.encoding_loss,
"the latch clears too, so a fixed-up buffer resumes auto save"
);
assert_eq!(
e.save_to_disk().unwrap(),
SaveOutcome::EncodingLoss,
"the next save must prompt again for the changed buffer"
);
assert_eq!(std::fs::read_to_string(tmp.path()).unwrap(), "cafe\n");
}
#[test]
fn a_failed_external_reload_is_reported_not_swallowed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("f.txt");
std::fs::write(&path, "one\n").unwrap();
let mut tabs = EditorTabs::new();
tabs.open_pinned(&path).unwrap();
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
let report = tabs.reload_externally_changed_tabs(&|_| false);
assert_eq!(
report.failed,
vec![path.clone()],
"the failure must surface in the report"
);
assert!(!report.is_empty(), "a failed reload is not an empty sweep");
assert_eq!(
tabs.iter_tabs().next().unwrap().lines[0],
"one",
"the last good buffer survives the failed reload"
);
}
#[test]
fn reload_externally_changed_tabs_reloads_background_tab() {
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join("a.txt");
let b = dir.path().join("b.txt");
std::fs::write(&a, "a old\n").unwrap();
std::fs::write(&b, "b old\n").unwrap();
let mut tabs = EditorTabs::new();
tabs.open_pinned(&a).unwrap(); tabs.open_pinned(&b).unwrap(); std::fs::write(&a, "a NEW\n").unwrap();
let bumped = std::time::SystemTime::now() + std::time::Duration::from_secs(2);
std::fs::OpenOptions::new()
.write(true)
.open(&a)
.unwrap()
.set_modified(bumped)
.unwrap();
let report = tabs.reload_externally_changed_tabs(&|_| false);
assert_eq!(report.reloaded, vec![a.clone()]);
assert!(report.conflicts.is_empty());
std::fs::write(&b, "b NEW\n").unwrap();
std::fs::OpenOptions::new()
.write(true)
.open(&b)
.unwrap()
.set_modified(bumped)
.unwrap();
let report = tabs.reload_externally_changed_tabs(&|p| p == b.as_path());
assert!(report.reloaded.is_empty());
let b_tab = tabs
.iter_tabs()
.find(|e| e.path.as_deref() == Some(b.as_path()))
.unwrap();
assert_eq!(b_tab.lines[0], "b old");
let a_tab = tabs
.iter_tabs()
.find(|e| e.path.as_deref() == Some(a.as_path()))
.unwrap();
assert_eq!(a_tab.lines[0], "a NEW");
}
#[test]
fn open_pdf_tab_keeps_last_good_page_through_a_mid_write_sweep() {
if crate::pdf::detect_backend().is_none() {
eprintln!("skipping: no PDF rasteriser installed");
return;
}
let one_page_pdf = concat!(
"%PDF-1.4\n",
"1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n",
"2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n",
"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 4 0 R>>endobj\n",
"4 0 obj<</Length 27>>stream\n0 0 1 rg 10 10 100 100 re f\nendstream endobj\n",
"trailer<</Root 1 0 R/Size 5>>\n%%EOF\n",
);
let bump_mtime = |path: &Path, secs: u64| {
let newer = std::time::SystemTime::now() + std::time::Duration::from_secs(secs);
std::fs::OpenOptions::new()
.write(true)
.open(path)
.unwrap()
.set_modified(newer)
.unwrap();
};
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("presentation.pdf");
std::fs::write(&path, one_page_pdf).unwrap();
let mut tabs = EditorTabs::new();
tabs.open_pinned(&path).unwrap();
let good_bytes = {
let tab = tabs.iter_tabs().next().unwrap();
tab.image
.as_ref()
.expect("PDF tab renders a page")
.bytes
.clone()
};
std::fs::write(&path, b"%PDF-1.7\ntruncated mid-write, no xref").unwrap();
bump_mtime(&path, 2);
let report = tabs.reload_externally_changed_tabs(&|_| false);
assert!(
report.reloaded.is_empty(),
"a failed render is not a reload"
);
assert!(
report.conflicts.is_empty(),
"a clean tab is never a conflict"
);
let tab = tabs.iter_tabs().next().unwrap();
assert_eq!(
tab.image
.as_ref()
.expect("last good page must survive")
.bytes,
good_bytes,
"mid-write failure must keep showing the last good render"
);
std::fs::write(&path, one_page_pdf).unwrap();
bump_mtime(&path, 4);
let report = tabs.reload_externally_changed_tabs(&|_| false);
assert_eq!(report.reloaded, vec![path.clone()]);
let tab = tabs.iter_tabs().next().unwrap();
assert!(tab.image.is_some(), "completed write renders again");
}
#[test]
fn pdf_reload_keeps_the_current_page() {
if crate::pdf::detect_backend().is_none() {
eprintln!("skipping: no PDF rasteriser installed");
return;
}
let two_page_pdf = concat!(
"%PDF-1.4\n",
"1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n",
"2 0 obj<</Type/Pages/Kids[3 0 R 5 0 R]/Count 2>>endobj\n",
"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 4 0 R>>endobj\n",
"4 0 obj<</Length 27>>stream\n0 0 1 rg 10 10 100 100 re f\nendstream endobj\n",
"5 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 6 0 R>>endobj\n",
"6 0 obj<</Length 27>>stream\n1 0 0 rg 10 10 100 100 re f\nendstream endobj\n",
"trailer<</Root 1 0 R/Size 7>>\n%%EOF\n",
);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("deck.pdf");
std::fs::write(&path, two_page_pdf).unwrap();
let mut tabs = EditorTabs::new();
tabs.open_pinned(&path).unwrap();
assert!(tabs.change_pdf_page(1), "two pages, so page 2 renders");
assert_eq!(tabs.pdf_page(), Some(2));
std::fs::write(&path, two_page_pdf).unwrap();
let newer = std::time::SystemTime::now() + std::time::Duration::from_secs(2);
std::fs::OpenOptions::new()
.write(true)
.open(&path)
.unwrap()
.set_modified(newer)
.unwrap();
let report = tabs.reload_externally_changed_tabs(&|_| false);
assert_eq!(report.reloaded, vec![path.clone()]);
assert_eq!(
tabs.pdf_page(),
Some(2),
"an external rebuild must not move the reader back to page 1; status: {:?}",
tabs.iter_tabs().next().unwrap().status
);
}
#[test]
fn a_transient_page_render_failure_during_reload_keeps_the_readers_place() {
if crate::pdf::detect_backend().is_none() {
eprintln!("skipping: no PDF rasteriser installed");
return;
}
let two_page_pdf = concat!(
"%PDF-1.4\n",
"1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n",
"2 0 obj<</Type/Pages/Kids[3 0 R 5 0 R]/Count 2>>endobj\n",
"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 4 0 R>>endobj\n",
"4 0 obj<</Length 27>>stream\n0 0 1 rg 10 10 100 100 re f\nendstream endobj\n",
"5 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 6 0 R>>endobj\n",
"6 0 obj<</Length 27>>stream\n1 0 0 rg 10 10 100 100 re f\nendstream endobj\n",
"trailer<</Root 1 0 R/Size 7>>\n%%EOF\n",
);
let bump_mtime = |path: &Path, secs: u64| {
let newer = std::time::SystemTime::now() + std::time::Duration::from_secs(secs);
std::fs::OpenOptions::new()
.write(true)
.open(path)
.unwrap()
.set_modified(newer)
.unwrap();
};
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("deck.pdf");
std::fs::write(&path, two_page_pdf).unwrap();
let mut tabs = EditorTabs::new();
tabs.open_pinned(&path).unwrap();
assert!(tabs.change_pdf_page(1), "two pages, so page 2 renders");
let good_bytes = tabs
.iter_tabs()
.next()
.unwrap()
.image
.as_ref()
.unwrap()
.bytes
.clone();
std::fs::write(&path, two_page_pdf).unwrap();
bump_mtime(&path, 2);
*crate::pdf::FAIL_RASTERIZE_ONCE_FOR_TEST.lock().unwrap() = Some((path.clone(), 2));
let report = tabs.reload_externally_changed_tabs(&|_| false);
assert!(
report.reloaded.is_empty(),
"a reload that cannot restore the reader's page is a failed \
reload, not a successful one that lost their place"
);
assert_eq!(
tabs.pdf_page(),
Some(2),
"a transient render failure must not snap the reader to page 1; status: {:?}",
tabs.iter_tabs().next().unwrap().status
);
assert_eq!(
tabs.iter_tabs()
.next()
.unwrap()
.image
.as_ref()
.unwrap()
.bytes,
good_bytes,
"the last good render survives the transient failure"
);
bump_mtime(&path, 4);
let report = tabs.reload_externally_changed_tabs(&|_| false);
assert_eq!(report.reloaded, vec![path.clone()]);
assert_eq!(
tabs.pdf_page(),
Some(2),
"recovery re-renders the reader's page"
);
}
#[test]
fn insert_str_inserts_newlines() {
let mut e = editor_with("");
e.insert_str("a\nb\nc");
assert_eq!(
e.lines,
vec!["a".to_string(), "b".to_string(), "c".to_string()]
);
assert_eq!(e.cursor_row, 2);
assert_eq!(e.cursor_col, 1);
}
#[test]
fn build_line_spans_no_highlights() {
let spans = build_line_spans("hello", &[]);
assert_eq!(spans.len(), 1);
}
fn chars(s: &str) -> Vec<char> {
s.chars().collect()
}
#[test]
fn wrap_segments_short_line_is_one_segment() {
assert_eq!(wrap_segments(&chars("hello"), 20), vec![(0, 5)]);
assert_eq!(wrap_segments(&chars(""), 20), vec![(0, 0)]);
assert_eq!(wrap_segments(&chars("abc"), 0), vec![(0, 3)]);
}
#[test]
fn wrap_segments_breaks_after_a_space() {
let segs = wrap_segments(&chars("the quick brown"), 10);
assert_eq!(segs, vec![(0, 10), (10, 15)]);
}
#[test]
fn wrap_segments_hard_breaks_a_too_long_word() {
let segs = wrap_segments(&chars("abcdefghij"), 6);
assert_eq!(segs, vec![(0, 6), (6, 10)]);
}
#[test]
fn wrap_segments_breaks_after_punctuation_like_vscode() {
let segs = wrap_segments(&chars("abc/defgh"), 6);
assert_eq!(segs, vec![(0, 4), (4, 9)]);
}
#[test]
fn wrap_segments_tile_the_line_without_gaps() {
let line = "alpha beta gamma delta epsilon zeta eta theta";
let segs = wrap_segments(&chars(line), 12);
assert_eq!(segs.first().unwrap().0, 0);
assert_eq!(segs.last().unwrap().1, line.chars().count());
for pair in segs.windows(2) {
assert_eq!(pair[0].1, pair[1].0, "segments must be contiguous");
}
}
#[test]
fn build_line_spans_full_line_highlighted() {
let hi = vec![HiSpan {
start: 0,
end: 5,
style: Style::default(),
}];
let spans = build_line_spans("hello", &hi);
assert_eq!(spans.len(), 1);
}
#[test]
fn build_line_spans_partial_highlights() {
let hi = vec![HiSpan {
start: 1,
end: 3,
style: Style::default(),
}];
let spans = build_line_spans("abcde", &hi);
assert_eq!(spans.len(), 3);
}
#[test]
fn merge_overlay_semantic_wins_and_base_fills_gaps() {
use ratatui::style::Color;
let base_style = Style::default().fg(Color::Rgb(1, 1, 1));
let over_style = Style::default().fg(Color::Rgb(2, 2, 2));
let base = vec![HiSpan {
start: 0,
end: 10,
style: base_style,
}];
let over = vec![HiSpan {
start: 3,
end: 6,
style: over_style,
}];
let merged = merge_overlay(&base, &over);
assert_eq!(merged.len(), 3);
assert_eq!((merged[0].start, merged[0].end), (0, 3));
assert_eq!(merged[0].style.fg, Some(Color::Rgb(1, 1, 1)));
assert_eq!((merged[1].start, merged[1].end), (3, 6));
assert_eq!(
merged[1].style.fg,
Some(Color::Rgb(2, 2, 2)),
"overlay must win over base where they overlap"
);
assert_eq!((merged[2].start, merged[2].end), (6, 10));
assert_eq!(merged[2].style.fg, Some(Color::Rgb(1, 1, 1)));
}
#[test]
fn merge_overlay_empty_overlay_returns_base() {
let base = vec![HiSpan {
start: 0,
end: 4,
style: Style::default(),
}];
assert_eq!(merge_overlay(&base, &[]).len(), 1);
}
#[test]
fn editor_selection_normalised_handles_anchor_after_head() {
let s = EditorSelection {
anchor: (5, 4),
head: (2, 1),
};
assert_eq!(s.normalised(), ((2, 1), (5, 4)));
}
#[test]
fn editor_selection_normalised_handles_same_row() {
let s = EditorSelection {
anchor: (3, 9),
head: (3, 2),
};
assert_eq!(s.normalised(), ((3, 2), (3, 9)));
}
#[test]
fn editor_selection_has_area_only_when_endpoints_differ() {
let s = EditorSelection::new(2, 5);
assert!(!s.has_area());
let s2 = EditorSelection {
anchor: (2, 5),
head: (2, 6),
};
assert!(s2.has_area());
}
#[test]
fn start_selection_at_cursor_creates_zero_area_selection() {
let mut e = editor_with("hello");
e.cursor_row = 0;
e.cursor_col = 2;
e.start_selection_at_cursor();
let sel = e.selection.expect("selection should exist");
assert_eq!(sel.anchor, (0, 2));
assert_eq!(sel.head, (0, 2));
assert!(!sel.has_area());
}
#[test]
fn extend_selection_to_cursor_updates_head_only() {
let mut e = editor_with("abcdef");
e.cursor_col = 1;
e.start_selection_at_cursor();
e.cursor_col = 4;
e.extend_selection_to_cursor();
let sel = e.selection.unwrap();
assert_eq!(sel.anchor, (0, 1));
assert_eq!(sel.head, (0, 4));
assert!(sel.has_area());
}
#[test]
fn selection_text_single_line() {
let mut e = editor_with("hello world");
e.cursor_col = 6;
e.start_selection_at_cursor();
e.cursor_col = 11;
e.extend_selection_to_cursor();
assert_eq!(e.selection_text(), "world");
}
#[test]
fn selection_text_handles_reversed_endpoints() {
let mut e = editor_with("hello world");
e.cursor_col = 11;
e.start_selection_at_cursor();
e.cursor_col = 6;
e.extend_selection_to_cursor();
assert_eq!(e.selection_text(), "world");
}
#[test]
fn selection_text_multi_line_includes_newlines() {
let mut e = editor_with("first line\nsecond line\nthird");
e.cursor_row = 0;
e.cursor_col = 6;
e.start_selection_at_cursor();
e.cursor_row = 1;
e.cursor_col = 6;
e.extend_selection_to_cursor();
assert_eq!(e.selection_text(), "line\nsecond");
}
#[test]
fn selection_text_multibyte_chars() {
let mut e = editor_with("héllo");
e.cursor_col = 1;
e.start_selection_at_cursor();
e.cursor_col = 3;
e.extend_selection_to_cursor();
assert_eq!(e.selection_text(), "él");
}
#[test]
fn clear_selection_removes_it() {
let mut e = editor_with("abc");
e.start_selection_at_cursor();
assert!(e.selection.is_some());
e.clear_selection();
assert!(e.selection.is_none());
}
#[test]
fn delete_selection_removes_range_within_one_line() {
let mut e = editor_with("hello world");
e.cursor_col = 5;
e.start_selection_at_cursor();
e.cursor_col = 11;
e.extend_selection_to_cursor();
assert!(e.delete_selection());
assert_eq!(e.lines, vec!["hello".to_string()]);
assert_eq!(e.cursor_row, 0);
assert_eq!(e.cursor_col, 5);
assert!(e.selection.is_none());
assert!(e.dirty);
}
#[test]
fn delete_selection_collapses_multiple_lines() {
let mut e = editor_with("first\nsecond\nthird");
e.cursor_row = 0;
e.cursor_col = 2;
e.start_selection_at_cursor();
e.cursor_row = 2;
e.cursor_col = 2;
e.extend_selection_to_cursor();
assert!(e.delete_selection());
assert_eq!(e.lines, vec!["fiird".to_string()]);
assert_eq!(e.cursor_row, 0);
assert_eq!(e.cursor_col, 2);
}
#[test]
fn delete_selection_returns_false_when_no_selection() {
let mut e = editor_with("abc");
assert!(!e.delete_selection());
assert_eq!(e.lines, vec!["abc".to_string()]);
}
#[test]
fn delete_selection_returns_false_when_zero_area() {
let mut e = editor_with("abc");
e.cursor_col = 1;
e.start_selection_at_cursor();
assert!(!e.delete_selection());
assert_eq!(e.lines, vec!["abc".to_string()]);
}
#[test]
fn insert_char_replaces_selection_when_active() {
let mut e = editor_with("hello world");
e.cursor_col = 6;
e.start_selection_at_cursor();
e.cursor_col = 11;
e.extend_selection_to_cursor();
e.insert_char('X');
assert_eq!(e.lines, vec!["hello X".to_string()]);
assert_eq!(e.cursor_col, 7);
assert!(e.selection.is_none());
}
#[test]
fn backspace_deletes_selection_when_active() {
let mut e = editor_with("hello world");
e.cursor_col = 6;
e.start_selection_at_cursor();
e.cursor_col = 11;
e.extend_selection_to_cursor();
e.backspace();
assert_eq!(e.lines, vec!["hello ".to_string()]);
assert!(e.selection.is_none());
}
#[test]
fn delete_forward_deletes_selection_when_active() {
let mut e = editor_with("hello world");
e.cursor_col = 6;
e.start_selection_at_cursor();
e.cursor_col = 11;
e.extend_selection_to_cursor();
e.delete_forward();
assert_eq!(e.lines, vec!["hello ".to_string()]);
assert!(e.selection.is_none());
}
#[test]
fn insert_str_replaces_selection_when_active() {
let mut e = editor_with("hello world");
e.cursor_col = 6;
e.start_selection_at_cursor();
e.cursor_col = 11;
e.extend_selection_to_cursor();
e.insert_str("everyone");
assert_eq!(e.lines, vec!["hello everyone".to_string()]);
assert!(e.selection.is_none());
}
#[test]
fn select_all_spans_entire_buffer() {
let mut e = editor_with("a\nbc\nd");
e.select_all();
let sel = e.selection.unwrap();
let (start, end) = sel.normalised();
assert_eq!(start, (0, 0));
assert_eq!(end, (2, 1));
assert_eq!(e.selection_text(), "a\nbc\nd");
}
#[test]
fn mouse_down_starts_zero_area_selection_at_click() {
let mut e = editor_with("hello");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
e.mouse_down(3, 0); assert_eq!(e.cursor_col, 0);
let sel = e.selection.expect("anchor created on mouse down");
assert_eq!(sel.anchor, (0, 0));
assert!(!sel.has_area());
}
#[test]
fn render_never_replaces_character_at_cursor() {
use ratatui::buffer::Buffer;
let mut e = editor_with("hello");
e.cursor_col = 2;
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 5,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let cell = &buf[(text_x + 2, e.last_inner.y)];
assert_eq!(
cell.symbol(),
"l",
"editor render must leave the underlying glyph alone"
);
}
#[test]
fn cursor_screen_pos_inside_viewport() {
let mut e = editor_with("hello\nworld");
e.last_inner = Rect {
x: 5,
y: 7,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
e.cursor_row = 1;
e.cursor_col = 3;
assert_eq!(e.cursor_screen_pos(), Some((8 + 3, 8)));
}
#[test]
fn cursor_screen_pos_wrap_shows_caret_on_blank_line() {
let mut e = editor_with("hello\n\nworld");
e.wrap_override = Some(true);
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
e.cursor_row = 1;
e.cursor_col = 0;
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_eq!(
e.cursor_screen_pos(),
Some((text_x, e.last_inner.y + 1)),
"the caret must be visible on a blank line in wrap mode"
);
}
#[test]
fn cursor_screen_pos_wrap_shows_caret_at_end_of_line() {
let mut e = editor_with("hello\nworld");
e.wrap_override = Some(true);
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
e.cursor_row = 0;
e.cursor_col = 5;
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_eq!(
e.cursor_screen_pos(),
Some((text_x + 5, e.last_inner.y)),
"the caret must be visible one past the last character in wrap mode"
);
}
#[test]
fn cursor_screen_pos_wrap_boundary_still_maps_to_next_row_start() {
let mut e = editor_with("aaaa bbbb cccc dddd eeee ffff gggg hhhh");
e.wrap_override = Some(true);
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 20,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
let Some((_, start, _)) = e.text_row(1) else {
panic!("expected a wrapped second row");
};
e.cursor_row = 0;
e.cursor_col = start;
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_eq!(
e.cursor_screen_pos(),
Some((text_x, e.last_inner.y + 1)),
"a wrap-boundary caret must land on the next row's first cell"
);
}
#[test]
fn cursor_screen_pos_wrap_zero_width_column_rejects_out_of_pane_cells() {
let mut e = editor_with("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
e.wrap_override = Some(true);
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 8,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
let (_, start, end) = e.text_row(0).expect("a text row");
assert_eq!(
(start, end),
(0, 40),
"expected the zero-width degenerate one-segment layout"
);
e.cursor_row = 0;
e.cursor_col = 20;
assert_eq!(
e.cursor_screen_pos(),
None,
"a caret cell past the pane edge must not be painted"
);
}
#[test]
fn cursor_screen_pos_returns_none_when_scrolled_off() {
let mut e = editor_with_lines(50);
e.last_inner = Rect {
x: 0,
y: 0,
width: 40,
height: 10,
};
e.last_gutter_width = 3;
e.scroll = 30;
e.cursor_row = 5; assert_eq!(e.cursor_screen_pos(), None);
}
#[test]
fn undo_restores_previous_buffer_and_cursor() {
let mut e = editor_with("abc");
e.cursor_col = 3;
e.insert_char('d');
assert_eq!(e.lines[0], "abcd");
assert!(e.undo());
assert_eq!(e.lines[0], "abc");
assert_eq!(e.cursor_col, 3);
}
#[test]
fn undo_on_empty_stack_returns_false() {
let mut e = editor_with("abc");
assert!(!e.undo());
assert_eq!(e.lines[0], "abc");
}
#[test]
fn undo_coalesces_consecutive_typed_chars_into_one_step() {
let mut e = editor_with("");
e.insert_char('h');
e.insert_char('i');
e.insert_char('!');
assert!(e.undo());
assert_eq!(e.lines[0], "");
}
#[test]
fn undo_does_not_coalesce_across_movement() {
let mut e = editor_with("abc");
e.cursor_col = 3;
e.insert_char('d');
e.move_left();
e.insert_char('z');
assert!(e.undo());
assert_eq!(e.lines[0], "abcd");
assert!(e.undo());
assert_eq!(e.lines[0], "abc");
}
#[test]
fn undo_does_not_coalesce_across_backspace() {
let mut e = editor_with("abc");
e.cursor_col = 3;
e.insert_char('d');
e.backspace();
e.insert_char('e');
assert!(e.undo());
assert_eq!(e.lines[0], "abc");
assert!(e.undo());
assert_eq!(e.lines[0], "abcd");
assert!(e.undo());
assert_eq!(e.lines[0], "abc");
}
#[test]
fn undo_paste_is_one_step() {
let mut e = editor_with("abc");
e.cursor_col = 3;
e.insert_str("XYZ");
assert_eq!(e.lines[0], "abcXYZ");
assert!(e.undo());
assert_eq!(e.lines[0], "abc");
}
#[test]
fn undo_after_replace_selection_restores_original() {
let mut e = editor_with("hello world");
e.cursor_col = 6;
e.start_selection_at_cursor();
e.cursor_col = 11;
e.extend_selection_to_cursor();
e.insert_char('X');
assert_eq!(e.lines[0], "hello X");
assert!(e.undo());
assert_eq!(e.lines[0], "hello world");
}
#[test]
fn undo_restores_dirty_flag() {
let mut e = editor_with("abc");
assert!(!e.dirty);
e.cursor_col = 3;
e.insert_char('d');
assert!(e.dirty);
e.undo();
assert!(!e.dirty, "undoing the only edit restores the clean state");
}
#[test]
fn editor_render_paints_search_match_cells_with_yellow_bg() {
use ratatui::buffer::Buffer;
let mut e = editor_with("alpha needle bravo needle zulu");
e.set_search_highlight(Some(String::from("needle")));
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 3,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y = e.last_inner.y;
let yellow = Color::Rgb(0xff, 0xd7, 0x4a);
for col in 6..12u16 {
assert_eq!(
buf[(text_x + col, y)].bg,
yellow,
"first match cell {col} must have yellow bg"
);
}
assert_ne!(buf[(text_x + 5, y)].bg, yellow, "cell before match");
assert_ne!(buf[(text_x + 12, y)].bg, yellow, "cell after match");
for col in 19..25u16 {
assert_eq!(
buf[(text_x + col, y)].bg,
yellow,
"second match cell {col} must have yellow bg"
);
}
}
#[test]
fn editor_render_lights_other_occurrences_of_selection_in_blue() {
use ratatui::buffer::Buffer;
let mut e = editor_with("alpha needle bravo needle zulu");
e.selection = Some(EditorSelection {
anchor: (0, 6),
head: (0, 12),
});
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 3,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y = e.last_inner.y;
let occurrence = Color::Rgb(0x37, 0x61, 0x8e);
let selection = Color::Rgb(0x26, 0x4f, 0x78);
for col in 6..12u16 {
assert_eq!(
buf[(text_x + col, y)].bg,
selection,
"selected occurrence cell {col} must show the selection band"
);
}
for col in 19..25u16 {
assert_eq!(
buf[(text_x + col, y)].bg,
occurrence,
"other occurrence cell {col} must show the occurrence blue"
);
}
assert_ne!(buf[(text_x + 18, y)].bg, occurrence, "space before match");
}
#[test]
fn editor_render_skips_occurrence_highlight_for_whitespace_selection() {
use ratatui::buffer::Buffer;
let mut e = editor_with("a b c d");
e.selection = Some(EditorSelection {
anchor: (0, 1),
head: (0, 3),
});
e.focused = true;
assert_eq!(e.selection_occurrence_needle(), None);
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 3,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y = e.last_inner.y;
let occurrence = Color::Rgb(0x37, 0x61, 0x8e);
for col in 0..10u16 {
assert_ne!(
buf[(text_x + col, y)].bg,
occurrence,
"whitespace-only selection must not light occurrences"
);
}
}
#[test]
fn editor_render_skips_occurrence_highlight_for_multiline_selection() {
let mut e = editor_with("needle\nneedle");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (1, 6),
});
assert_eq!(
e.selection_occurrence_needle(),
None,
"multi-line selections do not drive occurrence highlighting"
);
}
#[test]
fn editor_render_does_not_paint_search_highlight_when_unset() {
use ratatui::buffer::Buffer;
let mut e = editor_with("alpha needle bravo");
e.set_search_highlight(None);
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 3,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y = e.last_inner.y;
let yellow = Color::Rgb(0xff, 0xd7, 0x4a);
for col in 0..18u16 {
assert_ne!(
buf[(text_x + col, y)].bg,
yellow,
"no cell should be highlighted when search_highlight is None"
);
}
}
#[test]
fn editor_render_search_highlight_is_case_insensitive() {
use ratatui::buffer::Buffer;
let mut e = editor_with("Foo bar FOO baz");
e.set_search_highlight(Some(String::from("foo")));
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 3,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y = e.last_inner.y;
let yellow = Color::Rgb(0xff, 0xd7, 0x4a);
for col in 0..3u16 {
assert_eq!(buf[(text_x + col, y)].bg, yellow, "cell {col} of 'Foo'");
}
for col in 8..11u16 {
assert_eq!(buf[(text_x + col, y)].bg, yellow, "cell {col} of 'FOO'");
}
}
#[test]
fn open_diff_replaces_blank_initial_tab_with_diff_view() {
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "alpha\nbravo\ncharlie\n").unwrap();
std::fs::write(f2.path(), "alpha\nBRAVO\ncharlie\n").unwrap();
let mut t = EditorTabs::new();
t.open_diff(f1.path(), f2.path()).unwrap();
assert_eq!(t.tab_count(), 1, "blank initial slot should be reused");
let active = &t.editors[t.active_index()];
assert!(active.diff.is_some(), "active tab must hold diff data");
let diff = active.diff.as_ref().unwrap();
assert_eq!(diff.left_lines, vec!["alpha", "bravo", "charlie"]);
assert_eq!(diff.right_lines, vec!["alpha", "BRAVO", "charlie"]);
assert_eq!(diff.rows.len(), 3);
}
#[test]
fn tab_full_path_reports_the_whole_path_for_disambiguation() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("app.ts");
std::fs::write(&p, "export const x = 1;\n").unwrap();
let mut t = EditorTabs::new();
t.open_pinned(&p).unwrap();
let idx = t.active_index();
assert_eq!(
t.tab_full_path(idx).as_deref(),
Some(p.to_string_lossy().as_ref()),
"tooltip must expose the full path, not just the file name"
);
}
#[test]
fn tab_full_path_is_none_for_an_unsaved_buffer() {
let t = EditorTabs::new();
assert_eq!(
t.tab_full_path(t.active_index()),
None,
"an untitled buffer has no path to disambiguate"
);
}
#[test]
fn tab_full_path_shows_both_sides_of_a_diff() {
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "a\n").unwrap();
std::fs::write(f2.path(), "b\n").unwrap();
let mut t = EditorTabs::new();
t.open_diff(f1.path(), f2.path()).unwrap();
let label = t.tab_full_path(t.active_index()).unwrap();
assert!(label.contains(&f1.path().to_string_lossy().into_owned()));
assert!(label.contains(&f2.path().to_string_lossy().into_owned()));
assert!(label.contains('\u{2194}'), "diff tooltip shows both sides");
}
#[test]
fn diff_header_paints_prev_next_arrows_at_the_right_edge() {
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "alpha\nbravo\ncharlie\n").unwrap();
std::fs::write(f2.path(), "alpha\nBRAVO\ncharlie\n").unwrap();
let mut t = EditorTabs::new();
t.open_diff(f1.path(), f2.path()).unwrap();
let active_idx = t.active_index();
t.editors[active_idx].focused = true;
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 20,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut t.editors[active_idx], area, &mut buf);
let ed = &t.editors[active_idx];
assert!(
ed.diff_prev_arrow.width > 0,
"prev arrow rect must be tracked so a click can navigate to the previous hunk"
);
assert!(
ed.diff_next_arrow.width > 0,
"next arrow rect must be tracked so a click can navigate to the next hunk"
);
assert_eq!(
buf[(ed.diff_prev_arrow.x, ed.diff_prev_arrow.y)].symbol(),
"\u{2039}",
"prev arrow cell must paint ‹"
);
assert_eq!(
buf[(ed.diff_next_arrow.x, ed.diff_next_arrow.y)].symbol(),
"\u{203a}",
"next arrow cell must paint ›"
);
assert_eq!(ed.diff_prev_arrow.y, ed.diff_next_arrow.y);
assert!(ed.diff_prev_arrow.x < ed.diff_next_arrow.x);
let right_edge = ed.last_inner.x + ed.last_inner.width;
assert!(ed.diff_next_arrow.x < right_edge);
}
#[test]
fn non_diff_tab_clears_diff_arrow_hit_rects_on_render() {
let f = NamedTempFile::new().unwrap();
std::fs::write(f.path(), "alpha\nbravo\ncharlie\n").unwrap();
let mut ed = Editor::new();
ed.open(f.path()).unwrap();
ed.diff_prev_arrow = Rect {
x: 30,
y: 0,
width: 1,
height: 1,
};
ed.diff_next_arrow = Rect {
x: 32,
y: 0,
width: 1,
height: 1,
};
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
assert_eq!(ed.diff_prev_arrow, Rect::default());
assert_eq!(ed.diff_next_arrow, Rect::default());
}
#[test]
fn diff_hit_test_maps_click_in_left_text_column_to_left_side_and_char_col() {
use crate::widgets::diff::DiffSide;
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "alpha\nbravo\ncharlie\n").unwrap();
std::fs::write(f2.path(), "alpha\nBRAVO\ncharlie\n").unwrap();
let mut t = EditorTabs::new();
t.open_diff(f1.path(), f2.path()).unwrap();
let active_idx = t.active_index();
t.editors[active_idx].focused = true;
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut t.editors[active_idx], area, &mut buf);
let ed = &t.editors[active_idx];
let diff = ed.diff.as_ref().unwrap();
let body_top = ed.last_inner.y + 1;
let l_gutter = (diff.left_lines.len() + 1).to_string().len() as u16 + 1;
let l_text_x = ed.last_inner.x + l_gutter + 2;
let hit =
crate::widgets::editor::diff_hit_test(diff, ed.last_inner, l_text_x + 2, body_top + 1);
assert_eq!(
hit,
Some((DiffSide::Left, 1, 2)),
"a click two cells into the left text column of the second body row must map to Left, row 1, char col 2"
);
}
#[test]
fn diff_hit_test_maps_click_in_right_text_column_to_right_side() {
use crate::widgets::diff::DiffSide;
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "alpha\nbravo\n").unwrap();
std::fs::write(f2.path(), "alpha\nBRAVO\n").unwrap();
let mut t = EditorTabs::new();
t.open_diff(f1.path(), f2.path()).unwrap();
let active_idx = t.active_index();
t.editors[active_idx].focused = true;
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut t.editors[active_idx], area, &mut buf);
let ed = &t.editors[active_idx];
let diff = ed.diff.as_ref().unwrap();
let body_top = ed.last_inner.y + 1;
let half = ed.last_inner.width / 2;
let r_gutter = (diff.right_lines.len() + 1).to_string().len() as u16 + 1;
let r_text_x = ed.last_inner.x + half + 1 + r_gutter + 2;
let hit =
crate::widgets::editor::diff_hit_test(diff, ed.last_inner, r_text_x + 3, body_top + 1);
assert!(
matches!(hit, Some((DiffSide::Right, 1, 3))),
"a click three cells into the right text column of the second body row must map to Right, row 1, char col 3; got {hit:?}"
);
}
#[test]
fn diff_caret_screen_pos_inverts_the_right_column_hit_test() {
use crate::widgets::diff::DiffSide;
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "alpha\nbravo\n").unwrap();
std::fs::write(f2.path(), "alpha\nBRAVO\n").unwrap();
let mut t = EditorTabs::new();
t.open_diff(f1.path(), f2.path()).unwrap();
let active_idx = t.active_index();
t.editors[active_idx].focused = true;
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut t.editors[active_idx], area, &mut buf);
let body_top = t.editors[active_idx].last_inner.y + 1;
let half = t.editors[active_idx].last_inner.width / 2;
let diff = t.editors[active_idx].diff.as_ref().unwrap();
let r_gutter = (diff.right_lines.len() + 1).to_string().len() as u16 + 1;
let r_text_x = t.editors[active_idx].last_inner.x + half + 1 + r_gutter + 2;
t.editors[active_idx]
.diff
.as_mut()
.unwrap()
.start_selection(DiffSide::Right, 1, 3);
let pos = t.editors[active_idx].diff_caret_screen_pos();
assert_eq!(
pos,
Some((r_text_x + 3, body_top + 1)),
"caret at right row 1 col 3 must land on the cell diff_hit_test maps that screen point back to"
);
}
#[test]
fn render_diff_paints_selection_band_over_selected_cells() {
use crate::widgets::diff::DiffSide;
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "alpha\nbravo\n").unwrap();
std::fs::write(f2.path(), "alpha\nBRAVO\n").unwrap();
let mut t = EditorTabs::new();
t.open_diff(f1.path(), f2.path()).unwrap();
let active_idx = t.active_index();
t.editors[active_idx].focused = true;
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut t.editors[active_idx], area, &mut buf);
let diff_mut = t.editors[active_idx].diff.as_mut().unwrap();
diff_mut.start_selection(DiffSide::Left, 1, 0);
diff_mut.extend_selection_to(1, 5);
ratatui::widgets::Widget::render(&mut t.editors[active_idx], area, &mut buf);
let ed = &t.editors[active_idx];
let diff = ed.diff.as_ref().unwrap();
let l_gutter = (diff.left_lines.len() + 1).to_string().len() as u16 + 1;
let l_text_x = ed.last_inner.x + l_gutter + 2;
let y = ed.last_inner.y + 2;
let band_bg = Color::Rgb(0x26, 0x4f, 0x78);
for col in 0..5u16 {
assert_eq!(
buf[(l_text_x + col, y)].bg,
band_bg,
"cell {col} of the second body row must paint the selection band on the left column"
);
}
}
#[test]
fn open_diff_inserts_a_new_tab_when_an_open_file_already_exists() {
let existing = NamedTempFile::new().unwrap();
std::fs::write(existing.path(), "x\n").unwrap();
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "1\n").unwrap();
std::fs::write(f2.path(), "2\n").unwrap();
let mut t = EditorTabs::new();
t.open_pinned(existing.path()).unwrap();
let before = t.tab_count();
t.open_diff(f1.path(), f2.path()).unwrap();
assert_eq!(t.tab_count(), before + 1, "must insert a new diff tab");
assert!(t.editors[t.active_index()].diff.is_some());
}
#[test]
fn diff_tab_label_uses_arrow_between_filenames() {
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "a\n").unwrap();
std::fs::write(f2.path(), "b\n").unwrap();
let mut t = EditorTabs::new();
t.open_diff(f1.path(), f2.path()).unwrap();
let label = tab_label(&t.editors[t.active_index()]);
let l = f1
.path()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
let r = f2
.path()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
assert_eq!(label, format!("{l} \u{2194} {r}"));
}
#[test]
fn git_diff_text_tab_label_omits_arrow_when_right_side_is_synthetic() {
let mut t = EditorTabs::new();
t.open_git_diff_side_by_side(
std::path::Path::new("git diff master"),
"diff --git a/x b/x\n@@ -1 +1 @@\n-old\n+new\n",
)
.unwrap();
let label = tab_label(&t.editors[t.active_index()]);
assert_eq!(
label, "git diff master",
"synthetic git-diff tab must not show '↔ null' — the right side is virtual"
);
}
#[test]
fn editor_tabs_search_highlight_survives_close_then_open_via_preview() {
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "alpha needle bravo\n").unwrap();
std::fs::write(f2.path(), "second needle line\n").unwrap();
let mut t = EditorTabs::new();
t.open_pinned(f1.path()).unwrap();
t.set_search_highlight(
Some(String::from("needle")),
crate::widgets::search::SearchOpts::default(),
);
let close_idx = t
.editors
.iter()
.position(|e| e.path.as_deref() == Some(f1.path()))
.unwrap();
assert!(t.close_tab(close_idx));
t.open_preview(f2.path()).unwrap();
let active = t
.editors
.iter()
.find(|e| e.path.as_deref() == Some(f2.path()))
.unwrap();
assert_eq!(
active.search_highlight.as_deref(),
Some("needle"),
"newly opened tab must inherit the EditorTabs' current search term"
);
}
#[test]
fn editor_tabs_search_highlight_survives_open_pinned_after_close() {
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "first\n").unwrap();
std::fs::write(f2.path(), "second needle line\n").unwrap();
let mut t = EditorTabs::new();
t.open_pinned(f1.path()).unwrap();
t.open_pinned(f2.path()).unwrap();
t.set_search_highlight(
Some(String::from("needle")),
crate::widgets::search::SearchOpts::default(),
);
let f3 = NamedTempFile::new().unwrap();
std::fs::write(f3.path(), "third needle row\n").unwrap();
let close_idx = t
.editors
.iter()
.position(|e| e.path.as_deref() == Some(f1.path()))
.unwrap();
assert!(t.close_tab(close_idx));
t.open_pinned(f3.path()).unwrap();
let third = t
.editors
.iter()
.find(|e| e.path.as_deref() == Some(f3.path()))
.unwrap();
assert_eq!(third.search_highlight.as_deref(), Some("needle"));
}
#[test]
fn editor_tabs_set_search_highlight_propagates_to_every_tab() {
let mut t = EditorTabs::new();
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "hello").unwrap();
std::fs::write(f2.path(), "world").unwrap();
t.open_pinned(f1.path()).unwrap();
t.open_pinned(f2.path()).unwrap();
t.set_search_highlight(
Some(String::from("term")),
crate::widgets::search::SearchOpts::default(),
);
for ed in &t.editors {
assert_eq!(ed.search_highlight.as_deref(), Some("term"));
}
t.set_search_highlight(None, crate::widgets::search::SearchOpts::default());
for ed in &t.editors {
assert!(ed.search_highlight.is_none());
}
}
#[test]
fn editor_starts_with_zero_horizontal_scroll() {
let e = editor_with("abcdef");
assert_eq!(e.scroll_col, 0);
}
#[test]
fn scroll_right_by_advances_horizontal_offset() {
let mut e = editor_with("a".repeat(2000).as_str());
e.scroll_right_by(40);
assert_eq!(e.scroll_col, 40);
e.scroll_right_by(60);
assert_eq!(e.scroll_col, 100);
e.scroll_left_by(30);
assert_eq!(e.scroll_col, 70);
e.scroll_left_by(1000); assert_eq!(e.scroll_col, 0);
}
#[test]
fn move_right_past_visible_edge_advances_horizontal_scroll() {
let mut e = editor_with("a".repeat(500).as_str());
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_width = e
.last_inner
.width
.saturating_sub(e.last_gutter_width + 2 + u16::from(e.last_scrollbar.width > 0))
as usize;
assert!(text_width > 0 && text_width < 500);
e.cursor_col = text_width;
e.move_right();
assert!(
e.scroll_col > 0,
"moving the cursor past the visible edge must advance horizontal scroll"
);
}
#[test]
fn render_starts_line_from_scroll_col() {
let mut e = editor_with("ABCDEFGHIJ".repeat(10).as_str());
e.scroll_col = 3;
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_eq!(
buf[(text_x, e.last_inner.y)].symbol(),
"D",
"first visible column must be the (scroll_col)th character"
);
}
#[test]
fn render_clamps_scroll_col_to_content_width() {
let mut e = editor_with("a".repeat(40).as_str());
e.focused = true;
e.scroll_right_by(10_000);
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 5,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_width = e
.last_inner
.width
.saturating_sub(e.last_gutter_width + 2 + u16::from(e.last_scrollbar.width > 0))
as usize;
assert!(text_width > 0);
assert_eq!(
e.scroll_col,
40usize.saturating_sub(text_width),
"scroll_col must clamp to (content cols - text width)"
);
}
#[test]
fn render_shows_horizontal_scrollbar_only_on_overflow() {
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 6,
};
let mut short = editor_with("abc");
short.focused = true;
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut short).render(area, &mut buf);
assert_eq!(
short.last_hscrollbar,
Rect::default(),
"a line that fits must not reserve a horizontal scrollbar row"
);
let mut long = editor_with("a".repeat(500).as_str());
long.focused = true;
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut long).render(area, &mut buf);
assert!(
long.last_hscrollbar.width > 0 && long.last_hscrollbar.height == 1,
"an overflowing line must paint a one-row horizontal scrollbar"
);
assert_eq!(
long.last_hscrollbar.y,
long.last_inner.y + long.last_inner.height - 1,
"the horizontal scrollbar sits on the bottom inner row"
);
}
#[test]
fn scroll_to_bar_x_jumps_horizontal_offset() {
let mut e = editor_with("a".repeat(500).as_str());
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut e).render(area, &mut buf);
assert!(e.last_hscrollbar.width > 0);
let right_x = e.last_hscrollbar.x + e.last_hscrollbar.width - 1;
assert!(e.scroll_to_bar_x(right_x));
assert!(
e.scroll_col > 0,
"dragging the thumb to the right edge must advance scroll_col"
);
assert!(e.scroll_to_bar_x(e.last_hscrollbar.x));
assert_eq!(e.scroll_col, 0);
}
fn md_editor(text: &str) -> Editor {
let mut e = editor_with(text);
e.lang = Some(LangKind::Markdown);
e
}
fn render_at(e: &mut Editor, w: u16, h: u16) {
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: w,
height: h,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(e as &mut Editor).render(area, &mut buf);
}
#[test]
fn non_iterm2_canvases_paint_the_theme_background_not_reset() {
let themed = crate::theme::Theme::from_id("solarized-dark");
assert_eq!(themed.id(), "solarized-dark", "bundled theme resolves");
assert_eq!(
canvas_bg(false, themed),
themed.editor_bg(),
"a non-iTerm2 host fills the canvas with the theme bg"
);
assert_eq!(
canvas_bg(true, themed),
Color::Reset,
"iTerm2 keeps Reset so the SetColors session bg shows through"
);
let mut e = editor_with("");
e.theme = themed;
e.image = Some(ImageView {
bytes: Vec::new(),
format_label: String::from("png"),
pixel_w: 4,
pixel_h: 4,
byte_size: 1,
generation: 0,
pdf: None,
});
let area = Rect {
x: 0,
y: 0,
width: 20,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
render_image_placeholder(
e.image.as_ref().unwrap(),
None,
area,
&mut buf,
canvas_bg(false, themed),
);
assert_eq!(
buf[(1, area.height - 1)].bg,
themed.editor_bg(),
"the canvas body must wear the theme bg, not the host default"
);
}
#[test]
fn the_kitty_image_canvas_keeps_the_default_bg_so_the_deep_z_preview_shows() {
use crate::iterm2_inline::InlineImageProtocol;
let themed = crate::theme::Theme::from_id("solarized-dark");
assert_eq!(themed.id(), "solarized-dark", "bundled theme resolves");
assert_eq!(
image_canvas_bg(InlineImageProtocol::Kitty, themed),
Color::Reset,
"Kitty layers the deep-z image below non-default-bg cells, so the picture canvas must stay default-bg"
);
assert_eq!(
image_canvas_bg(InlineImageProtocol::ITerm2, themed),
Color::Reset,
"iTerm2 keeps Reset so the SetColors session bg shows through"
);
assert_eq!(
image_canvas_bg(InlineImageProtocol::Sixel, themed),
themed.editor_bg(),
"sixel blits into the cell buffer over the canvas, so the themed fill stays"
);
assert_eq!(
image_canvas_bg(InlineImageProtocol::None, themed),
themed.editor_bg(),
"with no graphics the placeholder is all the user sees; it stays themed"
);
let image = ImageView {
bytes: Vec::new(),
format_label: String::from("png"),
pixel_w: 4,
pixel_h: 4,
byte_size: 1,
generation: 0,
pdf: None,
};
let area = Rect {
x: 0,
y: 0,
width: 20,
height: 6,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
render_image_placeholder(
&image,
None,
area,
&mut buf,
image_canvas_bg(InlineImageProtocol::Kitty, themed),
);
assert_ne!(
buf[(1, area.y)].bg,
Color::Reset,
"the metadata pill row keeps its own background"
);
for y in area.y + 1..area.bottom() {
for x in area.x..area.right() {
assert_eq!(
buf[(x, y)].bg,
Color::Reset,
"canvas cell ({x}, {y}) must keep the default background or Kitty paints it over the image"
);
}
}
}
#[test]
fn a_theme_switch_rebuilds_an_open_markdown_preview() {
let mut e = md_editor("```notalanguage\nplain code line\n```");
assert!(e.toggle_markdown_preview());
let themed = *crate::theme::Theme::all()
.iter()
.find(|t| t.syntax().fg != crate::theme::SyntaxPalette::BASE16.fg)
.expect("a bundled theme with a non-Base16 code palette");
e.theme = themed;
e.rehighlight_for_theme();
let (r, g, b) = themed.syntax().fg;
let md = e.markdown_preview.as_ref().expect("preview stays open");
let code = md
.lines
.iter()
.flat_map(|l| l.spans.iter())
.find(|s| s.content.as_ref() == "plain code line")
.expect("the code line must render");
assert_eq!(
code.style.fg,
Some(Color::Rgb(r, g, b)),
"the preview must recolor on a theme switch, not wait for an edit"
);
}
#[test]
fn markdown_wraps_long_line_without_horizontal_scrollbar() {
let mut e = md_editor(&"word ".repeat(40)); render_at(&mut e, 30, 10);
assert_eq!(
e.last_hscrollbar,
Rect::default(),
"wrapped markdown must not show a horizontal scrollbar"
);
assert_eq!(e.scroll_col, 0, "wrap mode never scrolls horizontally");
let rows_for_line0 = e
.last_wrap_rows
.iter()
.filter(|r| matches!(r, VisRow::Text { line: 0, .. }))
.count();
assert!(
rows_for_line0 > 1,
"a 200-char paragraph must fold onto multiple visual rows"
);
}
#[test]
fn non_markdown_long_line_still_scrolls_horizontally() {
let mut e = editor_with(&"a".repeat(200));
e.lang = Some(LangKind::Rust);
render_at(&mut e, 30, 10);
assert!(
e.last_hscrollbar.width > 0,
"code keeps the horizontal scrollbar instead of wrapping"
);
}
#[test]
fn markdown_cursor_screen_pos_lands_on_the_wrapped_row() {
let mut e = md_editor(&"a".repeat(100));
render_at(&mut e, 30, 10);
let (_, seg0_start, seg0_end) = e.text_row(0).unwrap();
assert_eq!(seg0_start, 0);
e.cursor_row = 0;
e.cursor_col = seg0_end + 1;
let (_, cy) = e.cursor_screen_pos().expect("cursor must be visible");
assert_eq!(
cy,
e.last_inner.y + 1,
"a column past the first segment renders on the second visual row"
);
}
#[test]
fn markdown_click_on_second_visual_row_maps_into_the_line() {
let mut e = md_editor(&"a".repeat(100));
render_at(&mut e, 30, 10);
let seg0_end = e.text_row(0).unwrap().2;
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let (line, col) = e
.buffer_pos_at(text_x, e.last_inner.y + 1)
.expect("a click on the second visual row is a text hit");
assert_eq!(line, 0, "still the same logical line");
assert_eq!(
col, seg0_end,
"the first column of the second visual row is where segment one ended"
);
}
#[test]
fn markdown_mouse_down_below_wrapped_lines_lands_on_the_row_under_the_pointer() {
let mut e = md_editor(&format!("{}\nsecond\nthird\nfourth", "a".repeat(100)));
render_at(&mut e, 30, 10);
let vis_row = e
.last_wrap_rows
.iter()
.position(|r| matches!(r, VisRow::Text { line: 1, .. }))
.expect("line 1 is on screen");
assert!(vis_row > 1, "line 0 must wrap for the rows to be displaced");
let text_x = e.last_inner.x + e.last_gutter_width + 1;
e.mouse_down(text_x, e.last_inner.y + vis_row as u16);
assert_eq!(
e.cursor_row, 1,
"the press lands on the line under the pointer"
);
assert_eq!(e.cursor_col, 0);
}
#[test]
fn markdown_move_down_steps_within_a_wrapped_paragraph() {
let mut e = md_editor(&"a".repeat(100));
render_at(&mut e, 30, 10);
e.cursor_row = 0;
e.cursor_col = 0;
e.move_down();
assert_eq!(
e.cursor_row, 0,
"move_down stays on the same logical line - it steps to the next wrapped segment"
);
assert!(e.cursor_col > 0, "and advances into that next segment");
}
#[test]
fn markdown_scrolls_to_reveal_tail_of_a_tall_paragraph() {
let mut e = md_editor(&"a".repeat(400));
render_at(&mut e, 30, 6);
let before = e.text_row(0).unwrap();
e.scroll_down(3);
render_at(&mut e, 30, 6);
let after = e.text_row(0).unwrap();
assert_eq!(after.0, 0, "still the single logical line");
assert!(
after.1 > before.1,
"scrolling down advances into the paragraph (sub-line scroll)"
);
}
#[test]
fn render_paints_selection_band_on_selected_cells() {
use ratatui::buffer::Buffer;
let mut e = editor_with("hello world");
e.cursor_col = 0;
e.start_selection_at_cursor();
e.cursor_col = 5;
e.extend_selection_to_cursor();
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 5,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let selected_bg = Color::Rgb(0x26, 0x4f, 0x78);
for col in 0..5u16 {
let bg = buf[(text_x + col, e.last_inner.y)].bg;
assert_eq!(
bg, selected_bg,
"cell at col {col} should have selection bg, got {bg:?}"
);
}
let bg5 = buf[(text_x + 5, e.last_inner.y)].bg;
assert_ne!(bg5, selected_bg, "cell at col 5 should NOT be highlighted");
}
#[test]
fn render_paints_selection_band_across_multiple_lines() {
use ratatui::buffer::Buffer;
let mut e = editor_with("first\nsecond\nthird");
e.cursor_row = 0;
e.cursor_col = 2;
e.start_selection_at_cursor();
e.cursor_row = 2;
e.cursor_col = 2;
e.extend_selection_to_cursor();
e.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 6,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let selected_bg = Color::Rgb(0x26, 0x4f, 0x78);
let row0_y = e.last_inner.y;
assert_eq!(buf[(text_x + 2, row0_y)].bg, selected_bg, "row 0 col 2");
assert_eq!(buf[(text_x + 4, row0_y)].bg, selected_bg, "row 0 col 4");
assert_ne!(
buf[(text_x, row0_y)].bg,
selected_bg,
"row 0 col 0 not selected"
);
let row1_y = e.last_inner.y + 1;
assert_eq!(buf[(text_x, row1_y)].bg, selected_bg, "row 1 col 0");
assert_eq!(buf[(text_x + 5, row1_y)].bg, selected_bg, "row 1 col 5");
let row2_y = e.last_inner.y + 2;
assert_eq!(buf[(text_x, row2_y)].bg, selected_bg, "row 2 col 0");
assert_eq!(buf[(text_x + 1, row2_y)].bg, selected_bg, "row 2 col 1");
assert_ne!(
buf[(text_x + 2, row2_y)].bg,
selected_bg,
"row 2 col 2 not selected"
);
}
#[test]
fn double_click_selects_word_and_moves_cursor_to_end() {
let mut e = editor_with("hello world");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
let text_x: u16 = 3;
e.select_word_at(text_x + 7, 0);
let sel = e.selection.expect("word selection created");
assert_eq!(sel.normalised(), ((0, 6), (0, 11)));
assert_eq!(e.cursor_col, 11);
}
#[test]
fn double_click_on_first_word_selects_it_from_column_zero() {
let mut e = editor_with("foo bar");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
let text_x: u16 = 3;
e.select_word_at(text_x + 1, 0);
let sel = e.selection.unwrap();
assert_eq!(sel.normalised(), ((0, 0), (0, 3)));
assert_eq!(e.cursor_col, 3);
}
#[test]
fn double_click_on_whitespace_does_not_create_a_selection() {
let mut e = editor_with("hello world");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
let text_x: u16 = 3;
e.select_word_at(text_x + 5, 0);
assert!(
e.selection.map(|s| !s.has_area()).unwrap_or(true),
"whitespace double-click must not start a non-empty selection"
);
}
#[test]
fn double_click_past_end_of_line_extends_last_word() {
let mut e = editor_with("foo");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
let text_x: u16 = 3;
e.select_word_at(text_x + 12, 0);
let sel = e.selection.unwrap();
assert_eq!(sel.normalised(), ((0, 0), (0, 3)));
assert_eq!(e.cursor_col, 3);
}
#[test]
fn editor_tabs_starts_with_one_empty_editor() {
let t = EditorTabs::new();
assert_eq!(t.tab_count(), 1);
assert_eq!(t.active_index(), 0);
assert!(t.path.is_none());
}
#[test]
fn editor_tabs_open_in_new_tab_appends_and_activates() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/tmp/a.rs"));
t.add_tab_with_path(std::path::PathBuf::from("/tmp/b.rs"));
assert_eq!(t.tab_count(), 2);
assert_eq!(t.active_index(), 1);
assert_eq!(t.path.as_deref(), Some(std::path::Path::new("/tmp/b.rs")));
}
#[test]
fn editor_tabs_new_tab_lands_immediately_after_active() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
t.select(0);
t.add_tab_with_path(std::path::PathBuf::from("/d"));
let labels: Vec<_> = t
.iter_tabs()
.map(|e| e.path.as_ref().unwrap().to_string_lossy().into_owned())
.collect();
assert_eq!(labels, vec!["/a", "/d", "/b", "/c"]);
assert_eq!(t.active_index(), 1);
}
#[test]
fn editor_tabs_close_active_drops_tab_and_reselects() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
t.select(1); assert!(t.close_active());
assert_eq!(t.tab_count(), 2);
assert_eq!(t.path.as_deref(), Some(std::path::Path::new("/c")));
}
#[test]
fn editor_tabs_close_last_tab_resets_buffer_to_blank() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
assert!(
t.close_active(),
"closing the only tab resets it instead of refusing"
);
assert_eq!(t.tab_count(), 1);
assert!(t.path.is_none());
}
#[test]
fn close_at_maps_a_click_on_the_x_glyph_to_its_tab_index() {
use ratatui::buffer::Buffer;
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/foo.rs"));
t.add_tab_with_path(std::path::PathBuf::from("/bar.rs"));
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let cx0 = t
.close_screen_x(0)
.expect("tab 0 has a close button when count > 1");
let cx1 = t.close_screen_x(1).expect("tab 1 has a close button");
assert_eq!(t.close_at(cx0, area.y), Some(0));
assert_eq!(t.close_at(cx1, area.y), Some(1));
let (tab0_x, _) = t.tab_screen_x(0).unwrap();
assert_ne!(tab0_x, cx0);
assert_eq!(t.close_at(tab0_x, area.y), None);
assert_eq!(t.close_at(cx0, area.y + 2), None);
}
#[test]
fn hovering_the_close_cross_paints_a_pill_on_that_cell() {
use ratatui::buffer::Buffer;
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/foo.rs"));
t.add_tab_with_path(std::path::PathBuf::from("/bar.rs"));
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let cx = t.close_screen_x(0).expect("two tabs -> tab 0 has a cross");
let other = t.close_screen_x(1).expect("tab 1 has a cross");
t.hover_pointer = Some((cx, area.y));
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let pill = crate::theme::Theme::default().tab_close_pill_bg();
assert_eq!(
buf[(cx, area.y)].bg,
pill,
"the hovered cross cell wears the pill"
);
assert_eq!(buf[(cx, area.y)].fg, Color::White);
assert_eq!(
buf[(cx, area.y)].symbol(),
"\u{2715}",
"the pill sits behind the cross glyph, not a blank cell"
);
assert_ne!(
buf[(other, area.y)].bg,
pill,
"an un-hovered cross gets no pill"
);
}
#[test]
fn black_theme_close_pill_is_distinct_from_the_active_tab_bg() {
use ratatui::buffer::Buffer;
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/foo.rs"));
t.editors[0].focus_gradient = true; t.add_tab_with_path(std::path::PathBuf::from("/bar.rs"));
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let active = t.active;
let cx = t
.close_screen_x(active)
.expect("the active tab has a close cross");
t.hover_pointer = Some((cx, area.y));
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let black = crate::theme::Theme::from_id("black");
assert_eq!(
black.tab_active_bg(),
crate::gradient::rgb_color(crate::gradient::POPUP_SEL_BG),
"the Black theme's active chip is still the brand selection teal"
);
assert_eq!(
buf[(cx, area.y)].bg,
black.tab_close_pill_bg(),
"the Black-theme close pill uses the brighter teal"
);
assert_ne!(
buf[(cx, area.y)].bg,
black.tab_active_bg(),
"the pill must not equal the active tab bg, or the cross shows no hover at all"
);
}
#[test]
fn hovering_an_inactive_tab_lifts_its_body_not_the_active_one() {
use ratatui::buffer::Buffer;
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/foo.rs"));
t.add_tab_with_path(std::path::PathBuf::from("/bar.rs"));
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let (x0, _) = t.tab_screen_x(0).unwrap();
let (x1, _) = t.tab_screen_x(1).unwrap();
t.hover_pointer = Some((x0 + 1, area.y));
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let hover = crate::theme::Theme::default().tab_hover_bg();
assert_eq!(
buf[(x0 + 1, area.y)].bg,
hover,
"an inactive tab body lifts under the pointer"
);
assert_ne!(
buf[(x1 + 1, area.y)].bg,
hover,
"the active tab keeps its own bg when a sibling is hovered"
);
}
#[test]
fn tab_strip_follows_the_selected_theme() {
use ratatui::buffer::Buffer;
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/foo.rs"));
let solarized = crate::theme::Theme::from_id("solarized-dark");
assert_eq!(solarized.id(), "solarized-dark", "bundled theme resolves");
t.editors[0].theme = solarized;
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
assert_eq!(
buf[(area.width - 1, 0)].bg,
solarized.search_bg(),
"the gap right of the last tab wears the theme's strip color"
);
let (x0, _) = t.tab_screen_x(0).unwrap();
assert_eq!(
buf[(x0 + 1, 0)].bg,
solarized.selection(),
"the active tab wears the theme's selection fill, not the navy chip"
);
}
#[test]
fn close_tab_removes_specific_index_and_keeps_active_pointing_correctly() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
assert!(t.close_tab(1));
assert_eq!(t.tab_count(), 2);
assert_eq!(t.active_index(), 1);
assert_eq!(t.path.as_deref(), Some(std::path::Path::new("/c")));
}
#[test]
fn close_others_keeps_only_the_chosen_tab_and_makes_it_active() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
let removed = t.close_others(1);
assert_eq!(removed, 2, "close_others must report how many were dropped");
assert_eq!(t.tab_count(), 1);
assert_eq!(t.active_index(), 0);
assert_eq!(t.path.as_deref(), Some(std::path::Path::new("/b")));
assert!(t.focused, "the surviving tab takes focus");
}
#[test]
fn toggle_pin_keeps_pinned_tabs_leftmost_and_follows_the_active_tab() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c")); assert!(t.toggle_pin(2));
assert!(t.is_pinned(0));
assert_eq!(t.tab_path(0).as_deref(), Some(std::path::Path::new("/c")));
assert_eq!(t.active_index(), 0, "the active tab follows its editor");
assert_eq!(t.tab_path(1).as_deref(), Some(std::path::Path::new("/a")));
assert_eq!(t.tab_path(2).as_deref(), Some(std::path::Path::new("/b")));
let b_idx = 2;
assert!(t.toggle_pin(b_idx));
assert_eq!(t.tab_path(0).as_deref(), Some(std::path::Path::new("/c")));
assert_eq!(t.tab_path(1).as_deref(), Some(std::path::Path::new("/b")));
assert!(t.is_pinned(0) && t.is_pinned(1) && !t.is_pinned(2));
assert!(!t.toggle_pin(0));
assert!(t.is_pinned(0), "/b is still pinned and stays leftmost");
assert_eq!(t.tab_path(0).as_deref(), Some(std::path::Path::new("/b")));
assert_eq!(t.tab_path(1).as_deref(), Some(std::path::Path::new("/c")));
}
#[test]
fn close_others_keeps_pinned_tabs_alongside_the_kept_tab() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
t.add_tab_with_path(std::path::PathBuf::from("/d"));
t.toggle_pin(0); let removed = t.close_others(2); assert_eq!(removed, 2, "only the unpinned non-kept tabs (/b, /d) close");
assert_eq!(t.tab_count(), 2);
assert!(t.is_pinned(0));
assert_eq!(t.tab_path(0).as_deref(), Some(std::path::Path::new("/a")));
assert_eq!(t.tab_path(1).as_deref(), Some(std::path::Path::new("/c")));
assert_eq!(t.active_index(), 1, "the kept tab is active");
}
#[test]
fn close_to_right_keeps_pinned_tabs_to_the_right_of_the_pivot() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
t.add_tab_with_path(std::path::PathBuf::from("/d"));
t.toggle_pin(0); t.toggle_pin(1); let removed = t.close_to_right(0); assert_eq!(
removed, 2,
"/c and /d close; the pinned /b to the right survives"
);
assert_eq!(t.tab_count(), 2);
assert!(t.is_pinned(0) && t.is_pinned(1));
assert_eq!(t.tab_path(0).as_deref(), Some(std::path::Path::new("/a")));
assert_eq!(t.tab_path(1).as_deref(), Some(std::path::Path::new("/b")));
assert_eq!(t.active_index(), 0, "the pivot tab is active");
}
#[test]
fn keep_open_promotes_a_preview_tab_and_returns_true() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.editors[0].preview = true;
assert!(t.is_preview(0));
assert!(t.keep_open(0), "promoting a preview tab returns true");
assert!(!t.is_preview(0), "the tab is no longer the preview slot");
}
#[test]
fn keep_open_is_a_noop_on_an_already_permanent_tab() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.editors[0].preview = false;
assert!(
!t.keep_open(0),
"a permanent tab returns false (nothing to promote)"
);
}
#[test]
fn keep_open_out_of_range_is_false() {
let mut t = EditorTabs::new();
assert!(!t.keep_open(99));
}
#[test]
fn keep_open_only_affects_the_target_tab() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.editors[0].preview = true;
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.editors[1].preview = true;
t.keep_open(0);
assert!(!t.is_preview(0));
assert!(t.is_preview(1), "the sibling's preview flag is untouched");
}
#[test]
fn is_preview_and_is_pinned_are_false_out_of_range() {
let t = EditorTabs::new();
assert!(!t.is_preview(99));
assert!(!t.is_pinned(99));
}
#[test]
fn toggle_pin_clears_the_preview_flag_when_pinning() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.editors[0].preview = true;
assert!(t.toggle_pin(0), "pinning returns the new state = true");
assert!(t.is_pinned(0));
assert!(!t.is_preview(0), "a pinned tab is never the preview slot");
}
#[test]
fn toggle_pin_returns_new_state_and_round_trips() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
assert!(t.toggle_pin(0), "first toggle pins");
assert!(!t.toggle_pin(0), "second toggle unpins");
assert!(!t.is_pinned(0));
}
#[test]
fn toggle_pin_out_of_range_is_a_noop_and_false() {
let mut t = EditorTabs::new();
let before = t.tab_count();
assert!(!t.toggle_pin(99));
assert_eq!(t.tab_count(), before, "no panic, no mutation");
}
#[test]
fn close_all_closes_pinned_tabs_too() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.toggle_pin(0);
let removed = t.close_all();
assert_eq!(removed, 2);
assert_eq!(t.tab_count(), 1, "collapses to a single blank tab");
assert!(!t.is_pinned(0));
}
#[test]
fn close_saved_closes_clean_pinned_tabs() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.editors[1].dirty = true;
t.toggle_pin(0); let removed = t.close_saved();
assert_eq!(removed, 1, "the clean pinned tab is still closed");
assert_eq!(t.tab_path(0).as_deref(), Some(std::path::Path::new("/b")));
}
#[test]
fn pinned_tab_paints_the_thumb_tack_instead_of_the_close_cross() {
let f1 = NamedTempFile::new().unwrap();
let f2 = NamedTempFile::new().unwrap();
std::fs::write(f1.path(), "1\n").unwrap();
std::fs::write(f2.path(), "2\n").unwrap();
let mut t = EditorTabs::new();
t.open_pinned(f1.path()).unwrap();
t.open_pinned(f2.path()).unwrap();
t.toggle_pin(0); let active_idx = t.active_index();
t.editors[active_idx].focused = true;
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut t).render(area, &mut buf);
let strip: String = (0..area.width).map(|x| buf[(x, 0)].symbol()).collect();
assert!(
strip.contains('\u{f08d}'),
"the pinned tab shows the thumb-tack glyph in its close cell; strip was {strip:?}"
);
assert!(
strip.contains('\u{2715}'),
"the unpinned tab still shows the close cross; strip was {strip:?}"
);
}
#[test]
fn take_active_editor_removes_and_returns_the_active_tab() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b")); let ed = t.take_active_editor();
assert_eq!(ed.path.as_deref(), Some(std::path::Path::new("/b")));
assert_eq!(t.tab_count(), 1);
assert_eq!(t.tab_path(0).as_deref(), Some(std::path::Path::new("/a")));
}
#[test]
fn take_active_editor_on_the_last_tab_leaves_a_blank_group() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
let ed = t.take_active_editor();
assert_eq!(ed.path.as_deref(), Some(std::path::Path::new("/a")));
assert_eq!(t.tab_count(), 1);
assert!(t.is_blank_initial(), "the group falls back to a blank tab");
}
#[test]
fn push_editor_replaces_a_blank_group_then_appends() {
let mut src = EditorTabs::new();
src.editors[0].path = Some(std::path::PathBuf::from("/a"));
let ed = src.take_active_editor();
let mut dst = EditorTabs::new(); dst.push_editor(ed);
assert_eq!(dst.tab_count(), 1, "pushing into a blank group replaces it");
assert_eq!(dst.tab_path(0).as_deref(), Some(std::path::Path::new("/a")));
assert_eq!(dst.active_index(), 0);
let mut src2 = EditorTabs::new();
src2.editors[0].path = Some(std::path::PathBuf::from("/b"));
let ed2 = src2.take_active_editor();
dst.push_editor(ed2);
assert_eq!(dst.tab_count(), 2, "a second push appends and activates it");
assert_eq!(dst.active_index(), 1);
assert_eq!(dst.tab_path(1).as_deref(), Some(std::path::Path::new("/b")));
}
#[test]
fn close_others_is_a_noop_when_only_one_tab_is_open() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/only"));
let removed = t.close_others(0);
assert_eq!(removed, 0, "nothing to drop");
assert_eq!(t.tab_count(), 1);
assert_eq!(t.path.as_deref(), Some(std::path::Path::new("/only")));
}
#[test]
fn close_to_right_drops_only_tabs_past_the_pivot_and_keeps_left_side() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
t.add_tab_with_path(std::path::PathBuf::from("/d"));
let removed = t.close_to_right(1);
assert_eq!(removed, 2);
assert_eq!(t.tab_count(), 2);
assert_eq!(
t.editors[0].path.as_deref(),
Some(std::path::Path::new("/a")),
"left-side tabs are untouched"
);
assert_eq!(
t.editors[1].path.as_deref(),
Some(std::path::Path::new("/b"))
);
assert!(
t.active_index() < t.tab_count(),
"active must still point at a valid tab"
);
}
#[test]
fn close_to_right_at_last_tab_is_a_noop() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
let before = t.tab_count();
let removed = t.close_to_right(1);
assert_eq!(removed, 0);
assert_eq!(t.tab_count(), before);
}
#[test]
fn close_all_collapses_to_a_single_blank_tab() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
let removed = t.close_all();
assert_eq!(removed, 3, "report how many tabs were collapsed");
assert_eq!(t.tab_count(), 1, "always at least one tab survives");
assert!(t.path.is_none(), "the surviving tab is a fresh blank slot");
}
#[test]
fn close_saved_drops_clean_tabs_and_keeps_dirty_ones() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
t.editors[1].dirty = true;
let removed = t.close_saved();
assert_eq!(removed, 2, "the two saved tabs (a, c) are closed");
assert_eq!(t.tab_count(), 1, "only the dirty tab survives");
assert_eq!(
t.editors[0].path.as_deref(),
Some(std::path::Path::new("/b")),
"the kept tab is the dirty one"
);
assert_eq!(t.active_index(), 0, "the kept tab becomes active");
assert!(t.editors[0].focused, "the kept tab is focused");
}
#[test]
fn close_saved_collapses_to_blank_when_no_tab_is_dirty() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
let removed = t.close_saved();
assert_eq!(removed, 2, "both saved tabs are closed");
assert_eq!(t.tab_count(), 1, "always at least one tab survives");
assert!(t.path.is_none(), "the survivor is a fresh blank slot");
}
#[test]
fn close_saved_is_a_noop_when_every_tab_is_dirty() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.editors[0].dirty = true;
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.editors[1].dirty = true;
let removed = t.close_saved();
assert_eq!(removed, 0, "nothing saved means nothing to close");
assert_eq!(t.tab_count(), 2, "both dirty tabs stay open");
}
#[test]
fn close_tab_on_last_remaining_tab_resets_to_blank_buffer() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/only.rs"));
t.editors[0].lines = vec!["something".to_string()];
t.editors[0].dirty = true;
assert!(t.close_tab(0));
assert_eq!(t.tab_count(), 1);
assert!(t.path.is_none());
assert!(t.lines.is_empty() || t.lines == vec![String::new()]);
assert!(!t.dirty);
}
#[test]
fn close_screen_x_is_present_even_for_a_single_open_tab() {
use ratatui::buffer::Buffer;
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/only.rs"));
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 5,
};
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let close_x = t.close_screen_x(0).expect("single tab still shows X");
assert_eq!(t.close_at(close_x, area.y), Some(0));
}
#[test]
fn editor_tabs_tab_at_x_returns_index_of_clicked_tab() {
use ratatui::buffer::Buffer;
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/long_name.rs"));
t.add_tab_with_path(std::path::PathBuf::from("/b.rs"));
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let first = t.tab_screen_x(0).expect("tab 0 laid out");
let second = t.tab_screen_x(1).expect("tab 1 laid out");
assert_eq!(t.tab_at(first.0, area.y), Some(0));
assert_eq!(t.tab_at(second.0, area.y), Some(1));
assert_eq!(t.tab_at(area.x + area.width - 1, area.y + 5), None);
}
#[test]
fn open_preview_creates_a_preview_tab_when_none_exists() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.editors[0].preview = false;
t.add_preview_tab_with_path(std::path::PathBuf::from("/b"));
assert_eq!(t.tab_count(), 2);
assert_eq!(t.preview_index(), Some(1));
assert_eq!(t.active_index(), 1);
}
#[test]
fn open_preview_reuses_existing_preview_slot_for_a_new_path() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.editors[0].preview = false;
t.add_preview_tab_with_path(std::path::PathBuf::from("/b"));
t.repoint_preview_to(std::path::PathBuf::from("/c"));
assert_eq!(t.tab_count(), 2);
assert_eq!(t.preview_index(), Some(1));
assert_eq!(
t.editors[1].path.as_deref(),
Some(std::path::Path::new("/c"))
);
}
#[test]
fn open_preview_reuses_blank_initial_tab_instead_of_stacking() {
let mut t = EditorTabs::new();
let mut f = NamedTempFile::new().unwrap();
write!(f, "hello").unwrap();
t.open_preview(f.path()).unwrap();
assert_eq!(t.tab_count(), 1, "blank initial tab must be reused");
assert_eq!(t.preview_index(), Some(0));
assert_eq!(t.path.as_deref(), Some(f.path()));
}
#[test]
fn tab_labels_disambiguate_colliding_names_with_the_shortest_dir_context() {
let tmp = tempfile::tempdir().unwrap();
for d in ["alpha", "beta", "a/x", "b/x"] {
std::fs::create_dir_all(tmp.path().join(d)).unwrap();
}
for f in [
"alpha/main.rs",
"beta/main.rs",
"solo.rs",
"a/x/mod.rs",
"b/x/mod.rs",
] {
std::fs::write(tmp.path().join(f), "x\n").unwrap();
}
let mut tabs = EditorTabs::new();
for f in [
"alpha/main.rs",
"beta/main.rs",
"solo.rs",
"a/x/mod.rs",
"b/x/mod.rs",
] {
tabs.open_pinned(&tmp.path().join(f)).unwrap();
}
let labels = tabs.tab_display_labels();
assert_eq!(labels[0], "main.rs — alpha");
assert_eq!(labels[1], "main.rs — beta");
assert_eq!(labels[2], "solo.rs", "a unique name stays bare");
assert_eq!(labels[3], "mod.rs — a/x");
assert_eq!(labels[4], "mod.rs — b/x");
}
#[test]
fn tab_labels_disambiguate_deep_shared_tails_and_measure_wide_names_in_cells() {
let tmp = tempfile::tempdir().unwrap();
let deep = "d01/d02/d03/d04/d05/d06/d07/d08/d09/d10/d11/d12/d13/d14/d15/d16/d17";
let a = tmp.path().join("alpha").join(deep);
let b = tmp.path().join("beta").join(deep);
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
std::fs::write(a.join("main.rs"), "a\n").unwrap();
std::fs::write(b.join("main.rs"), "b\n").unwrap();
let wide = tmp.path().join("日本語");
std::fs::create_dir_all(&wide).unwrap();
std::fs::write(wide.join("main.rs"), "w\n").unwrap();
let mut tabs = EditorTabs::new();
tabs.open_pinned(&a.join("main.rs")).unwrap();
tabs.open_pinned(&b.join("main.rs")).unwrap();
tabs.open_pinned(&wide.join("main.rs")).unwrap();
let labels = tabs.tab_display_labels();
let mut seen = std::collections::HashSet::new();
assert!(
labels.iter().all(|l| seen.insert(l.clone())),
"every colliding tab gets a distinct title, however deep the shared tail: {labels:?}"
);
assert!(
labels[2].contains("日本語"),
"the wide dir name suffixes too: {labels:?}"
);
let area = ratatui::layout::Rect {
x: 0,
y: 0,
width: 600,
height: 20,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
use ratatui::widgets::Widget;
(&mut tabs).render(area, &mut buf);
let ranges: Vec<(u16, u16)> = tabs.tab_screen_ranges.clone();
for (i, (x, w)) in ranges.iter().enumerate() {
if *w == 0 {
continue;
}
let row: String = (*x..*x + *w)
.map(|cx| buf[(cx, tabs.tab_strip_y_for_test())].symbol().to_string())
.collect();
assert!(
row.contains('✕'),
"tab {i}'s close glyph must sit inside its hit range; range painted: {row:?}"
);
}
}
#[test]
fn open_pinned_reuses_blank_initial_tab_instead_of_stacking() {
let mut t = EditorTabs::new();
let mut f = NamedTempFile::new().unwrap();
write!(f, "hello").unwrap();
t.open_pinned(f.path()).unwrap();
assert_eq!(t.tab_count(), 1, "blank initial tab must be reused");
assert!(
t.preview_index().is_none(),
"pinned open must not leave preview state"
);
}
#[test]
fn open_preview_drops_stale_preview_when_switching_to_pinned_tab() {
let mut t = EditorTabs::new();
let mut f1 = NamedTempFile::new().unwrap();
write!(f1, "a").unwrap();
let mut f2 = NamedTempFile::new().unwrap();
write!(f2, "b").unwrap();
t.open_preview(f1.path()).unwrap(); t.pin_active(); t.open_preview(f2.path()).unwrap(); assert_eq!(t.tab_count(), 2);
t.open_preview(f1.path()).unwrap(); assert_eq!(t.tab_count(), 1);
assert!(t.preview_index().is_none());
assert_eq!(t.path.as_deref(), Some(f1.path()));
}
#[test]
fn pin_active_clears_preview_flag() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_preview_tab_with_path(std::path::PathBuf::from("/b"));
assert_eq!(t.preview_index(), Some(1));
t.pin_active();
assert!(
t.preview_index().is_none(),
"no tab should be in preview state"
);
assert!(!t.editors[1].preview);
}
#[test]
fn editor_tabs_find_tab_with_path_returns_index_when_open() {
let mut t = EditorTabs::new();
t.editors[0].path = Some(std::path::PathBuf::from("/a"));
t.add_tab_with_path(std::path::PathBuf::from("/b"));
t.add_tab_with_path(std::path::PathBuf::from("/c"));
assert_eq!(t.find_tab_with_path(std::path::Path::new("/a")), Some(0));
assert_eq!(t.find_tab_with_path(std::path::Path::new("/b")), Some(1));
assert_eq!(t.find_tab_with_path(std::path::Path::new("/c")), Some(2));
assert_eq!(t.find_tab_with_path(std::path::Path::new("/missing")), None);
}
#[test]
fn editor_tabs_deref_exposes_active_editor_state() {
let mut t = EditorTabs::new();
t.lines = vec!["abc".to_string()];
t.cursor_col = 3;
assert_eq!(t.lines, vec!["abc".to_string()]);
assert_eq!(t.cursor_col, 3);
}
#[test]
fn mouse_drag_extends_selection() {
let mut e = editor_with("hello world");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
let text_x: u16 = 3;
e.mouse_down(text_x, 0);
e.mouse_drag(text_x + 5, 0);
let sel = e.selection.unwrap();
assert_eq!(sel.anchor, (0, 0));
assert_eq!(sel.head, (0, 5));
assert_eq!(e.cursor_col, 5);
}
#[test]
fn editor_tabs_rename_open_path_updates_matching_tab_only() {
let mut tabs = EditorTabs::new();
tabs.add_tab_with_path(std::path::PathBuf::from("/work/old.txt"));
tabs.add_tab_with_path(std::path::PathBuf::from("/work/other.txt"));
let old = std::path::PathBuf::from("/work/old.txt");
let new = std::path::PathBuf::from("/work/renamed.txt");
tabs.rename_open_path(&old, &new);
let paths: Vec<Option<std::path::PathBuf>> =
tabs.iter_tabs().map(|e| e.path.clone()).collect();
assert!(paths.contains(&Some(new.clone())));
assert!(!paths.contains(&Some(old)));
assert!(paths.contains(&Some(std::path::PathBuf::from("/work/other.txt"))));
}
#[test]
fn editor_tabs_rename_open_path_is_noop_when_path_not_open() {
let mut tabs = EditorTabs::new();
tabs.add_tab_with_path(std::path::PathBuf::from("/work/a.txt"));
let before: Vec<Option<std::path::PathBuf>> =
tabs.iter_tabs().map(|e| e.path.clone()).collect();
tabs.rename_open_path(
std::path::Path::new("/work/never-opened.txt"),
std::path::Path::new("/work/whatever.txt"),
);
let after: Vec<Option<std::path::PathBuf>> =
tabs.iter_tabs().map(|e| e.path.clone()).collect();
assert_eq!(before, after);
}
#[test]
fn move_line_down_swaps_with_next_and_follows_cursor() {
let mut e = editor_with("a\nb\nc");
e.cursor_row = 0;
e.move_lines_down();
assert_eq!(e.lines, vec!["b", "a", "c"]);
assert_eq!(e.cursor_row, 1, "cursor follows the moved line");
}
#[test]
fn move_line_up_swaps_with_previous_and_follows_cursor() {
let mut e = editor_with("a\nb\nc");
e.cursor_row = 2;
e.move_lines_up();
assert_eq!(e.lines, vec!["a", "c", "b"]);
assert_eq!(e.cursor_row, 1);
}
#[test]
fn move_line_up_at_top_is_noop() {
let mut e = editor_with("a\nb");
e.cursor_row = 0;
e.move_lines_up();
assert_eq!(e.lines, vec!["a", "b"]);
assert_eq!(e.cursor_row, 0);
}
#[test]
fn move_line_down_at_bottom_is_noop() {
let mut e = editor_with("a\nb");
e.cursor_row = 1;
e.move_lines_down();
assert_eq!(e.lines, vec!["a", "b"]);
assert_eq!(e.cursor_row, 1);
}
#[test]
fn move_line_down_moves_whole_selected_block() {
let mut e = editor_with("a\nb\nc\nd");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (1, 1),
});
e.cursor_row = 1;
e.move_lines_down();
assert_eq!(e.lines, vec!["c", "a", "b", "d"]);
assert_eq!(e.cursor_row, 2);
let sel = e.selection.unwrap();
assert_eq!((sel.anchor.0, sel.head.0), (1, 2), "selection rows shift");
}
#[test]
fn toggle_line_comment_adds_rust_token() {
let mut e = editor_with(" let x = 1;");
e.lang = Some(LangKind::Rust);
e.cursor_row = 0;
assert!(e.toggle_line_comment());
assert_eq!(e.lines, vec![" // let x = 1;"]);
}
#[test]
fn toggle_line_comment_removes_existing_rust_token() {
let mut e = editor_with(" // let x = 1;");
e.lang = Some(LangKind::Rust);
e.cursor_row = 0;
assert!(e.toggle_line_comment());
assert_eq!(e.lines, vec![" let x = 1;"]);
}
#[test]
fn toggle_line_comment_python_hash() {
let mut e = editor_with("x = 1");
e.lang = Some(LangKind::Python);
e.cursor_row = 0;
assert!(e.toggle_line_comment());
assert_eq!(e.lines, vec!["# x = 1"]);
}
#[test]
fn toggle_line_comment_refreshes_highlights() {
let mut e = editor_with("x = 1");
e.lang = Some(LangKind::Python);
e.recompute_highlights();
e.cursor_row = 0;
assert!(e.toggle_line_comment());
let after: Vec<(usize, usize, Option<Color>)> = e.highlights[0]
.iter()
.map(|s| (s.start, s.end, s.style.fg))
.collect();
e.recompute_highlights();
let fresh: Vec<(usize, usize, Option<Color>)> = e.highlights[0]
.iter()
.map(|s| (s.start, s.end, s.style.fg))
.collect();
assert_eq!(
after, fresh,
"toggle_line_comment must refresh syntax highlights to match the new buffer"
);
}
#[test]
fn toggle_line_comment_block_comments_at_min_indent() {
let mut e = editor_with(" a\n b");
e.lang = Some(LangKind::Python);
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (1, 5),
});
assert!(e.toggle_line_comment());
assert_eq!(e.lines, vec![" # a", " # b"]);
}
#[test]
fn toggle_line_comment_block_uncomments_when_all_commented() {
let mut e = editor_with(" # a\n # b");
e.lang = Some(LangKind::Python);
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (1, 7),
});
assert!(e.toggle_line_comment());
assert_eq!(e.lines, vec![" a", " b"]);
}
#[test]
fn toggle_line_comment_unknown_lang_is_noop() {
let mut e = editor_with("x = 1");
e.lang = None;
assert!(!e.toggle_line_comment());
assert_eq!(e.lines, vec!["x = 1"]);
}
#[test]
fn toggle_block_comment_wraps_selection() {
let mut e = editor_with("let x = 1;");
e.lang = Some(LangKind::Rust);
e.selection = Some(EditorSelection {
anchor: (0, 4),
head: (0, 5),
});
assert!(e.toggle_block_comment());
assert_eq!(e.lines, vec!["let /* x */ = 1;"]);
}
#[test]
fn toggle_block_comment_unwraps_when_already_wrapped() {
let mut e = editor_with("let /* x */ = 1;");
e.lang = Some(LangKind::Rust);
e.selection = Some(EditorSelection {
anchor: (0, 4),
head: (0, 11),
});
assert!(e.toggle_block_comment());
assert_eq!(e.lines, vec!["let x = 1;"]);
}
#[test]
fn toggle_block_comment_python_wraps_in_triple_quotes() {
let mut e = editor_with("x = 1");
e.lang = Some(LangKind::Python);
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (0, 5),
});
assert!(e.toggle_block_comment());
assert_eq!(e.lines, vec!["\"\"\" x = 1 \"\"\""]);
}
#[test]
fn toggle_block_comment_python_unwraps_triple_quotes() {
let mut e = editor_with("\"\"\" x = 1 \"\"\"");
e.lang = Some(LangKind::Python);
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (0, 13),
});
assert!(e.toggle_block_comment());
assert_eq!(e.lines, vec!["x = 1"]);
}
#[test]
fn join_lines_merges_current_with_next() {
let mut e = editor_with("hello\n world");
e.cursor_row = 0;
e.join_lines();
assert_eq!(e.lines, vec!["hello world"]);
}
#[test]
fn join_lines_merges_whole_selection() {
let mut e = editor_with("a\n b\n c\nd");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (2, 3),
});
e.cursor_row = 2;
e.join_lines();
assert_eq!(e.lines, vec!["a b c", "d"]);
}
#[test]
fn join_lines_on_last_line_is_noop() {
let mut e = editor_with("a\nb");
e.cursor_row = 1;
e.join_lines();
assert_eq!(e.lines, vec!["a", "b"]);
}
#[test]
fn transform_upper_on_selection() {
let mut e = editor_with("hello world");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (0, 5),
});
e.transform_selection_case(CaseTransform::Upper);
assert_eq!(e.lines, vec!["HELLO world"]);
}
#[test]
fn transform_lower_on_selection() {
let mut e = editor_with("HELLO world");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (0, 5),
});
e.transform_selection_case(CaseTransform::Lower);
assert_eq!(e.lines, vec!["hello world"]);
}
#[test]
fn transform_title_on_selection() {
let mut e = editor_with("hello there world");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (0, 17),
});
e.transform_selection_case(CaseTransform::Title);
assert_eq!(e.lines, vec!["Hello There World"]);
}
#[test]
fn transform_upper_falls_back_to_word_at_cursor() {
let mut e = editor_with("alpha beta");
e.cursor_row = 0;
e.cursor_col = 7; e.transform_selection_case(CaseTransform::Upper);
assert_eq!(e.lines, vec!["alpha BETA"]);
}
#[test]
fn sort_lines_ascending_over_selection() {
let mut e = editor_with("banana\napple\ncherry");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (2, 6),
});
e.sort_lines(true);
assert_eq!(e.lines, vec!["apple", "banana", "cherry"]);
}
#[test]
fn sort_lines_descending_over_selection() {
let mut e = editor_with("apple\nbanana\ncherry");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (2, 6),
});
e.sort_lines(false);
assert_eq!(e.lines, vec!["cherry", "banana", "apple"]);
}
#[test]
fn sort_lines_without_selection_sorts_whole_buffer() {
let mut e = editor_with("c\na\nb");
e.selection = None;
e.sort_lines(true);
assert_eq!(e.lines, vec!["a", "b", "c"]);
}
#[test]
fn trim_trailing_whitespace_strips_every_line() {
let mut e = editor_with("a \nb\t\n c ");
assert!(e.trim_trailing_whitespace());
assert_eq!(e.lines, vec!["a", "b", " c"]);
}
#[test]
fn trim_trailing_whitespace_clamps_cursor() {
let mut e = editor_with("abc ");
e.cursor_row = 0;
e.cursor_col = 7;
assert!(e.trim_trailing_whitespace());
assert_eq!(e.cursor_col, 3, "cursor clamps to trimmed end");
}
#[test]
fn trim_trailing_whitespace_noop_when_clean() {
let mut e = editor_with("a\nb");
assert!(!e.trim_trailing_whitespace());
assert_eq!(e.lines, vec!["a", "b"]);
}
#[test]
fn add_cursor_below_pushes_caret_on_next_row() {
let mut e = editor_with("aaaa\nbbbb\ncccc");
e.cursor_row = 0;
e.cursor_col = 2;
e.add_cursor_below();
assert_eq!(e.carets.len(), 1);
let c = e.carets[0];
assert_eq!(c.head, (1, 2));
assert_eq!(c.anchor, (1, 2), "zero-width caret");
}
#[test]
fn add_cursor_above_pushes_caret_on_previous_row() {
let mut e = editor_with("aaaa\nbbbb\ncccc");
e.cursor_row = 2;
e.cursor_col = 3;
e.add_cursor_above();
assert_eq!(e.carets.len(), 1);
assert_eq!(e.carets[0].head, (1, 3));
}
#[test]
fn add_cursor_below_clamps_to_short_line() {
let mut e = editor_with("aaaa\nbb");
e.cursor_row = 0;
e.cursor_col = 4;
e.add_cursor_below();
assert_eq!(e.carets[0].head, (1, 2), "column clamps to line length");
}
#[test]
fn add_cursor_below_at_last_row_is_noop() {
let mut e = editor_with("aaaa\nbbbb");
e.cursor_row = 1;
e.cursor_col = 1;
e.add_cursor_below();
assert!(e.carets.is_empty());
}
#[test]
fn select_next_occurrence_grows_selection_one_match_at_a_time() {
let mut e = editor_with("foo bar foo baz foo");
e.cursor_row = 0;
e.cursor_col = 1; assert_eq!(e.select_next_occurrence(), 1);
assert!(!e.has_multi_cursor());
assert_eq!(e.selection.unwrap().normalised(), ((0, 0), (0, 3)));
assert_eq!(e.select_next_occurrence(), 2);
assert!(e.has_multi_cursor());
assert_eq!(e.select_next_occurrence(), 3);
assert_eq!(e.select_next_occurrence(), 3);
}
#[test]
fn add_caret_at_screen_adds_and_toggles_a_secondary_caret() {
let mut e = editor_with("fn main() {}\nlet x = 1;");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2;
e.cursor_row = 0;
e.cursor_col = 0;
assert!(e.add_caret_at_screen(6, 1));
assert_eq!((e.cursor_row, e.cursor_col), (1, 3));
assert_eq!(e.carets.len(), 1, "the previous cursor is now a caret");
assert_eq!(e.carets[0].head, (0, 0));
assert!(e.add_caret_at_screen(3, 0));
assert_eq!(e.carets.len(), 0, "clicking an existing caret removes it");
}
#[test]
fn box_select_spans_rows_into_a_column_of_carets() {
let mut e = editor_with("aaaa\nbbbb\ncccc");
e.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
e.last_gutter_width = 2; assert!(e.begin_box_select(4, 0));
e.box_drag_to_screen(6, 2);
assert!(e.box_selecting());
assert_eq!(e.selection.unwrap().normalised(), ((2, 1), (2, 3)));
assert_eq!(e.carets.len(), 2);
assert_eq!(e.carets[0].normalised(), ((0, 1), (0, 3)));
assert_eq!(e.carets[1].normalised(), ((1, 1), (1, 3)));
e.end_box_select();
assert!(!e.box_selecting());
}
#[test]
fn select_next_occurrence_noop_off_a_word() {
let mut e = editor_with(" foo");
e.cursor_row = 0;
e.cursor_col = 0; assert_eq!(e.select_next_occurrence(), 0);
assert!(e.selection.is_none());
}
#[test]
fn toggle_wrap_turns_wrap_on_for_code_file() {
let mut e = editor_with("fn main() {}");
e.lang = Some(LangKind::Rust);
assert!(!e.wrap_enabled(), "code files default to no wrap");
e.toggle_wrap();
assert!(e.wrap_enabled());
}
#[test]
fn toggle_wrap_turns_wrap_off_for_markdown() {
let mut e = editor_with("# title");
e.lang = Some(LangKind::Markdown);
assert!(e.wrap_enabled(), "markdown defaults to wrap on");
e.toggle_wrap();
assert!(!e.wrap_enabled());
}
#[test]
fn jump_to_bracket_from_open_moves_to_matching_close() {
let mut e = editor_with("foo(bar)baz");
e.cursor_row = 0;
e.cursor_col = 3; assert!(e.jump_to_matching_bracket());
assert_eq!((e.cursor_row, e.cursor_col), (0, 7)); }
#[test]
fn jump_to_bracket_from_close_moves_to_matching_open() {
let mut e = editor_with("foo(bar)baz");
e.cursor_row = 0;
e.cursor_col = 8; assert!(e.jump_to_matching_bracket());
assert_eq!((e.cursor_row, e.cursor_col), (0, 3)); }
#[test]
fn jump_to_bracket_from_inside_goes_to_enclosing_close() {
let mut e = editor_with("foo(bar)baz");
e.cursor_row = 0;
e.cursor_col = 5; assert!(e.jump_to_matching_bracket());
assert_eq!((e.cursor_row, e.cursor_col), (0, 7)); }
#[test]
fn jump_to_bracket_respects_nesting() {
let mut e = editor_with("(a(b)c)");
e.cursor_row = 0;
e.cursor_col = 0; assert!(e.jump_to_matching_bracket());
assert_eq!((e.cursor_row, e.cursor_col), (0, 6)); }
#[test]
fn jump_to_bracket_works_across_lines() {
let mut e = editor_with("fn f() {\n x\n}");
e.cursor_row = 0;
e.cursor_col = 7; assert!(e.jump_to_matching_bracket());
assert_eq!((e.cursor_row, e.cursor_col), (2, 0)); }
#[test]
fn jump_to_bracket_noop_without_a_bracket() {
let mut e = editor_with("hello world");
e.cursor_row = 0;
e.cursor_col = 2;
assert!(!e.jump_to_matching_bracket());
assert_eq!((e.cursor_row, e.cursor_col), (0, 2));
}
#[test]
fn sticky_scroll_never_covers_the_caret_row() {
let mut e = editor_with(&format!("fn a() {{\n{}}}\n", " x\n".repeat(60)));
e.scroll = 3;
e.cursor_row = 3;
e.sticky_lines = vec![0];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let caret = e
.cursor_screen_pos()
.expect("the caret must have a screen row");
assert!(
!e.sticky_click_rows.iter().any(|&(y, _)| y == caret.1),
"the sticky band painted over the caret's own row {}",
caret.1
);
}
#[test]
fn sticky_band_erases_accept_spans_it_paints_over() {
let mut e = editor_with(
"fn outer() {\n a();\n<<<<<<< HEAD\n ours();\n=======\n theirs();\n>>>>>>> feature\n b();\n}",
);
e.scroll = 2; e.cursor_row = 7;
e.sticky_lines = vec![0];
let area = Rect {
x: 0,
y: 0,
width: 120,
height: 12,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
assert!(
!e.sticky_click_rows.is_empty(),
"precondition: the sticky band must have painted"
);
let band_rows: Vec<u16> = e.sticky_click_rows.iter().map(|&(y, _)| y).collect();
assert!(
!e.merge_action_spans
.iter()
.any(|(y, _, _, _)| band_rows.contains(y)),
"spans under the sticky band must be dropped; spans={:?} band={band_rows:?}",
e.merge_action_spans
);
assert!(
e.merge_action_spans.iter().all(|(_, _, row, _)| *row == 2),
"the header's spans below the band (if visible elsewhere) still target the real block"
);
}
#[test]
fn breadcrumb_row_renders_below_tab_strip_and_maps_symbol_clicks() {
let mut tabs = EditorTabs::new();
tabs.breadcrumbs = vec![
Crumb {
label: "src".into(),
target: None,
},
Crumb {
label: "m.rs".into(),
target: None,
},
Crumb {
label: "build".into(),
target: Some((5, 2)),
},
];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut tabs).render(area, &mut buf);
let by = area.y + 1;
let hit = (0..area.width).find_map(|x| tabs.breadcrumb_target_at(x, by));
assert_eq!(hit, Some((5, 2)), "clicking the symbol crumb jumps there");
assert_eq!(tabs.breadcrumb_target_at(10, area.y), None);
}
#[test]
fn breadcrumbs_measure_wide_glyphs_in_display_cells() {
let mut tabs = EditorTabs::new();
tabs.breadcrumbs = vec![
Crumb {
label: "文档文档".into(),
target: None,
},
Crumb {
label: "build".into(),
target: Some((5, 2)),
},
];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut tabs).render(area, &mut buf);
let by = area.y + 1;
let row: String = (0..area.width)
.map(|x| buf[(x, by)].symbol().to_string())
.collect::<Vec<_>>()
.concat();
assert_eq!(
(row.matches('文').count(), row.matches('档').count()),
(2, 2),
"the whole wide label must survive, got {row:?}"
);
assert!(
row.contains("build"),
"and the next crumb must still be painted, got {row:?}"
);
let (x, w, _) = tabs.breadcrumb_ranges[0];
assert_eq!(w, 8, "a 4-char CJK label occupies 8 cells, not 4");
let (next_x, _, _) = tabs.breadcrumb_ranges[1];
assert!(
next_x >= x + w,
"the next crumb must start past this one, got {next_x} vs {x}+{w}"
);
}
#[test]
fn breadcrumb_bar_hidden_when_there_are_no_crumbs() {
let mut tabs = EditorTabs::new();
tabs.breadcrumbs.clear();
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut tabs).render(area, &mut buf);
assert_eq!(tabs.breadcrumb_target_at(10, area.y + 1), None);
}
#[test]
fn sticky_scroll_pins_header_rows_and_maps_clicks_to_their_lines() {
let text = (0..40)
.map(|i| format!("line{i}"))
.collect::<Vec<_>>()
.join("\n");
let mut e = editor_with(&text);
e.focused = true;
e.scroll = 20;
e.cursor_row = 25;
e.sticky_lines = vec![0, 10];
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 15,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let top = e.last_inner.y;
assert_eq!(e.sticky_line_at(5, top), Some(0), "row 0 pins line 0");
assert_eq!(e.sticky_line_at(5, top + 1), Some(10), "row 1 pins line 10");
assert_eq!(
e.sticky_line_at(5, top + 5),
None,
"a content row below the band is not sticky"
);
}
#[test]
fn a_wheel_scroll_keeps_the_band_and_parks_the_caret_below_it() {
let text = (0..80)
.map(|i| format!("line{i}"))
.collect::<Vec<_>>()
.join("\n");
let mut e = editor_with(&text);
e.focused = true;
e.sticky_lines = vec![0, 10];
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 15,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf); assert_eq!(e.cursor_row, 0, "caret starts on the first line");
e.scroll_down(20);
(&mut e).render(area, &mut buf);
let top = e.last_inner.y;
assert_eq!(
e.sticky_line_at(5, top),
Some(0),
"the band must survive a wheel scroll"
);
assert_eq!(e.sticky_line_at(5, top + 1), Some(10));
assert!(
e.cursor_row >= e.scroll + 2,
"caret dragged below the two-row band, not under it (row {}, scroll {})",
e.cursor_row,
e.scroll
);
}
#[test]
fn the_band_stops_above_the_caret_with_a_fold_between_them() {
let mut text: Vec<String> = (0..10).map(|i| format!("head{i}")).collect();
text.push(String::from("def f():"));
text.extend((0..3).map(|i| format!(" body{i}")));
text.extend((0..10).map(|i| format!("tail{i}")));
let mut e = editor_with(&text.join("\n"));
e.focused = true;
e.scroll = 10;
e.toggle_fold(10); assert!(e.is_line_hidden(12), "the fold body is hidden");
e.cursor_row = 14;
e.sticky_lines = vec![0, 5];
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 15,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let top = e.last_inner.y;
assert_eq!(e.sticky_line_at(5, top), Some(0), "outermost header pins");
assert_eq!(
e.sticky_line_at(5, top + 1),
None,
"the caret's own painted row must stay clear of the band"
);
}
#[test]
fn sticky_scroll_hidden_without_pinned_lines() {
let mut e = editor_with("a\nb\nc\n");
e.focused = true;
e.sticky_lines.clear();
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
assert_eq!(e.sticky_line_at(5, e.last_inner.y), None);
}
#[test]
fn bracket_match_pair_from_open_returns_both_brackets() {
let mut e = editor_with("foo(bar)baz");
e.cursor_col = 3; assert_eq!(e.bracket_match_pair(), Some(((0, 3), (0, 7))));
}
#[test]
fn bracket_match_pair_from_after_close_returns_both_brackets() {
let mut e = editor_with("foo(bar)baz");
e.cursor_col = 8; assert_eq!(e.bracket_match_pair(), Some(((0, 3), (0, 7))));
}
#[test]
fn bracket_match_pair_none_when_caret_touches_no_bracket() {
let mut e = editor_with("foo(bar)baz");
e.cursor_col = 5; assert_eq!(e.bracket_match_pair(), None);
}
#[test]
fn render_paints_bracket_match_background_on_both_brackets() {
let mut e = editor_with("foo(bar)baz");
e.focused = true;
e.cursor_col = 3; let area = Rect {
x: 0,
y: 0,
width: 40,
height: 6,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y = e.last_inner.y;
let bm = e.theme.bracket_match_bg();
assert_eq!(buf[(text_x + 3, y)].bg, bm, "the '(' is highlighted");
assert_eq!(buf[(text_x + 7, y)].bg, bm, "the ')' is highlighted");
assert_ne!(
buf[(text_x + 5, y)].bg,
bm,
"a non-bracket cell is not highlighted"
);
}
fn guide_buf(e: &mut Editor, w: u16, h: u16) -> Buffer {
let area = Rect {
x: 0,
y: 0,
width: w,
height: h,
};
let mut buf = Buffer::empty(area);
(e as &mut Editor).render(area, &mut buf);
buf
}
#[test]
fn render_paints_indent_guides_at_each_indent_level() {
let mut e = editor_with("fn main() {\n if x {\n y();\n }\n}");
let buf = guide_buf(&mut e, 40, 8);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
let g = e.theme.indent_guide();
assert_eq!(buf[(text_x, y0 + 1)].symbol(), "\u{2502}", "level-1 guide");
assert_eq!(buf[(text_x, y0 + 1)].fg, g);
assert_eq!(
buf[(text_x, y0 + 2)].symbol(),
"\u{2502}",
"level-1 guide, row 2"
);
assert_eq!(
buf[(text_x + 4, y0 + 2)].symbol(),
"\u{2502}",
"level-2 guide"
);
assert_eq!(buf[(text_x + 4, y0 + 2)].fg, g);
assert_eq!(
buf[(text_x, y0)].symbol(),
"f",
"a top-level line gets no guide and keeps its text"
);
assert_eq!(
buf[(text_x + 4, y0 + 1)].symbol(),
"i",
"guides never overwrite text"
);
}
#[test]
fn indent_guides_continue_through_blank_lines_inside_a_block_only() {
let mut e = editor_with("def f():\n a = 1\n\n b = 2\n\ndef g():\n pass");
let buf = guide_buf(&mut e, 40, 9);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
assert_eq!(
buf[(text_x, y0 + 2)].symbol(),
"\u{2502}",
"a blank line inside a block continues the guide"
);
assert_eq!(
buf[(text_x, y0 + 4)].symbol(),
" ",
"a blank line between top-level blocks shows no guide"
);
}
#[test]
fn active_indent_guide_highlights_the_cursor_block_only() {
let mut e = editor_with("fn a() {\n x();\n}\nfn b() {\n y();\n}");
e.focused = true;
e.cursor_row = 4;
e.cursor_col = 4;
let buf = guide_buf(&mut e, 40, 8);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
assert_eq!(
buf[(text_x, y0 + 4)].fg,
e.theme.indent_guide_active(),
"the cursor's block guide is highlighted"
);
assert_eq!(
buf[(text_x, y0 + 1)].fg,
e.theme.indent_guide(),
"the other block's guide stays dim"
);
}
#[test]
fn header_line_activates_the_guide_of_the_block_it_opens() {
let mut e = editor_with("fn a() {\n x();\n y();\n}");
e.focused = true;
e.cursor_row = 0;
e.cursor_col = 0;
let buf = guide_buf(&mut e, 40, 8);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
assert_eq!(buf[(text_x, y0 + 1)].fg, e.theme.indent_guide_active());
assert_eq!(buf[(text_x, y0 + 2)].fg, e.theme.indent_guide_active());
}
#[test]
fn indent_guides_toggle_off_paints_plain_whitespace() {
let mut e = editor_with("fn main() {\n if x {\n y();\n }\n}");
e.show_indent_guides = false;
let buf = guide_buf(&mut e, 40, 8);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
assert_eq!(buf[(text_x, y0 + 1)].symbol(), " ");
assert_eq!(buf[(text_x + 4, y0 + 2)].symbol(), " ");
}
#[test]
fn indent_guides_honour_horizontal_scroll() {
let mut e = editor_with(
"fn main() {\n if x {\n y(); // padding so the pane really scrolls\n }\n}",
);
e.scroll_col = 4;
let buf = guide_buf(&mut e, 40, 8);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
assert_eq!(
buf[(text_x, y0 + 2)].symbol(),
"\u{2502}",
"the level-2 guide shifts left with the scroll"
);
assert_eq!(
buf[(text_x, y0 + 1)].symbol(),
"i",
"the scrolled-off level-1 guide leaves the text alone"
);
}
#[test]
fn guide_indent_width_resolves_blank_lines_from_neighbours() {
let e = editor_with("def f():\n a = 1\n\n b = 2\n\ndef g():\n pass");
assert_eq!(e.guide_indent_width(2), 4, "blank inside a block");
assert_eq!(e.guide_indent_width(4), 0, "blank between blocks");
}
#[test]
fn active_indent_guide_spans_the_enclosing_block() {
let mut e = editor_with("fn a() {\n x();\n}\nfn b() {\n y();\n z();\n}");
e.cursor_row = 4;
assert_eq!(e.active_indent_guide(), Some((0, 4, 5)));
e.cursor_row = 0; assert_eq!(e.active_indent_guide(), Some((0, 1, 1)));
e.cursor_row = 2; assert_eq!(e.active_indent_guide(), None);
}
#[test]
fn scan_colors_brackets_by_shared_nesting_depth() {
let lines = vec![String::from("a(b[c{d}e]f)g")];
let out = scan_bracket_colors(&lines, &[]);
assert_eq!(
out[0],
vec![(1, 0), (3, 1), (5, 2), (7, 2), (9, 1), (11, 0)],
"openers colour at their depth, closers at their opener's depth"
);
}
#[test]
fn scan_marks_unmatched_and_mismatched_closers_unexpected() {
let lines = vec![String::from("x)"), String::from("(]y)")];
let out = scan_bracket_colors(&lines, &[]);
assert_eq!(out[0], vec![(1, UNEXPECTED_BRACKET)], "no opener at all");
assert_eq!(
out[1],
vec![(0, 0), (1, UNEXPECTED_BRACKET), (3, 0)],
"a mismatched closer reddens without consuming the open bracket"
);
}
#[test]
fn scan_skips_brackets_inside_protected_ranges() {
let lines = vec![String::from("s("), String::from("f()")];
let out = scan_bracket_colors(&lines, &[(1, 2)]);
assert!(out[0].is_empty(), "the protected '(' does not participate");
assert_eq!(out[1], vec![(1, 0), (2, 0)]);
}
#[test]
fn scan_depth_cycles_past_the_palette() {
let lines = vec![String::from("([{(x)}])")];
let out = scan_bracket_colors(&lines, &[]);
assert_eq!(
out[0][3],
(3, 0),
"depth 3 wraps back to the first cycle colour"
);
}
#[test]
fn recompute_highlights_skips_brackets_in_rust_strings_and_comments() {
let mut e = editor_with("let s = \"(prose)\";\nf(1); // (note)\n");
e.set_language(Some(LangKind::Rust));
assert!(
e.bracket_colors[0].is_empty(),
"string-literal brackets are prose: {:?}",
e.bracket_colors[0]
);
assert_eq!(
e.bracket_colors[1],
vec![(1, 0), (3, 0)],
"code brackets colour; comment brackets do not: {:?}",
e.bracket_colors[1]
);
}
#[test]
fn plain_text_bracket_scan_is_gated_by_buffer_size() {
let big_line = "x".repeat(64 * 1024);
let mut e = editor_with("");
e.lines = vec![big_line; (BRACKET_SCAN_MAX_BYTES / (64 * 1024)) + 2];
e.lines.push(String::from("f()"));
e.recompute_highlights();
assert!(
e.bracket_colors.iter().all(Vec::is_empty),
"an oversized plain-text buffer opts out of the scan"
);
let mut small = editor_with("f()");
small.recompute_highlights();
assert_eq!(small.bracket_colors[0], vec![(1, 0), (2, 0)]);
}
#[test]
fn render_colors_brackets_by_nesting_depth() {
let mut e = editor_with("a(b[c{d}e]f)g");
e.recompute_highlights();
let buf = guide_buf(&mut e, 40, 6);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
for (col, depth) in [(1u16, 0), (3, 1), (5, 2), (7, 2), (9, 1), (11, 0)] {
assert_eq!(
buf[(text_x + col, y0)].fg,
e.theme.bracket_pair_color(depth),
"bracket at col {col} wears depth-{depth} colour"
);
}
assert_ne!(
buf[(text_x + 2, y0)].fg,
e.theme.bracket_pair_color(0),
"non-bracket text keeps its syntax colour"
);
}
#[test]
fn render_paints_unmatched_closer_red() {
let mut e = editor_with("x)");
e.recompute_highlights();
let buf = guide_buf(&mut e, 40, 6);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_eq!(
buf[(text_x + 1, e.last_inner.y)].fg,
e.theme.bracket_unexpected_fg()
);
}
#[test]
fn render_bracket_colors_toggle_off_keeps_syntax_color() {
let mut e = editor_with("a(b)c");
e.recompute_highlights();
e.show_bracket_colors = false;
let buf = guide_buf(&mut e, 40, 6);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_ne!(
buf[(text_x + 1, e.last_inner.y)].fg,
e.theme.bracket_pair_color(0)
);
}
#[test]
fn selection_mode_paints_whitespace_glyphs_only_inside_the_selection() {
let mut e = editor_with("a b c d");
e.selection = Some(EditorSelection {
anchor: (0, 3),
head: (0, 6),
});
let buf = guide_buf(&mut e, 40, 6);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
assert_eq!(buf[(text_x + 3, y0)].symbol(), "\u{b7}", "selected space");
assert_eq!(buf[(text_x + 3, y0)].fg, e.theme.whitespace_fg());
assert_eq!(buf[(text_x + 5, y0)].symbol(), "\u{b7}");
assert_eq!(
buf[(text_x + 1, y0)].symbol(),
" ",
"an unselected space stays invisible"
);
assert_eq!(buf[(text_x + 4, y0)].symbol(), "c", "text is untouched");
}
#[test]
fn all_mode_paints_every_space_and_tab() {
let mut e = editor_with("a b\n\tc");
e.whitespace_mode = WhitespaceMode::All;
let buf = guide_buf(&mut e, 40, 6);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
assert_eq!(buf[(text_x + 1, y0)].symbol(), "\u{b7}");
assert_eq!(
buf[(text_x, y0 + 1)].symbol(),
"\u{2192}",
"a tab renders as an arrow"
);
}
#[test]
fn none_mode_paints_no_whitespace_glyphs_even_selected() {
let mut e = editor_with("a b");
e.whitespace_mode = WhitespaceMode::None;
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (0, 3),
});
let buf = guide_buf(&mut e, 40, 6);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert_eq!(buf[(text_x + 1, e.last_inner.y)].symbol(), " ");
}
#[test]
fn selection_mode_covers_every_line_of_a_multiline_selection() {
let mut e = editor_with("a b\nc d");
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (1, 3),
});
let buf = guide_buf(&mut e, 40, 6);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
assert_eq!(buf[(text_x + 1, y0)].symbol(), "\u{b7}");
assert_eq!(buf[(text_x + 1, y0 + 1)].symbol(), "\u{b7}");
}
fn locals(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(n, v)| ((*n).to_string(), (*v).to_string()))
.collect()
}
#[test]
fn inline_values_annotate_function_lines_up_to_the_stop_only() {
let mut e = editor_with("def f():\n x = 1\n y = x + 1\n print(x, y)\n\nz = 9");
e.set_inline_values_from_locals(3, &locals(&[("x", "1"), ("y", "2")]));
assert_eq!(e.inline_values.get(&1).map(String::as_str), Some("x = 1"));
assert_eq!(
e.inline_values.get(&2).map(String::as_str),
Some("y = 2, x = 1"),
"first-mention order on the stop line"
);
assert!(
!e.inline_values.contains_key(&3),
"lines past the execution point stay bare"
);
assert!(!e.inline_values.contains_key(&5), "outside the function");
}
#[test]
fn inline_values_span_the_whole_function_from_a_nested_block_stop() {
let mut e =
editor_with("def f():\n x = 1\n if True:\n y = 2\n print(x, y)");
e.set_inline_values_from_locals(5, &locals(&[("x", "1"), ("y", "2")]));
assert_eq!(
e.inline_values.get(&1).map(String::as_str),
Some("x = 1"),
"a line above the nested block still annotates"
);
assert_eq!(
e.inline_values.get(&4).map(String::as_str),
Some("x = 1, y = 2")
);
}
#[test]
fn inline_values_clear_when_a_reused_tab_opens_a_different_file() {
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join("a.py");
let b = dir.path().join("b.py");
std::fs::write(&a, "x = 1\n").unwrap();
std::fs::write(&b, "y = 2\n").unwrap();
let mut e = Editor::new();
e.open(&a).unwrap();
e.inline_values.insert(0, String::from("x = 1"));
e.open(&b).unwrap();
assert!(
e.inline_values.is_empty(),
"a different file must not inherit the old file's trailers"
);
}
#[test]
fn inline_values_match_whole_identifiers_only() {
let mut e = editor_with("def f():\n max = 9\n q = max");
e.set_inline_values_from_locals(3, &locals(&[("x", "1"), ("q", "7")]));
assert!(
!e.inline_values.contains_key(&1),
"`x` must not match inside `max`"
);
assert_eq!(e.inline_values.get(&2).map(String::as_str), Some("q = 7"));
}
#[test]
fn inline_values_elide_long_values_in_the_middle() {
let mut e = editor_with("def f():\n x = 1");
let long = "a".repeat(60);
e.set_inline_values_from_locals(2, &locals(&[("x", &long)]));
let note = e.inline_values.get(&1).unwrap();
assert!(note.contains('\u{2026}'), "middle ellipsis: {note}");
assert!(note.chars().count() < 60, "elided: {note}");
}
#[test]
fn inline_values_clear_when_locals_are_empty() {
let mut e = editor_with("def f():\n x = 1");
e.set_inline_values_from_locals(2, &locals(&[("x", "1")]));
assert!(!e.inline_values.is_empty());
e.set_inline_values_from_locals(2, &[]);
assert!(e.inline_values.is_empty());
}
#[test]
fn render_paints_inline_value_trailer_after_the_line_end() {
let mut e = editor_with("x = 1\ny = 2");
e.inline_values.insert(0, String::from("x = 1"));
let buf = guide_buf(&mut e, 40, 6);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
let y0 = e.last_inner.y;
let start = text_x + 5 + 2;
assert_eq!(buf[(start, y0)].symbol(), "x");
assert_eq!(buf[(start, y0)].fg, e.theme.ignored_fg());
assert_eq!(buf[(start + 2, y0)].symbol(), "=");
assert_eq!(
buf[(text_x + 5 + 2, y0 + 1)].symbol(),
" ",
"an unannotated line gets no trailer"
);
}
#[test]
fn identifier_tokens_split_on_word_boundaries() {
assert_eq!(
identifier_tokens("print(x, _y2) + max"),
vec!["print", "x", "_y2", "max"]
);
}
#[test]
fn select_to_bracket_includes_both_brackets() {
let mut e = editor_with("foo(bar)baz");
e.cursor_row = 0;
e.cursor_col = 3; assert!(e.select_to_matching_bracket());
assert_eq!(e.selection_text(), "(bar)");
}
#[test]
fn select_to_bracket_from_inside_selects_enclosing_pair() {
let mut e = editor_with("foo(bar)baz");
e.cursor_row = 0;
e.cursor_col = 5; assert!(e.select_to_matching_bracket());
assert_eq!(e.selection_text(), "(bar)");
}
#[test]
fn select_to_bracket_spans_multiple_lines() {
let mut e = editor_with("fn f() {\n x\n}");
e.cursor_row = 0;
e.cursor_col = 7; assert!(e.select_to_matching_bracket());
assert_eq!(e.selection_text(), "{\n x\n}");
}
#[test]
fn transpose_swaps_chars_around_cursor_and_advances() {
let mut e = editor_with("abcd");
e.cursor_row = 0;
e.cursor_col = 2; e.transpose_chars();
assert_eq!(e.lines, vec!["acbd"]);
assert_eq!((e.cursor_row, e.cursor_col), (0, 3));
}
#[test]
fn transpose_at_line_start_only_advances() {
let mut e = editor_with("abcd");
e.cursor_row = 0;
e.cursor_col = 0;
e.transpose_chars();
assert_eq!(e.lines, vec!["abcd"]);
assert_eq!((e.cursor_row, e.cursor_col), (0, 1));
}
#[test]
fn transpose_at_end_of_line_moves_char_across_break() {
let mut e = editor_with("ab\ncd");
e.cursor_row = 0;
e.cursor_col = 2; e.transpose_chars();
assert_eq!(e.lines, vec!["a", "bcd"]);
assert_eq!((e.cursor_row, e.cursor_col), (1, 1));
}
#[test]
fn transpose_at_end_of_final_line_is_noop() {
let mut e = editor_with("abc");
e.cursor_row = 0;
e.cursor_col = 3; e.transpose_chars();
assert_eq!(e.lines, vec!["abc"]);
assert_eq!((e.cursor_row, e.cursor_col), (0, 3));
}
#[test]
fn indentation_to_spaces_converts_only_leading_tabs() {
let mut e = editor_with("\tfoo\n\t\tbar\nbaz\ta");
e.indentation_to_spaces();
assert_eq!(e.lines, vec![" foo", " bar", "baz\ta"]);
}
#[test]
fn indentation_to_tabs_converts_leading_space_groups() {
let mut e = editor_with(" foo\n bar\nb c");
e.indentation_to_tabs();
assert_eq!(e.lines, vec!["\tfoo", "\t bar", "b c"]);
}
#[test]
fn indent_override_switches_tab_to_a_literal_tab() {
let mut e = editor_with("foo");
e.cursor_row = 0;
e.cursor_col = 0;
e.indent_at_cursor();
assert_eq!(e.lines[0], " foo");
assert_eq!(e.indent_preference(), (4, true));
let mut t = editor_with("foo");
t.set_indent_style(IndentStyle {
width: 4,
use_spaces: false,
});
t.cursor_row = 0;
t.cursor_col = 0;
t.indent_at_cursor();
assert_eq!(t.lines[0], "\tfoo");
assert_eq!(t.indent_preference(), (4, false));
}
#[test]
fn indent_override_width_changes_status_label_and_unit() {
let mut e = editor_with("");
e.set_indent_style(IndentStyle {
width: 2,
use_spaces: true,
});
assert_eq!(e.indent_style().label(), "Spaces: 2");
assert_eq!(e.indent_style().unit(), " ");
e.set_indent_style(IndentStyle {
width: 4,
use_spaces: false,
});
assert_eq!(e.indent_style().label(), "Tab Size: 4");
assert_eq!(e.indent_style().unit(), "\t");
}
#[test]
fn trim_final_newlines_removes_trailing_blank_lines() {
let mut e = editor_with("a\nb\n\n\n");
e.lines = vec![
String::from("a"),
String::from("b"),
String::new(),
String::new(),
];
assert!(e.trim_final_newlines());
assert_eq!(e.lines, vec!["a", "b"]);
}
#[test]
fn trim_final_newlines_keeps_at_least_one_line() {
let mut e = editor_with("");
e.lines = vec![String::new(), String::new(), String::new()];
assert!(e.trim_final_newlines());
assert_eq!(e.lines, vec![""]);
}
#[test]
fn trim_final_newlines_noop_when_no_trailing_blanks() {
let mut e = editor_with("a\nb");
assert!(!e.trim_final_newlines());
assert_eq!(e.lines, vec!["a", "b"]);
}
#[test]
fn fold_range_covers_an_indented_block() {
let e = editor_with("fn a() {\n let x = 1;\n let y = 2;\n}\nfn b() {}");
assert_eq!(e.fold_range(0), Some((0, 2)));
assert_eq!(e.fold_range(1), None);
assert_eq!(e.fold_range(4), None);
}
#[test]
fn fold_range_absorbs_interior_blank_lines_but_not_trailing_ones() {
let e = editor_with("fn a() {\n x\n\n y\n}\n");
assert_eq!(e.fold_range(0), Some((0, 3)));
}
#[test]
fn folding_a_header_hides_its_body_only() {
let mut e = editor_with("fn a() {\n let x = 1;\n let y = 2;\n}\nfn b() {}");
e.toggle_fold(0);
assert!(!e.is_line_hidden(0), "the header line stays visible");
assert!(e.is_line_hidden(1));
assert!(e.is_line_hidden(2));
assert!(
!e.is_line_hidden(3),
"the closing brace at base indent stays"
);
assert!(!e.is_line_hidden(4));
}
#[test]
fn moving_down_steps_over_a_folded_block_instead_of_into_it() {
let mut e = editor_with("fn a() {\n x\n y\n}\nafter");
e.toggle_fold(0);
assert_eq!(e.cursor_row, 0, "the fold snapped the caret to the header");
e.move_down();
assert_eq!(
e.cursor_row, 3,
"Down clears the whole collapsed body, landing on the next visible line"
);
assert!(!e.is_line_hidden(e.cursor_row));
e.move_up();
assert_eq!(e.cursor_row, 0, "Up steps back over it the same way");
}
#[test]
fn editing_reveals_a_fold_the_caret_ended_up_inside() {
let mut e = editor_with("fn a() {\n x\n y\n}\nafter");
e.toggle_fold(0);
e.cursor_row = 1;
e.cursor_col = 5;
assert!(e.is_line_hidden(1), "the caret is parked inside the fold");
e.insert_char('Z');
assert!(
!e.is_line_hidden(1),
"the edit revealed the region it landed in"
);
assert!(e.lines[1].contains('Z'), "and the text went to line 1");
}
#[test]
fn jumping_into_a_collapsed_block_opens_it_so_the_caret_is_painted() {
let mut e = editor_with("fn a() {\n x\n y\n}\nafter");
e.focused = true;
e.toggle_fold(0);
assert!(e.is_line_hidden(1), "the block starts collapsed");
e.goto_line(2); assert_eq!(e.cursor_row, 1);
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 10,
};
let mut buf = Buffer::empty(area);
(&mut e).render(area, &mut buf);
assert!(
!e.is_line_hidden(1),
"the jump target's own block must open"
);
assert!(
e.cursor_screen_pos().is_some(),
"so the caret has somewhere to be painted"
);
}
#[test]
fn opening_another_file_clears_fold_state() {
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join("a.rs");
let b = dir.path().join("b.rs");
std::fs::write(&a, "fn a() {\n x\n}\n").unwrap();
std::fs::write(&b, "fn b() {\n y\n}\n").unwrap();
let mut e = Editor::new();
e.open(&a).unwrap();
e.toggle_fold(0);
assert!(e.is_line_hidden(1), "a.rs is folded");
e.open(&b).unwrap();
assert!(
!e.is_line_hidden(1),
"the next file must not inherit the previous file's folds"
);
}
#[test]
fn the_fold_lookup_is_derived_once_per_fold_change_not_per_query() {
let text = (0..400)
.map(|i| format!("fn f{i}() {{\n body\n}}"))
.collect::<Vec<_>>()
.join("\n");
let mut e = editor_with(&text);
e.fold_all();
assert!(
!e.folded.is_empty(),
"Fold All must actually fold something"
);
FOLD_RANGE_REBUILDS.with(|c| c.set(0));
for line in 0..e.lines.len() {
std::hint::black_box(e.is_line_hidden(line));
}
assert_eq!(
FOLD_RANGE_REBUILDS.with(|c| c.get()),
0,
"querying must never rebuild the spans"
);
e.toggle_fold(0);
assert_eq!(
FOLD_RANGE_REBUILDS.with(|c| c.get()),
1,
"changing the fold set rebuilds exactly once"
);
}
#[test]
fn toggling_a_fold_twice_restores_visibility() {
let mut e = editor_with("fn a() {\n body\n}");
e.toggle_fold(0);
assert!(e.is_line_hidden(1));
e.toggle_fold(0);
assert!(!e.is_line_hidden(1), "a second toggle unfolds the block");
}
#[test]
fn folding_from_inside_the_body_folds_the_enclosing_block() {
let mut e = editor_with("fn a() {\n body\n}");
e.cursor_row = 1;
e.toggle_fold(e.cursor_row);
assert!(
e.is_line_hidden(1),
"folding at a body line folds its owner"
);
assert_eq!(
e.cursor_row, 0,
"cursor on a hidden line snaps up to the header"
);
}
#[test]
fn render_omits_folded_body_lines() {
let mut e = editor_with("fn a() {\n x\n y\n}\nfn b() {}");
e.toggle_fold(0);
render_at(&mut e, 40, 10);
let shown: Vec<usize> = (0..e.last_wrap_rows.len())
.filter_map(|i| e.text_row(i).map(|t| t.0))
.collect();
assert!(shown.contains(&0), "the header row is drawn");
assert!(!shown.contains(&1), "a folded body line is not drawn");
assert!(!shown.contains(&2), "a folded body line is not drawn");
assert!(
shown.contains(&3) && shown.contains(&4),
"lines after the fold are still drawn"
);
}
#[test]
fn fold_all_collapses_every_block_and_unfold_all_restores() {
let mut e = editor_with("fn a() {\n x\n}\nfn b() {\n y\n}");
e.fold_all();
assert!(
e.is_line_hidden(1) && e.is_line_hidden(4),
"every body is hidden"
);
e.unfold_all();
assert!(
!e.is_line_hidden(1) && !e.is_line_hidden(4),
"unfold restores all"
);
}
#[test]
fn clicking_the_gutter_chevron_toggles_the_fold() {
let mut e = editor_with("fn a() {\n x\n}\nfn b() {}");
render_at(&mut e, 40, 10);
let cx = e.last_inner.x + 1;
let cy = e.last_inner.y;
assert!(
e.fold_chevron_at(cx, cy),
"a click on the header chevron hits"
);
assert!(e.is_line_hidden(1), "the body is now folded");
assert!(e.fold_chevron_at(cx, cy), "a second click unfolds");
assert!(!e.is_line_hidden(1));
}
#[test]
fn clicking_off_the_chevron_column_is_not_a_fold_toggle() {
let mut e = editor_with("fn a() {\n x\n}");
render_at(&mut e, 40, 10);
let text_x = e.last_inner.x + e.last_gutter_width + 1;
assert!(
!e.fold_chevron_at(text_x, e.last_inner.y),
"the text area is not the chevron"
);
assert!(!e.is_line_hidden(1));
}
#[test]
fn ghost_carets_paint_participant_colored_cells() {
let f = NamedTempFile::new().unwrap();
std::fs::write(f.path(), "hello world\nsecond line\n").unwrap();
let mut ed = Editor::new();
ed.open(f.path()).unwrap();
let color = Color::Rgb(1, 2, 3);
ed.ghost_carets = vec![(0, 6, color), (99, 0, color)];
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 10,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
let hits: Vec<(u16, u16)> = (area.y..area.bottom())
.flat_map(|y| (area.x..area.right()).map(move |x| (x, y)))
.filter(|&(x, y)| buf[(x, y)].style().bg == Some(color))
.collect();
assert_eq!(hits.len(), 1, "exactly one ghost caret cell: {hits:?}");
let (x, y) = hits[0];
assert_eq!(y, ed.last_inner.y, "ghost sits on the first content row");
let text_x = ed.last_inner.x + ed.last_gutter_width + 1;
assert_eq!(x, text_x + 6, "ghost sits at char column 6");
}
#[test]
fn ghost_caret_labels_paint_name_above_and_fall_back_below() {
let f = NamedTempFile::new().unwrap();
std::fs::write(f.path(), "hello world\nsecond line\nthird line\n").unwrap();
let mut ed = Editor::new();
ed.open(f.path()).unwrap();
let color = Color::Rgb(9, 8, 7);
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 10,
};
let text_x = |ed: &Editor| ed.last_inner.x + ed.last_gutter_width + 1;
ed.ghost_caret_labels = vec![(1, 2, "alice".into(), color)];
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
let x0 = text_x(&ed) + 2;
let y0 = ed.last_inner.y;
let shown: String = (0..5)
.map(|i| buf[(x0 + i, y0)].symbol().to_string())
.collect();
assert_eq!(shown, "alice", "tag paints above the caret at its column");
assert_eq!(
buf[(x0, y0)].style().bg,
Some(color),
"tag wears the participant color"
);
ed.ghost_caret_labels = vec![(0, 0, "bob".into(), color)];
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut ed, area, &mut buf);
let x1 = text_x(&ed);
let y1 = ed.last_inner.y + 1;
let shown: String = (0..3)
.map(|i| buf[(x1 + i, y1)].symbol().to_string())
.collect();
assert_eq!(shown, "bob", "tag falls back below on the top row");
}
#[test]
fn typing_an_opener_auto_closes_with_the_caret_between() {
let mut e = editor_with("fn main() ");
e.cursor_row = 0;
e.cursor_col = 10; e.insert_char('{');
assert_eq!(e.lines[0], "fn main() {}");
assert_eq!(e.cursor_col, 11, "the caret sits between the pair");
e.undo();
assert_eq!(e.lines[0], "fn main() ");
}
#[test]
fn openers_do_not_auto_close_before_a_word_character() {
let mut e = editor_with("foo");
e.cursor_row = 0;
e.cursor_col = 0;
e.insert_char('(');
assert_eq!(
e.lines[0], "(foo",
"no closer may be jammed into the following word"
);
}
#[test]
fn typing_the_closer_steps_over_instead_of_inserting() {
let mut e = editor_with("");
e.insert_char('(');
assert_eq!(e.lines[0], "()");
e.insert_char(')');
assert_eq!(e.lines[0], "()", "the closer types over, never doubles");
assert_eq!(e.cursor_col, 2);
}
#[test]
fn an_apostrophe_inside_a_word_stays_single() {
let mut e = editor_with("don");
e.cursor_row = 0;
e.cursor_col = 3;
e.insert_char('\'');
assert_eq!(e.lines[0], "don'", "no auto-pair after a word character");
}
#[test]
fn typing_a_bracket_with_a_selection_surrounds_it() {
let mut e = editor_with("abc def");
e.cursor_row = 0;
e.selection = Some(EditorSelection {
anchor: (0, 0),
head: (0, 3),
}); e.insert_char('(');
assert_eq!(e.lines[0], "(abc) def");
let sel = e
.selection
.expect("the selection survives, on the inner text");
let ((sr, sc), (er, ec)) = sel.normalised();
assert_eq!((sr, sc, er, ec), (0, 1, 0, 4));
e.undo();
assert_eq!(e.lines[0], "abc def", "surround is one undo step");
}
#[test]
fn backspace_between_an_empty_pair_deletes_both() {
let mut e = editor_with("");
e.insert_char('(');
assert_eq!(e.lines[0], "()");
e.backspace();
assert_eq!(e.lines[0], "", "the empty pair dies together");
}
#[test]
fn typing_an_opener_into_a_fresh_empty_buffer_never_panics() {
let mut e = Editor::new();
e.auto_close_pairs = true;
e.insert_char('(');
assert_eq!(e.lines[0], "()");
}
#[test]
fn backspace_keeps_the_closer_of_a_pre_existing_pair() {
let mut e = editor_with("()");
e.cursor_row = 0;
e.cursor_col = 1;
e.backspace();
assert_eq!(e.lines[0], ")", "the manual pair loses only one side");
}
#[test]
fn the_toggle_disables_every_pair_behavior() {
let mut e = editor_with("");
e.auto_close_pairs = false;
e.insert_char('(');
assert_eq!(e.lines[0], "(", "off means plain inserts");
e.insert_char(')');
assert_eq!(e.lines[0], "()");
e.cursor_col = 1;
e.backspace();
assert_eq!(e.lines[0], ")", "off means plain backspace");
}
}