breed/src/buffer.rs

358 lines
11 KiB
Rust

/*
* 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
* 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::io::Write;
use std::sync::Arc;
use crossterm::{cursor, QueueableCommand};
use parking_lot::Mutex;
use ropey::{Rope, RopeSlice};
use syntect::easy::ScopeRangeIterator;
use syntect::parsing::{BasicScopeStackOp, ParseState, ScopeStack, SyntaxSet};
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>>,
text: Rope,
syntax_set: Arc<SyntaxSet>,
parser: ParseState,
style_dirty: bool,
style_generation: usize,
styled: Vec<StyledString>,
}
impl AsRef<Rope> for Buffer {
fn as_ref(&self) -> &Rope {
&self.text
}
}
impl Buffer {
pub fn from_str(styles: Arc<Mutex<StyleStore>>, text: &str) -> Self {
let syntax_set = SyntaxSet::load_defaults_nonewlines();
// TODO load non-Rust syntax highlighting
let syntax_ref = syntax_set.find_syntax_by_extension("rs").unwrap();
let parser = ParseState::new(syntax_ref);
let mut buf = Self {
styles,
text: Rope::from_str(text),
syntax_set: Arc::new(SyntaxSet::load_defaults_newlines()),
parser,
style_dirty: true,
style_generation: 0,
styled: Vec::new(),
};
buf.parse();
buf
}
pub fn draw(
&mut self,
cols: u16,
rows: u16,
scroll: Cursor,
cursor: Cursor,
out: &mut impl Write,
) -> crossterm::Result<u32> {
self.parse();
let mut styles = self.styles.lock();
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))?;
for (row, line) in self.text.lines_at(scroll.line).enumerate() {
if row == rows as usize {
break;
}
let linenr = row as usize + scroll.line;
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],
};
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_char(&mut self, cursor: Cursor) {
let index = self.cursor_to_char(cursor);
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) {
let index = self.cursor_to_char(cursor);
self.text.insert_char(index, c);
self.style_dirty = true;
}
fn parse(&mut self) {
use std::fmt::Write;
let mut styles = self.styles.lock();
if styles.generation() == self.style_generation && !self.style_dirty {
return;
}
self.styled.clear();
let mut parser = self.parser.clone();
let mut line_buf = String::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() {
// display line to a pre-allocated buffer for fast parsing
line_buf.clear();
write!(line_buf, "{}", line).unwrap();
let end = line_buf.trim_end().len();
line_buf.truncate(end);
// parse the line into a sequence of stack operations
let stack_ops = parser.parse_line(&line_buf, &self.syntax_set).unwrap();
// queue the operations on the stack
let range_iter = ScopeRangeIterator::new(&stack_ops, &line_buf);
styled_buf.clear();
for (range, op) in range_iter {
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 {
continue;
}
let len = range.end - range.start;
let style = style_stack.last().cloned().unwrap_or_default();
styled_buf.push((len, style));
}
let line = StyledString {
content: line.to_string(),
styles: styled_buf.clone(),
};
self.styled.push(line);
}
self.style_dirty = false;
self.style_generation = styles.generation();
}
pub fn clamped_cursor(&self, cursor: Cursor) -> Cursor {
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,
column: cursor.column.min(line_end),
}
}
pub fn cursor_to_char(&self, cursor: Cursor) -> usize {
let cursor = self.clamped_cursor(cursor);
self.text.line_to_char(cursor.line) + cursor.column
}
pub fn move_cursor(&self, cursor: &mut Cursor, direction: Direction, enable_linewrap: bool) {
*cursor = self.clamped_cursor(*cursor);
match direction {
Direction::Left => {
if cursor.column > 0 {
cursor.column -= 1;
} else if enable_linewrap && cursor.line > 0 {
cursor.line -= 1;
let line = self.text.line(cursor.line);
cursor.column = line.len_chars() - 1;
}
}
Direction::Down => {
if cursor.line + 1 < self.text.len_lines() {
cursor.line += 1;
}
}
Direction::Up => {
if cursor.line > 0 {
cursor.line -= 1;
}
}
Direction::Right => {
let line = self.text.line(cursor.line);
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)]
mod tests {
use super::*;
#[test]
fn style_scopes() {
let text = include_str!("buffer.rs");
let mut buffer = Buffer::from_str(Default::default(), text);
buffer.parse();
println!("{:#?}", buffer.styled);
}
}