use super::*;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum GitMark {
Added,
Modified,
Deleted,
}
#[derive(Clone, Copy, Debug)]
pub enum LineBlame<'a> {
Uncommitted,
Commit(&'a crate::git::BlameCommit),
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum OverviewMark {
GitAdded,
GitModified,
GitDeleted,
SearchMatch,
Warning,
Error,
}
impl OverviewMark {
pub(super) fn color(self, theme: crate::theme::Theme) -> Color {
match self {
OverviewMark::GitAdded => theme.git_added(),
OverviewMark::GitModified => theme.git_modified(),
OverviewMark::GitDeleted => theme.git_deleted(),
OverviewMark::SearchMatch => theme.ui(Color::Rgb(0xea, 0x9c, 0x2a)),
OverviewMark::Warning => theme.ui(Color::Rgb(0xcc, 0xa7, 0x00)),
OverviewMark::Error => theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c)),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum SignGlyph {
Stop,
Breakpoint(BreakpointMark),
StreamStop,
Bookmark,
TestPlay(String),
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub(super) enum BreakpointMark {
Unverified,
Conditional,
Logpoint,
Plain,
}
impl Editor {
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);
}
}
if let Some(hits) = self.breakpoint_hit_conditions.get_mut(&path) {
hits.remove(&line);
if hits.is_empty() {
self.breakpoint_hit_conditions.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 line_number_line_at(&self, col: u16, row: u16) -> Option<usize> {
let x = self.last_inner.x;
let numbers = x + 2..x + self.last_gutter_width.saturating_sub(1);
if !numbers.contains(&col) || self.has_non_text_view() || self.markdown_preview.is_some() {
return None;
}
self.gutter_line_at(col, row)
}
pub fn breakpoint_lane_line_at(&self, col: u16, row: u16) -> Option<usize> {
if col != self.last_inner.x || self.has_non_text_view() || self.markdown_preview.is_some() {
return None;
}
self.gutter_line_at(col, row)
}
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> {
match self.sign_glyph(self.sign_line_at(col, row)?) {
Some(SignGlyph::TestPlay(name)) => Some(name),
_ => None,
}
}
pub fn stream_stop_at(&self, col: u16, row: u16) -> bool {
self.stream_stop_line.is_some()
&& self
.sign_line_at(col, row)
.is_some_and(|line| self.sign_glyph(line) == Some(SignGlyph::StreamStop))
}
fn sign_line_at(&self, col: u16, row: u16) -> Option<usize> {
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)?;
(!self.wrap_enabled() || start == 0).then_some(line)
}
pub(super) fn sign_glyph(&self, line: usize) -> Option<SignGlyph> {
let here = line + 1; if let Some(path) = self.path.as_deref() {
if self
.stop_line
.as_ref()
.is_some_and(|(p, l)| p == path && *l == here)
{
return Some(SignGlyph::Stop);
}
if self
.breakpoints
.get(path)
.is_some_and(|s| s.contains(&here))
{
return Some(SignGlyph::Breakpoint(self.breakpoint_mark(path, here)));
}
}
if self.stream_stop_line == Some(line) {
return Some(SignGlyph::StreamStop);
}
if self.is_bookmarked(line) {
return Some(SignGlyph::Bookmark);
}
crate::testing::locate::test_fn_on_line(self.path.as_deref(), &self.lines, line)
.map(SignGlyph::TestPlay)
}
fn breakpoint_mark(&self, path: &Path, here: usize) -> BreakpointMark {
if self
.unverified_breakpoints
.get(path)
.is_some_and(|s| s.contains(&here))
{
return BreakpointMark::Unverified;
}
if self
.breakpoint_conditions
.get(path)
.is_some_and(|c| c.contains_key(&here))
|| self
.breakpoint_hit_conditions
.get(path)
.is_some_and(|h| h.contains_key(&here))
{
return BreakpointMark::Conditional;
}
if self
.breakpoint_logs
.get(path)
.is_some_and(|m| m.contains_key(&here))
{
return BreakpointMark::Logpoint;
}
BreakpointMark::Plain
}
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 toggle_bookmark_at(&mut self, line: usize) -> Option<bool> {
let path = self.path.clone()?;
self.sync_bookmarks_to_buffer();
let set = self.bookmarks.entry(path.clone()).or_default();
let added = if set.contains(&line) {
set.remove(&line);
false
} else {
set.insert(line);
true
};
if set.is_empty() {
self.bookmarks.remove(&path);
}
self.seed_bookmark_shadow();
Some(added)
}
pub fn toggle_bookmark(&mut self) -> Option<bool> {
self.toggle_bookmark_at(self.cursor_row + 1)
}
pub fn bookmarked_lines(&self) -> Vec<usize> {
let len = self.lines.len();
self.path
.as_deref()
.and_then(|p| self.bookmarks.get(p))
.map(|s| {
s.iter()
.copied()
.filter(|&l| (1..=len).contains(&l))
.collect()
})
.unwrap_or_default()
}
pub fn restore_bookmarks(
&mut self,
marks: &std::collections::HashMap<PathBuf, std::collections::BTreeSet<usize>>,
) {
if marks.is_empty() {
return;
}
self.bookmarks = marks.clone();
self.sync_bookmarks_to_buffer();
}
pub fn adopt_bookmarks(
&mut self,
path: &Path,
marks: Option<&std::collections::BTreeSet<usize>>,
) {
match marks {
Some(set) if !set.is_empty() => {
self.bookmarks.insert(path.to_path_buf(), set.clone());
}
_ => {
self.bookmarks.remove(path);
}
}
if self.path.as_deref() == Some(path) {
self.sync_bookmarks_to_buffer();
}
}
pub fn bookmarks_on_disk(
&self,
) -> std::collections::HashMap<PathBuf, std::collections::BTreeSet<usize>> {
let mut marks = self.bookmarks.clone();
if self.dirty
&& let Some(path) = self.path.as_deref()
&& let Some(set) = marks.get_mut(path)
&& let Ok(bytes) = std::fs::read(path)
{
let (text, _, _) = self.encoding.decode(&bytes);
*set = carry_marks(set, &self.lines, &split_into_lines(&text));
}
marks.retain(|_, set| !set.is_empty());
marks
}
pub fn is_bookmarked(&self, line: usize) -> bool {
self.path
.as_deref()
.and_then(|p| self.bookmarks.get(p))
.is_some_and(|s| s.contains(&(line + 1)))
}
pub fn goto_next_bookmark(&mut self) -> Option<usize> {
let marks = self.bookmarked_lines();
let here = self.cursor_row + 1;
let target = *marks
.iter()
.find(|&&l| l > here)
.or_else(|| marks.first())?;
self.jump_to_bookmark(target);
Some(target)
}
pub fn goto_prev_bookmark(&mut self) -> Option<usize> {
let marks = self.bookmarked_lines();
let here = self.cursor_row + 1;
let target = *marks
.iter()
.rev()
.find(|&&l| l < here)
.or_else(|| marks.last())?;
self.jump_to_bookmark(target);
Some(target)
}
pub fn clear_bookmarks(&mut self) -> usize {
self.bookmark_shadow = None;
self.path
.clone()
.and_then(|p| self.bookmarks.remove(&p))
.map(|s| s.len())
.unwrap_or(0)
}
pub(super) fn has_line_marks(&self, path: Option<&Path>) -> bool {
!self.folded.is_empty()
|| path.is_some_and(|p| self.bookmarks.contains_key(p) || self.has_breakpoints_in(p))
}
pub(super) fn has_breakpoints_in(&self, path: &Path) -> bool {
self.breakpoints.contains_key(path)
|| self.breakpoint_conditions.contains_key(path)
|| self.breakpoint_logs.contains_key(path)
|| self.breakpoint_hit_conditions.contains_key(path)
}
pub(super) fn seed_bookmark_shadow(&mut self) {
let path = self.path.as_deref();
if !self.has_line_marks(path)
|| self
.bookmark_shadow
.as_ref()
.is_some_and(|(p, _)| p.as_deref() == path)
{
return;
}
self.bookmark_shadow = Some((self.path.clone(), self.lines.clone()));
}
pub(super) fn sync_bookmarks_to_buffer(&mut self) {
if self.bookmark_sync_paused {
return;
}
let path = self.path.clone();
if !self.has_line_marks(path.as_deref()) {
self.bookmark_shadow = None;
return;
}
let len = self.lines.len();
let mut folds_moved = false;
let mut shadow = match self.bookmark_shadow.take() {
Some((shadow_path, old)) if shadow_path == path => {
let map = line_mapper(&old, &self.lines);
if let Some(path) = &path {
if let Some(set) = self.bookmarks.get_mut(path) {
*set = set.iter().filter_map(|&l| map(l)).collect();
}
if let Some(set) = self.breakpoints.get_mut(path) {
*set = set.iter().filter_map(|&l| map(l)).collect();
}
for per_line in [
&mut self.breakpoint_conditions,
&mut self.breakpoint_logs,
&mut self.breakpoint_hit_conditions,
] {
if let Some(m) = per_line.get_mut(path) {
*m = std::mem::take(m)
.into_iter()
.filter_map(|(l, v)| map(l).map(|n| (n, v)))
.collect();
}
}
}
if !self.folded.is_empty() && old != self.lines {
let moved: std::collections::BTreeSet<usize> = self
.folded
.iter()
.filter_map(|&h| map(h + 1).map(|l| l - 1))
.collect();
if moved != self.folded || old.len() != len {
self.folded = moved;
folds_moved = true;
}
}
drop(map);
old
}
_ => Vec::new(),
};
if folds_moved {
self.fold_epoch_lines = len;
self.refresh_fold_tables();
self.rebuild_hidden_ranges();
}
if let Some(path) = &path {
let in_range = |l: &usize| (1..=len).contains(l);
if let Some(set) = self.bookmarks.get_mut(path) {
set.retain(in_range);
if set.is_empty() {
self.bookmarks.remove(path);
}
}
if let Some(set) = self.breakpoints.get_mut(path) {
set.retain(in_range);
if set.is_empty() {
self.breakpoints.remove(path);
}
}
for per_line in [
&mut self.breakpoint_conditions,
&mut self.breakpoint_logs,
&mut self.breakpoint_hit_conditions,
] {
if let Some(m) = per_line.get_mut(path) {
m.retain(|l, _| in_range(l));
if m.is_empty() {
per_line.remove(path);
}
}
}
}
if !self.has_line_marks(path.as_deref()) {
return;
}
shadow.truncate(len);
for (old, new) in shadow.iter_mut().zip(&self.lines) {
if old != new {
old.clone_from(new);
}
}
let have = shadow.len();
shadow.extend(self.lines[have..].iter().cloned());
self.bookmark_shadow = Some((path, shadow));
}
pub fn jump_to_bookmark(&mut self, line: usize) {
if self.lines.is_empty() {
return;
}
self.selection = None;
self.collapse_carets();
self.goto_line_centered(line.saturating_sub(1));
self.reveal_cursor_fold();
self.ensure_cursor_col_visible();
}
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);
let hits = self.breakpoint_hit_conditions.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(),
hit_condition: hits.and_then(|h| h.get(&l)).cloned(),
})
.collect()
}
pub fn set_git_head_lines(&mut self, path: PathBuf, head: Option<PackedLines>) {
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<crate::git::Blame>) {
self.blame_for = Some(path);
self.blame_lines = blame;
}
pub fn current_line_blame_annotation(&self) -> Option<String> {
let note = self.committed_blame_annotation();
if !self.provenance_overlay {
return note;
}
let in_conflict =
crate::merge::conflict_containing(&self.conflicts, self.cursor_row).is_some();
match (note, self.provenance.seat(self.cursor_row)) {
(Some(n), Some(seat)) => Some(format!("{n} • {}", seat.label())),
(Some(n), None) => Some(n),
(None, Some(seat)) if self.blame_enabled && !in_conflict => Some(seat.label()),
(None, _) => None,
}
}
pub(super) fn committed_blame_annotation(&self) -> Option<String> {
Some(match self.cursor_line_blame()? {
LineBlame::Uncommitted => "Uncommitted changes".to_string(),
LineBlame::Commit(commit) => format!(
"{}, {} • {}",
commit.author,
crate::git::humanize_age(commit.age_secs),
commit.summary
),
})
}
pub fn cursor_line_blame(&self) -> Option<LineBlame<'_>> {
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(LineBlame::Uncommitted);
}
if blame.len() != self.lines.len() {
return None;
}
let (commit, text) = blame.line(self.cursor_row)?;
if text.is_some_and(|t| Some(t) != self.lines.get(self.cursor_row).map(String::as_str)) {
return None;
}
Some(if commit.uncommitted {
LineBlame::Uncommitted
} else {
LineBlame::Commit(commit)
})
}
pub fn blame_commit_at(&self, col: u16, row: u16) -> Option<&str> {
self.blame_span
.as_ref()
.filter(|(y, xs, _)| *y == row && xs.contains(&col))
.map(|(_, _, hash)| hash.as_str())
}
pub(super) 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 head: Vec<&str> = head.iter().collect();
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 overview_ruler_rows(&mut self, track_rows: u16) -> Vec<Option<OverviewMark>> {
self.overview_ruler_rows_wrapped(track_rows, None)
}
pub fn overview_ruler_rows_wrapped(
&mut self,
track_rows: u16,
wrap_width: Option<usize>,
) -> Vec<Option<OverviewMark>> {
let rows = track_rows as usize;
let mut out = vec![None; rows];
if rows == 0 || self.lines.is_empty() {
return out;
}
let n = self.lines.len();
let (starts, boxes): (Vec<usize>, Vec<(usize, usize)>) = match wrap_width {
Some(w) => {
let fresh = matches!(
&self.ruler_starts_cache,
Some((seq, cw, _)) if *seq == self.edit_seq && *cw == w
);
if !fresh {
let mut acc = 0;
let text: Vec<usize> = (0..=n)
.map(|l| {
let at = acc;
if l < n {
acc += self.line_visual_rows(l, w);
}
at
})
.collect();
self.ruler_starts_cache = Some((self.edit_seq, w, text));
}
let mut boxes: Vec<(usize, usize)> = (0..self.comment_boxes.len())
.map(|i| (self.comment_boxes[i].line, self.comment_box_height(i, w)))
.collect();
boxes.sort_unstable();
let starts = self
.ruler_starts_cache
.as_ref()
.map(|(_, _, t)| t.clone())
.unwrap_or_default();
(starts, boxes)
}
None => ((0..=n).collect(), Vec::new()),
};
let box_rows_before = |line: usize| -> usize {
boxes
.iter()
.take_while(|(l, _)| *l < line)
.map(|(_, h)| h)
.sum()
};
let total = (starts[n] + box_rows_before(n)).max(1);
let last = n - 1;
let search_hits: Vec<usize> = match self.search_highlight.clone().filter(|n| !n.is_empty())
{
Some(needle) => {
let opts = self.search_highlight_opts;
let fresh = matches!(
&self.ruler_search_cache,
Some((seq, cn, co, _)) if *seq == self.edit_seq && *cn == needle && *co == opts
);
if !fresh {
let hits = self
.lines
.iter()
.enumerate()
.filter(|(_, line)| {
crate::widgets::search::split_for_highlight(line, &needle, opts)
.iter()
.any(|(text, is_match)| *is_match && !text.is_empty())
})
.map(|(i, _)| i)
.collect();
self.ruler_search_cache = Some((self.edit_seq, needle, opts, hits));
}
self.ruler_search_cache
.as_ref()
.map(|(_, _, _, h)| h.clone())
.unwrap_or_default()
}
None => Vec::new(),
};
self.refresh_git_marks();
let mut put = |line: usize, mark: OverviewMark| {
let line = line.min(last);
let row = ((starts[line] + box_rows_before(line)) * rows / total).min(rows - 1);
out[row] = Some(out[row].map_or(mark, |cur: OverviewMark| cur.max(mark)));
};
for (&line, mark) in &self.git_marks {
put(
line,
match mark {
GitMark::Added => OverviewMark::GitAdded,
GitMark::Modified => OverviewMark::GitModified,
GitMark::Deleted => OverviewMark::GitDeleted,
},
);
}
for &i in &search_hits {
put(i, OverviewMark::SearchMatch);
}
for (i, spans) in self.diagnostic_spans.iter().enumerate() {
for (_, _, severity) in spans {
let mark = match severity {
crate::lsp::manager::DiagnosticSeverity::Error => OverviewMark::Error,
crate::lsp::manager::DiagnosticSeverity::Warning => OverviewMark::Warning,
_ => continue,
};
put(i, mark);
}
}
out
}
pub fn git_change_from(&mut self, row: usize, forward: bool) -> Option<usize> {
self.refresh_git_marks();
let mut lines: Vec<usize> = self.git_marks.keys().copied().collect();
lines.sort_unstable();
let starts: Vec<usize> = lines
.iter()
.copied()
.filter(|&l| l == 0 || !self.git_marks.contains_key(&(l - 1)))
.collect();
if forward {
starts
.iter()
.copied()
.find(|&s| s > row)
.or_else(|| starts.first().copied())
} else {
let here = starts.iter().copied().rev().find(|&s| s <= row);
let from = match here {
Some(s) if self.git_marks.contains_key(&row) => s,
_ => row,
};
starts
.iter()
.copied()
.rev()
.find(|&s| s < from)
.or_else(|| starts.last().copied())
}
}
pub fn git_mark_at(&self, line: usize) -> Option<GitMark> {
self.git_marks.get(&line).copied()
}
pub fn current_git_mark_at(&mut self, line: usize) -> Option<GitMark> {
self.refresh_git_marks();
self.git_mark_at(line)
}
pub fn gutter_number(&self, line: usize) -> Option<usize> {
match self.line_numbers {
LineNumbers::On => Some(line + 1),
LineNumbers::Off => None,
LineNumbers::Relative if line == self.cursor_row => Some(line + 1),
LineNumbers::Relative => Some(self.visible_line_distance(self.cursor_row, line)),
LineNumbers::Interval => {
((line + 1).is_multiple_of(10) || line == self.cursor_row).then_some(line + 1)
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineNumbers {
#[default]
On,
Relative,
Interval,
Off,
}
impl LineNumbers {
pub fn pref_id(self) -> &'static str {
match self {
Self::On => "on",
Self::Relative => "relative",
Self::Interval => "interval",
Self::Off => "off",
}
}
pub fn from_pref(id: &str) -> Self {
match id {
"relative" => Self::Relative,
"interval" => Self::Interval,
"off" => Self::Off,
_ => Self::On,
}
}
pub fn next(self) -> Self {
match self {
Self::On => Self::Relative,
Self::Relative => Self::Interval,
Self::Interval => Self::Off,
Self::Off => Self::On,
}
}
}
#[cfg_attr(not(test), allow(dead_code))]
pub(super) fn shift_bookmark_lines(
marks: &std::collections::BTreeSet<usize>,
old: &[String],
new: &[String],
) -> std::collections::BTreeSet<usize> {
let map = shift_line_mapper(old, new);
marks.iter().filter_map(|&line| map(line)).collect()
}
pub(super) fn line_mapper<'a>(
old: &'a [String],
new: &'a [String],
) -> Box<dyn Fn(usize) -> Option<usize> + 'a> {
if old.len() != new.len() {
shift_line_mapper(old, new)
} else {
Box::new(move |line| {
let one = std::collections::BTreeSet::from([line]);
follow_moved_bookmark_lines(&one, old, new)
.into_iter()
.next()
})
}
}
pub fn carry_marks(
marks: &std::collections::BTreeSet<usize>,
old: &[String],
new: &[String],
) -> std::collections::BTreeSet<usize> {
if old == new {
return marks.clone();
}
let map = line_mapper(old, new);
marks.iter().filter_map(|&line| map(line)).collect()
}
pub(super) fn shift_line_mapper<'a>(
old: &'a [String],
new: &'a [String],
) -> Box<dyn Fn(usize) -> Option<usize> + 'a> {
use similar::DiffOp;
let common = old.len().min(new.len());
let prefix = old
.iter()
.zip(new)
.take_while(|(a, b)| a == b)
.count()
.min(common);
let suffix = old
.iter()
.rev()
.zip(new.iter().rev())
.take_while(|(a, b)| a == b)
.count()
.min(common - prefix);
let old_end = old.len() - suffix;
let new_end = new.len() - suffix;
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(20);
let ops = similar::capture_diff_slices_deadline(
similar::Algorithm::Myers,
&old[prefix..old_end],
&new[prefix..new_end],
Some(deadline),
);
let map_middle = move |row: usize| -> Option<usize> {
let r = row - prefix;
for op in &ops {
match *op {
DiffOp::Equal {
old_index,
new_index,
len,
} if (old_index..old_index + len).contains(&r) => {
return Some(prefix + new_index + (r - old_index));
}
DiffOp::Delete {
old_index, old_len, ..
} if (old_index..old_index + old_len).contains(&r) => return None,
DiffOp::Replace {
old_index,
old_len,
new_index,
new_len,
} if (old_index..old_index + old_len).contains(&r) => {
return Some(prefix + new_index + (r - old_index).min(new_len - 1));
}
_ => {}
}
}
None
};
Box::new(move |line: usize| {
let row = line.checked_sub(1)?;
let mapped = if row < prefix {
row
} else if row >= old_end {
row - old_end + new_end
} else {
map_middle(row)?
};
Some(mapped + 1)
})
}
pub(super) fn follow_moved_bookmark_lines(
marks: &std::collections::BTreeSet<usize>,
old: &[String],
new: &[String],
) -> std::collections::BTreeSet<usize> {
let Some(first) = old.iter().zip(new).position(|(a, b)| a != b) else {
return marks.clone();
};
let last = old.len()
- 1
- old
.iter()
.rev()
.zip(new.iter().rev())
.position(|(a, b)| a != b)
.unwrap_or(0);
marks
.iter()
.map(|&line| {
let row = line - 1;
if !(first..=last).contains(&row) || old.get(row) == new.get(row) {
return line;
}
let text = &old[row];
let mut hits = (first..=last).filter(|&j| &new[j] == text);
match (hits.next(), hits.next()) {
(Some(j), None) => j + 1,
_ => line,
}
})
.collect()
}
pub(super) fn paint_overview_ruler(
buf: &mut Buffer,
area: Rect,
ticks: &[Option<OverviewMark>],
theme: crate::theme::Theme,
) {
if area.width == 0 {
return;
}
for (row, tick) in ticks.iter().enumerate() {
let Some(mark) = tick else { continue };
let y = area.y.saturating_add(row as u16);
if y >= area.y.saturating_add(area.height) {
break;
}
let cell = &mut buf[(area.x, y)];
cell.set_symbol("\u{2501}"); cell.set_fg(mark.color(theme));
}
}