forked from mars/breed
1
0
Fork 0

Compare commits

...

40 Commits
main ... main

Author SHA1 Message Date
mars 4dd6307c12 Window drawing 2023-09-14 17:41:42 -06:00
mars cce42ef240 Refactor text rendering 2023-09-14 17:19:51 -06:00
mars 15b6739586 Add README 2023-04-29 19:34:32 -04:00
mars ca2d97adb7 Add backspace_start_of_buffer unit test 2023-04-19 23:51:30 -04:00
mars 6f643b1750 Merge pull request 'New keybinds `$`, `0`, and `^`' (#15) from emma/breed:keybinds into main
Reviewed-on: mars/breed#15
2023-04-20 03:47:26 +00:00
mars adb5e444b6 Merge branch 'main' into keybinds 2023-04-20 03:47:02 +00:00
mars 8b90eb647a Merge pull request 'Better way to attain config & theme directories' (#14) from emma/breed:main into main
Reviewed-on: mars/breed#14
2023-04-20 03:46:49 +00:00
mars 6049ee6136 Merge branch 'main' into main 2023-04-20 03:46:34 +00:00
mars d6138d5986 Fixed get_*_dir() result handling 2023-04-19 23:46:08 -04:00
mars 344b3b5145 Add placeholder word movement actions 2023-04-18 20:19:32 -04:00
mars 9ab272823d Implement rudimentary undo/redo support 2023-04-18 20:05:28 -04:00
mars ae45c3392f Refactor State into submodule 2023-04-18 19:28:59 -04:00
Emma Tebibyte ece0976813 fixed minor issue 2023-04-15 17:38:12 -04:00
Emma Tebibyte 2766539622 added $, ^, and 0 keybinds 2023-04-15 17:34:53 -04:00
Emma Tebibyte 487b8e4580 removed println macro used for testing 2023-04-15 17:22:32 -04:00
Emma Tebibyte 4b6e5edbd3 Revert "removed println macro used for testing"
This reverts commit ddbdc3f7a7.
2023-04-15 17:21:55 -04:00
Emma Tebibyte ddbdc3f7a7 removed println macro used for testing 2023-04-15 17:21:17 -04:00
Emma Tebibyte 70f242f8f6 fall back to $HOME/.config and $HOME/.local/share 2023-04-15 16:25:20 -04:00
Emma Tebibyte a3ba320016 changed themes directory to $XDG_DATA_HOME and config directory to $XDG_CONFIG_HOME 2023-04-15 16:20:07 -04:00
mars 5aed7766c9 Add open_below_at_eof() test 2023-04-15 11:57:28 -04:00
mars bde9c9987a Add d keybind 2023-04-14 22:19:05 -04:00
mars 042ea6d420 Better handling of EOF 2023-04-14 22:15:48 -04:00
mars e910608805 Add panic handler hook to exit alternative screen and raw mode 2023-04-14 21:25:42 -04:00
mars b2b69bf7b3 Remove NormalState + simplify event-handling 2023-04-14 20:59:59 -04:00
mars e47275cb88 Add goto_file_start and goto_file_end 2023-04-14 17:29:19 -04:00
mars a7e121ba18 Merge pull request 'minor fixes to main()' (#12) from emma/breed:main into main
Reviewed-on: mars/breed#12
2023-04-14 19:47:22 +00:00
mars 65b8986d30 Merge branch 'main' into main 2023-04-14 19:47:17 +00:00
mars 075b74afca Add goto_first_nonwhitespace + impl insert_at_line_start and end 2023-04-14 15:43:22 -04:00
mars 74e1bd88c6 Fix Buffer::goto_first_whitespace 2023-04-14 15:41:19 -04:00
mars 9558cdadb4 Remove unused imports 2023-04-14 15:34:54 -04:00
mars 5fd2620121 Implement goto_line_start and goto_line_end 2023-04-14 15:31:31 -04:00
Emma Tebibyte 64249e0f67 minor fixes to main() 2023-04-14 15:14:21 -04:00
mars d68a719a90 Merge branch 'main' of https://git.tebibyte.media/mars/breed 2023-04-14 15:10:15 -04:00
mars da33dcce1d Handle and render submodes 2023-04-14 15:10:11 -04:00
mars 1496a39a1a Add initial goto keybinds 2023-04-14 15:09:55 -04:00
mars 7f46721caf Better hardcoded keybind semantics 2023-04-14 14:51:46 -04:00
mars c03991f110 Rename minor modes to submodes in keybinds 2023-04-14 14:31:29 -04:00
mars 3020d14081 Migrate keybind handling to State::on_key() 2023-04-14 14:11:36 -04:00
mars 9f6eecfa26 Merge pull request 'fixed writing buffer to file' (#11) from emma/breed:main into main
Reviewed-on: mars/breed#11
2023-04-14 18:09:52 +00:00
Emma Tebibyte 5c3a21e35e fixed writing buffer to file 2023-04-14 14:08:00 -04:00
9 changed files with 895 additions and 478 deletions

31
README.md Normal file
View File

@ -0,0 +1,31 @@
# Breed
Breed is a minimalistic modal editor inspired by Helix, but hopefully without
all of the extra junk I don't care about.
It would be really neat for it to support LSP, Treesitter, and kakoune-like
client-server operation.
# To-Do List
- [ ] detect correct syntax from file info
- [ ] word and WORD navigation
- [ ] config file
- [ ] keybind modifiers
- [ ] better submode key rendering
- [ ] tab insertion
- [ ] treesitter support
- [ ] LSP support
- [ ] keybind configuration
- [ ] page up and page down
- [ ] selection/visual mode
- [ ] multicursor
- [ ] command callbacks
- [ ] configurable autoscroll margins
- [ ] configurable newline hide
- [ ] `:theme`
- [ ] copy/cut/paste
- [ ] mouse input
- [ ] theme style modifiers
- [ ] configurable indents
- [ ] client/server with UDS socket

View File

@ -19,7 +19,10 @@
use std::collections::HashMap;
use crate::{Direction, InsertState, Mode, NormalState, State};
use crate::{
state::{InsertState, Mode, State},
Cursor, Direction,
};
pub type Action = fn(&mut State);
@ -29,10 +32,19 @@ pub fn load_actions() -> HashMap<String, Action> {
("move_line_down", move_line_down),
("move_line_up", move_line_up),
("move_char_right", move_char_right),
("move_next_word_start", move_next_word_start),
("move_prev_word_start", move_prev_word_start),
("move_next_word_end", move_next_word_end),
("move_next_long_word_start", move_next_long_word_start),
("move_prev_long_word_start", move_prev_long_word_start),
("move_next_long_word_end", move_next_long_word_end),
("page_up", page_up),
("page_down", page_down),
("goto_line_start", goto_line_start),
("goto_line_end_newline", goto_line_end_newline),
("goto_line_end", goto_line_end),
("goto_first_nonwhitespace", goto_first_nonwhitespace),
("goto_file_start", goto_file_start),
("goto_file_end", goto_file_end),
("command_mode", command_mode),
("normal_mode", normal_mode),
("visual_mode", visual_mode),
@ -72,6 +84,30 @@ pub fn move_line_up(state: &mut State) {
state.move_cursor(Direction::Up);
}
pub fn move_next_word_start(state: &mut State) {
state.set_error("move_next_word_start is unimplemented");
}
pub fn move_prev_word_start(state: &mut State) {
state.set_error("move_prev_word_start is unimplemented");
}
pub fn move_next_word_end(state: &mut State) {
state.set_error("move_next_word_end is unimplemented");
}
pub fn move_next_long_word_start(state: &mut State) {
state.set_error("move_next_long_word_start is unimplemented");
}
pub fn move_prev_long_word_start(state: &mut State) {
state.set_error("move_prev_long_word_start is unimplemented");
}
pub fn move_next_long_word_end(state: &mut State) {
state.set_error("move_next_long_word_end is unimplemented");
}
pub fn page_up(state: &mut State) {
state.set_error("page_up is unimplemented");
}
@ -81,11 +117,27 @@ pub fn page_down(state: &mut State) {
}
pub fn goto_line_start(state: &mut State) {
state.set_error("goto_line_start is unimplemented");
state.cursor.column = 0;
}
pub fn goto_line_end_newline(state: &mut State) {
state.set_error("goto_line_end_newline is unimplemented");
pub fn goto_line_end(state: &mut State) {
state.cursor = state.buffer.cursor_at_line_end(state.cursor.line);
}
pub fn goto_first_nonwhitespace(state: &mut State) {
state.cursor = state
.buffer
.cursor_at_first_nonwhitespace(state.cursor.line);
}
pub fn goto_file_start(state: &mut State) {
state.cursor = Cursor { line: 0, column: 0 };
state.scroll_to_cursor();
}
pub fn goto_file_end(state: &mut State) {
state.cursor = state.buffer.cursor_at_file_end();
state.scroll_to_cursor();
}
pub fn command_mode(state: &mut State) {
@ -100,7 +152,7 @@ pub fn normal_mode(state: &mut State) {
_ => {}
}
state.mode = Mode::Normal(NormalState::default());
state.mode = Mode::Normal;
}
pub fn visual_mode(state: &mut State) {
@ -108,50 +160,54 @@ pub fn visual_mode(state: &mut State) {
}
pub fn insert_mode(state: &mut State) {
state.save_buffer();
state.mode = Mode::Insert(InsertState { append: false });
}
pub fn append_mode(state: &mut State) {
state.save_buffer();
state.move_cursor(Direction::Right);
state.mode = Mode::Insert(InsertState { append: true });
}
pub fn insert_at_line_start(state: &mut State) {
state.set_error("insert_at_line_start is unimplemented");
goto_first_nonwhitespace(state);
insert_mode(state);
}
pub fn insert_at_line_end(state: &mut State) {
state.set_error("insert_at_line_end is unimplemented");
goto_line_end(state);
insert_mode(state);
}
pub fn open_below(state: &mut State) {
insert_mode(state);
state.cursor.line += 1;
state.cursor.column = 0;
state.buffer.insert_char(state.cursor, '\n');
state.mode = Mode::Insert(InsertState { append: false });
}
pub fn open_above(state: &mut State) {
insert_mode(state);
state.cursor.column = 0;
state.buffer.insert_char(state.cursor, '\n');
state.mode = Mode::Insert(InsertState { append: false });
}
pub fn undo(state: &mut State) {
state.set_error("undo is unimplemented");
state.undo();
}
pub fn redo(state: &mut State) {
state.set_error("redo is unimplemented");
state.redo();
}
pub fn delete_char_backward(state: &mut State) {
state.move_cursor(Direction::Left);
state.buffer.remove(state.cursor);
state.buffer.remove_char(state.cursor);
}
pub fn delete_char_forward(state: &mut State) {
state.buffer.remove(state.cursor);
state.buffer.remove_char(state.cursor);
}
pub fn insert_newline(state: &mut State) {
@ -174,6 +230,14 @@ mod tests {
delete_char_backward(&mut state);
}
#[test]
fn backspace_start_of_buffer() {
let mut state = state("test\n");
let original = state.buffer.as_ref().clone();
delete_char_backward(&mut state);
assert_eq!(original, *state.buffer.as_ref());
}
#[test]
fn append_on_newline() {
let mut state = state("test\ntest\n");
@ -192,6 +256,14 @@ mod tests {
assert_eq!(state.cursor.column, 0);
}
#[test]
fn open_below_at_eof() {
let mut state = state("test\n");
state.cursor.line = 1;
open_below(&mut state);
assert_eq!(state.cursor.line, 1);
}
#[test]
fn move_line_up_preserve_column() {
let mut state = state("test\n\ntest\n");

View File

@ -18,18 +18,71 @@
*/
use std::io::Write;
use std::ops::Range;
use std::sync::Arc;
use crossterm::{cursor, ExecutableCommand, QueueableCommand};
use crossterm::{cursor, QueueableCommand};
use parking_lot::Mutex;
use ropey::Rope;
use ropey::{Rope, RopeSlice};
use syntect::easy::ScopeRangeIterator;
use syntect::parsing::{BasicScopeStackOp, ParseState, Scope, ScopeStack, SyntaxSet};
use syntect::parsing::{BasicScopeStackOp, ParseState, ScopeStack, SyntaxSet};
use crate::theme::{Style, StyleStore};
use crate::theme::{Style, StyleStore, StyledString};
use crate::{Cursor, Direction};
pub struct LineBuf<'a> {
pub buf: Vec<u8>,
pub padding: &'a str,
pub remaining_width: usize,
pub styles: &'a mut StyleStore,
pub is_selected: bool,
pub text: RopeSlice<'a>,
pub styled: &'a StyledString,
}
impl<'a> LineBuf<'a> {
pub fn draw_linenr(&mut self, linenr: usize, width: usize) -> crossterm::Result<()> {
let linenr_style = self.styles.get_scope("ui.linenr").clone();
let linenr_style = if self.is_selected {
self.styles.get_scope("ui.linenr.selected").clone()
} else {
linenr_style
};
let linenr = if self.text.len_chars() > 0 {
format!("{:>width$} ", linenr)
} else {
// only the last line is empty
format!("{:>width$}", "~")
};
linenr_style.print_styled(&mut self.buf, &linenr)?;
self.remaining_width -= width;
Ok(())
}
pub fn draw_text(&mut self, lhs: usize) -> crossterm::Result<()> {
let line_style = if self.is_selected {
self.styles.get_scope("ui.cursorline.primary").clone()
} else {
Default::default()
};
let remaining = if lhs < self.remaining_width {
let sub = lhs..self.remaining_width;
self.styled.print_sub(&mut self.buf, sub, line_style)?
} else {
self.remaining_width
};
let padding = &self.padding[0..remaining];
line_style.print_styled(&mut self.buf, padding)?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct Buffer {
styles: Arc<Mutex<StyleStore>>,
@ -38,7 +91,7 @@ pub struct Buffer {
parser: ParseState,
style_dirty: bool,
style_generation: usize,
styled: Vec<Vec<(Style, Range<usize>)>>,
styled: Vec<StyledString>,
}
impl AsRef<Rope> for Buffer {
@ -80,79 +133,45 @@ impl Buffer {
self.parse();
let mut styles = self.styles.lock();
let linenr_style = styles.get_scope("ui.linenr").clone();
let linenr_width = self.text.len_lines().ilog10() + 1;
let gutter_width = linenr_width + 1;
let text_width = cols as usize - gutter_width as usize;
let linenr_width = (self.text.len_lines().ilog10() + 1) as usize;
let gutter_width = linenr_width as u32 + 1;
let text_width = cols as usize - linenr_width;
let line_padding: String = std::iter::repeat(' ').take(text_width).collect();
out.queue(cursor::MoveTo(0, 0))?;
let mut line_buf = Vec::<u8>::with_capacity(text_width);
for (row, line) in (0..rows).zip(self.text.lines_at(scroll.line)) {
// only the last line is empty and should be skipped
if line.len_chars() == 0 {
for (row, line) in self.text.lines_at(scroll.line).enumerate() {
if row == rows as usize {
break;
}
let row = row as usize + scroll.line;
let is_selected = row == cursor.line;
let linenr = row as usize + scroll.line;
let linenr_style = if is_selected {
styles.get_scope("ui.linenr.selected").clone()
} else {
linenr_style
let mut line = LineBuf {
buf: Vec::with_capacity(text_width * 2),
padding: &line_padding,
remaining_width: cols as usize - 1,
styles: &mut styles,
is_selected: linenr == cursor.line,
text: line,
styled: &self.styled[linenr],
};
let line_style = if is_selected {
styles.get_scope("ui.cursorline.primary").clone()
} else {
Default::default()
};
let linenr = format!("{:width$} ", row, width = linenr_width as usize);
linenr_style.print_styled(out, &linenr)?;
let lhs = scroll.column;
let width = line.len_chars();
let mut remaining = text_width;
line_buf.clear();
if lhs < width {
let window = text_width.min(width - lhs);
let rhs = lhs + window;
let styled = &self.styled[row];
for (chunk_style, range) in styled.iter() {
let range = range.start.max(lhs)..range.end.min(rhs);
if range.start < range.end {
// this range is in view so display
let content = line.slice(range.clone());
let mut style = line_style.clone();
style.apply(chunk_style);
style.print_styled(&mut line_buf, content)?;
remaining = text_width.saturating_sub(range.end);
}
if range.end >= rhs {
// past the end of the window so we're done
break;
}
}
}
let padding = &line_padding[0..remaining];
line_style.print_styled(&mut line_buf, padding)?;
out.write_all(&line_buf)?;
line.draw_linenr(linenr, linenr_width)?;
line.draw_text(scroll.column)?;
out.write_all(&line.buf)?;
out.queue(cursor::MoveToNextLine(1))?;
}
Ok(gutter_width)
}
pub fn remove(&mut self, cursor: Cursor) {
pub fn remove_char(&mut self, cursor: Cursor) {
let index = self.cursor_to_char(cursor);
self.text.remove(index..=index);
self.style_dirty = true;
if index < self.text.len_chars() {
self.text.remove(index..=index);
self.style_dirty = true;
}
}
pub fn insert_char(&mut self, cursor: Cursor, c: char) {
@ -210,11 +229,17 @@ impl Buffer {
continue;
}
let len = range.end - range.start;
let style = style_stack.last().cloned().unwrap_or_default();
styled_buf.push((style, range));
styled_buf.push((len, style));
}
self.styled.push(styled_buf.clone());
let line = StyledString {
content: line.to_string(),
styles: styled_buf.clone(),
};
self.styled.push(line);
}
self.style_dirty = false;
@ -222,7 +247,13 @@ impl Buffer {
}
pub fn clamped_cursor(&self, cursor: Cursor) -> Cursor {
let line_end = self.text.line(cursor.line).len_chars().saturating_sub(1);
let line_len = self.text.line(cursor.line).len_chars();
let line_end = if cursor.line + 1 == self.text.len_lines() {
line_len
} else {
line_len.saturating_sub(1)
};
Cursor {
line: cursor.line,
@ -248,7 +279,7 @@ impl Buffer {
}
}
Direction::Down => {
if cursor.line + 2 < self.text.len_lines() {
if cursor.line + 1 < self.text.len_lines() {
cursor.line += 1;
}
}
@ -259,17 +290,57 @@ impl Buffer {
}
Direction::Right => {
let line = self.text.line(cursor.line);
if cursor.column + 2 > line.len_chars() {
if enable_linewrap && cursor.line + 2 < self.text.len_lines() {
cursor.line += 1;
cursor.column = 0;
}
} else {
if cursor.line + 1 == self.text.len_lines() && cursor.column < line.len_chars() {
cursor.column += 1;
} else if cursor.column + 1 < line.len_chars() {
cursor.column += 1
} else if enable_linewrap && cursor.line + 1 < self.text.len_lines() {
cursor.line += 1;
cursor.column = 0;
}
}
}
}
pub fn cursor_at_first_nonwhitespace(&self, line: usize) -> Cursor {
if let Some(line_slice) = self.text.get_line(line) {
let mut column = 0;
for c in line_slice.chars() {
if !c.is_whitespace() {
break;
}
column += 1;
}
Cursor { line, column }
} else {
Cursor { line, column: 0 }
}
}
pub fn cursor_at_line_end(&self, line: usize) -> Cursor {
Cursor {
line,
column: self
.text
.get_line(line)
.map(|line| line.len_chars().saturating_sub(1))
.unwrap_or(0),
}
}
pub fn cursor_at_file_end(&self) -> Cursor {
let last_line = if self.text.len_lines() == 0 {
0
} else if self.text.line(self.text.len_lines() - 1).len_chars() == 0 {
self.text.len_lines().saturating_sub(2)
} else {
self.text.len_lines() - 1
};
self.cursor_at_line_end(last_line)
}
}
#[cfg(test)]

View File

@ -46,11 +46,29 @@ impl Default for Config {
/// Gets the configuration directory. Panics if unavailable.
pub fn get_config_dir() -> PathBuf {
std::env::var_os("HOME")
.map(PathBuf::try_from)
.expect("$HOME is unset")
.unwrap()
.join(".config/breed")
std::env::var_os("XDG_CONFIG_HOME")
.map(|p| PathBuf::try_from(p).expect("$XDG_CONFIG_HOME is not a valid path."))
.unwrap_or_else(|| {
std::env::var_os("HOME")
.map(PathBuf::try_from)
.expect("$HOME is not a valid path.")
.expect("User has no $HOME or $XDG_CONFIG_HOME.")
.join(".config")
})
.join("breed")
}
pub fn get_data_dir() -> PathBuf {
std::env::var_os("XDG_DATA_HOME")
.map(|p| PathBuf::try_from(p).expect("$XDG_DATA_HOME is not a valid path."))
.unwrap_or_else(|| {
std::env::var_os("HOME")
.map(PathBuf::try_from)
.expect("$HOME is not a valid path.")
.expect("User has no $HOME or $XDG_DATA_HOME.")
.join(".local/share")
})
.join("breed")
}
/// Watches a theme file and automatically reloads it into a [StyleStore].
@ -65,7 +83,7 @@ pub struct ThemeWatcher {
impl ThemeWatcher {
pub fn spawn(styles: Arc<Mutex<StyleStore>>) -> Sender<PathBuf> {
let themes_dir = get_config_dir().join("themes");
let themes_dir = get_data_dir().join("themes");
let default_path = themes_dir.join("default.toml");
let (fs_tx, fs_rx) = unbounded();
let (command_tx, command_rx) = unbounded();

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2023 Marceline Cramer
* Copyright (c) 2023 Emma Tebibyte <emma@tebibyte.media>
* SPDX-License-Identifier: AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify it under
@ -47,15 +48,32 @@ impl Default for Keybinds {
(PageUp, page_up),
(PageDown, page_down),
(Home, goto_line_start),
(End, goto_line_end_newline),
(End, goto_line_end),
];
let normalish_keys = &[
let goto_keys = &[
(Char('h'), goto_line_start as Action),
(Char('l'), goto_line_end),
(Char('s'), goto_first_nonwhitespace),
(Char('g'), goto_file_start),
(Char('e'), goto_file_end),
];
let normalish_keys = [
(Char(':'), command_mode as Action),
(Char('$'), goto_line_end),
(Char('0'), goto_line_start),
(Char('^'), goto_first_nonwhitespace),
(Char('h'), move_char_left),
(Char('j'), move_line_down),
(Char('k'), move_line_up),
(Char('l'), move_char_right),
(Char('w'), move_next_word_start),
(Char('b'), move_prev_word_start),
(Char('e'), move_next_word_end),
(Char('W'), move_next_long_word_start),
(Char('B'), move_prev_long_word_start),
(Char('E'), move_next_long_word_end),
(Char('i'), insert_mode),
(Char('a'), append_mode),
(Char('I'), insert_at_line_start),
@ -64,11 +82,15 @@ impl Default for Keybinds {
(Char('O'), open_above),
(Char('u'), undo),
(Char('U'), redo),
(Char('d'), delete_char_forward),
]
.iter()
.chain(basic_nav);
let insert_keys = &[
let normalish_submodes: HashMap<Key, KeyMap> =
[(Char('g'), key_map_from_iter(goto_keys))].into();
let insert_keys = [
(Backspace, delete_char_backward as Action),
(Delete, delete_char_forward),
(Enter, insert_newline),
@ -77,34 +99,28 @@ impl Default for Keybinds {
.chain(basic_nav);
Self {
normal: normalish_keys.clone().into(),
insert: insert_keys.clone().into(),
visual: normalish_keys.clone().into(),
normal: ModeKeys {
submodes: normalish_submodes.clone(),
map: key_map_from_iter(normalish_keys.clone()),
},
insert: ModeKeys {
submodes: [].into(),
map: key_map_from_iter(insert_keys),
},
visual: ModeKeys {
submodes: normalish_submodes,
map: key_map_from_iter(normalish_keys.clone()),
},
}
}
}
#[derive(Clone, Default)]
pub struct ModeKeys {
pub minor_modes: HashMap<Key, KeyMap>,
pub submodes: HashMap<Key, KeyMap>,
pub map: KeyMap,
}
impl<'a, T> From<T> for ModeKeys
where
T: IntoIterator<Item = &'a (Key, Action)>,
{
fn from(iter: T) -> Self {
let minor_modes = HashMap::new();
let mut map = KeyMap::new();
for (key, action) in iter {
map.insert(*key, Keybind::Action(*action));
}
Self { minor_modes, map }
}
}
impl ModeKeys {
pub fn apply_table(values: Table) -> Result<Self, String> {
let mut keys = Self::default();
@ -114,7 +130,7 @@ impl ModeKeys {
match value {
Value::Table(table) => {
let map = parse_key_map(table)?;
keys.minor_modes.insert(key, map);
keys.submodes.insert(key, map);
}
Value::String(keybind) => {
let bind = Keybind::try_from(keybind.as_str())?;
@ -162,6 +178,18 @@ impl TryFrom<&str> for Keybind {
}
}
pub fn key_map_from_iter<'a, T>(iter: T) -> KeyMap
where
T: IntoIterator<Item = &'a (Key, Action)>,
{
let mut map = KeyMap::new();
for (key, action) in iter {
map.insert(*key, Keybind::Action(*action));
}
map
}
pub fn parse_key_map(values: Table) -> Result<KeyMap, String> {
let mut map = KeyMap::with_capacity(values.len());

View File

@ -20,82 +20,28 @@
use std::{
env::args,
ffi::OsString,
fs::{File, OpenOptions},
io::{stdout, Read, Stdout, Write},
fs::File,
io::{Read, Stdout, Write},
os::fd::FromRawFd,
path::{Path, PathBuf},
sync::Arc,
path::Path,
};
use crossbeam_channel::Sender;
use crossterm::{
cursor,
event::{Event, KeyCode, KeyEvent},
terminal, QueueableCommand, Result,
};
use keybinds::Keybind;
use parking_lot::Mutex;
use ropey::Rope;
use crossterm::{terminal, QueueableCommand, Result};
use yacexits::{exit, EX_DATAERR, EX_UNAVAILABLE};
mod actions;
mod buffer;
mod config;
mod keybinds;
mod state;
mod theme;
use buffer::Buffer;
use config::Config;
use theme::StyleStore;
#[derive(Copy, Clone, Debug, Default)]
pub struct Cursor {
pub column: usize,
pub line: usize,
}
#[derive(Clone, Debug, Default)]
pub struct NormalState {
pub error: Option<String>,
}
#[derive(Clone, Debug, Default)]
pub struct CommandState {
pub buf: String,
pub cursor: usize,
}
#[derive(Copy, Clone, Debug)]
pub struct InsertState {
append: bool,
}
#[derive(Clone, Debug)]
pub enum Mode {
Normal(NormalState),
Command(CommandState),
Visual,
Insert(InsertState),
}
impl Default for Mode {
fn default() -> Self {
Mode::Normal(Default::default())
}
}
impl Mode {
pub fn cursor_style(&self) -> cursor::SetCursorStyle {
use cursor::SetCursorStyle as Style;
match self {
Mode::Normal(_) => Style::SteadyBlock,
Mode::Visual => Style::BlinkingBlock,
Mode::Insert(_) => Style::BlinkingBar,
Mode::Command(_) => Style::SteadyUnderScore,
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Direction {
Left,
@ -104,303 +50,7 @@ pub enum Direction {
Right,
}
pub struct State {
pub styles: Arc<Mutex<StyleStore>>,
pub config: Config,
pub buffer: Buffer,
pub cursor: Cursor,
pub file: Option<OsString>,
pub mode: Mode,
pub last_saved: Rope,
pub scroll: Cursor,
pub size: (usize, usize),
pub quit: bool,
pub theme_tx: Sender<PathBuf>,
}
impl State {
pub fn from_str(file_name: Option<OsString>, text: &str) -> Result<Self> {
let styles = Arc::new(Mutex::new(StyleStore::default()));
let buffer = Buffer::from_str(styles.clone(), text);
let last_saved = buffer.as_ref().clone();
let (cols, rows) = terminal::size()?;
let theme_tx = config::ThemeWatcher::spawn(styles.clone());
Ok(Self {
styles,
config: Default::default(),
buffer,
cursor: Cursor::default(),
file: file_name,
mode: Mode::default(),
last_saved,
scroll: Cursor::default(),
size: (cols as usize, rows as usize),
quit: false,
theme_tx,
})
}
pub fn draw(&mut self, out: &mut impl Write) -> Result<()> {
// begin update
let (cols, rows) = terminal::size()?;
out.queue(terminal::BeginSynchronizedUpdate)?;
out.queue(terminal::Clear(terminal::ClearType::All))?;
let mut styles = self.styles.lock();
// draw status line
let mut set_cursor_pos = None;
let mut show_status_bar = false;
match &self.mode {
Mode::Command(CommandState { buf, cursor }) => {
let col = *cursor as u16 + 1;
let row = rows - 1;
out.queue(cursor::MoveTo(0, row))?;
write!(out, ":{}", buf)?;
set_cursor_pos = Some((col, row));
show_status_bar = true;
}
Mode::Normal(NormalState { error: Some(error) }) => {
let error_style = styles.get_scope("error");
out.queue(cursor::MoveTo(0, rows - 1))?;
error_style.print_styled(out, error)?;
show_status_bar = true;
}
_ => {}
}
// done with styles
drop(styles);
// draw buffer
let buffer_rows = if show_status_bar { rows - 1 } else { rows };
let lr_width = self
.buffer
.draw(cols, buffer_rows, self.scroll, self.cursor, out)?;
// draw cursor
let cursor_pos = set_cursor_pos.unwrap_or_else(|| {
// calculate cursor position on buffer
let cursor = self.buffer.clamped_cursor(self.cursor);
let col = cursor.column.saturating_sub(self.scroll.column) as u16;
let row = cursor.line.saturating_sub(self.scroll.line) as u16;
let col = col + lr_width as u16;
(col, row)
});
out.queue(cursor::MoveTo(cursor_pos.0, cursor_pos.1))?;
out.queue(self.mode.cursor_style())?;
// finish update
out.queue(terminal::EndSynchronizedUpdate)?;
out.flush()?;
Ok(())
}
/// Sets the state to `Mode::Normal` with an error message.
pub fn set_error(&mut self, error: impl ToString) {
self.mode = Mode::Normal(NormalState {
error: Some(error.to_string()),
});
}
pub fn on_event(&mut self, event: Event) {
match &self.mode {
Mode::Normal(state) => self.on_normal_event(event, state.clone()),
Mode::Command(state) => self.on_command_event(event, state.clone()),
Mode::Visual => self.on_visual_event(event),
Mode::Insert(state) => self.on_insert_event(event, state.clone()),
}
}
fn on_normal_event(&mut self, event: Event, mut state: NormalState) {
// reset the error from the last event
state.error = None;
self.mode = Mode::Normal(state);
match event {
Event::Key(KeyEvent { code, .. }) => {
if let Some(keybind) = self.config.keybinds.visual.map.get(&code) {
self.execute_keybind(keybind.clone());
}
}
event => self.on_any_event(event),
}
}
fn on_command_event(&mut self, event: Event, mut state: CommandState) {
match event {
Event::Key(KeyEvent { code, .. }) => match code {
KeyCode::Char(c) => {
state.buf.insert(state.cursor, c);
state.cursor += 1;
}
KeyCode::Backspace => {
if state.cursor > 0 {
state.cursor -= 1;
state.buf.remove(state.cursor);
}
}
KeyCode::Delete if state.cursor < state.buf.len() => {
state.buf.remove(state.cursor);
}
KeyCode::Left if state.cursor > 0 => {
state.cursor -= 1;
}
KeyCode::Right if state.cursor < state.buf.len() => {
state.cursor += 1;
}
KeyCode::Enter => {
// TODO add to command history
let result = self.execute_command(&state.buf);
let error = result.err();
self.mode = Mode::Normal(NormalState { error });
return;
}
KeyCode::Esc => {
self.mode = Mode::default();
return;
}
_ => {}
},
event => return self.on_any_event(event),
}
self.mode = Mode::Command(state);
}
fn on_visual_event(&mut self, event: Event) {
match event {
Event::Key(KeyEvent { code, .. }) => {
if let Some(keybind) = self.config.keybinds.visual.map.get(&code) {
self.execute_keybind(keybind.clone());
}
}
event => self.on_any_event(event),
}
}
fn on_insert_event(&mut self, event: Event, _state: InsertState) {
match event {
Event::Key(KeyEvent { code, .. }) => match self.config.keybinds.insert.map.get(&code) {
Some(keybind) => self.execute_keybind(keybind.clone()),
None => {
if let KeyCode::Char(c) = code {
self.buffer.insert_char(self.cursor, c);
self.move_cursor(Direction::Right);
}
}
},
event => self.on_any_event(event),
}
}
fn on_any_event(&mut self, event: Event) {
match event {
Event::Resize(cols, rows) => {
self.size = (cols as usize, rows as usize);
}
_ => {}
}
}
fn write_buffer(&mut self, file: OsString) -> Result<()> {
self.last_saved = self.buffer.as_ref().clone();
let out = self.buffer.as_ref().bytes().collect::<Vec<u8>>();
let mut handle = OpenOptions::new().write(true).open(file)?;
handle.write_all(out.as_slice())?;
Ok(())
}
fn write_command(&mut self, command: &str, args: &[&str]) -> std::result::Result<(), String> {
let handle = match self.file.clone() {
Some(handle) => handle,
None => match args.get(0) {
Some(part) => OsString::from(part),
None => {
return Err(format!("{}: No file name.", command));
}
},
};
self.write_buffer(handle).map_err(|err| format!("{}", err))
}
fn execute_keybind(&mut self, keybind: Keybind) {
match keybind {
Keybind::Action(action) => action(self),
Keybind::Command(command) => {
let result = self.execute_command(&command);
let error = result.err();
self.mode = Mode::Normal(NormalState { error });
return;
}
}
}
fn execute_command(&mut self, command: &str) -> std::result::Result<(), String> {
let command_parts = command.split(' ').collect::<Vec<&str>>();
let command = match command_parts.get(0) {
Some(command) => command,
None => return Ok(()),
};
let args = &command_parts[1..];
match *command {
"q!" => self.quit = true,
"q" => {
if self.last_saved == *self.buffer.as_ref() {
self.quit = true;
} else {
return Err("Buffer is unsaved (add ! to override)".into());
}
}
"w" => return self.write_command(command, args),
"wq" => {
self.write_command(command, args)?;
self.quit = true;
}
command => match command.parse::<usize>() {
Err(_) => return Err(format!("{}: Unrecognized command.", command)),
Ok(line) if line >= self.buffer.as_ref().len_lines() => {
return Err(format!("Line {} is out-of-bounds", line))
}
Ok(line) => {
self.cursor.line = line;
self.scroll_to_cursor();
}
},
}
Ok(())
}
fn move_cursor(&mut self, direction: Direction) {
let wrap = self.config.move_linewrap;
self.buffer.move_cursor(&mut self.cursor, direction, wrap);
self.scroll_to_cursor();
}
fn scroll_to_cursor(&mut self) {
if self.cursor.column < self.scroll.column + 3 {
self.scroll.column = self.cursor.column.saturating_sub(3);
} else if self.cursor.column + 6 >= self.scroll.column + self.size.0 {
self.scroll.column = self.cursor.column.saturating_sub(self.size.0 - 6);
}
if self.cursor.line < self.scroll.line {
self.scroll.line = self.cursor.line;
} else if self.cursor.line + 3 >= self.scroll.line + self.size.1 {
self.scroll.line = self.cursor.line + 3 - self.size.1;
}
}
}
fn screen_main(stdout: &mut Stdout, mut state: State) -> Result<()> {
fn screen_main(stdout: &mut Stdout, mut state: state::State) -> Result<()> {
let poll_timeout = std::time::Duration::from_millis(100);
while !state.quit {
state.draw(stdout)?;
@ -425,12 +75,12 @@ fn main() -> Result<()> {
if unsafe { libc::isatty(stdin) } == 0 {
unsafe { File::from_raw_fd(stdin) }
} else {
File::open("/dev/null").unwrap()
File::open("/dev/null")?
}
}
Some(path) => {
let input_file = Path::new(path);
file_name = Some(OsString::from(input_file.clone().display().to_string()));
file_name = Some(OsString::from(&path));
File::open(input_file).unwrap_or_else(|_| {
let mut err = String::new();
@ -444,8 +94,7 @@ fn main() -> Result<()> {
})
}
}
.read_to_end(&mut buf)
.unwrap();
.read_to_end(&mut buf)?;
let text = String::from_utf8(buf).unwrap_or_else(|_| {
eprintln!(
@ -455,12 +104,29 @@ fn main() -> Result<()> {
exit(EX_DATAERR);
});
let state = State::from_str(file_name, &text)?;
let mut stdout = stdout();
let state = state::State::from_str(file_name, &text)?;
// begin to enter alternate screen
let mut stdout = std::io::stdout();
terminal::enable_raw_mode()?;
stdout.queue(terminal::EnterAlternateScreen)?;
// register a panic handler to exit the alternate screen
let old_panic_handler = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let mut stdout = std::io::stdout();
let _ = stdout.queue(terminal::LeaveAlternateScreen);
let _ = terminal::disable_raw_mode();
let _ = stdout.flush();
old_panic_handler(info)
}));
// run inner event loop
let result = screen_main(&mut stdout, state);
// exit alternate screen
stdout.queue(terminal::LeaveAlternateScreen)?;
terminal::disable_raw_mode()?;
result
}

467
src/state.rs Normal file
View File

@ -0,0 +1,467 @@
/*
* Copyright (c) 2023 Marceline Cramer
* SPDX-License-Identifier: AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
use std::{ffi::OsString, fs::OpenOptions, io::Write, path::PathBuf, sync::Arc};
use crossbeam_channel::Sender;
use crossterm::{
cursor,
event::{Event, KeyCode, KeyEvent},
terminal, QueueableCommand, Result,
};
use parking_lot::Mutex;
use ropey::Rope;
use crate::{
buffer::Buffer,
config::{Config, ThemeWatcher},
keybinds::{Key, Keybind},
theme::{StyleStore, StyledString},
Cursor, Direction,
};
#[derive(Clone, Debug, Default)]
pub struct CommandState {
pub buf: String,
pub cursor: usize,
}
#[derive(Copy, Clone, Debug)]
pub struct InsertState {
pub append: bool,
}
#[derive(Clone, Debug, Default)]
pub enum Mode {
#[default]
Normal,
Command(CommandState),
Visual,
Insert(InsertState),
}
impl Mode {
pub fn cursor_style(&self) -> cursor::SetCursorStyle {
use cursor::SetCursorStyle as Style;
match self {
Mode::Normal => Style::SteadyBlock,
Mode::Visual => Style::BlinkingBlock,
Mode::Insert(_) => Style::BlinkingBar,
Mode::Command(_) => Style::SteadyUnderScore,
}
}
}
pub struct Rect {
pub position: (usize, usize),
pub size: (usize, usize),
}
pub struct Window {
pub rect: Rect,
pub contents: Vec<StyledString>,
}
impl Window {
pub fn draw(
&self,
out: &mut impl QueueableCommand,
styles: &mut StyleStore,
) -> crossterm::Result<()> {
let x = self.rect.position.0 as u16;
let base = *styles.get_scope("ui.window");
let width = self.rect.size.0;
let clip = 0..width;
let padding: String = std::iter::repeat(' ').take(width).collect();
for row in 0..self.rect.size.1 {
let y = self.rect.position.1 as u16 + row as u16;
out.queue(cursor::MoveTo(x, y))?;
let remaining = if let Some(line) = self.contents.get(row) {
line.print_sub(out, clip.clone(), base)?
} else {
width
};
let padding = &padding[0..remaining];
base.print_styled(out, padding)?;
}
Ok(())
}
}
pub struct State {
pub styles: Arc<Mutex<StyleStore>>,
pub config: Config,
pub buffer: Buffer,
pub undo_buffers: Vec<Buffer>,
pub redo_buffers: Vec<Buffer>,
pub cursor: Cursor,
pub file: Option<OsString>,
pub window: Option<Window>,
pub mode: Mode,
pub submode: Option<Key>,
pub last_saved: Rope,
pub scroll: Cursor,
pub size: (usize, usize),
pub quit: bool,
pub error: Option<String>,
pub theme_tx: Sender<PathBuf>,
}
impl State {
pub fn from_str(file_name: Option<OsString>, text: &str) -> Result<Self> {
let styles = Arc::new(Mutex::new(StyleStore::default()));
let buffer = Buffer::from_str(styles.clone(), text);
let last_saved = buffer.as_ref().clone();
let (cols, rows) = terminal::size()?;
let theme_tx = ThemeWatcher::spawn(styles.clone());
Ok(Self {
styles,
config: Default::default(),
buffer,
undo_buffers: Vec::new(),
redo_buffers: Vec::new(),
cursor: Cursor::default(),
file: file_name,
mode: Mode::default(),
submode: None,
last_saved,
scroll: Cursor::default(),
size: (cols as usize, rows as usize),
quit: false,
error: None,
theme_tx,
window: None,
})
}
pub fn draw(&mut self, out: &mut impl Write) -> Result<()> {
// begin update
let (cols, rows) = terminal::size()?;
out.queue(terminal::BeginSynchronizedUpdate)?;
out.queue(terminal::Clear(terminal::ClearType::All))?;
let mut styles = self.styles.lock();
// draw status line
let mut set_cursor_pos = None;
let mut show_status_bar = false;
if let Mode::Command(CommandState { buf, cursor }) = &self.mode {
let col = *cursor as u16 + 1;
let row = rows - 1;
out.queue(cursor::MoveTo(0, row))?;
write!(out, ":{}", buf)?;
set_cursor_pos = Some((col, row));
show_status_bar = true;
} else if let Some(error) = self.error.as_ref() {
let error_style = styles.get_scope("error");
out.queue(cursor::MoveTo(0, rows - 1))?;
error_style.print_styled(out, error)?;
show_status_bar = true;
}
// done with styles
drop(styles);
// draw buffer
let buffer_rows = if show_status_bar { rows - 1 } else { rows };
let lr_width = self
.buffer
.draw(cols, buffer_rows, self.scroll, self.cursor, out)?;
// draw submode
if let Some(submode) = self.submode {
out.queue(cursor::MoveTo(cols - 10, rows - 1))?;
write!(out, "{:?}", submode)?;
}
// draw open window
if let Some(window) = self.window.as_ref() {
let mut styles = self.styles.lock();
window.draw(out, &mut styles)?;
}
// draw cursor
let cursor_pos = set_cursor_pos.unwrap_or_else(|| {
// calculate cursor position on buffer
let cursor = self.buffer.clamped_cursor(self.cursor);
let col = cursor.column.saturating_sub(self.scroll.column) as u16;
let row = cursor.line.saturating_sub(self.scroll.line) as u16;
let col = col + lr_width as u16;
(col, row)
});
out.queue(cursor::MoveTo(cursor_pos.0, cursor_pos.1))?;
out.queue(self.mode.cursor_style())?;
// finish update
out.queue(terminal::EndSynchronizedUpdate)?;
out.flush()?;
Ok(())
}
/// Sets the current error message.
pub fn set_error(&mut self, error: impl ToString) {
self.error = Some(error.to_string());
}
pub fn on_event(&mut self, event: Event) {
// reset the error from the last event
self.error = None;
// close open window
self.window.take();
match event {
Event::Resize(cols, rows) => {
self.size = (cols as usize, rows as usize);
}
Event::Key(KeyEvent { code, .. }) => match &self.mode {
Mode::Normal | Mode::Visual => {
self.on_key(code);
}
Mode::Command(state) => self.on_command_key(code, state.clone()),
Mode::Insert(_) => {
if !self.on_key(code) {
if let KeyCode::Char(c) = code {
self.buffer.insert_char(self.cursor, c);
self.move_cursor(Direction::Right);
}
}
}
},
_ => {}
}
}
fn on_command_key(&mut self, code: KeyCode, mut state: CommandState) {
match code {
KeyCode::Char(c) => {
state.buf.insert(state.cursor, c);
state.cursor += 1;
}
KeyCode::Backspace => {
if state.cursor > 0 {
state.cursor -= 1;
state.buf.remove(state.cursor);
}
}
KeyCode::Delete if state.cursor < state.buf.len() => {
state.buf.remove(state.cursor);
}
KeyCode::Left if state.cursor > 0 => {
state.cursor -= 1;
}
KeyCode::Right if state.cursor < state.buf.len() => {
state.cursor += 1;
}
KeyCode::Enter => {
// TODO add to command history
let _ = self
.execute_command(&state.buf)
.map_err(|err| self.set_error(err));
self.mode = Mode::Normal;
return;
}
KeyCode::Esc => {
self.mode = Mode::default();
return;
}
_ => {}
}
self.mode = Mode::Command(state);
}
/// Processes a key press event.
///
/// Returns `true` if the key was handled by a keybind, `false` otherwise.
fn on_key(&mut self, key: Key) -> bool {
let keybinds = match &self.mode {
Mode::Normal => &self.config.keybinds.normal,
Mode::Insert(_) => &self.config.keybinds.insert,
Mode::Visual => &self.config.keybinds.visual,
Mode::Command(_) => return false, // command mode is handled in [on_command_event]
};
if let Some(submode) = self.submode {
// if we're currently in a submode, try to run this submode's keybind
keybinds
.submodes
.get(&submode)
.and_then(|submode| submode.get(&key))
.cloned()
.map(|keybind| self.execute_keybind(keybind));
// whether or not there is a keybind we exit the submode
self.submode = None;
} else if keybinds.submodes.contains_key(&key) {
// enter a submode if available
self.submode = Some(key);
} else if let Some(keybind) = keybinds.map.get(&key) {
// run the keybind if available
self.execute_keybind(keybind.clone());
} else {
// key is not bound; don't handle
return false;
}
true
}
fn write_buffer(&mut self, file: OsString) -> Result<()> {
self.last_saved = self.buffer.as_ref().clone();
let out = self.buffer.as_ref().bytes().collect::<Vec<u8>>();
let mut handle = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(file)?;
handle.write_all(out.as_slice())?;
Ok(())
}
fn write_command(&mut self, command: &str, args: &[&str]) -> std::result::Result<(), String> {
let handle = match self.file.clone() {
Some(handle) => handle,
None => match args.get(0) {
Some(part) => {
let file = OsString::from(part);
self.file = Some(file.clone());
file
}
None => {
return Err(format!("{}: No file name.", command));
}
},
};
self.write_buffer(handle).map_err(|err| format!("{}", err))
}
fn execute_keybind(&mut self, keybind: Keybind) {
match keybind {
Keybind::Action(action) => action(self),
Keybind::Command(command) => {
let _ = self
.execute_command(&command)
.map_err(|err| self.set_error(err));
self.mode = Mode::Normal;
return;
}
}
}
fn execute_command(&mut self, command: &str) -> std::result::Result<(), String> {
let command_parts = command.split(' ').collect::<Vec<&str>>();
let command = match command_parts.get(0) {
Some(command) => command,
None => return Ok(()),
};
let args = &command_parts[1..];
match *command {
"q!" => self.quit = true,
"q" => {
if self.last_saved == *self.buffer.as_ref() {
self.quit = true;
} else {
return Err("Buffer is unsaved (add ! to override)".into());
}
}
"w" => return self.write_command(command, args),
"wq" => {
self.write_command(command, args)?;
self.quit = true;
}
command => match command.parse::<usize>() {
Err(_) => return Err(format!("{}: Unrecognized command.", command)),
Ok(line) if line >= self.buffer.as_ref().len_lines() => {
return Err(format!("Line {} is out-of-bounds", line))
}
Ok(line) => {
self.cursor.line = line;
self.scroll_to_cursor();
}
},
}
Ok(())
}
pub fn move_cursor(&mut self, direction: Direction) {
let wrap = self.config.move_linewrap;
self.buffer.move_cursor(&mut self.cursor, direction, wrap);
self.scroll_to_cursor();
}
pub fn scroll_to_cursor(&mut self) {
if self.cursor.column < self.scroll.column + 3 {
self.scroll.column = self.cursor.column.saturating_sub(3);
} else if self.cursor.column + 6 >= self.scroll.column + self.size.0 {
self.scroll.column = self.cursor.column.saturating_sub(self.size.0 - 6);
}
if self.cursor.line < self.scroll.line {
self.scroll.line = self.cursor.line;
} else if self.cursor.line + 3 >= self.scroll.line + self.size.1 {
self.scroll.line = self.cursor.line + 3 - self.size.1;
}
}
/// If modified, saves the current buffer in undo history and clears the redo history.
pub fn save_buffer(&mut self) {
/*if let Some(last) = self.undo_buffers.last() {
if *last.as_ref() == *self.buffer.as_ref() {
return;
}
}*/
let current = self.buffer.clone();
self.undo_buffers.push(current);
self.redo_buffers.clear();
}
/// Pops the last undo state from the history and pushes the current state to the redo buffers.
pub fn undo(&mut self) {
match self.undo_buffers.pop() {
None => self.set_error("Already at oldest change"),
Some(last) => {
let current = std::mem::replace(&mut self.buffer, last);
self.redo_buffers.push(current);
}
}
}
/// Pops the next redo state from the history and pushes the current state to the undo buffers.
pub fn redo(&mut self) {
match self.redo_buffers.pop() {
None => self.set_error("Already at newest change"),
Some(next) => {
let current = std::mem::replace(&mut self.buffer, next);
self.undo_buffers.push(current);
}
}
}
}

View File

@ -17,7 +17,7 @@
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
use std::{collections::HashMap, fmt::Display};
use std::{collections::HashMap, fmt::Display, ops::Range};
use crossterm::style::Color;
use crossterm::QueueableCommand;
@ -122,6 +122,68 @@ impl StyleStore {
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StyledString {
pub content: String,
pub styles: Vec<(usize, Style)>,
}
impl StyledString {
pub fn new_unstyled(content: String) -> Self {
Self {
styles: vec![(content.len(), Style::default())],
content,
}
}
pub fn print(&self, out: &mut impl QueueableCommand, base: Style) -> crossterm::Result<()> {
let mut cursor = 0;
for (size, style) in self.styles.iter() {
let end = cursor + size;
let range = cursor..end;
let sub = &self.content[range];
let mut style = style.clone();
style.apply(&base);
style.print_styled(out, sub)?;
cursor = end;
}
Ok(())
}
pub fn print_sub(
&self,
out: &mut impl QueueableCommand,
clip: Range<usize>,
base: Style,
) -> crossterm::Result<usize> {
let mut remaining = clip.end - clip.start;
let mut cursor = 0;
for (size, style) in self.styles.iter() {
let end = cursor + size;
let clipped = (cursor.max(clip.start))..(end.min(clip.end));
cursor = end;
if clipped.start >= clipped.end {
continue;
}
remaining -= clipped.end - clipped.start;
let sub = &self.content[clipped];
let mut style = style.clone();
style.apply(&base);
style.print_styled(out, sub)?;
if cursor >= clip.end {
break;
}
}
Ok(remaining)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Style {
pub fg: Option<Color>,

View File

@ -2,6 +2,8 @@
"ui.linenr" = "black"
"ui.linenr.selected" = "white"
"ui.window" = { bg = "magenta" }
"error" = "red"
"comment" = { fg = "black", modifiers = ["italics"] }