forked from mars/breed
Compare commits
6 Commits
a7e121ba18
...
5aed7766c9
Author | SHA1 | Date |
---|---|---|
mars | 5aed7766c9 | |
mars | bde9c9987a | |
mars | 042ea6d420 | |
mars | e910608805 | |
mars | b2b69bf7b3 | |
mars | e47275cb88 |
|
@ -19,7 +19,7 @@
|
|||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{Direction, InsertState, Mode, NormalState, State};
|
||||
use crate::{Cursor, Direction, InsertState, Mode, State};
|
||||
|
||||
pub type Action = fn(&mut State);
|
||||
|
||||
|
@ -34,6 +34,8 @@ pub fn load_actions() -> HashMap<String, Action> {
|
|||
("goto_line_start", goto_line_start),
|
||||
("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),
|
||||
|
@ -90,7 +92,19 @@ pub fn goto_line_end(state: &mut State) {
|
|||
}
|
||||
|
||||
pub fn goto_first_nonwhitespace(state: &mut State) {
|
||||
state.cursor = state.buffer.cursor_at_first_nonwhitespace(state.cursor.line);
|
||||
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) {
|
||||
|
@ -105,7 +119,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) {
|
||||
|
@ -154,11 +168,11 @@ pub fn redo(state: &mut State) {
|
|||
|
||||
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) {
|
||||
|
@ -199,6 +213,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");
|
||||
|
|
|
@ -90,11 +90,6 @@ impl Buffer {
|
|||
|
||||
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 {
|
||||
break;
|
||||
}
|
||||
|
||||
let row = row as usize + scroll.line;
|
||||
let is_selected = row == cursor.line;
|
||||
|
||||
|
@ -104,13 +99,19 @@ impl Buffer {
|
|||
linenr_style
|
||||
};
|
||||
|
||||
let linenr = if line.len_chars() > 0 {
|
||||
format!("{:>width$} ", row, width = linenr_width as usize)
|
||||
} else {
|
||||
// only the last line is empty
|
||||
format!("{:>width$}", "~", width = linenr_width as usize)
|
||||
};
|
||||
|
||||
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;
|
||||
|
@ -149,10 +150,12 @@ impl Buffer {
|
|||
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) {
|
||||
|
@ -222,7 +225,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 +257,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,13 +268,13 @@ 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -298,6 +307,18 @@ impl Buffer {
|
|||
.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)]
|
||||
|
|
|
@ -54,6 +54,8 @@ impl Default for Keybinds {
|
|||
(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 = [
|
||||
|
@ -70,6 +72,7 @@ impl Default for Keybinds {
|
|||
(Char('O'), open_above),
|
||||
(Char('u'), undo),
|
||||
(Char('U'), redo),
|
||||
(Char('d'), delete_char_forward),
|
||||
]
|
||||
.iter()
|
||||
.chain(basic_nav);
|
||||
|
|
216
src/main.rs
216
src/main.rs
|
@ -21,7 +21,7 @@ use std::{
|
|||
env::args,
|
||||
ffi::OsString,
|
||||
fs::{File, OpenOptions},
|
||||
io::{stdout, Read, Stdout, Write},
|
||||
io::{Read, Stdout, Write},
|
||||
os::fd::FromRawFd,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
|
@ -54,11 +54,6 @@ pub struct Cursor {
|
|||
pub line: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NormalState {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CommandState {
|
||||
pub buf: String,
|
||||
|
@ -70,25 +65,20 @@ pub struct InsertState {
|
|||
append: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub enum Mode {
|
||||
Normal(NormalState),
|
||||
#[default]
|
||||
Normal,
|
||||
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::Normal => Style::SteadyBlock,
|
||||
Mode::Visual => Style::BlinkingBlock,
|
||||
Mode::Insert(_) => Style::BlinkingBar,
|
||||
Mode::Command(_) => Style::SteadyUnderScore,
|
||||
|
@ -116,6 +106,7 @@ pub struct State {
|
|||
pub scroll: Cursor,
|
||||
pub size: (usize, usize),
|
||||
pub quit: bool,
|
||||
pub error: Option<String>,
|
||||
pub theme_tx: Sender<PathBuf>,
|
||||
}
|
||||
|
||||
|
@ -139,6 +130,7 @@ impl State {
|
|||
scroll: Cursor::default(),
|
||||
size: (cols as usize, rows as usize),
|
||||
quit: false,
|
||||
error: None,
|
||||
theme_tx,
|
||||
})
|
||||
}
|
||||
|
@ -154,22 +146,18 @@ impl State {
|
|||
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;
|
||||
}
|
||||
_ => {}
|
||||
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
|
||||
|
@ -207,105 +195,82 @@ impl State {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets the state to `Mode::Normal` with an error message.
|
||||
/// Sets the current error message.
|
||||
pub fn set_error(&mut self, error: impl ToString) {
|
||||
self.mode = Mode::Normal(NormalState {
|
||||
error: Some(error.to_string()),
|
||||
});
|
||||
self.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);
|
||||
self.error = None;
|
||||
|
||||
match event {
|
||||
Event::Key(KeyEvent { code, .. }) => {
|
||||
self.on_key(code);
|
||||
Event::Resize(cols, rows) => {
|
||||
self.size = (cols as usize, rows as usize);
|
||||
}
|
||||
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;
|
||||
Event::Key(KeyEvent { code, .. }) => match &self.mode {
|
||||
Mode::Normal | Mode::Visual => {
|
||||
self.on_key(code);
|
||||
}
|
||||
KeyCode::Backspace => {
|
||||
if state.cursor > 0 {
|
||||
state.cursor -= 1;
|
||||
state.buf.remove(state.cursor);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Delete if state.cursor < state.buf.len() => {
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
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::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),
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
fn on_visual_event(&mut self, event: Event) {
|
||||
match event {
|
||||
Event::Key(KeyEvent { code, .. }) => {
|
||||
self.on_key(code);
|
||||
}
|
||||
event => self.on_any_event(event),
|
||||
}
|
||||
}
|
||||
|
||||
fn on_insert_event(&mut self, event: Event, _state: InsertState) {
|
||||
match event {
|
||||
Event::Key(KeyEvent { code, .. }) => {
|
||||
if !self.on_key(code) {
|
||||
if let KeyCode::Char(c) = code {
|
||||
self.buffer.insert_char(self.cursor, c);
|
||||
self.move_cursor(Direction::Right);
|
||||
}
|
||||
}
|
||||
}
|
||||
event => self.on_any_event(event),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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::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]
|
||||
|
@ -335,15 +300,6 @@ impl State {
|
|||
true
|
||||
}
|
||||
|
||||
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>>();
|
||||
|
@ -365,7 +321,7 @@ impl State {
|
|||
let file = OsString::from(part);
|
||||
self.file = Some(file.clone());
|
||||
file
|
||||
},
|
||||
}
|
||||
None => {
|
||||
return Err(format!("{}: No file name.", command));
|
||||
}
|
||||
|
@ -379,9 +335,10 @@ impl State {
|
|||
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 });
|
||||
let _ = self
|
||||
.execute_command(&command)
|
||||
.map_err(|err| self.set_error(err));
|
||||
self.mode = Mode::Normal;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
@ -502,11 +459,28 @@ fn main() -> Result<()> {
|
|||
});
|
||||
|
||||
let state = State::from_str(file_name, &text)?;
|
||||
let mut stdout = stdout();
|
||||
|
||||
// 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
|
||||
}
|
||||
|
|
Reference in New Issue