Merge branch 'main' into main

This commit is contained in:
mars 2023-04-12 22:53:48 +00:00
commit f1be638ea7
3 changed files with 113 additions and 61 deletions

View File

@ -21,11 +21,11 @@ use std::io::Write;
use std::ops::Range; use std::ops::Range;
use std::sync::Arc; use std::sync::Arc;
use crossterm::{cursor, ExecutableCommand}; use crossterm::{cursor, ExecutableCommand, QueueableCommand};
use parking_lot::Mutex; use parking_lot::Mutex;
use ropey::Rope; use ropey::Rope;
use syntect::easy::ScopeRangeIterator; use syntect::easy::ScopeRangeIterator;
use syntect::parsing::{ParseState, Scope, ScopeStack, SyntaxSet}; use syntect::parsing::{BasicScopeStackOp, ParseState, Scope, ScopeStack, SyntaxSet};
use crate::theme::{Style, StyleStore}; use crate::theme::{Style, StyleStore};
use crate::{Cursor, Direction}; use crate::{Cursor, Direction};
@ -33,7 +33,7 @@ use crate::{Cursor, Direction};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Buffer { pub struct Buffer {
styles: Arc<Mutex<StyleStore>>, styles: Arc<Mutex<StyleStore>>,
pub text: Rope, text: Rope,
syntax_set: Arc<SyntaxSet>, syntax_set: Arc<SyntaxSet>,
parser: ParseState, parser: ParseState,
style_dirty: bool, style_dirty: bool,
@ -41,6 +41,12 @@ pub struct Buffer {
styled: Vec<Vec<(Style, Range<usize>)>>, styled: Vec<Vec<(Style, Range<usize>)>>,
} }
impl AsRef<Rope> for Buffer {
fn as_ref(&self) -> &Rope {
&self.text
}
}
impl Buffer { impl Buffer {
pub fn from_str(styles: Arc<Mutex<StyleStore>>, text: &str) -> Self { pub fn from_str(styles: Arc<Mutex<StyleStore>>, text: &str) -> Self {
let syntax_set = SyntaxSet::load_defaults_nonewlines(); let syntax_set = SyntaxSet::load_defaults_nonewlines();
@ -68,7 +74,7 @@ impl Buffer {
cols: u16, cols: u16,
rows: u16, rows: u16,
scroll: Cursor, scroll: Cursor,
out: &mut (impl ExecutableCommand + Write), out: &mut impl Write,
) -> crossterm::Result<u32> { ) -> crossterm::Result<u32> {
self.parse(); self.parse();
@ -78,8 +84,9 @@ impl Buffer {
let gutter_width = linenr_width + 1; let gutter_width = linenr_width + 1;
let text_width = cols as usize - gutter_width as usize; let text_width = cols as usize - gutter_width as usize;
out.execute(cursor::MoveTo(0, 0))?; 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)) { for (row, line) in (0..rows).zip(self.text.lines_at(scroll.line)) {
// only the last line is empty and should be skipped // only the last line is empty and should be skipped
if line.len_chars() == 0 { if line.len_chars() == 0 {
@ -92,6 +99,7 @@ impl Buffer {
let lhs = scroll.column; let lhs = scroll.column;
let width = line.len_chars(); let width = line.len_chars();
line_buf.clear();
if lhs < width { if lhs < width {
let window = text_width.min(width - lhs); let window = text_width.min(width - lhs);
let rhs = lhs + window; let rhs = lhs + window;
@ -101,7 +109,7 @@ impl Buffer {
if range.start < range.end { if range.start < range.end {
// this range is in view so display // this range is in view so display
let content = line.slice(range.clone()); let content = line.slice(range.clone());
style.print_styled(out, content)?; style.print_styled(&mut line_buf, content)?;
} }
if range.end >= rhs { if range.end >= rhs {
@ -111,7 +119,8 @@ impl Buffer {
} }
} }
out.execute(cursor::MoveToNextLine(1))?; out.write_all(&line_buf)?;
out.queue(cursor::MoveToNextLine(1))?;
} }
Ok(gutter_width) Ok(gutter_width)
@ -141,6 +150,11 @@ impl Buffer {
let mut parser = self.parser.clone(); let mut parser = self.parser.clone();
let mut line_buf = String::new(); let mut line_buf = String::new();
let mut stack = ScopeStack::new(); let mut stack = ScopeStack::new();
let mut styled_buf = Vec::new();
let mut style_stack = Vec::<Style>::new();
style_stack.push(Default::default());
for line in self.text.lines() { for line in self.text.lines() {
// display line to a pre-allocated buffer for fast parsing // display line to a pre-allocated buffer for fast parsing
line_buf.clear(); line_buf.clear();
@ -151,30 +165,36 @@ impl Buffer {
// parse the line into a sequence of stack operations // parse the line into a sequence of stack operations
let stack_ops = parser.parse_line(&line_buf, &self.syntax_set).unwrap(); let stack_ops = parser.parse_line(&line_buf, &self.syntax_set).unwrap();
// execute the operations on the stack // queue the operations on the stack
let mut line = Vec::new();
let range_iter = ScopeRangeIterator::new(&stack_ops, &line_buf); let range_iter = ScopeRangeIterator::new(&stack_ops, &line_buf);
styled_buf.clear();
for (range, op) in range_iter { for (range, op) in range_iter {
stack.apply(&op).unwrap(); stack
.apply_with_hook(&op, |op, _scopes| match op {
BasicScopeStackOp::Push(scope) => {
let style = styles.get_syntect_scope(&scope);
let mut top_style = style_stack.last().unwrap().clone();
top_style.apply(style);
style_stack.push(top_style);
}
BasicScopeStackOp::Pop => {
style_stack.pop();
}
})
.unwrap();
if range.start == range.end { if range.start == range.end {
continue; continue;
} }
let mut style = Style::default(); let style = style_stack.last().cloned().unwrap_or_default();
for scope in stack.scopes.clone() { styled_buf.push((style, range));
// TODO docs say that build_string "shouldn't be done frequently"
let scope = scope.build_string();
style.apply(&styles.get_scope(&scope));
}
line.push((style, range));
} }
self.styled.push(line); self.styled.push(styled_buf.clone());
} }
self.style_dirty = true; self.style_dirty = false;
self.style_generation = styles.generation(); self.style_generation = styles.generation();
} }

View File

@ -31,7 +31,7 @@ use crossbeam_channel::Sender;
use crossterm::{ use crossterm::{
cursor, cursor,
event::{Event, KeyCode, KeyEvent}, event::{Event, KeyCode, KeyEvent},
terminal, ExecutableCommand, Result, terminal, Result, QueueableCommand,
}; };
use parking_lot::Mutex; use parking_lot::Mutex;
use yacexits::{exit, EX_DATAERR, EX_UNAVAILABLE}; use yacexits::{exit, EX_DATAERR, EX_UNAVAILABLE};
@ -135,8 +135,8 @@ impl State {
pub fn draw(&mut self, out: &mut impl Write) -> Result<()> { pub fn draw(&mut self, out: &mut impl Write) -> Result<()> {
// begin update // begin update
let (cols, rows) = terminal::size()?; let (cols, rows) = terminal::size()?;
out.execute(terminal::BeginSynchronizedUpdate)?; out.queue(terminal::BeginSynchronizedUpdate)?;
out.execute(terminal::Clear(terminal::ClearType::All))?; out.queue(terminal::Clear(terminal::ClearType::All))?;
let mut styles = self.styles.lock(); let mut styles = self.styles.lock();
// draw status line // draw status line
@ -147,14 +147,14 @@ impl State {
Mode::Command(CommandState { buf, cursor }) => { Mode::Command(CommandState { buf, cursor }) => {
let col = *cursor as u16 + 1; let col = *cursor as u16 + 1;
let row = rows - 1; let row = rows - 1;
out.execute(cursor::MoveTo(0, row))?; out.queue(cursor::MoveTo(0, row))?;
write!(out, ":{}", buf)?; write!(out, ":{}", buf)?;
set_cursor_pos = Some((col, row)); set_cursor_pos = Some((col, row));
show_status_bar = true; show_status_bar = true;
} }
Mode::Normal(NormalState { error: Some(error) }) => { Mode::Normal(NormalState { error: Some(error) }) => {
let error_style = styles.get_scope("error"); let error_style = styles.get_scope("error");
out.execute(cursor::MoveTo(0, rows - 1))?; out.queue(cursor::MoveTo(0, rows - 1))?;
error_style.print_styled(out, error)?; error_style.print_styled(out, error)?;
show_status_bar = true; show_status_bar = true;
} }
@ -178,11 +178,13 @@ impl State {
(col, row) (col, row)
}); });
out.execute(cursor::MoveTo(cursor_pos.0, cursor_pos.1))?; out.queue(cursor::MoveTo(cursor_pos.0, cursor_pos.1))?;
out.execute(self.mode.cursor_style())?; out.queue(self.mode.cursor_style())?;
// finish update // finish update
out.execute(terminal::EndSynchronizedUpdate)?; out.queue(terminal::EndSynchronizedUpdate)?;
out.flush()?;
Ok(()) Ok(())
} }
@ -246,7 +248,7 @@ impl State {
} }
KeyCode::Enter => { KeyCode::Enter => {
// TODO add to command history // TODO add to command history
let result = self.execute_command(&state.buf); let result = self.queue_command(&state.buf);
let error = result.err(); let error = result.err();
self.mode = Mode::Normal(NormalState { error }); self.mode = Mode::Normal(NormalState { error });
return; return;
@ -325,7 +327,7 @@ impl State {
} }
fn write_buffer(&mut self, file: OsString) -> Result<()> { fn write_buffer(&mut self, file: OsString) -> Result<()> {
let out = self.buffer.text.bytes().collect::<Vec<u8>>(); let out = self.buffer.as_ref().bytes().collect::<Vec<u8>>();
let mut handle = OpenOptions::new().write(true).open(file)?; let mut handle = OpenOptions::new().write(true).open(file)?;
handle.write_all(out.as_slice())?; handle.write_all(out.as_slice())?;
@ -347,7 +349,7 @@ impl State {
self.write_buffer(handle).map_err(|err| format!("{}", err)) self.write_buffer(handle).map_err(|err| format!("{}", err))
} }
fn execute_command(&mut self, command: &str) -> std::result::Result<(), String> { fn queue_command(&mut self, command: &str) -> std::result::Result<(), String> {
let command_parts = command.split(' ').collect::<Vec<&str>>(); let command_parts = command.split(' ').collect::<Vec<&str>>();
let command = match command_parts.get(0) { let command = match command_parts.get(0) {
@ -364,9 +366,16 @@ impl State {
self.write_command(command, args)?; self.write_command(command, args)?;
self.quit = true; self.quit = true;
} }
command => { command => match command.parse::<usize>() {
return Err(format!("{}: Unrecognized command.", command)); 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(()) Ok(())
@ -374,7 +383,10 @@ impl State {
fn move_cursor(&mut self, direction: Direction) { fn move_cursor(&mut self, direction: Direction) {
self.buffer.move_cursor(&mut self.cursor, direction, true); self.buffer.move_cursor(&mut self.cursor, direction, true);
self.scroll_to_cursor();
}
fn scroll_to_cursor(&mut self) {
if self.cursor.column < self.scroll.column + 3 { if self.cursor.column < self.scroll.column + 3 {
self.scroll.column = self.cursor.column.saturating_sub(3); self.scroll.column = self.cursor.column.saturating_sub(3);
} else if self.cursor.column + 6 >= self.scroll.column + self.size.0 { } else if self.cursor.column + 6 >= self.scroll.column + self.size.0 {
@ -447,9 +459,9 @@ fn main() -> Result<()> {
let state = State::from_str(file_name, &text)?; let state = State::from_str(file_name, &text)?;
let mut stdout = stdout(); let mut stdout = stdout();
terminal::enable_raw_mode()?; terminal::enable_raw_mode()?;
stdout.execute(terminal::EnterAlternateScreen)?; stdout.queue(terminal::EnterAlternateScreen)?;
let result = screen_main(&mut stdout, state); let result = screen_main(&mut stdout, state);
stdout.execute(terminal::LeaveAlternateScreen)?; stdout.queue(terminal::LeaveAlternateScreen)?;
terminal::disable_raw_mode()?; terminal::disable_raw_mode()?;
result result
} }

View File

@ -17,11 +17,11 @@
* along with this program. If not, see https://www.gnu.org/licenses/. * along with this program. If not, see https://www.gnu.org/licenses/.
*/ */
use std::io::Write;
use std::{collections::HashMap, fmt::Display}; use std::{collections::HashMap, fmt::Display};
use crossterm::{style::Color, ExecutableCommand}; use crossterm::style::Color;
use once_cell::sync::Lazy; use crossterm::QueueableCommand;
use syntect::parsing::Scope;
use toml::{map::Map, Value}; use toml::{map::Map, Value};
#[derive(Debug, Default)] #[derive(Debug, Default)]
@ -35,6 +35,9 @@ pub struct StyleStore {
/// Maps named scopes to indices. /// Maps named scopes to indices.
scopes: HashMap<String, usize>, scopes: HashMap<String, usize>,
/// Maps syntect scopes to indices.
syntect_scopes: HashMap<Scope, usize>,
/// The style data store. /// The style data store.
styles: Vec<Style>, styles: Vec<Style>,
} }
@ -46,41 +49,59 @@ impl StyleStore {
theme, theme,
generation: 0, generation: 0,
scopes: HashMap::new(), scopes: HashMap::new(),
syntect_scopes: HashMap::new(),
styles: Vec::new(), styles: Vec::new(),
} }
} }
/// Adds a scope to this store and returns its index. Reuses indices for existing scopes. /// Adds a scope to this store and returns its index. Reuses indices for existing scopes.
pub fn add_scope(&mut self, scope: &str) -> usize { pub fn add_scope(&mut self, scope: &str) -> usize {
let style = self.theme.get_scope_style(scope); if let Some(style_idx) = self.scopes.get(scope) {
*style_idx
if let Some(style_idx) = self.scopes.get(scope).copied() {
let old_style = self
.styles
.get_mut(style_idx)
.expect("StyleStore index is out-of-bounds");
let _ = std::mem::replace(old_style, style);
style_idx
} else { } else {
let style_idx = self.styles.len(); let style_idx = self.styles.len();
let style = self.theme.get_scope_style(scope);
self.styles.push(style); self.styles.push(style);
self.scopes.insert(scope.to_string(), style_idx); self.scopes.insert(scope.to_string(), style_idx);
if let Ok(scope) = Scope::new(scope) {
self.syntect_scopes.insert(scope, style_idx);
}
style_idx style_idx
} }
} }
/// Gets the style for a scope by name. /// Gets the style for a scope by name.
pub fn get_scope(&mut self, scope: &str) -> Style { pub fn get_scope(&mut self, scope: &str) -> &Style {
let idx = self.add_scope(scope); let idx = self.add_scope(scope);
self.get_style(idx) self.get_style(idx)
} }
/// Adds a Syntect [Scope] and returns its index. Resues indices for existing scopes.
pub fn add_syntect_scope(&mut self, scope: &Scope) -> usize {
if let Some(style_idx) = self.syntect_scopes.get(scope) {
*style_idx
} else {
let style_idx = self.styles.len();
let scope_str = scope.build_string();
let style = self.theme.get_scope_style(&scope_str);
self.styles.push(style);
self.scopes.insert(scope_str, style_idx);
self.syntect_scopes.insert(*scope, style_idx);
style_idx
}
}
/// Gets the style for a Syntect [Scope].
pub fn get_syntect_scope(&mut self, scope: &Scope) -> &Style {
let idx = self.add_syntect_scope(scope);
self.get_style(idx)
}
/// Gets the style for a scope index. Panics if out-of-bounds. /// Gets the style for a scope index. Panics if out-of-bounds.
pub fn get_style(&self, index: usize) -> Style { pub fn get_style(&self, index: usize) -> &Style {
self.styles self.styles.get(index).expect("StyleStore is out-of-bounds")
.get(index)
.expect("StyleStore is out-of-bounds")
.to_owned()
} }
/// The current generation of the store. Increments every update. /// The current generation of the store. Increments every update.
@ -110,22 +131,21 @@ pub struct Style {
impl Style { impl Style {
pub fn print_styled( pub fn print_styled(
&self, &self,
out: &mut (impl ExecutableCommand + Write), out: &mut impl QueueableCommand,
content: impl Display, content: impl Display,
) -> crossterm::Result<()> { ) -> crossterm::Result<()> {
use crossterm::style::{ResetColor, SetBackgroundColor, SetForegroundColor}; use crossterm::style::{Print, ResetColor, SetBackgroundColor, SetForegroundColor};
if let Some(fg) = self.fg { if let Some(fg) = self.fg {
out.execute(SetForegroundColor(fg))?; out.queue(SetForegroundColor(fg))?;
} }
if let Some(bg) = self.bg { if let Some(bg) = self.bg {
out.execute(SetBackgroundColor(bg))?; out.queue(SetBackgroundColor(bg))?;
} }
write!(out, "{}", content)?; out.queue(Print(content))?;
out.queue(ResetColor)?;
out.execute(ResetColor)?;
Ok(()) Ok(())
} }