use super::*;
pub(super) fn write_cell(buf: &mut Buffer, x: u16, y: u16, w: u16, text: &str, style: Style) {
use unicode_segmentation::UnicodeSegmentation;
let width = w as usize;
buf.set_stringn(x, y, " ".repeat(width), width, style);
let mut col = 0;
for g in text.graphemes(true) {
let gw = crate::sheet::grapheme_width(g);
if gw == 0 {
continue;
}
if col + gw > width {
break;
}
if g.contains(char::is_control) {
let shown: String = g.chars().map(visible_control).collect();
buf.set_stringn(x + col as u16, y, &shown, gw, style);
} else {
buf.set_stringn(x + col as u16, y, g, gw, style);
}
col += gw;
}
}
pub(super) fn visible_control(c: char) -> char {
match c {
'\n' => '\u{23ce}',
'\t' => '\u{2192}',
'\u{0}'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
'\u{7f}' => '\u{2421}',
c if c.is_control() => '\u{fffd}',
c => c,
}
}
impl Editor {
pub(super) fn warm_render_caches(&mut self) {
self.refresh_fold_tables();
self.conflicts();
}
pub(super) fn row_origin(&self, line: &str, start: usize) -> usize {
if self.wrap_enabled() {
0
} else {
cells_before(line, start)
}
}
pub fn cursor_visual_col(&self) -> usize {
self.sync_tab_cells();
self.lines
.get(self.cursor_row)
.map_or(self.cursor_col, |l| {
l.chars().take(self.cursor_col).fold(0, |col, c| {
col + if c == '\t' { tab_cells_at(col) } else { 1 }
})
})
+ 1
}
pub(crate) fn sync_tab_cells(&self) {
set_tab_cells(self.indent_style().width as usize);
}
}
pub(super) fn set_tab_cells(n: usize) {
TAB_CELLS.with(|t| t.set(n.max(1)));
}
pub(super) fn char_cells(c: char) -> usize {
if c == '\t' {
TAB_CELLS.with(std::cell::Cell::get)
} else {
unicode_width::UnicodeWidthChar::width(c).unwrap_or(0)
}
}
pub(super) fn tab_cells_at(col: usize) -> usize {
let t = TAB_CELLS.with(std::cell::Cell::get).max(1);
t - col % t
}
pub(super) fn char_cells_at(c: char, col: usize) -> usize {
if c == '\t' {
tab_cells_at(col)
} else {
char_cells(c)
}
}
pub(super) fn cluster_cells_at(cluster: &str, col: usize) -> usize {
let mut chars = cluster.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => char_cells_at(c, col),
(Some(_), Some(_)) => unicode_width::UnicodeWidthStr::width(cluster),
(None, _) => 0,
}
}
pub(super) fn char_cells_from(
text: &str,
origin: usize,
) -> impl Iterator<Item = (char, usize)> + '_ {
use unicode_segmentation::UnicodeSegmentation;
let mut col = origin;
text.graphemes(true).flat_map(move |cluster| {
let w = cluster_cells_at(cluster, col);
col += w;
cluster
.chars()
.enumerate()
.map(move |(i, c)| (c, if i == 0 { w } else { 0 }))
})
}
pub(super) fn cells_from(text: &str, origin: usize) -> usize {
char_cells_from(text, origin).map(|(_, w)| w).sum()
}
pub(super) fn cells_before(line: &str, chars: usize) -> usize {
cells_from(&line[..byte_index_of_char(line, chars)], 0)
}
pub(super) fn blank_tabs(text: &str) -> std::borrow::Cow<'_, str> {
blank_tabs_from(text, 0)
}
pub(super) fn blank_tabs_from(text: &str, origin: usize) -> std::borrow::Cow<'_, str> {
if !text.contains('\t') {
return text.into();
}
let mut out = String::with_capacity(text.len() + 8);
for (c, w) in char_cells_from(text, origin) {
if c == '\t' {
out.extend(std::iter::repeat_n(' ', w));
} else {
out.push(c);
}
}
out.into()
}
pub(super) fn shift_spans_for_view(spans: &[HiSpan], byte_start: usize) -> Vec<HiSpan> {
let mut out = Vec::with_capacity(spans.len());
for sp in spans {
let range = sp.range();
if range.end <= byte_start {
continue;
}
out.push(HiSpan::new(
range.start.saturating_sub(byte_start),
range.end - byte_start,
sp.style,
));
}
out
}
fn shift_and_clip_spans_into<'a>(
spans: &'a [HiSpan],
byte_start: usize,
seg_bytes: usize,
scratch: &'a mut Vec<HiSpan>,
) -> &'a [HiSpan] {
if byte_start == 0
&& spans.iter().all(|sp| {
let r = sp.range();
r.start < seg_bytes && r.end <= seg_bytes && r.start < r.end
})
{
return spans;
}
scratch.clear();
for sp in spans {
let range = sp.range();
if range.end <= byte_start {
continue;
}
let shifted = HiSpan::new(
range.start.saturating_sub(byte_start),
range.end - byte_start,
sp.style,
);
if let Some(clipped) = shifted.clipped(seg_bytes) {
scratch.push(clipped);
}
}
scratch.as_slice()
}
pub(super) 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,
}
}
pub(super) fn merge_overlay(base: &[HiSpan], over: &[HiSpan]) -> Vec<HiSpan> {
if over.is_empty() {
return base.to_vec();
}
let mut out = Vec::new();
merge_overlay_into(base, over, &mut out);
out
}
fn merge_overlay_into<'a>(
base: &'a [HiSpan],
over: &[HiSpan],
scratch: &'a mut Vec<HiSpan>,
) -> &'a [HiSpan] {
if over.is_empty() {
return base;
}
scratch.clear();
scratch.reserve(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 {
scratch.push(HiSpan {
start: cur,
end: o.start,
style: b.style,
});
}
cur = cur.max(o.end);
if cur >= b.end {
break;
}
}
if cur < b.end {
scratch.push(HiSpan {
start: cur,
end: b.end,
style: b.style,
});
}
}
for o in over {
let mut cur = o.start;
for k in base
.iter()
.filter(|b| crate::highlight::is_comment_tag_style(b.style))
.filter(|k| k.end > o.start && k.start < o.end)
{
if k.start > cur {
scratch.push(HiSpan {
start: cur,
end: k.start,
style: o.style,
});
}
scratch.push(HiSpan {
start: k.start.max(o.start),
end: k.end.min(o.end),
style: k.style,
});
cur = cur.max(k.end);
if cur >= o.end {
break;
}
}
if cur < o.end {
scratch.push(HiSpan {
start: cur,
end: o.end,
style: o.style,
});
}
}
scratch.sort_by_key(|s| s.start);
scratch.as_slice()
}
pub(super) fn build_line_spans<'a>(
line: &'a str,
spans: &[HiSpan],
origin: usize,
) -> Vec<Span<'a>> {
if spans.is_empty() {
return vec![Span::raw(blank_tabs_from(line, origin))];
}
let mut out: Vec<Span> = Vec::with_capacity(spans.len() * 2);
let mut cursor = 0usize;
let mut col = origin;
let mut push = |out: &mut Vec<Span<'a>>, text: &'a str, style: Option<Style>| {
let shown = blank_tabs_from(text, col);
col += cells_from(text, col);
out.push(match style {
Some(st) => Span::styled(shown, st),
None => Span::raw(shown),
});
};
for sp in spans {
let range = sp.range();
if range.start > cursor && range.start <= line.len() {
let slice = &line[cursor..range.start];
if !slice.is_empty() {
push(&mut out, slice, None);
}
}
let s = range.start.min(line.len());
let e = range.end.min(line.len());
if e > s {
push(&mut out, &line[s..e], Some(sp.style));
cursor = e;
}
}
if cursor < line.len() {
push(&mut out, &line[cursor..], None);
}
out
}
fn paint_line_spans(
buf: &mut Buffer,
x: u16,
y: u16,
max_width: u16,
line: &str,
spans: &[HiSpan],
origin: usize,
) {
let mut cur_x = x;
let end_x = x.saturating_add(max_width);
let mut col = origin;
let mut paint = |text: &str, style: Option<Style>| {
if cur_x >= end_x {
return;
}
let shown = blank_tabs_from(text, col);
col += cells_from(text, col);
let span = match style {
Some(st) => Span::styled(shown, st),
None => Span::raw(shown),
};
let (next_x, _) = buf.set_span(cur_x, y, &span, end_x - cur_x);
cur_x = next_x;
};
if spans.is_empty() {
paint(line, None);
return;
}
let mut cursor = 0usize;
for sp in spans {
let range = sp.range();
if range.start > cursor && range.start <= line.len() {
let slice = &line[cursor..range.start];
if !slice.is_empty() {
paint(slice, None);
}
}
let s = range.start.min(line.len());
let e = range.end.min(line.len());
if e > s {
paint(&line[s..e], Some(sp.style));
cursor = e;
}
}
if cursor < line.len() {
paint(&line[cursor..], None);
}
}
fn paint_gutter_number(
buf: &mut Buffer,
x: u16,
y: u16,
width: u16,
max_x: u16,
num: Option<usize>,
style: Style,
) {
let total = usize::from(width);
if total == 0 || y < buf.area.y || y >= buf.area.bottom() {
return;
}
let limit_x = max_x.min(buf.area.right());
if x >= limit_x {
return;
}
let vis_total = total.min(usize::from(limit_x - x));
let mut digits = [0u8; 20];
let mut len = 0usize;
if let Some(mut n) = num {
loop {
digits[len] = b'0' + (n % 10) as u8;
len += 1;
n /= 10;
if n == 0 {
break;
}
}
}
let num_w = total.saturating_sub(1);
let pad = num_w.saturating_sub(len);
let mut col = 0usize;
while col < pad && col < vis_total {
buf[(x + col as u16, y)].set_symbol(" ").set_style(style);
col += 1;
}
for i in (0..len).rev() {
if col >= vis_total {
break;
}
let ch = [digits[i]];
let s = std::str::from_utf8(&ch).unwrap_or(" ");
buf[(x + col as u16, y)].set_symbol(s).set_style(style);
col += 1;
}
while col < vis_total {
buf[(x + col as u16, y)].set_symbol(" ").set_style(style);
col += 1;
}
}
#[derive(Default)]
struct SpanScratch {
merged: Vec<HiSpan>,
shifted: Vec<HiSpan>,
}
struct RowFrame<'a> {
inner: Rect,
visual_rows: &'a [VisRow],
gutter_width: u16,
text_x: u16,
text_width: u16,
wrap: bool,
sel_norm: Option<((usize, usize), (usize, usize))>,
occ_needle: Option<String>,
bracket_pair: Option<(BPos, BPos)>,
guide_step: usize,
active_guide: Option<(usize, usize, usize)>,
guide_fg: Color,
guide_active_fg: Color,
surfaces: bool,
gutter_hovered: bool,
}
impl Widget for &mut Editor {
fn render(self, area: Rect, buf: &mut Buffer) {
self.settle_semantic_carry();
self.clamp_to_symbol_view();
self.sync_tab_cells();
let block_style = if self.focused {
Style::default().fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)))
} else {
Style::default().fg(Color::DarkGray)
};
let surfaces = self.theme.surfaces().is_some();
let block = if surfaces {
crate::widgets::surface::pane_block(self.theme.editor_bg())
} else {
Block::default()
.borders(Borders::ALL)
.border_style(block_style)
};
let mut inner = block.inner(area);
block.render(area, buf);
if surfaces {
crate::widgets::surface::paint_pane_top(
buf,
area,
self.theme,
self.focused && !self.overlay_has_keyboard,
);
} else 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();
self.code_lens_spans.clear();
self.blame_span = None;
if let Some(log) = self.log.as_mut() {
log.last_body = Rect::default();
}
if inner.height == 0 {
return;
}
let cbg = canvas_bg(
crate::iterm2_inline::detect_iterm2_inline_support(),
self.theme,
);
let (len, seq, row) = (self.lines.len(), self.edit_seq, self.merge_edit_row);
let theme = self.theme;
if let Some(mv) = self.merge.as_mut() {
mv.sync_with_buffer(len, seq, row);
inner = render_merge_panes(mv, inner, buf, theme);
self.last_inner = inner;
}
let height = inner.height as usize;
if height == 0 {
return;
}
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.pdf_jobs.rendering(),
self.path.as_deref(),
inner,
buf,
ibg,
self.theme,
);
if self.cell_images {
let area = Rect {
y: inner.y + 1,
height: inner.height.saturating_sub(1),
..inner
};
let key = (image.generation, area.width, area.height, ibg);
if self.cell_image.as_ref().map(|c| c.key) != Some(key) {
let (cols, rows, cells) =
halfblock_cells(&image.bytes, area.width, area.height, ibg)
.unwrap_or_default();
self.cell_image = Some(CellImage {
key,
cols,
rows,
cells,
});
}
if let Some(picture) = self.cell_image.as_ref() {
paint_cell_image(picture, area, buf);
}
}
return;
}
if let Some(view) = self.sheet.as_mut() {
render_sheet(view, self.path.as_deref(), inner, buf, cbg, self.theme);
return;
}
if let Some(view) = self.archive.as_mut() {
render_archive(view, self.path.as_deref(), inner, buf, cbg, self.theme);
return;
}
if let Some(view) = self.pr_review.as_mut() {
crate::widgets::pr_review::render(view, inner, buf, cbg, self.theme);
return;
}
if let Some(view) = self.fleet.as_mut() {
crate::widgets::fleet::render(view, inner, buf, cbg, self.theme);
return;
}
if let Some(view) = self.sarif.as_mut() {
crate::sarif::render::render(view, self.path.as_deref(), inner, buf, cbg, self.theme);
return;
}
if let Some(view) = self.log.as_mut() {
let search = self
.search_highlight
.as_deref()
.map(|t| (t, self.search_highlight_opts));
let active = self.active_search_match;
render_log(
view,
self.path.as_deref(),
inner,
buf,
cbg,
self.theme,
self.scroll,
search,
active,
);
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.theme, self.pointer);
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 digits = match self.line_numbers {
LineNumbers::Off => 0,
_ => (self.lines.len() + 1).to_string().len() as u16,
};
let gutter_width = digits + 1 + SIGN_MARGIN;
self.last_gutter_width = gutter_width;
self.refresh_git_marks();
self.refresh_fold_tables();
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 provisional_text_width = inner
.width
.saturating_sub(gutter_width + 2 + u16::from(self.lines.len() > height))
as usize;
let content_cols = self.content_cols(provisional_text_width);
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 = match self.clip_content_rows(wide, true) {
Some((_, rows)) => rows > text_height,
None => self.total_visual_rows(wide) > text_height,
};
let tw = if vbar { wide.saturating_sub(1) } else { wide };
let (base, content_rows) = match self.clip_content_rows(tw, true) {
Some(clip) => clip,
None => (0, 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(base + content_rows.saturating_sub(text_height))
.max(base);
self.set_top_to_visual_row(top, tw);
}
let metrics = scrollbar::vertical_metrics(
scrollbar_area,
content_rows,
text_height,
self.top_visual_row(tw).saturating_sub(base),
);
(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 let Some((first, end)) = self.symbol_clip() {
let bw = inner.width.saturating_sub(gutter_width + 3) as usize;
let (mut top, mut rows) = (end, 0);
while top > first {
let line = top - 1;
let need = if self.is_line_hidden(line) {
0
} else {
1 + self.box_rows_between(line, top, bw)
};
if rows + need > text_height {
break;
}
rows += need;
top = line;
}
self.scroll = self.scroll.clamp(first, top.min(end - 1));
}
if self.scroll != scroll_before {
self.scroll_sub = 0;
}
let bw = inner.width.saturating_sub(gutter_width + 3) as usize;
let (base, content) = self.clip_content_rows(bw, false).unwrap_or((
0,
self.lines.len() + self.box_rows_between(0, self.lines.len(), bw),
));
let metrics = scrollbar::vertical_metrics(
scrollbar_area,
content,
text_height,
(self.scroll + self.box_rows_between(0, self.scroll, bw) + self.scroll_sub)
.saturating_sub(base),
);
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 content_cols = self.content_cols(text_width as usize);
let max_scroll_col = content_cols.saturating_sub(text_width as usize);
let limit = if !self.wrap_enabled()
&& self.caret_scroll_allowed
&& self.scroll_col > max_scroll_col
{
max_scroll_col.max(self.caret_scroll_for_width(text_width as usize, 0))
} else {
max_scroll_col
};
self.scroll_col = self.scroll_col.min(limit);
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> = std::mem::take(&mut self.last_wrap_rows);
visual_rows.clear();
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;
}
}
};
let ghost_tail = if self.focused {
self.live_ghost()
.map_or(0, |t| t.split('\n').count().saturating_sub(1))
} else {
0
};
let push_ghost_rows = |rows: &mut Vec<VisRow>| {
for index in 1..=ghost_tail {
if rows.len() >= text_height {
break;
}
rows.push(VisRow::Ghost { index });
}
};
let clip_end = self.symbol_clip().map_or(self.lines.len(), |(_, end)| end);
if wrap {
let tw = text_width as usize;
let mut line = self.scroll;
let mut skip = self.scroll_sub;
while line < clip_end && 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,
});
}
if line == self.cursor_row && skip < segs.len() {
push_ghost_rows(&mut visual_rows);
}
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 < clip_end && 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,
});
if line == self.cursor_row {
push_ghost_rows(&mut visual_rows);
}
}
push_box_rows(&mut visual_rows, self, line, skip, 1, tw);
skip = 0;
}
line += 1;
}
}
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.cached_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();
let surfaces = self.theme.surfaces().is_some();
let gutter_hovered = self.pointer.is_some_and(|(px, py)| {
px >= inner.x
&& px <= inner.x + gutter_width
&& py >= inner.y
&& py < inner.y + inner.height
});
let frame = RowFrame {
inner,
visual_rows: &visual_rows,
gutter_width,
text_x,
text_width,
wrap,
sel_norm,
occ_needle,
bracket_pair,
guide_step,
active_guide,
guide_fg,
guide_active_fg,
surfaces,
gutter_hovered,
};
let mut row_cells = RowCells::with_capacity(text_width as usize + 1);
let mut span_scratch = SpanScratch::default();
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::Ghost { index } => {
self.paint_ghost_row(
buf,
inner,
y,
gutter_width,
text_x,
text_width,
index,
wrap,
);
continue;
}
VisRow::Text { line, start, end } => (line, start, end),
};
self.paint_row_gutter(buf, &frame, y, line_idx, !wrap || row_start == 0);
let (line_len, row_width) = self.paint_row_text(
buf,
&frame,
&mut row_cells,
&mut span_scratch,
y,
line_idx,
row_start,
row_end,
);
self.paint_row_overlays(
buf, &frame, &row_cells, y, line_idx, row_start, row_end, line_len, row_width,
);
}
self.last_wrap_rows = visual_rows;
if !self.rulers.is_empty() {
let ruler_fg = self.theme.ruler();
let shift = if wrap { 0 } else { self.scroll_col };
for row in 0..text_height {
if matches!(self.last_wrap_rows.get(row), Some(VisRow::Box { .. })) {
continue;
}
let y = inner.y + row as u16;
for &ruler in &self.rulers {
let Some(col) = usize::from(ruler).checked_sub(shift) else {
continue;
};
if col >= text_width as usize {
continue;
}
let cell = &mut buf[(text_x + col as u16, y)];
if cell.symbol() != " " {
continue;
}
cell.set_symbol("\u{2502}");
let style = cell.style().fg(ruler_fg).remove_modifier(Modifier::ITALIC);
cell.set_style(style);
}
}
}
for (cl, cc, name, color) in &self.ghost_caret_labels {
let Some(caret_vidx) = self.last_wrap_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 >= self.last_wrap_rows.len() {
continue;
}
let VisRow::Text {
start: caret_start,
end: caret_end,
..
} = self.last_wrap_rows[caret_vidx]
else {
continue;
};
if *cc < caret_start {
continue;
}
let caret_raw = &self.lines[*cl];
let hint_cap = caret_end.min(self.line_char_len(*cl));
row_cells.fill(
&caret_raw[byte_index_of_char(caret_raw, caret_start)
..byte_index_of_char(caret_raw, caret_end)],
caret_start,
self.row_origin(caret_raw, caret_start),
self.row_inlay_spans(*cl)
.iter()
.filter(|(hc, _, _)| *hc >= caret_start && *hc <= hint_cap)
.map(|(hc, l, _)| (*hc, l.chars().count())),
);
let x0 = row_cells.caret(*cc) 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));
}
paint_gutter_number(
buf,
inner.x,
y,
gutter_width,
inner.right(),
self.gutter_number(line as usize),
Style::default().fg(self.theme.line_number_fg()).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 self.overview_ruler {
let ticks = self.overview_ruler_rows_wrapped(
metrics.area.height,
wrap.then_some(text_width as usize),
);
paint_overview_ruler(buf, metrics.area, &ticks, self.theme);
}
}
if let Some(metrics) = hbar_metrics {
scrollbar::render_horizontal(buf, metrics, self.focused, self.theme);
}
}
}
impl Editor {
fn paint_row_gutter(
&self,
buf: &mut Buffer,
frame: &RowFrame<'_>,
y: u16,
line_idx: usize,
first_row: bool,
) {
if self.focused && line_idx == self.cursor_row && frame.sel_norm.is_none() {
buf.set_style(
Rect::new(
frame.inner.x,
y,
frame.gutter_width + 1 + frame.text_width,
1,
),
Style::default().bg(self.theme.current_line_bg()),
);
}
if first_row {
let number_fg = match self
.live_run
.as_ref()
.and_then(|v| v.coverage(line_idx, &self.lines[line_idx]))
{
Some(crate::live_run::Coverage::Ran) => self.theme.git_added(),
Some(crate::live_run::Coverage::NeverRan) => {
self.theme.ui(Color::Rgb(0xa0, 0x55, 0x55))
}
None if self.is_caret_line(line_idx) => self.theme.line_number_active(),
None => self.theme.line_number_fg(),
};
paint_gutter_number(
buf,
frame.inner.x,
y,
frame.gutter_width,
frame.inner.right(),
self.gutter_number(line_idx),
Style::default().fg(number_fg),
);
} else if y >= buf.area.y && y < buf.area.bottom() {
let clear_end = frame
.inner
.x
.saturating_add(frame.gutter_width)
.min(frame.inner.right())
.min(buf.area.right());
for cx in frame.inner.x..clear_end {
buf[(cx, y)].set_symbol(" ");
}
}
let sign_x = frame.inner.x;
if let Some(glyph) = first_row.then(|| self.sign_glyph(line_idx)).flatten() {
let (symbol, color) = match glyph {
SignGlyph::Stop => ("▶", Color::Rgb(0xff, 0xcc, 0x00)),
SignGlyph::Breakpoint(BreakpointMark::Unverified) => {
("○", Color::Rgb(0x99, 0x99, 0x99))
}
SignGlyph::Breakpoint(BreakpointMark::Conditional) => {
("◆", Color::Rgb(0xe5, 0x1c, 0x23))
}
SignGlyph::Breakpoint(BreakpointMark::Logpoint) => {
("◆", Color::Rgb(0xe5, 0xc0, 0x7b))
}
SignGlyph::Breakpoint(BreakpointMark::Plain) => ("●", Color::Rgb(0xe5, 0x1c, 0x23)),
SignGlyph::StreamStop => ("■", Color::Rgb(0xff, 0x9d, 0x2f)),
SignGlyph::Bookmark => ("\u{2691}", Color::Rgb(0x4f, 0xc1, 0xff)),
SignGlyph::TestPlay(_) => ("\u{eb2c}", Color::Rgb(0x73, 0xc9, 0x91)),
};
buf.set_string(sign_x, y, symbol, Style::default().fg(self.theme.ui(color)));
}
if first_row && self.is_foldable(line_idx) {
let collapsed = self.folded.contains(&line_idx);
let glyph = if collapsed {
let ink = crate::theme::tones(self.theme)
.map_or_else(|| self.theme.ui(Color::Gray), |t| t.muted());
Some(("▸", ink))
} else if !frame.surfaces || frame.gutter_hovered || self.is_caret_line(line_idx) {
Some(("▾", self.theme.line_number_fg()))
} else {
None
};
if let Some((glyph, color)) = glyph {
buf.set_string(sign_x + 1, y, glyph, Style::default().fg(color));
}
}
if first_row && 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(),
};
let bar = if frame.surfaces {
"\u{258e}"
} else {
"\u{2503}"
};
buf.set_string(
frame.inner.x + frame.gutter_width,
y,
bar,
Style::default().fg(color),
);
}
if first_row
&& let Some(lens) = self.coverage.as_ref()
&& let Some(cov) = lens.lines.get(&line_idx)
{
use crate::testing::coverage::LineCov;
let (rgb, glyph) = match cov {
LineCov::Covered => ((0x4e, 0xc9, 0x7a), "\u{258c}"),
LineCov::Uncovered => ((0xe0, 0x55, 0x55), "\u{258c}"),
LineCov::Partial => ((0xe0, 0xb0, 0x40), "\u{2596}"),
};
let (r, g, b) = if lens.stale {
(rgb.0 / 2, rgb.1 / 2, rgb.2 / 2)
} else {
rgb
};
buf.set_string(
frame.inner.x + frame.gutter_width,
y,
glyph,
Style::default().fg(self.theme.ui(Color::Rgb(r, g, b))),
);
}
if self.provenance_overlay
&& first_row
&& let Some(seat) = self.provenance.seat(line_idx)
{
let (r, g, b) = seat.hue();
let bar = if frame.surfaces {
"\u{258f}"
} else {
"\u{258e}"
};
buf.set_string(
frame.inner.x + frame.gutter_width,
y,
bar,
Style::default().fg(self.theme.ui(Color::Rgb(r, g, b))),
);
}
}
#[allow(clippy::too_many_arguments)]
fn paint_row_text(
&self,
buf: &mut Buffer,
frame: &RowFrame<'_>,
row_cells: &mut RowCells,
span_scratch: &mut SpanScratch,
y: u16,
line_idx: usize,
row_start: usize,
row_end: usize,
) -> (usize, u16) {
let raw = &self.lines[line_idx];
let line_len = self.line_char_len(line_idx);
let byte_start = byte_index_of_char(raw, row_start);
let byte_end = byte_index_of_char(raw, row_end);
let row_origin = self.row_origin(raw, row_start);
let row_width = {
let cells: usize = cells_from(&raw[byte_start..byte_end], row_origin);
cells
.max(row_end - row_start)
.min(frame.text_width as usize) as u16
};
let visible_raw = &raw[byte_start..byte_end];
let seg_bytes = byte_end - byte_start;
let line_spans = self.highlights.get(line_idx).map_or(&[][..], Vec::as_slice);
let sem_spans = self
.semantic_overlay
.get(line_idx)
.map_or(&[][..], Vec::as_slice);
let merged = merge_overlay_into(line_spans, sem_spans, &mut span_scratch.merged);
let hint_cap = row_end.min(line_len);
row_cells.fill(
visible_raw,
row_start,
row_origin,
self.row_inlay_spans(line_idx)
.iter()
.filter(|(hc, _, _)| *hc >= row_start && *hc <= hint_cap)
.map(|(hc, l, _)| (*hc, l.chars().count())),
);
if row_cells.hints.is_empty() {
let shifted =
shift_and_clip_spans_into(merged, byte_start, seg_bytes, &mut span_scratch.shifted);
paint_line_spans(
buf,
frame.text_x,
y,
row_width,
visible_raw,
shifted,
row_origin,
);
} 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, swatch) 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,
(row_start, row_origin),
from,
*hcol,
));
}
let style = match swatch {
Some(c) => Style::default().fg(*c),
None => hint_style,
};
out.push(Span::styled(label.clone(), style));
from = from.max(*hcol);
}
if row_end > from {
out.extend(inlay_text_segment(
raw,
merged,
(row_start, row_origin),
from,
row_end,
));
}
buf.set_line(frame.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 {
let c = c as usize;
if c < row_start {
continue;
}
let fg = if ci == UNEXPECTED_BRACKET {
self.theme.bracket_unexpected_fg()
} else {
self.theme.bracket_pair_color(usize::from(ci))
};
if !paint_row_cells(buf, frame.text_x, y, row_width, row_cells, c, |s| s.fg(fg)) {
break;
}
}
}
let scanned;
let hits = match self.color_swatches.get(line_idx) {
Some(hits) => Some(hits.as_slice()),
None if self.show_color_swatches => {
scanned = scan_color_swatches_in_window(
raw,
byte_start,
byte_end,
row_start,
self.swatch_decimal_short(),
);
Some(scanned.as_slice())
}
None => None,
};
if self.show_color_swatches
&& let Some(hits) = hits
{
for &(start_c, end_c, bg, fg) in hits {
if end_c <= row_start {
continue;
}
let from = start_c.max(row_start);
for c in from..end_c {
let tint = |s: Style| s.bg(bg).fg(fg);
if !paint_row_cells(buf, frame.text_x, y, row_width, row_cells, c, tint) {
break;
}
}
}
}
if self.show_indent_guides && (!frame.wrap || row_start == 0) {
let (guide_width, guide_src) = self.guide_indent(line_idx);
let src_cells;
let geometry = if guide_src == line_idx {
&*row_cells
} else {
src_cells = RowCells::of_line_at(
&self.lines[guide_src],
row_start,
self.row_origin(&self.lines[guide_src], row_start),
);
&src_cells
};
for c in (0..guide_width).step_by(frame.guide_step) {
if c < row_start {
continue;
}
let col = geometry.cell(c);
if col >= usize::from(row_width) {
break;
}
let cell = &mut buf[(frame.text_x + col as u16, y)];
if cell.symbol() != " " {
continue;
}
let fg = match frame.active_guide {
Some((ac, lo, hi)) if ac == c && (lo..=hi).contains(&line_idx) => {
frame.guide_active_fg
}
_ => frame.guide_fg,
};
cell.set_symbol("\u{2502}");
let style = cell.style().fg(fg).remove_modifier(Modifier::ITALIC);
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))) = frame.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 = row_cells.cell(ci);
if col >= usize::from(row_width) {
break;
}
let cell = &mut buf[(frame.text_x + col as u16, y)];
cell.set_symbol(glyph);
let style = cell.style().fg(ws_fg).remove_modifier(Modifier::ITALIC);
cell.set_style(style);
}
}
}
(line_len, row_width)
}
#[allow(clippy::too_many_arguments)]
fn paint_row_overlays(
&mut self,
buf: &mut Buffer,
frame: &RowFrame<'_>,
row_cells: &RowCells,
y: u16,
line_idx: usize,
row_start: usize,
row_end: usize,
line_len: usize,
row_width: u16,
) {
let raw = &self.lines[line_idx];
if let Some(tint) = conflict_row_tint(&self.conflicts, line_idx, self.theme) {
paint_full_row_bg(buf, frame.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 = row_cells.text_before(line_len) as u16;
if marker_len <= row_width {
use crate::merge::Resolution;
let chips = [
AcceptChip::new("Accept Current", "Current", ACCEPT_CURRENT_FILL),
AcceptChip::new("Accept Incoming", "Incoming", ACCEPT_INCOMING_FILL),
AcceptChip::new("Accept Both", "Both", ACCEPT_BOTH_FILL),
];
let res = [Resolution::Current, Resolution::Incoming, Resolution::Both];
let x0 = frame.text_x + marker_len + 2;
for (i, xs) in
paint_accept_chips(buf, &chips, x0, frame.text_x + row_width, y, self.theme)
{
self.merge_action_spans
.push((y, xs, block.ours_start, res[i]));
}
}
}
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 = row_cells.cell(sc);
let ve = row_cells.end(ec);
if ve > vs {
paint_diagnostic_underline(
buf,
frame.text_x,
y,
row_width,
vs,
ve,
severity,
self.theme,
);
}
}
let empty_tags: Vec<(usize, usize, crate::lsp::manager::DiagnosticTags)> = Vec::new();
for &(sc, ec, tags) in self
.diagnostic_tag_spans
.get(line_idx)
.unwrap_or(&empty_tags)
{
let vs = row_cells.cell(sc);
let ve = row_cells.end(ec);
if ve > vs {
paint_diagnostic_tags(buf, frame.text_x, y, row_width, vs, ve, tags);
}
}
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.max(row_start)..occ_end {
if !paint_row_cells(buf, frame.text_x, y, row_width, row_cells, c, |s| s.bg(bg)) {
break;
}
}
}
if let Some(term) = self
.search_highlight
.as_deref()
.filter(|_| find_window(self.find_range, line_idx) != Some((0, 0)))
{
let active_on_line = self
.active_search_match
.filter(|(r, _, _)| *r == line_idx)
.map(|(_, c, l)| (c, l));
paint_search_highlight(
buf,
frame.text_x,
y,
row_width,
raw,
term,
self.search_highlight_opts,
row_cells,
active_on_line,
None,
find_window(self.find_range, line_idx),
self.theme,
);
}
if let Some(needle) = frame.occ_needle.as_deref() {
paint_selection_occurrences(
buf,
frame.text_x,
y,
row_width,
raw,
needle,
row_cells,
self.theme,
);
}
if let Some(((sr, sc), (er, ec))) = frame.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 = row_cells.cell(sel_start);
let visible_end = row_cells.end(sel_end);
if visible_end > visible_start {
paint_selection_band(
buf,
frame.text_x,
y,
row_width,
visible_start,
visible_end,
self.theme,
);
}
}
if let Some((open, close)) = frame.bracket_pair {
for pos in [open, close] {
if pos.0 == line_idx && pos.1 >= row_start {
paint_bracket_match(
buf,
frame.text_x,
y,
row_width,
row_cells.cell(pos.1),
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 = row_cells.cell(cs);
let ve = row_cells.end(ce);
if ve > vs {
paint_selection_band(buf, frame.text_x, y, row_width, vs, ve, self.theme);
}
}
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,
frame.text_x,
y,
row_width,
row_cells.caret(c),
self.theme,
);
}
}
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, frame.text_x, y, row_width, row_cells.caret(gc), color);
}
}
if self.focused
&& line_idx == self.cursor_row
&& row_end >= line_len
&& !self.inline_values.contains_key(&line_idx)
&& self.live_note(line_idx).is_none()
&& self.lenses_on_line(line_idx).is_empty()
&& self.live_ghost().is_none()
&& let Some(note) = self.current_line_blame_annotation()
{
let text_cols = row_cells.cell(line_len);
let start_x = frame.text_x + text_cols as u16 + 2;
let right = frame.inner.x + frame.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 let Some(LineBlame::Commit(c)) = self.cursor_line_blame() {
let hash = c.hash.clone();
let w = unicode_width::UnicodeWidthStr::width(shown.as_str()) as u16;
self.blame_span = Some((y, start_x..(start_x + w).min(right), hash));
}
}
}
if row_end >= line_len
&& let Some(note) = self.inline_values.get(&line_idx)
{
let text_cols = row_cells.cell(line_len);
let start_x = frame.text_x + text_cols as u16 + 2;
let right = frame.inner.x + frame.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),
);
}
}
let replaces = self
.live_ghost_full()
.and_then(|g| g.replaces.clone())
.filter(|_| self.focused && line_idx == self.cursor_row);
if let Some(r) = &replaces {
let (vs, ve) = (row_cells.cell(r.start), row_cells.end(r.end));
if ve > vs {
let struck = crate::lsp::manager::DiagnosticTags {
unnecessary: true,
deprecated: true,
};
paint_diagnostic_tags(buf, frame.text_x, y, row_width, vs, ve, struck);
}
}
let ghost_here = self.focused
&& line_idx == self.cursor_row
&& row_end >= line_len
&& self.live_ghost().is_some();
if ghost_here && let Some(text) = self.live_ghost() {
let text_cols = row_cells.cell(line_len) + usize::from(replaces.is_some());
let x = frame.text_x + text_cols as u16;
let right = frame.inner.x + frame.inner.width;
if x < right {
let first = text.split('\n').next().unwrap_or("");
let shown_rows = frame
.visual_rows
.iter()
.filter(|r| matches!(r, VisRow::Ghost { .. }))
.count();
let more = text.split('\n').count() - 1 - shown_rows;
let shown = if more > 0 {
format!(
"{first} (+{more} line{})",
if more == 1 { "" } else { "s" }
)
} else {
first.to_string()
};
let clipped: String = shown.chars().take((right - x) as usize).collect();
buf.set_string(
x,
y,
&clipped,
Style::default()
.fg(self.theme.ignored_fg())
.add_modifier(Modifier::ITALIC),
);
}
}
if row_end >= line_len
&& !ghost_here
&& !self.inline_values.contains_key(&line_idx)
&& self.live_note(line_idx).is_none()
{
let lenses = self.lenses_on_line(line_idx);
if !lenses.is_empty() {
let text_cols = row_cells.cell(line_len);
let mut x = frame.text_x + text_cols as u16 + 2;
let right = frame.inner.x + frame.inner.width;
let style = Style::default()
.fg(self.theme.ignored_fg())
.add_modifier(Modifier::UNDERLINED);
for (n, idx) in lenses.into_iter().enumerate() {
if n > 0 && x + 3 < right {
buf.set_string(x, y, " | ", Style::default().fg(self.theme.ignored_fg()));
x += 3;
}
if x >= right {
break;
}
let title = &self.code_lenses[idx].title;
let shown: String = title.chars().take((right - x) as usize).collect();
let w = unicode_width::UnicodeWidthStr::width(shown.as_str()) as u16;
buf.set_string(x, y, &shown, style);
self.code_lens_spans.push((y, x..x + w, idx));
x += w;
}
}
}
if row_end >= line_len
&& !ghost_here
&& !self.inline_values.contains_key(&line_idx)
&& let Some(note) = self.live_note(line_idx)
{
let text_cols = row_cells.cell(line_len);
let mut x = frame.text_x + text_cols as u16 + 2;
let right = frame.inner.x + frame.inner.width;
for (text, kind) in note {
if x >= right {
break;
}
let color = match kind {
crate::live_run::Kind::Value => self.theme.ignored_fg(),
crate::live_run::Kind::Output => self.theme.ui(Color::Rgb(0x3b, 0x9e, 0xff)),
crate::live_run::Kind::Error => self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c)),
crate::live_run::Kind::Timeout => self.theme.ui(Color::Rgb(0xcc, 0xa7, 0x00)),
};
let avail = (right - x) as usize;
let shown: String = text.chars().take(avail).collect();
let width = unicode_width::UnicodeWidthStr::width(shown.as_str()) as u16;
buf.set_string(
x,
y,
&shown,
Style::default().fg(color).add_modifier(Modifier::ITALIC),
);
x = x.saturating_add(width + 2);
}
}
}
pub(super) 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 line_spans = self.highlights.get(line_idx).map_or(&[][..], Vec::as_slice);
let sem_spans = self
.semantic_overlay
.get(line_idx)
.map_or(&[][..], Vec::as_slice);
let mut merged_scratch = Vec::new();
let mut shifted_scratch = Vec::new();
let merged = merge_overlay_into(line_spans, sem_spans, &mut merged_scratch);
let clamped = shift_and_clip_spans_into(merged, 0, raw.len(), &mut shifted_scratch);
paint_line_spans(buf, text_x, y, width, raw, clamped, 0);
}
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;
}
self.sync_tab_cells();
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 = RowCells::of_line_at(&self.lines[self.cursor_row], start, 0)
.text_before(self.cursor_col);
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
.lines
.get(self.cursor_row)
.map_or(self.cursor_col - self.scroll_col, |l| {
RowCells::of_line(l, self.scroll_col).text_before(self.cursor_col)
})
+ extra;
if visible_col >= text_width as usize {
return None;
}
Some((
text_x + visible_col as u16,
self.last_inner.y + row_in_view as u16,
))
}
pub(super) 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(super) fn inlay_cells_before(hints: &[(usize, usize)], c: usize) -> usize {
hints
.iter()
.filter(|(hc, _)| *hc <= c)
.map(|(_, n)| n)
.sum()
}
pub(super) fn inlay_cells_strictly_before(hints: &[(usize, usize)], c: usize) -> usize {
hints.iter().filter(|(hc, _)| *hc < c).map(|(_, n)| n).sum()
}
#[derive(Debug, Default)]
pub(super) struct RowCells {
start: usize,
before: Vec<usize>,
hints: Vec<(usize, usize)>,
}
impl RowCells {
pub(super) fn with_capacity(cap: usize) -> Self {
Self {
start: 0,
before: Vec::with_capacity(cap),
hints: Vec::new(),
}
}
pub(super) fn of_line(line: &str, start: usize) -> Self {
Self::of_line_at(line, start, cells_before(line, start))
}
pub(super) fn of_line_at(line: &str, start: usize, origin: usize) -> Self {
let mut row = Self::default();
row.fill(&line[byte_index_of_char(line, start)..], start, origin, []);
row
}
pub(super) fn fill(
&mut self,
text: &str,
start: usize,
origin: usize,
hints: impl IntoIterator<Item = (usize, usize)>,
) {
self.start = start;
self.before.clear();
self.before.push(0);
let mut cells = 0;
for (_, w) in char_cells_from(text, origin) {
cells += w;
self.before.push(cells);
}
self.hints.clear();
self.hints.extend(hints);
}
pub(super) fn text_before(&self, col: usize) -> usize {
let i = col.saturating_sub(self.start);
match self.before.get(i) {
Some(&cells) => cells,
None => {
let end = self.before.len().saturating_sub(1);
self.before.last().copied().unwrap_or(0) + (i - end)
}
}
}
pub(super) fn cell(&self, col: usize) -> usize {
self.text_before(col) + inlay_cells_before(&self.hints, col)
}
pub(super) fn caret(&self, col: usize) -> usize {
self.text_before(col) + inlay_cells_strictly_before(&self.hints, col)
}
pub(super) fn end(&self, col: usize) -> usize {
self.text_before(col) + inlay_cells_before(&self.hints, col.saturating_sub(1))
}
pub(super) fn width(&self, col: usize) -> usize {
self.text_before(col + 1) - self.text_before(col)
}
}
pub(super) fn paint_row_cells(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
row: &RowCells,
col: usize,
restyle: impl Fn(Style) -> Style,
) -> bool {
let first = row.cell(col);
let width = row.width(col);
if first >= usize::from(text_width) || first + width > usize::from(text_width) {
return false;
}
for x in first..first + width {
let cell = &mut buf[(text_x + x as u16, y)];
cell.set_style(restyle(cell.style()));
}
true
}
pub(super) fn inlay_text_segment<'a>(
raw: &'a str,
merged: &[HiSpan],
row: (usize, usize),
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(|sp| sp.clipped(seg_bytes))
.collect();
let row_start = byte_index_of_char(raw, row.0).min(byte_from);
let origin = row.1 + cells_from(&raw[row_start..byte_from], row.1);
build_line_spans(seg, &shifted, origin)
}
pub(super) fn search_highlight_styles(theme: crate::theme::Theme) -> (Style, Style) {
let inactive = Style::default()
.fg(Color::Black)
.bg(theme.ui(Color::Rgb(0xff, 0xd7, 0x4a)))
.add_modifier(Modifier::BOLD);
let active = Style::default()
.fg(Color::Black)
.bg(theme.ui(Color::Rgb(0xff, 0x8c, 0x2a)))
.add_modifier(Modifier::BOLD);
(inactive, active)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn paint_search_highlight(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
raw_line: &str,
needle: &str,
opts: crate::search::SearchOpts,
row: &RowCells,
active_match_on_line: Option<(usize, usize)>,
cells: Option<&crate::cell_map::CellMap>,
window: Option<(usize, usize)>,
theme: crate::theme::Theme,
) {
if needle.is_empty() {
return;
}
let (inactive_style, active_style) = search_highlight_styles(theme);
let tones = crate::theme::tones(theme);
let restyle = |active: bool| {
move |s: Style| match tones {
Some(t) => crate::widgets::surface::match_style(s, t, theme, active),
None if active => active_style,
None => inactive_style,
}
};
let segments = crate::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();
let in_window = window.is_none_or(|(lo, hi)| abs_col >= lo && abs_col + chunk_cols <= hi);
if is_match && in_window {
let is_active =
active_match_on_line.is_some_and(|(c, l)| c == abs_col && l == chunk_cols);
let style = restyle(is_active);
for c in 0..chunk_cols {
let absolute = abs_col + c;
if absolute < row.start {
continue;
}
if let Some(cells) = cells {
if !paint_log_cells(buf, text_x, text_x + text_width, y, cells, absolute, style)
{
break;
}
continue;
}
if !paint_row_cells(buf, text_x, y, text_width, row, absolute, style) {
break;
}
}
}
abs_col = abs_col.saturating_add(chunk_cols);
if row.cell(abs_col) >= usize::from(text_width) {
break;
}
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn paint_selection_occurrences(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
raw_line: &str,
needle: &str,
row: &RowCells,
theme: crate::theme::Theme,
) {
if needle.is_empty() {
return;
}
let bg = theme.ui(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 absolute in char_start.max(row.start)..char_start + needle_cols {
if !paint_row_cells(buf, text_x, y, text_width, row, absolute, |s| s.bg(bg)) {
break;
}
}
search_from = byte_start + needle.len();
}
}
pub(super) fn paint_block_cursor(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
col: usize,
theme: crate::theme::Theme,
) {
if col >= usize::from(text_width) {
return;
}
let cell = &mut buf[(text_x + col as u16, y)];
let fg = crate::theme::tones(theme).map_or(Color::Black, |t| t.canvas());
cell.set_style(
Style::default()
.fg(fg)
.bg(theme.secondary_caret_bg())
.add_modifier(Modifier::BOLD),
);
}
pub(super) fn paint_ghost_caret(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
col: usize,
color: Color,
) {
if col >= usize::from(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),
);
}
pub(super) 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));
}
}
pub(super) fn paint_selection_band(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
start_char: usize,
end_char: usize,
theme: crate::theme::Theme,
) {
let bg = theme.ui(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));
}
}
#[allow(clippy::too_many_arguments)]
pub(super) 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,
theme: crate::theme::Theme,
) {
use crate::lsp::manager::DiagnosticSeverity;
let color = match severity {
DiagnosticSeverity::Error => theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c)),
DiagnosticSeverity::Warning => theme.ui(Color::Rgb(0xcc, 0xa7, 0x00)),
DiagnosticSeverity::Information => theme.ui(Color::Rgb(0x3b, 0x9e, 0xff)),
DiagnosticSeverity::Hint => theme.ui(Color::Rgb(0x80, 0x80, 0x80)),
};
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),
);
}
}
pub(super) fn message_with_code(d: &crate::lsp::manager::Diagnostic) -> String {
let Some(code) = &d.code else {
return d.message.clone();
};
let mut text = format!("{} {}", d.message, code.label(""));
if let Some(href) = &code.href {
text.push('\n');
text.push_str(href);
}
text
}
pub(super) fn paint_diagnostic_tags(
buf: &mut Buffer,
text_x: u16,
y: u16,
text_width: u16,
start_char: usize,
end_char: usize,
tags: crate::lsp::manager::DiagnosticTags,
) {
let mut look = Modifier::empty();
if tags.unnecessary {
look |= Modifier::DIM;
}
if tags.deprecated {
look |= Modifier::CROSSED_OUT;
}
let s = start_char.min(text_width as usize);
let e = end_char.min(text_width as usize);
for col in s..e {
let cell = &mut buf[(text_x + col as u16, y)];
cell.set_style(cell.style().add_modifier(look));
}
}