clean up files, parse arguments with clap

This commit is contained in:
alice pellerin
2026-04-12 22:59:54 -05:00
parent 44553a5328
commit a689949044
21 changed files with 2452 additions and 1856 deletions
+923
View File
@@ -0,0 +1,923 @@
use std::{cmp::min, collections::hash_set::Entry, convert::identity, fs::File, io::Write, iter, mem::{replace, swap}};
use itertools::Itertools;
use ratatui::{style::{Color, Stylize}, text::Span};
use crate::{BYTES_OF_PADDING, BYTES_PER_LINE, LINES_OF_PADDING, action::BufferAction, buffer::{Buffer, InspectionStatus, Mode, PartialAction}, cursor::Cursor, edit_action::EditAction, popup::Popup, window_size::WindowSize};
impl Buffer {
pub fn execute(&mut self, action: BufferAction, window_size: WindowSize) {
match action {
BufferAction::NormalMode => self.normal_mode(),
BufferAction::SelectMode => self.select_mode(),
BufferAction::Goto => self.goto(),
BufferAction::View => self.view(),
BufferAction::Replace => self.replace(),
BufferAction::Space => self.space(),
BufferAction::Repeat => self.repeat(),
BufferAction::To => self.to(),
BufferAction::ScrollDown => self.scroll_down(window_size),
BufferAction::ScrollUp => self.scroll_up(window_size),
BufferAction::PageCursorHalfDown => self.page_cursor_half_down(window_size),
BufferAction::PageCursorHalfUp => self.page_cursor_half_up(window_size),
BufferAction::PageDown => self.page_down(window_size),
BufferAction::PageUp => self.page_up(window_size),
BufferAction::CollapseSelection => self.collapse_selection(),
BufferAction::FlipSelections => self.flip_selection(window_size),
BufferAction::Delete => self.delete(window_size),
BufferAction::Undo => self.undo(window_size),
BufferAction::Redo => self.redo(window_size),
BufferAction::Save => self.save(),
BufferAction::CopySelectionOnNextLine => self.copy_selection_on_next_line(window_size),
BufferAction::RotateSelectionsBackward => self.rotate_selections_backward(window_size),
BufferAction::RotateSelectionsForward => self.rotate_selections_forward(window_size),
BufferAction::KeepPrimarySelection => self.keep_primary_selection(),
BufferAction::RemovePrimarySelection => self.remove_primary_selection(),
BufferAction::SplitSelectionsInto1s => self.split_selections_into_size(1, window_size),
BufferAction::SplitSelectionsInto2s => self.split_selections_into_size(2, window_size),
BufferAction::SplitSelectionsInto3s => self.split_selections_into_size(3, window_size),
BufferAction::SplitSelectionsInto4s => self.split_selections_into_size(4, window_size),
BufferAction::SplitSelectionsInto5s => self.split_selections_into_size(5, window_size),
BufferAction::SplitSelectionsInto6s => self.split_selections_into_size(6, window_size),
BufferAction::SplitSelectionsInto7s => self.split_selections_into_size(7, window_size),
BufferAction::SplitSelectionsInto8s => self.split_selections_into_size(8, window_size),
BufferAction::SplitSelectionsInto9s => self.split_selections_into_size(9, window_size),
BufferAction::JumpToSelectedOffset => self.jump_to_selected_offset(window_size),
BufferAction::JumpToSelectedOffsetRelativeToMark => self.jump_to_selected_offset_relative_to_mark(window_size),
BufferAction::ToggleMark => self.toggle_mark(),
BufferAction::AlignViewCenter => self.align_view_center(window_size),
BufferAction::AlignViewBottom => self.align_view_bottom(window_size),
BufferAction::AlignViewTop => self.align_view_top(),
BufferAction::ExtendToMark => self.extend_to_mark(window_size),
BufferAction::ExtendToNull => self.extend_to_null(window_size),
BufferAction::ExtendToFF => self.extend_to_FF(window_size),
BufferAction::InspectSelection => self.inspect_selection(),
BufferAction::InspectSelectionColor => self.inspect_selection_color(),
}
}
const fn normal_mode(&mut self) {
self.mode = Mode::Normal;
}
const fn select_mode(&mut self) {
self.mode = Mode::Select;
}
const fn goto(&mut self) {
self.partial_action = Some(PartialAction::Goto);
}
const fn view(&mut self) {
self.partial_action = Some(PartialAction::View);
}
const fn replace(&mut self) {
if !self.contents.is_empty() {
self.partial_action = Some(PartialAction::Replace);
}
}
const fn space(&mut self) {
self.partial_action = Some(PartialAction::Space);
}
const fn repeat(&mut self) {
self.partial_action = Some(PartialAction::Repeat);
}
const fn to(&mut self) {
self.partial_action = Some(PartialAction::To);
}
pub fn scroll_down(&mut self, window_size: WindowSize) {
if self.contents.len() <= BYTES_OF_PADDING { return; }
self.scroll_position = min(
self.scroll_position + BYTES_PER_LINE,
self.contents.len() - BYTES_OF_PADDING - self.contents.len() % BYTES_PER_LINE
);
if window_size.hex_rows() > LINES_OF_PADDING * 2 {
self.primary_cursor.clamp(
self.scroll_position + BYTES_OF_PADDING,
window_size.visible_byte_count() - BYTES_OF_PADDING * 2
);
} else {
self.primary_cursor.clamp(self.scroll_position, window_size.visible_byte_count());
}
self.combine_cursors_if_overlapping();
}
pub fn scroll_up(&mut self, window_size: WindowSize) {
self.scroll_position = self.scroll_position.saturating_sub(BYTES_PER_LINE);
if window_size.hex_rows() > LINES_OF_PADDING * 2 {
self.primary_cursor.clamp(
self.scroll_position + BYTES_OF_PADDING,
window_size.visible_byte_count() - BYTES_OF_PADDING * 2
);
} else {
self.primary_cursor.clamp(self.scroll_position, window_size.visible_byte_count());
}
self.combine_cursors_if_overlapping();
}
fn page_cursor_half_down(&mut self, window_size: WindowSize) {
if self.contents.len() <= BYTES_OF_PADDING { return; }
let old_scroll_position = self.scroll_position;
self.scroll_position = min(
self.scroll_position + (window_size.visible_byte_count() / 2).next_multiple_of(BYTES_PER_LINE),
self.contents.len() - BYTES_OF_PADDING - self.contents.len() % BYTES_PER_LINE
);
let scroll_position_change = self.scroll_position - old_scroll_position;
let max_contents_index = self.max_contents_index();
self.primary_cursor.head = min(
self.primary_cursor.head + scroll_position_change,
max_contents_index
);
self.primary_cursor.tail = min(
self.primary_cursor.tail + scroll_position_change,
max_contents_index
);
for cursor in &mut self.cursors {
cursor.head = (cursor.head + scroll_position_change).min(max_contents_index);
cursor.tail = (cursor.tail + scroll_position_change).min(max_contents_index);
}
self.combine_cursors_if_overlapping();
}
fn page_cursor_half_up(&mut self, window_size: WindowSize) {
let old_scroll_position = self.scroll_position;
self.scroll_position = self.scroll_position.saturating_sub(
(window_size.visible_byte_count() / 2).next_multiple_of(BYTES_PER_LINE)
);
let scroll_position_change = old_scroll_position - self.scroll_position;
let max_contents_index = self.max_contents_index();
self.primary_cursor.head = min(
self.primary_cursor.head - scroll_position_change,
max_contents_index
);
self.primary_cursor.tail = min(
self.primary_cursor.tail - scroll_position_change,
max_contents_index
);
for cursor in &mut self.cursors {
cursor.head = (cursor.head - scroll_position_change).min(max_contents_index);
cursor.tail = (cursor.tail - scroll_position_change).min(max_contents_index);
}
self.combine_cursors_if_overlapping();
}
fn page_down(&mut self, window_size: WindowSize) {
if self.contents.len() <= BYTES_OF_PADDING { return; }
self.scroll_position = min(
self.scroll_position + window_size.visible_byte_count(),
self.max_contents_index() - BYTES_OF_PADDING - self.max_contents_index() % BYTES_PER_LINE
);
if window_size.hex_rows() > LINES_OF_PADDING * 2 {
self.primary_cursor.clamp(
self.scroll_position + BYTES_OF_PADDING,
window_size.visible_byte_count() - BYTES_OF_PADDING * 2
);
} else {
self.primary_cursor.clamp(self.scroll_position, window_size.visible_byte_count());
}
self.combine_cursors_if_overlapping();
}
fn page_up(&mut self, window_size: WindowSize) {
self.scroll_position = self.scroll_position.saturating_sub(
window_size.visible_byte_count()
);
if window_size.hex_rows() > LINES_OF_PADDING * 2 {
self.primary_cursor.clamp(
self.scroll_position + BYTES_OF_PADDING,
window_size.visible_byte_count() - BYTES_OF_PADDING * 2
);
} else {
self.primary_cursor.clamp(self.scroll_position, window_size.visible_byte_count());
}
self.combine_cursors_if_overlapping();
}
fn collapse_selection(&mut self) {
self.primary_cursor.collapse();
for cursor in &mut self.cursors {
cursor.collapse();
}
}
fn flip_selection(&mut self, window_size: WindowSize) {
self.primary_cursor.flip();
for cursor in &mut self.cursors {
cursor.flip();
}
self.clamp_screen_to_primary_cursor(window_size);
}
fn delete(&mut self, window_size: WindowSize) {
if !self.contents.is_empty() {
self.execute_and_add(
EditAction::Delete {
primary_cursor: self.primary_cursor,
cursors: self.cursors.clone(),
primary_old_data: self.contents[self.primary_cursor.range()].into(),
old_data: self.cursors
.iter()
.map(|cursor| self.contents[cursor.range()].to_vec())
.collect(),
},
window_size
);
}
if self.mode == Mode::Select {
self.mode = Mode::Normal;
}
}
fn undo(&mut self, window_size: WindowSize) {
if self.time_traveling == Some(0) || self.edit_history.is_empty() { return; }
let current_date = self.time_traveling
.map_or(self.edit_history.len() - 1, |date| date - 1);
self.time_traveling = Some(current_date);
let edit_action = replace(
&mut self.edit_history[current_date],
EditAction::Placeholder
);
self.undo_edit(&edit_action, window_size);
self.edit_history[current_date] = edit_action;
}
fn redo(&mut self, window_size: WindowSize) {
let Some(previous_date) = self.time_traveling else { return; };
let current_date = previous_date + 1;
self.time_traveling = if current_date == self.edit_history.len() {
None
} else {
Some(current_date)
};
let edit_action = replace(
&mut self.edit_history[previous_date],
EditAction::Placeholder
);
self.execute_edit(&edit_action, window_size);
self.edit_history[previous_date] = edit_action;
}
fn save(&mut self) {
let mut file = File::create(&self.file_path).unwrap();
file.write_all(&self.contents).unwrap();
self.last_saved_at = Some(
self.time_traveling.unwrap_or(self.edit_history.len())
);
}
fn copy_selection_on_next_line(&mut self, window_size: WindowSize) {
let new_cursors: Vec<Cursor> = iter::once(&self.primary_cursor)
.chain(&self.cursors)
.filter_map(|cursor| {
let number_of_lines_tall = (cursor.upper_bound() - cursor.lower_bound()) / BYTES_PER_LINE;
let offset_to_add = (number_of_lines_tall + 1) * BYTES_PER_LINE;
if cursor.lower_bound() + offset_to_add < self.contents.len() {
Some(
Cursor {
head: min(cursor.head + offset_to_add, self.max_contents_index()),
tail: min(cursor.tail + offset_to_add, self.max_contents_index())
}
)
} else {
None
}
})
.collect();
self.cursors.extend(new_cursors);
self.cursors.sort_by_key(|cursor| cursor.head);
self.combine_cursors_if_overlapping();
self.rotate_selections_forward(window_size);
}
fn rotate_selections_backward(&mut self, window_size: WindowSize) {
if self.cursors.is_empty() { return; }
let next_cursor_index = self.cursors
.binary_search_by_key(&self.primary_cursor.head, |cursor| cursor.head)
.unwrap_or_else(identity);
if next_cursor_index == 0 {
let cursor_count = self.cursors.len();
swap(&mut self.primary_cursor, &mut self.cursors[cursor_count - 1]);
self.cursors.sort_by_key(|cursor| cursor.head);
} else {
swap(&mut self.primary_cursor, &mut self.cursors[next_cursor_index - 1]);
}
self.clamp_screen_to_primary_cursor(window_size);
}
fn rotate_selections_forward(&mut self, window_size: WindowSize) {
if self.cursors.is_empty() { return; }
let next_cursor_index = self.cursors
.binary_search_by_key(&self.primary_cursor.head, |cursor| cursor.head)
.unwrap_or_else(identity);
if next_cursor_index == self.cursors.len() {
swap(&mut self.primary_cursor, &mut self.cursors[0]);
self.cursors.sort_by_key(|cursor| cursor.head);
} else {
swap(&mut self.primary_cursor, &mut self.cursors[next_cursor_index]);
}
self.clamp_screen_to_primary_cursor(window_size);
}
fn keep_primary_selection(&mut self) {
self.cursors.clear();
}
fn remove_primary_selection(&mut self) {
if self.cursors.is_empty() { return; }
let next_cursor_index = self.cursors
.binary_search_by_key(&self.primary_cursor.head, |cursor| cursor.head)
.unwrap_or_else(identity);
if next_cursor_index == self.cursors.len() {
self.primary_cursor = self.cursors.remove(0);
} else {
self.primary_cursor = self.cursors.remove(next_cursor_index);
}
}
fn split_selections_into_size(&mut self, size: usize, window_size: WindowSize) {
if !iter::once(&self.primary_cursor)
.chain(&self.cursors)
.all(|cursor| cursor.len().is_multiple_of(size))
{
self.alert_message = Span::from(
format!("not all selections are a multiple of {size} long")
).red();
return;
}
let mut new_cursors = iter::once(self.primary_cursor)
.chain(self.cursors.iter().copied())
.flat_map(|cursor| {
cursor
.range()
.step_by(size)
.map(|tail| Cursor { head: tail + size - 1, tail })
});
self.primary_cursor = new_cursors.next().unwrap();
self.cursors = new_cursors.collect();
self.clamp_screen_to_primary_cursor(window_size);
}
fn jump_to_selected_offset(&mut self, window_size: WindowSize) {
if !iter::once(&self.primary_cursor)
.chain(&self.cursors)
.all(|cursor| {
bytes_to_nat(&self.contents[cursor.range()])
.map(|nat| nat as usize)
.is_some_and(|offset| offset < self.contents.len())
})
{
if self.cursors.is_empty() {
self.alert_message = Span::from(
"selection is not a valid offset"
).red();
} else {
self.alert_message = Span::from(
"not all selections are valid offsets"
).red();
}
return;
}
self.primary_cursor = Cursor::at(
bytes_to_nat(&self.contents[self.primary_cursor.range()]).unwrap() as usize
);
for cursor in &mut self.cursors {
*cursor = Cursor::at(
bytes_to_nat(&self.contents[cursor.range()]).unwrap() as usize
);
}
self.cursors.sort_by_key(|cursor| cursor.head);
self.combine_cursors_if_overlapping();
self.clamp_screen_to_primary_cursor(window_size);
}
fn jump_to_selected_offset_relative_to_mark(&mut self, window_size: WindowSize) {
let mut sorted_marks: Vec<_> = self.marks.iter().copied().collect();
sorted_marks.sort_unstable();
if !iter::once(&self.primary_cursor)
.chain(&self.cursors)
.all(|cursor| {
bytes_to_nat(&self.contents[cursor.range()])
.map(|offset| mark_before(cursor.lower_bound(), &sorted_marks) + offset as usize)
.is_some_and(|offset| offset < self.contents.len())
})
{
if self.cursors.is_empty() {
self.alert_message = Span::from(
"selection is not a valid offset"
).red();
} else {
self.alert_message = Span::from(
"not all selections are valid offsets"
).red();
}
return;
}
self.primary_cursor = Cursor::at(
bytes_to_nat(&self.contents[self.primary_cursor.range()])
.map(|offset| {
mark_before(self.primary_cursor.lower_bound(), &sorted_marks) + offset as usize
})
.unwrap()
);
for cursor in &mut self.cursors {
*cursor = Cursor::at(
bytes_to_nat(&self.contents[cursor.range()])
.map(|offset| {
mark_before(cursor.lower_bound(), &sorted_marks) + offset as usize
})
.unwrap()
);
}
self.cursors.sort_by_key(|cursor| cursor.head);
self.combine_cursors_if_overlapping();
self.clamp_screen_to_primary_cursor(window_size);
}
fn toggle_mark(&mut self) {
match self.marks.entry(self.primary_cursor.lower_bound()) {
Entry::Occupied(occupied_entry) => { occupied_entry.remove(); },
Entry::Vacant(vacant_entry) => vacant_entry.insert(),
}
for cursor in &self.cursors {
match self.marks.entry(cursor.lower_bound()) {
Entry::Occupied(occupied_entry) => { occupied_entry.remove(); },
Entry::Vacant(vacant_entry) => vacant_entry.insert(),
}
}
}
const fn align_view_center(&mut self, window_size: WindowSize) {
let half_a_screen = window_size.visible_byte_count() / 2;
self.scroll_position = self.primary_cursor.head
.saturating_sub(self.primary_cursor.head % BYTES_PER_LINE)
.saturating_sub(half_a_screen - (half_a_screen % BYTES_PER_LINE));
}
fn align_view_bottom(&mut self, window_size: WindowSize) {
self.scroll_position = self.primary_cursor.head
.saturating_sub(self.primary_cursor.head % BYTES_PER_LINE)
.saturating_sub(
window_size
.visible_byte_count()
.saturating_sub(BYTES_PER_LINE + BYTES_OF_PADDING)
)
.min(self.max_contents_index() - self.max_contents_index() % BYTES_PER_LINE);
}
const fn align_view_top(&mut self) {
self.scroll_position = self.primary_cursor.head
.saturating_sub(self.primary_cursor.head % BYTES_PER_LINE)
.saturating_sub(BYTES_OF_PADDING);
}
fn extend_to_mark(&mut self, window_size: WindowSize) {
let mut sorted_marks: Vec<_> = self.marks.iter().copied().collect();
sorted_marks.sort_unstable();
let max_contents_index = self.max_contents_index();
let mark_after_primary = mark_after(
self.primary_cursor.head,
&sorted_marks,
max_contents_index
);
self.primary_cursor.tail = self.primary_cursor.head;
self.primary_cursor.head = mark_after_primary - 1;
for cursor in &mut self.cursors {
let mark_after_cursor = mark_after(
cursor.head,
&sorted_marks,
max_contents_index
);
cursor.tail = cursor.head;
cursor.head = mark_after_cursor - 1;
}
self.clamp_screen_to_primary_cursor(window_size);
}
fn extend_to_null(&mut self, window_size: WindowSize) {
if let Some(null_offset_after_primary) = self.contents[self.primary_cursor.head..]
.iter()
.skip(1)
.position(|&byte| byte == 0)
{
self.primary_cursor.tail = self.primary_cursor.head;
self.primary_cursor.head += null_offset_after_primary;
}
for cursor in &mut self.cursors {
if let Some(null_offset_after_primary) = self.contents[cursor.head..]
.iter()
.skip(1)
.position(|&byte| byte == 0)
{
cursor.tail = cursor.head;
cursor.head += null_offset_after_primary;
}
}
self.clamp_screen_to_primary_cursor(window_size);
}
#[allow(non_snake_case)]
fn extend_to_FF(&mut self, window_size: WindowSize) {
if let Some(null_offset_after_primary) = self.contents[self.primary_cursor.head..]
.iter()
.skip(1)
.position(|&byte| byte == 0xFF)
{
self.primary_cursor.tail = self.primary_cursor.head;
self.primary_cursor.head += null_offset_after_primary;
}
for cursor in &mut self.cursors {
if let Some(null_offset_after_primary) = self.contents[cursor.head..]
.iter()
.skip(1)
.position(|&byte| byte == 0xFF)
{
cursor.tail = cursor.head;
cursor.head += null_offset_after_primary;
}
}
self.clamp_screen_to_primary_cursor(window_size);
}
#[allow(clippy::too_many_lines)]
fn inspect_selection(&mut self) {
if self.inspection_status == Some(InspectionStatus::Normal) {
self.inspection_status = None;
return;
}
self.inspection_status = Some(InspectionStatus::Normal);
self.popups.extend(
iter::once(&self.primary_cursor)
.chain(&self.cursors)
.filter_map(|cursor| {
let selection = &self.contents[cursor.range()];
let popup_lines = inspect(selection);
if popup_lines.is_empty() {
None
} else {
Some(Popup::new(cursor.lower_bound(), popup_lines))
}
})
.sorted_unstable_by_key(|popup| popup.at)
);
if self.popups.is_empty() {
self.inspection_status = None;
}
}
fn inspect_selection_color(&mut self) {
if self.inspection_status == Some(InspectionStatus::ColorsOnly) {
self.inspection_status = None;
return;
}
self.inspection_status = Some(InspectionStatus::ColorsOnly);
self.popups.extend(
iter::once(&self.primary_cursor)
.chain(&self.cursors)
.filter_map(|cursor| {
let selection = &self.contents[cursor.range()];
let popup_lines = inspect_color(selection);
if popup_lines.is_empty() {
None
} else {
Some(Popup::new(cursor.lower_bound(), popup_lines))
}
})
.sorted_unstable_by_key(|popup| popup.at)
);
if self.popups.is_empty() {
self.inspection_status = None;
}
}
}
fn inspect(selection: &[u8]) -> Vec<Span<'static>> {
let nat = bytes_to_nat(selection);
let int = nat.and_then(|nat| nat_to_int_if_different(nat, selection.len()));
let utf8 = str::from_utf8(selection).ok()
.filter(|_| selection.len() == 1)
.map(|utf8| utf8.trim_suffix('\0'))
.filter(|utf8| !utf8.contains(is_illegal_control_character))
.map(|utf8| Span::from(format!("\"{utf8}\"")).red());
let fixedpoint2012 = nat
.filter(|_| selection.len() == 4)
.map(|nat| f64::from(nat as u32) / f64::from(1 << 12))
.map(|fixedpoint2012| {
let two_decimals_is_enough = (fixedpoint2012 * 100.0).fract() == 0.0;
let approximate_symbol = if two_decimals_is_enough { "" } else { "~" };
format!("20.12: {approximate_symbol}{fixedpoint2012:.2}").into()
});
let fixedpoint2012_signed = int
.filter(|_| selection.len() == 4)
.map(|int| f64::from(int as i32) / f64::from(1 << 12))
.map(|fixedpoint2012_signed| {
let two_decimals_is_enough = (fixedpoint2012_signed * 100.0).fract() == 0.0;
let approximate_symbol = if two_decimals_is_enough { "" } else { "~" };
format!("i20.12: {approximate_symbol}{fixedpoint2012_signed:.2}").into()
});
let fixedpoint1616 = nat
.filter(|_| selection.len() == 4)
.map(|nat| f64::from(nat as u32) / f64::from(1 << 16))
.map(|fixedpoint1616| {
let two_decimals_is_enough = (fixedpoint1616 * 100.0).fract() == 0.0;
let approximate_symbol = if two_decimals_is_enough { "" } else { "~" };
format!("16.16: {approximate_symbol}{fixedpoint1616:.2}").into()
});
let fixedpoint1616_signed = int
.filter(|_| selection.len() == 4)
.map(|int| f64::from(int as i32) / f64::from(1 << 16))
.map(|fixedpoint1616_signed| {
let two_decimals_is_enough = (fixedpoint1616_signed * 100.0).fract() == 0.0;
let approximate_symbol = if two_decimals_is_enough { "" } else { "~" };
format!("i16.16: {approximate_symbol}{fixedpoint1616_signed:.2}").into()
});
let fixedpoint124 = nat
.filter(|_| selection.len() == 2)
.map(|nat| f64::from(nat as u16) / f64::from(1 << 4))
.map(|fixedpoint124| {
let two_decimals_is_enough = (fixedpoint124 * 100.0).fract() == 0.0;
let approximate_symbol = if two_decimals_is_enough { "" } else { "~" };
format!("12.4: {approximate_symbol}{fixedpoint124:.2}").into()
});
let fixedpoint88 = nat
.filter(|_| selection.len() == 2)
.map(|nat| f64::from(nat as u16) / f64::from(1 << 8))
.map(|fixedpoint88| {
let two_decimals_is_enough = (fixedpoint88 * 100.0).fract() == 0.0;
let approximate_symbol = if two_decimals_is_enough { "" } else { "~" };
format!("8.8: {approximate_symbol}{fixedpoint88:.2}").into()
});
let fixedpoint412 = nat
.filter(|_| selection.len() == 2)
.map(|nat| f64::from(nat as u16) / f64::from(1 << 12))
.map(|fixedpoint412| {
let two_decimals_is_enough = (fixedpoint412 * 100.0).fract() == 0.0;
let approximate_symbol = if two_decimals_is_enough { "" } else { "~" };
format!("4.12: {approximate_symbol}{fixedpoint412:.2}").into()
});
let color888 = (selection.len() == 3)
.then(|| [selection[0], selection[1], selection[2]])
.map(|[red, green, blue]| {
Span::from(format!("#{red:02X}{green:02X}{blue:02X}"))
.fg(Color::Rgb(red, green, blue))
});
let color555 = nat
.filter(|_| selection.len() == 2)
.filter(|&nat| nat >> 15 == 0)
.map(|nat| color555_to_color888(nat as u16))
.map(|[red, green, blue]| {
Span::from(format!("555: #{red:02X}{green:02X}{blue:02X}"))
.fg(Color::Rgb(red, green, blue))
});
int.map(|int| format!("{int}").into())
.into_iter()
.chain(nat.map(|nat| format!("{nat}").into()))
.chain(utf8)
.chain(fixedpoint2012_signed)
.chain(fixedpoint2012)
.chain(fixedpoint1616_signed)
.chain(fixedpoint1616)
.chain(fixedpoint124)
.chain(fixedpoint88)
.chain(fixedpoint412)
.chain(color888)
.chain(color555)
.collect()
}
fn inspect_color(selection: &[u8]) -> Vec<Span<'static>> {
let nat = bytes_to_nat(selection);
let color888 = (selection.len() == 3)
.then(|| [selection[0], selection[1], selection[2]])
.map(|[red, green, blue]| {
Span::from(format!("#{red:02X}{green:02X}{blue:02X}"))
.fg(Color::Rgb(red, green, blue))
});
let color555 = nat
.filter(|_| selection.len() == 2)
.filter(|&nat| nat >> 15 == 0)
.map(|nat| color555_to_color888(nat as u16))
.map(|[red, green, blue]| {
Span::from(format!("#{red:02X}{green:02X}{blue:02X}"))
.fg(Color::Rgb(red, green, blue))
});
color888
.into_iter()
.chain(color555)
.collect()
}
// MARK: helpers
impl Buffer {
pub fn clamp_screen_to_primary_cursor(&mut self, window_size: WindowSize) {
if self.primary_cursor.head < self.scroll_position + BYTES_OF_PADDING {
self.align_view_top();
} else if self.primary_cursor.head > self.scroll_position + (window_size.visible_byte_count() - 1).saturating_sub(BYTES_OF_PADDING) {
self.align_view_bottom(window_size);
}
}
}
pub fn bytes_to_nat(bytes: &[u8]) -> Option<u64> {
bytes
.iter()
.rev() // little-endian
.skip_while(|&&byte| byte == 0)
.try_fold(u64::default(), |result, &byte| {
Some(result.shl_exact(8)? | u64::from(byte))
})
}
const fn nat_to_int_if_different(nat: u64, bytes: usize) -> Option<i64> {
match bytes {
1 if nat > i8::MAX as u64 => Some((nat as u8).cast_signed() as i64),
2 if nat > i16::MAX as u64 => Some((nat as u16).cast_signed() as i64),
4 if nat > i32::MAX as u64 => Some((nat as u32).cast_signed() as i64),
8 if nat > i64::MAX as u64 => Some(nat.cast_signed()),
_ => None,
}
}
#[test]
fn nat_to_int_tests() {
assert_eq!(nat_to_int_if_different(0, 1), None);
assert_eq!(nat_to_int_if_different(i8::MAX as u64, 1), None);
assert_eq!(nat_to_int_if_different(i8::MAX as u64 + 1, 1), Some(i8::MIN.into()));
assert_eq!(nat_to_int_if_different(u8::MAX.into(), 1), Some(-1));
assert_eq!(nat_to_int_if_different(0, 2), None);
assert_eq!(nat_to_int_if_different(i16::MAX as u64, 2), None);
assert_eq!(nat_to_int_if_different(i16::MAX as u64 + 1, 2), Some(i16::MIN.into()));
assert_eq!(nat_to_int_if_different(u16::MAX.into(), 2), Some(-1));
}
// or 0 if no mark is before
fn mark_before(offset: usize, sorted_marks: &[usize]) -> usize {
match sorted_marks.binary_search(&offset) {
Ok(_) => offset,
Err(0) => 0,
Err(mark_after_index) => sorted_marks[mark_after_index - 1],
}
}
// or end index if no mark is after
fn mark_after(offset: usize, sorted_marks: &[usize], max: usize) -> usize {
if sorted_marks.is_empty() { return max + 1; }
match sorted_marks.binary_search(&offset) {
Ok(mark_before_index) => if mark_before_index == sorted_marks.len() - 1 {
max + 1
} else {
sorted_marks[mark_before_index + 1]
},
Err(mark_after_index) => {
if mark_after_index == sorted_marks.len() {
max + 1
} else {
sorted_marks[mark_after_index]
}
},
}
}
const fn is_illegal_control_character(character: char) -> bool {
match character {
'\t' | '\n' | '\r' => false,
_ if character.is_ascii_control() => true,
_ => false,
}
}
const fn color555_to_color888(color555: u16) -> [u8; 3] {
[
// 8 is the ratio between the number of colors in 555 vs 888 (32:256)
(color555 & 0b11111) as u8 * 8,
(color555 >> 5 & 0b11111) as u8 * 8,
(color555 >> 10 & 0b11111) as u8 * 8
]
}
-457
View File
@@ -1,457 +0,0 @@
use core::slice::GetDisjointMutIndex;
use std::{collections::HashSet, fs::File, io::{self, Read}, path::PathBuf};
use crossterm::event::KeyEvent;
use ratatui::{layout::{Constraint, Rect}, style::{Color, Style, Stylize}, text::Span, widgets::{Block, Borders, Clear, Widget}};
use serde::{Deserialize, Serialize};
use crate::{BYTES_PER_LINE, action::{Action, AppAction, bytes_to_nat}, app::WindowSize, config::Config, cursor::Cursor, edit_action::EditAction};
mod widget;
pub struct Buffer {
pub file_name: String,
pub file_path: PathBuf,
pub contents: Vec<u8>,
pub scroll_position: usize,
pub primary_cursor: Cursor,
pub cursors: Vec<Cursor>,
pub marks: HashSet<usize>,
pub mode: Mode,
pub partial_action: Option<PartialAction>,
pub partial_replace: Option<u8>,
pub alert_message: Span<'static>,
pub popups: Vec<Popup>,
pub inspection_status: Option<InspectionStatus>,
pub edit_history: Vec<EditAction>,
// the index *after* the latest edit action
pub time_traveling: Option<usize>,
// the index *after* the last saved edit action
pub last_saved_at: Option<usize>,
pub logs: Vec<String>,
}
#[derive(Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
Normal, Select, Insert
}
#[derive(Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug)]
#[serde(rename_all = "snake_case")]
pub enum PartialAction {
Goto, View, Replace, Space, Repeat, To
}
#[derive(Clone)]
pub struct Popup {
pub at: usize,
width: u16,
primary: bool,
lines: Vec<Span<'static>>
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum InspectionStatus {
Normal, ColorsOnly
}
impl Mode {
pub const fn label(self) -> &'static str {
match self {
Self::Normal => " NORMAL ",
Self::Select => " SELECT ",
Self::Insert => " INSERT ",
}
}
pub const fn color(self) -> Color {
match self {
Self::Normal => Color::Blue,
Self::Select => Color::Yellow,
Self::Insert => Color::Green,
}
}
}
impl PartialAction {
pub const fn label(self) -> &'static str {
use PartialAction::*;
match self {
Goto => "g",
View => "z",
Replace => "r",
Space => "",
Repeat => "×",
To => "t",
}
}
}
impl TryFrom<&str> for PartialAction {
type Error = ();
fn try_from(value: &str) -> Result<Self, Self::Error> {
use PartialAction::*;
match value {
"goto" => Ok(Goto),
"view" => Ok(View),
"replace" => Ok(Replace),
"space" => Ok(Space),
"repeat" => Ok(Repeat),
"to" => Ok(To),
_ => Err(()),
}
}
}
impl Popup {
pub fn new(at: usize, lines: Vec<Span<'static>>) -> Self {
Self {
at,
width: lines
.iter()
.map(|line| line.width() as u16)
.max()
.unwrap_or(0),
primary: false,
lines
}
}
const fn area_at(&self, x: u16, y: u16) -> Rect {
Rect {
x,
y,
width: self.width + 2,
height: self.lines.len() as u16
}
}
#[allow(clippy::wrong_self_convention)]
const fn as_primary(mut self) -> Self {
self.primary = true;
self
}
}
impl Widget for Popup {
fn render(self, area: Rect, buf: &mut ratatui::prelude::Buffer) {
Clear.render(area, buf);
let border_color = if self.primary {
Style::new().white()
} else {
Style::new().gray()
};
Block::new()
.on_dark_gray()
.borders(Borders::LEFT | Borders::RIGHT)
.border_style(border_color)
.render(area, buf);
for (line, area) in self.lines.iter().zip(area.rows()) {
line.render(
area.centered_horizontally(Constraint::Length(line.width() as u16)),
buf
);
}
}
}
impl Buffer {
pub fn from_file_at(file_path: PathBuf) -> io::Result<Self> {
let mut file = File::open(&file_path)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
Ok(Self::new(file_path, contents))
}
pub fn new(file_path: PathBuf, contents: Vec<u8>) -> Self {
Self {
file_name: file_path.file_name().unwrap().to_str().unwrap().to_owned(),
file_path,
contents,
scroll_position: 0,
primary_cursor: Cursor::default(),
cursors: Vec::new(),
marks: HashSet::new(),
mode: Mode::Normal,
partial_action: None,
partial_replace: None,
alert_message: "".into(),
popups: Vec::new(),
inspection_status: None,
edit_history: Vec::new(),
time_traveling: None,
last_saved_at: Some(0),
logs: Vec::new(),
}
}
pub fn handle_key(
&mut self,
event: KeyEvent,
config: &Config,
primary_cursor_register: &[u8],
other_cursor_registers: &[Vec<u8>],
window_size: WindowSize
) -> Option<AppAction> {
self.alert_message = "".into();
// self.logs.push(format!("{event:?}"));
let app_action = match self.partial_action {
Some(PartialAction::Replace) => {
self.handle_replace(event, window_size);
None
},
Some(PartialAction::Repeat) => {
self.handle_repeat(
event,
config,
primary_cursor_register,
other_cursor_registers,
window_size
);
None
},
_ => self.handle_other_modes(event, config, window_size),
};
assert!(self.scroll_position.is_multiple_of(BYTES_PER_LINE));
assert!(self.scroll_position < self.contents.len());
assert!(self.primary_cursor.head < self.contents.len());
assert!(self.primary_cursor.tail < self.contents.len());
assert!(self.scroll_position <= self.primary_cursor.head);
assert!(self.primary_cursor.head < self.scroll_position + window_size.visible_byte_count());
app_action
}
fn handle_replace(&mut self, event: KeyEvent, window_size: WindowSize) {
if let Some(hex_character) = event.code.as_char() &&
let Some(nybble) = nybble_from_hex(hex_character)
{
if let Some(partial_replace) = self.partial_replace.take() {
self.execute_and_add(
EditAction::Replace {
primary_cursor: self.primary_cursor,
cursors: self.cursors.clone(),
primary_old_data: self.contents[self.primary_cursor.range()].to_vec(),
old_data: self.cursors
.iter()
.map(|cursor| self.contents[cursor.range()].to_vec())
.collect(),
new_byte: partial_replace << 4 | nybble
},
window_size
);
self.partial_action = None;
} else {
self.partial_replace = Some(nybble);
}
} else {
self.partial_action = None;
self.partial_replace = None;
}
}
fn handle_other_modes(
&mut self,
event: KeyEvent,
config: &Config,
window_size: WindowSize
) -> Option<AppAction> {
use Action::*;
let mut result = None;
let should_reset_partial = self.partial_action.is_some();
if let Some(mode_config) = config.0.get(&self.mode) &&
let Some(keybinds) = mode_config.0.get(&self.partial_action) &&
let Some(action) = keybinds.0.get(&event.into())
{
if action.clears_popups() {
self.popups.clear();
}
match action {
App(app_action) => result = Some(*app_action),
Buffer(buffer_action) => self.execute(*buffer_action, window_size),
Cursor(cursor_action) => {
let max_contents_index = self.max_contents_index();
self.primary_cursor.execute(*cursor_action, max_contents_index);
for cursor in &mut self.cursors {
cursor.execute(*cursor_action, max_contents_index);
}
self.cursors.sort_by_key(|cursor| cursor.head);
self.combine_cursors_if_overlapping();
self.clamp_screen_to_primary_cursor(window_size);
},
}
if action.clears_popups() && !action.is_inspection() {
self.inspection_status = None;
}
}
if should_reset_partial {
self.partial_action = None;
}
result
}
fn handle_repeat(
&mut self,
event: KeyEvent,
config: &Config,
primary_cursor_register: &[u8],
other_cursor_registers: &[Vec<u8>],
window_size: WindowSize
) {
self.partial_action = None;
if let Some(mode_config) = config.0.get(&self.mode) &&
let Some(keybinds) = mode_config.0.get(&Some(PartialAction::Repeat)) &&
let Some(action) = keybinds.0.get(&event.into())
{
match action {
Action::Cursor(cursor_action) => {
let Some(primary_repeat_count) = bytes_to_nat(primary_cursor_register) else {
self.alert_message = Span::from(
"repeat count is too large"
).red();
return;
};
let other_repeat_counts = other_cursor_registers
.iter()
.map(|register| bytes_to_nat(register));
if other_repeat_counts.clone().any(|count| count.is_none()) {
self.alert_message = Span::from(
"repeat count is too large"
).red();
return;
}
let max_contents_index = self.max_contents_index();
for _ in 0..primary_repeat_count {
self.primary_cursor.execute(*cursor_action, max_contents_index);
}
for (cursor, repeat_count) in self.cursors.iter_mut().zip(other_repeat_counts) {
for _ in 0..repeat_count.unwrap() {
cursor.execute(*cursor_action, max_contents_index);
}
}
self.cursors.sort_by_key(|cursor| cursor.head);
self.combine_cursors_if_overlapping();
self.clamp_screen_to_primary_cursor(window_size);
},
_ => panic!("repeated actions may only be cursor actions"),
}
}
}
pub const fn has_unsaved_changes(&self) -> bool {
!self.all_changes_saved()
}
pub const fn all_changes_saved(&self) -> bool {
if let Some(last_saved_at) = self.last_saved_at {
if let Some(time_traveling) = self.time_traveling {
last_saved_at == time_traveling
} else {
last_saved_at == self.edit_history.len()
}
} else {
false
}
}
// returns 0 if empty
pub const fn max_contents_index(&self) -> usize {
self.contents.len().saturating_sub(1)
}
pub fn combine_cursors_if_overlapping(&mut self) {
let mut index = 0;
while !self.cursors.is_empty() && index < self.cursors.len() {
while index < self.cursors.len() - 1 &&
self.cursors[index].range().is_overlapping(
&self.cursors[index + 1].range())
{
let next_cursor = self.cursors[index + 1];
self.cursors[index].combine_with(next_cursor);
self.cursors.remove(index + 1);
}
if self.primary_cursor.range()
.is_overlapping(&self.cursors[index].range())
{
self.primary_cursor.combine_with(self.cursors[index]);
self.cursors.remove(index);
}
index += 1;
}
}
}
fn nybble_from_hex(hex: char) -> Option<u8> {
if !hex.is_ascii() { return None; }
match hex {
'0'..='9' => Some(u8::try_from(hex).unwrap() - u8::try_from('0').unwrap()),
'a'..='f' => Some(u8::try_from(hex).unwrap() - u8::try_from('a').unwrap() + 10),
'A'..='F' => Some(u8::try_from(hex).unwrap() - u8::try_from('A').unwrap() + 10),
_ => None
}
}
mod tests {
#[allow(unused_imports)]
use crate::buffer::nybble_from_hex;
#[test]
fn nybble_from_hex_case_doesnt_matter() {
for character in 'a'..='f' {
assert_eq!(nybble_from_hex(character), nybble_from_hex(character.to_ascii_uppercase()));
}
}
#[test]
fn nybble_from_hex_digits_are_correct() {
for (index, character) in ('0'..='9').enumerate() {
assert_eq!(nybble_from_hex(character), Some(index as u8));
}
}
}
+6 -399
View File
@@ -2,6 +2,12 @@ use std::{cmp::min, iter};
use ratatui::{layout::Rect, text::{Line, Text}, widgets::Widget};
use crate::{BYTES_PER_LINE, buffer::Buffer};
mod address;
mod hex;
mod character_panel;
mod status_line;
mod extra_statuses;
impl Widget for &Buffer {
fn render(self, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let screen_end = self.scroll_position + BYTES_PER_LINE * (area.height as usize - 1);
@@ -102,405 +108,6 @@ impl Buffer {
}
}
mod address {
use ratatui::{style::{Color, Style}, text::Span};
pub fn render_address(address: usize) -> Span<'static> {
Span {
style: style_for_address(address),
content: format!("{address:08x}").into()
}
}
pub const fn style_for_address(address: usize) -> Style {
if address.is_multiple_of(0x100) {
Style::new().fg(Color::Rgb(0x68, 0x99, 0xA0))
} else {
Style::new().fg(Color::Rgb(0x8A, 0xBB, 0xC3))
}
}
}
mod hex {
use std::{borrow::Cow, iter::{self, repeat_n}, mem};
use itertools::Itertools;
use ratatui::{style::{Color, Style, Stylize}, text::Span};
use crate::{BYTES_PER_CHUNK, BYTES_PER_LINE, CHUNKS_PER_LINE, buffer::{Buffer, Mode, PartialAction}, cardinality::HasCardinality, cursor::InCursor, custom_greys::CustomGreys, empty_span::empty_span};
impl Buffer {
pub fn render_chunks(
&self,
address: usize,
bytes: &[u8; BYTES_PER_LINE]
) -> impl Iterator<Item=Span<'static>> {
let (chunks, remainder) = bytes.as_chunks::<BYTES_PER_CHUNK>();
assert!(remainder.is_empty(), "BYTES_PER_LINE should be a multiple of BYTES_PER_CHUNK");
#[allow(unstable_name_collisions)]
chunks
.iter()
.copied()
.zip((address..).step_by(BYTES_PER_CHUNK))
.flat_map(|(chunk, address)| {
self.render_chunk(address, &chunk).collect::<Vec<_>>()
})
}
pub fn render_partial_chunks(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
let (chunks, remainder) = bytes.as_chunks::<BYTES_PER_CHUNK>();
let remainder_address = address + chunks.len() * BYTES_PER_CHUNK;
#[allow(clippy::if_not_else)]
let remainder_chunks: Option<Vec<_>> = if !remainder.is_empty() {
Some(self.render_partial_chunk(remainder_address, remainder).collect())
} else {
None
};
let chunks_rendered = chunks.len() + remainder_chunks.iter().len();
let chunks_not_rendered = CHUNKS_PER_LINE - chunks_rendered;
let spaces_per_chunk = BYTES_PER_CHUNK - 1 + 2;
let bytes_not_rendered = BYTES_PER_LINE - bytes.len();
let padding_width = 2 * bytes_not_rendered +
spaces_per_chunk * chunks_not_rendered;
#[allow(unstable_name_collisions)]
chunks
.iter()
.copied()
.zip((address..).step_by(BYTES_PER_CHUNK))
.map(|(chunk, address)| self.render_chunk(address, &chunk).collect())
.chain(remainder_chunks)
.flatten()
.chain(repeat_n(" ".into(), padding_width))
}
fn render_chunk(
&self,
address: usize,
bytes: &[u8; BYTES_PER_CHUNK]
) -> impl Iterator<Item=Span<'static>> {
iter::once(self.render_large_space_before(address))
.chain(
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_byte_at(address, byte))
.interleave(
(address..)
.take(BYTES_PER_CHUNK)
.skip(1)
.map(|address| self.render_space_before(address))
)
)
}
fn render_partial_chunk(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
iter::once(self.render_large_space_before(address))
.chain(
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_byte_at(address, byte))
.interleave(
(address..)
.take(BYTES_PER_CHUNK)
.skip(1)
.map(|address| self.render_space_before(address))
)
)
}
fn render_byte_at(
&self,
address: usize,
byte: u8
) -> Span<'static> {
if self.partial_action == Some(PartialAction::Replace) &&
iter::once(&self.primary_cursor)
.chain(&self.cursors)
.any(|cursor| cursor.contains(address).is_some())
{
let replaced_byte = self.partial_replace.unwrap_or(0) << 4;
self.render_byte_without_replace_preview(address, replaced_byte)
.black()
} else {
self.render_byte_without_replace_preview(address, byte)
}
}
fn render_byte_without_replace_preview(
&self,
address: usize,
byte: u8
) -> Span<'static> {
const SPAN_FOR_BYTE: [Span; u8::CARDINALITY] = create_byte_lookup_table();
let span = SPAN_FOR_BYTE[byte as usize].clone();
if let Some(place_in_cursor) = self.primary_cursor.contains(address) {
let head_color = match self.mode {
Mode::Select => Color::Yellow,
_ => Color::Gray
};
match place_in_cursor {
InCursor::Head => span.bg(head_color),
InCursor::Rest => span.bg(Color::selection_tail_grey()),
}
} else {
match self.cursors
.iter()
.find_map(|cursor| cursor.contains(address))
{
Some(InCursor::Head) => span.bg(Color::secondary_selection_head_grey()),
Some(InCursor::Rest) => span.bg(Color::selection_tail_grey()),
None => span,
}
}
}
fn render_large_space_before(&self, address: usize) -> Span<'static> {
let span: Span = if self.marks.contains(&address) {
"".into()
} else {
" ".into()
};
if !address.is_multiple_of(BYTES_PER_LINE) &&
iter::once(&self.primary_cursor)
.chain(&self.cursors)
.any(|cursor| cursor.contains_space_before(address))
{
span.bg(Color::selection_tail_grey())
} else {
span
}
}
fn render_space_before(&self, address: usize) -> Span<'static> {
let span: Span = if self.marks.contains(&address) {
"".into()
} else {
" ".into()
};
if iter::once(&self.primary_cursor)
.chain(&self.cursors)
.any(|cursor| cursor.contains_space_before(address))
{
span.bg(Color::selection_tail_grey())
} else {
span
}
}
}
const fn create_byte_lookup_table() -> [Span<'static>; u8::CARDINALITY] {
let mut result = [const { empty_span() }; u8::CARDINALITY];
let mut index = 0;
while index < u8::CARDINALITY {
result[index].style = style_for_byte(index as u8);
mem::forget(mem::replace(&mut result[index].content, content_for_byte(index as u8)));
index += 1;
}
result
}
const fn style_for_byte(byte: u8) -> Style {
Style::new().fg(fg_for_byte(byte))
}
const fn fg_for_byte(byte: u8) -> Color {
match byte {
0x00 => Color::Rgb(0x80, 0x80, 0x80), // grey
0x01..0x10 => Color::Rgb(0xFF, 0x71, 0xA9), // red
0x10..0x20 => Color::Rgb(0xFF, 0x7A, 0x78), // salmon
0x20..0x30 => Color::Rgb(0xFF, 0x81, 0x23), // red-orange
0x30..0x40 => Color::Rgb(0xF7, 0x93, 0x00), // yellow-orange
0x40..0x50 => Color::Rgb(0xE6, 0x9F, 0x00), // yellow
0x50..0x60 => Color::Rgb(0xC1, 0xB2, 0x00), // green-yellow
0x60..0x70 => Color::Rgb(0x82, 0xC6, 0x00), // lime
0x70..0x80 => Color::Rgb(0x00, 0xD5, 0x00), // green
0x80..0x90 => Color::Rgb(0x00, 0xD4, 0x59), // clover
0x90..0xA0 => Color::Rgb(0x00, 0xD0, 0x91), // teal
0xA0..0xB0 => Color::Rgb(0x00, 0xCC, 0xBB), // cyan
0xB0..0xC0 => Color::Rgb(0x00, 0xC7, 0xDE), // light blue
0xC0..0xD0 => Color::Rgb(0x00, 0xBE, 0xFF), // blue
0xD0..0xE0 => Color::Rgb(0x6C, 0xAF, 0xFF), // blurple
0xE0..0xF0 => Color::Rgb(0xB2, 0x98, 0xFF), // purple
0xF0..0xFF => Color::Rgb(0xFF, 0x4D, 0xFF), // pink
0xFF => Color::White
}
}
const fn content_for_byte(byte: u8) -> Cow<'static, str> {
Cow::Borrowed(hex_for_byte(byte))
}
const fn hex_for_byte(byte: u8) -> &'static str {
const LOOK_UP_TABLE: [&str; u8::CARDINALITY] = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"];
LOOK_UP_TABLE[byte as usize]
}
}
mod character_panel {
use std::{borrow::Cow, iter, mem};
use ratatui::{style::{Color, Style, Stylize}, text::Span};
use crate::{buffer::Buffer, cardinality::HasCardinality, cursor::InCursor, custom_greys::CustomGreys, empty_span::empty_span};
impl Buffer {
pub fn render_character_panel(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_character_at(address, byte))
}
fn render_character_at(
&self,
address: usize,
byte: u8
) -> Span<'static> {
const SPAN_FOR_BYTE: [Span; u8::CARDINALITY] = create_character_lookup_table();
let span = SPAN_FOR_BYTE[byte as usize].clone();
match iter::once(&self.primary_cursor)
.chain(&self.cursors)
.find_map(|cursor| cursor.contains(address))
{
Some(InCursor::Head) => span.bg(Color::selection_tail_grey()),
Some(InCursor::Rest) => span.on_dark_gray(),
None => span,
}
}
}
const fn create_character_lookup_table() -> [Span<'static>; u8::CARDINALITY] {
let mut result = [const { empty_span() }; u8::CARDINALITY];
let mut index = 0;
while index < u8::CARDINALITY {
result[index].style = style_for_character(index as u8);
mem::forget(mem::replace(
&mut result[index].content,
content_for_character(index as u8)
));
index += 1;
}
result
}
const fn style_for_character(byte: u8) -> Style {
Style::new().fg(fg_for_character(byte))
}
const fn fg_for_character(byte: u8) -> Color {
match byte {
b'\0' => Color::Rgb(0xA0, 0xA0, 0xA0), // grey
b'\t' | b'\n' | b'\r' | b' ' => Color::Red,
_ if byte.is_ascii_graphic() => Color::Red,
_ if byte.is_ascii() => Color::Green,
0xFF => Color::White,
_ => Color::Yellow,
}
}
const fn content_for_character(byte: u8) -> Cow<'static, str> {
Cow::Borrowed(character_for_byte(byte))
}
const fn character_for_byte(byte: u8) -> &'static str {
const LOOK_UP_TABLE: [&str; u8::CARDINALITY] = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", ""];
LOOK_UP_TABLE[byte as usize]
}
}
mod status_line {
use crate::{buffer::Buffer, custom_greys::CustomGreys};
use ratatui::{style::{Color, Stylize}, text::{Line, Span, Text}};
impl Buffer {
pub fn render_status_line(&self) -> Text<'_> {
Text::from(
Line::from_iter([
self.render_mode(),
" ".into(),
self.render_file_name(),
self.modified_indicator(),
" ".into(),
self.alert_message.clone()
])
)
.bg(Color::ui_grey())
}
fn render_mode(&self) -> Span<'static> {
Span::from(self.mode.label())
.black()
.bg(self.mode.color())
}
fn render_file_name(&self) -> Span<'_> {
Span::from(&self.file_name)
}
fn modified_indicator(&self) -> Span<'static> {
if self.has_unsaved_changes() {
" [+]".into()
} else {
"".into()
}
}
}
}
mod extra_statuses {
use crate::buffer::Buffer;
use ratatui::text::Line;
impl Buffer {
pub fn render_extra_statuses(&self) -> Line<'_> {
let partial_action = self.partial_action
.as_ref()
.map_or("", |partial_action| partial_action.label());
if self.contents.is_empty() {
format!("{partial_action} ").into()
} else {
#[allow(clippy::cast_precision_loss)]
let percentage = self.primary_cursor.head as f64 / self.max_contents_index() as f64 * 100.0;
format!("{partial_action} {percentage:.0}% ").into()
}
}
}
}
fn byte_column_to_screen_column(byte_column: usize) -> usize {
match byte_column {
0 => 10,
+16
View File
@@ -0,0 +1,16 @@
use ratatui::{style::{Color, Style}, text::Span};
pub fn render_address(address: usize) -> Span<'static> {
Span {
style: style_for_address(address),
content: format!("{address:08x}").into()
}
}
pub const fn style_for_address(address: usize) -> Style {
if address.is_multiple_of(0x100) {
Style::new().fg(Color::Rgb(0x68, 0x99, 0xA0))
} else {
Style::new().fg(Color::Rgb(0x8A, 0xBB, 0xC3))
}
}
+76
View File
@@ -0,0 +1,76 @@
use std::{borrow::Cow, iter, mem};
use ratatui::{style::{Color, Style, Stylize}, text::Span};
use crate::{buffer::Buffer, cardinality::HasCardinality, cursor::InCursor, custom_greys::CustomGreys, empty_span::empty_span};
impl Buffer {
pub fn render_character_panel(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_character_at(address, byte))
}
fn render_character_at(
&self,
address: usize,
byte: u8
) -> Span<'static> {
const SPAN_FOR_BYTE: [Span; u8::CARDINALITY] = create_character_lookup_table();
let span = SPAN_FOR_BYTE[byte as usize].clone();
match iter::once(&self.primary_cursor)
.chain(&self.cursors)
.find_map(|cursor| cursor.contains(address))
{
Some(InCursor::Head) => span.bg(Color::selection_tail_grey()),
Some(InCursor::Rest) => span.on_dark_gray(),
None => span,
}
}
}
const fn create_character_lookup_table() -> [Span<'static>; u8::CARDINALITY] {
let mut result = [const { empty_span() }; u8::CARDINALITY];
let mut index = 0;
while index < u8::CARDINALITY {
result[index].style = style_for_character(index as u8);
mem::forget(mem::replace(
&mut result[index].content,
content_for_character(index as u8)
));
index += 1;
}
result
}
const fn style_for_character(byte: u8) -> Style {
Style::new().fg(fg_for_character(byte))
}
const fn fg_for_character(byte: u8) -> Color {
match byte {
b'\0' => Color::Rgb(0xA0, 0xA0, 0xA0), // grey
b'\t' | b'\n' | b'\r' | b' ' => Color::Red,
_ if byte.is_ascii_graphic() => Color::Red,
_ if byte.is_ascii() => Color::Green,
0xFF => Color::White,
_ => Color::Yellow,
}
}
const fn content_for_character(byte: u8) -> Cow<'static, str> {
Cow::Borrowed(character_for_byte(byte))
}
const fn character_for_byte(byte: u8) -> &'static str {
const LOOK_UP_TABLE: [&str; u8::CARDINALITY] = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", ""];
LOOK_UP_TABLE[byte as usize]
}
+34
View File
@@ -0,0 +1,34 @@
use crate::buffer::{Buffer, PartialAction};
use ratatui::text::Line;
impl Buffer {
pub fn render_extra_statuses(&self) -> Line<'_> {
let partial_action = self.partial_action
.as_ref()
.map_or("", |partial_action| partial_action.label());
if self.contents.is_empty() {
format!("{partial_action} ").into()
} else {
#[allow(clippy::cast_precision_loss)]
let percentage = self.primary_cursor.head as f64 / self.max_contents_index() as f64 * 100.0;
format!("{partial_action} {percentage:.0}% ").into()
}
}
}
impl PartialAction {
pub const fn label(self) -> &'static str {
use PartialAction::*;
match self {
Goto => "g",
View => "z",
Replace => "r",
Space => "",
Repeat => "×",
To => "t",
}
}
}
+237
View File
@@ -0,0 +1,237 @@
use std::{borrow::Cow, iter::{self, repeat_n}, mem};
use itertools::Itertools;
use ratatui::{style::{Color, Style, Stylize}, text::Span};
use crate::{BYTES_PER_CHUNK, BYTES_PER_LINE, CHUNKS_PER_LINE, buffer::{Buffer, Mode, PartialAction}, cardinality::HasCardinality, cursor::InCursor, custom_greys::CustomGreys, empty_span::empty_span};
impl Buffer {
pub fn render_chunks(
&self,
address: usize,
bytes: &[u8; BYTES_PER_LINE]
) -> impl Iterator<Item=Span<'static>> {
let (chunks, remainder) = bytes.as_chunks::<BYTES_PER_CHUNK>();
assert!(remainder.is_empty(), "BYTES_PER_LINE should be a multiple of BYTES_PER_CHUNK");
#[allow(unstable_name_collisions)]
chunks
.iter()
.copied()
.zip((address..).step_by(BYTES_PER_CHUNK))
.flat_map(|(chunk, address)| {
self.render_chunk(address, &chunk).collect::<Vec<_>>()
})
}
pub fn render_partial_chunks(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
let (chunks, remainder) = bytes.as_chunks::<BYTES_PER_CHUNK>();
let remainder_address = address + chunks.len() * BYTES_PER_CHUNK;
#[allow(clippy::if_not_else)]
let remainder_chunks: Option<Vec<_>> = if !remainder.is_empty() {
Some(self.render_partial_chunk(remainder_address, remainder).collect())
} else {
None
};
let chunks_rendered = chunks.len() + remainder_chunks.iter().len();
let chunks_not_rendered = CHUNKS_PER_LINE - chunks_rendered;
let spaces_per_chunk = BYTES_PER_CHUNK - 1 + 2;
let bytes_not_rendered = BYTES_PER_LINE - bytes.len();
let padding_width = 2 * bytes_not_rendered +
spaces_per_chunk * chunks_not_rendered;
#[allow(unstable_name_collisions)]
chunks
.iter()
.copied()
.zip((address..).step_by(BYTES_PER_CHUNK))
.map(|(chunk, address)| self.render_chunk(address, &chunk).collect())
.chain(remainder_chunks)
.flatten()
.chain(repeat_n(" ".into(), padding_width))
}
fn render_chunk(
&self,
address: usize,
bytes: &[u8; BYTES_PER_CHUNK]
) -> impl Iterator<Item=Span<'static>> {
iter::once(self.render_large_space_before(address))
.chain(
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_byte_at(address, byte))
.interleave(
(address..)
.take(BYTES_PER_CHUNK)
.skip(1)
.map(|address| self.render_space_before(address))
)
)
}
fn render_partial_chunk(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
iter::once(self.render_large_space_before(address))
.chain(
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_byte_at(address, byte))
.interleave(
(address..)
.take(BYTES_PER_CHUNK)
.skip(1)
.map(|address| self.render_space_before(address))
)
)
}
fn render_byte_at(
&self,
address: usize,
byte: u8
) -> Span<'static> {
if self.partial_action == Some(PartialAction::Replace) &&
iter::once(&self.primary_cursor)
.chain(&self.cursors)
.any(|cursor| cursor.contains(address).is_some())
{
let replaced_byte = self.partial_replace.unwrap_or(0) << 4;
self.render_byte_without_replace_preview(address, replaced_byte)
.black()
} else {
self.render_byte_without_replace_preview(address, byte)
}
}
fn render_byte_without_replace_preview(
&self,
address: usize,
byte: u8
) -> Span<'static> {
const SPAN_FOR_BYTE: [Span; u8::CARDINALITY] = create_byte_lookup_table();
let span = SPAN_FOR_BYTE[byte as usize].clone();
if let Some(place_in_cursor) = self.primary_cursor.contains(address) {
let head_color = match self.mode {
Mode::Select => Color::Yellow,
_ => Color::Gray
};
match place_in_cursor {
InCursor::Head => span.bg(head_color),
InCursor::Rest => span.bg(Color::selection_tail_grey()),
}
} else {
match self.cursors
.iter()
.find_map(|cursor| cursor.contains(address))
{
Some(InCursor::Head) => span.bg(Color::secondary_selection_head_grey()),
Some(InCursor::Rest) => span.bg(Color::selection_tail_grey()),
None => span,
}
}
}
fn render_large_space_before(&self, address: usize) -> Span<'static> {
let span: Span = if self.marks.contains(&address) {
"".into()
} else {
" ".into()
};
if !address.is_multiple_of(BYTES_PER_LINE) &&
iter::once(&self.primary_cursor)
.chain(&self.cursors)
.any(|cursor| cursor.contains_space_before(address))
{
span.bg(Color::selection_tail_grey())
} else {
span
}
}
fn render_space_before(&self, address: usize) -> Span<'static> {
let span: Span = if self.marks.contains(&address) {
"".into()
} else {
" ".into()
};
if iter::once(&self.primary_cursor)
.chain(&self.cursors)
.any(|cursor| cursor.contains_space_before(address))
{
span.bg(Color::selection_tail_grey())
} else {
span
}
}
}
const fn create_byte_lookup_table() -> [Span<'static>; u8::CARDINALITY] {
let mut result = [const { empty_span() }; u8::CARDINALITY];
let mut index = 0;
while index < u8::CARDINALITY {
result[index].style = style_for_byte(index as u8);
mem::forget(mem::replace(&mut result[index].content, content_for_byte(index as u8)));
index += 1;
}
result
}
const fn style_for_byte(byte: u8) -> Style {
Style::new().fg(fg_for_byte(byte))
}
const fn fg_for_byte(byte: u8) -> Color {
match byte {
0x00 => Color::Rgb(0x80, 0x80, 0x80), // grey
0x01..0x10 => Color::Rgb(0xFF, 0x71, 0xA9), // red
0x10..0x20 => Color::Rgb(0xFF, 0x7A, 0x78), // salmon
0x20..0x30 => Color::Rgb(0xFF, 0x81, 0x23), // red-orange
0x30..0x40 => Color::Rgb(0xF7, 0x93, 0x00), // yellow-orange
0x40..0x50 => Color::Rgb(0xE6, 0x9F, 0x00), // yellow
0x50..0x60 => Color::Rgb(0xC1, 0xB2, 0x00), // green-yellow
0x60..0x70 => Color::Rgb(0x82, 0xC6, 0x00), // lime
0x70..0x80 => Color::Rgb(0x00, 0xD5, 0x00), // green
0x80..0x90 => Color::Rgb(0x00, 0xD4, 0x59), // clover
0x90..0xA0 => Color::Rgb(0x00, 0xD0, 0x91), // teal
0xA0..0xB0 => Color::Rgb(0x00, 0xCC, 0xBB), // cyan
0xB0..0xC0 => Color::Rgb(0x00, 0xC7, 0xDE), // light blue
0xC0..0xD0 => Color::Rgb(0x00, 0xBE, 0xFF), // blue
0xD0..0xE0 => Color::Rgb(0x6C, 0xAF, 0xFF), // blurple
0xE0..0xF0 => Color::Rgb(0xB2, 0x98, 0xFF), // purple
0xF0..0xFF => Color::Rgb(0xFF, 0x4D, 0xFF), // pink
0xFF => Color::White
}
}
const fn content_for_byte(byte: u8) -> Cow<'static, str> {
Cow::Borrowed(hex_for_byte(byte))
}
const fn hex_for_byte(byte: u8) -> &'static str {
const LOOK_UP_TABLE: [&str; u8::CARDINALITY] = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"];
LOOK_UP_TABLE[byte as usize]
}
+54
View File
@@ -0,0 +1,54 @@
use crate::{buffer::{Buffer, Mode}, custom_greys::CustomGreys};
use ratatui::{style::{Color, Stylize}, text::{Line, Span, Text}};
impl Buffer {
pub fn render_status_line(&self) -> Text<'_> {
Text::from(
Line::from_iter([
self.render_mode(),
" ".into(),
self.render_file_name(),
self.modified_indicator(),
" ".into(),
self.alert_message.clone()
])
)
.bg(Color::ui_grey())
}
fn render_mode(&self) -> Span<'static> {
Span::from(self.mode.label())
.black()
.bg(self.mode.color())
}
fn render_file_name(&self) -> Span<'_> {
Span::from(&self.file_name)
}
fn modified_indicator(&self) -> Span<'static> {
if self.has_unsaved_changes() {
" [+]".into()
} else {
"".into()
}
}
}
impl Mode {
pub const fn label(self) -> &'static str {
match self {
Self::Normal => " NORMAL ",
Self::Select => " SELECT ",
Self::Insert => " INSERT ",
}
}
pub const fn color(self) -> Color {
match self {
Self::Normal => Color::Blue,
Self::Select => Color::Yellow,
Self::Insert => Color::Green,
}
}
}