feat: first take at milestone M3

This commit is contained in:
2026-04-05 16:28:59 +02:00
parent 118633de81
commit b755c6bcbc
27 changed files with 5372 additions and 134 deletions

View File

@@ -1,12 +1,44 @@
use ropey::Rope;
/// Rope-based text buffer with edit operations and cursor management.
use crate::history::{EditAction, UndoHistory};
/// Selection anchor and head (cursor). Both are (line, col) positions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Selection {
pub anchor_line: usize,
pub anchor_col: usize,
pub head_line: usize,
pub head_col: usize,
}
impl Selection {
/// Returns (start, end) as (line, col) pairs in document order.
pub fn ordered(&self) -> ((usize, usize), (usize, usize)) {
let a = (self.anchor_line, self.anchor_col);
let h = (self.head_line, self.head_col);
if a <= h { (a, h) } else { (h, a) }
}
pub fn is_empty(&self) -> bool {
self.anchor_line == self.head_line && self.anchor_col == self.head_col
}
}
/// Rope-based text buffer with edit operations, cursor, selection, and undo/redo.
pub struct EditorBuffer {
rope: Rope,
cursor_line: usize,
cursor_col: usize,
/// Vertical scroll offset in lines.
scroll_offset: usize,
/// Selection state (None = no selection).
selection: Option<Selection>,
/// Undo/redo history.
history: UndoHistory,
/// Whether the buffer has been modified since last save/checkpoint.
dirty: bool,
/// Soft wrap enabled.
soft_wrap: bool,
}
impl EditorBuffer {
@@ -16,6 +48,10 @@ impl EditorBuffer {
cursor_line: 0,
cursor_col: 0,
scroll_offset: 0,
selection: None,
history: UndoHistory::new(),
dirty: false,
soft_wrap: false,
}
}
@@ -47,16 +83,108 @@ impl EditorBuffer {
self.scroll_offset
}
pub fn selection(&self) -> Option<&Selection> {
self.selection.as_ref()
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
pub fn set_dirty(&mut self, dirty: bool) {
self.dirty = dirty;
}
pub fn soft_wrap(&self) -> bool {
self.soft_wrap
}
pub fn set_soft_wrap(&mut self, wrap: bool) {
self.soft_wrap = wrap;
}
pub fn set_cursor(&mut self, line: usize, col: usize) {
self.cursor_line = line.min(self.line_count().saturating_sub(1));
let line_len = self.current_line_len();
self.cursor_col = col.min(line_len);
}
/// Insert text at the current cursor position.
/// Clear the current selection.
pub fn clear_selection(&mut self) {
self.selection = None;
}
/// Start or extend a selection from the current cursor to the new cursor position.
fn extend_selection(&mut self, new_line: usize, new_col: usize) {
let sel = self.selection.get_or_insert(Selection {
anchor_line: self.cursor_line,
anchor_col: self.cursor_col,
head_line: self.cursor_line,
head_col: self.cursor_col,
});
sel.head_line = new_line;
sel.head_col = new_col;
}
/// Set selection explicitly (for double-click word select, etc).
pub fn set_selection(&mut self, anchor_line: usize, anchor_col: usize, head_line: usize, head_col: usize) {
self.selection = Some(Selection {
anchor_line,
anchor_col,
head_line,
head_col,
});
}
/// Get the selected text, or empty string if no selection.
pub fn selected_text(&self) -> String {
match &self.selection {
None => String::new(),
Some(sel) if sel.is_empty() => String::new(),
Some(sel) => {
let (start, end) = sel.ordered();
let start_idx = self.pos_to_char_idx(start.0, start.1);
let end_idx = self.pos_to_char_idx(end.0, end.1);
self.rope.slice(start_idx..end_idx).to_string()
}
}
}
/// Delete the selected text and place cursor at start of selection.
/// Returns the deleted text.
pub fn delete_selection(&mut self) -> String {
let sel = match self.selection.take() {
Some(s) if !s.is_empty() => s,
_ => return String::new(),
};
let (start, end) = sel.ordered();
let start_idx = self.pos_to_char_idx(start.0, start.1);
let end_idx = self.pos_to_char_idx(end.0, end.1);
let deleted: String = self.rope.slice(start_idx..end_idx).to_string();
self.history.push(EditAction::Delete {
pos: start_idx,
text: deleted.clone(),
});
self.rope.remove(start_idx..end_idx);
self.cursor_line = start.0;
self.cursor_col = start.1;
self.dirty = true;
deleted
}
/// Insert text at the current cursor position. Deletes selection first if any.
pub fn insert(&mut self, text: &str) {
if self.selection.is_some() && self.selection.as_ref().map_or(false, |s| !s.is_empty()) {
self.delete_selection();
}
let char_idx = self.cursor_char_idx();
self.rope.insert(char_idx, text);
self.history.push(EditAction::Insert {
pos: char_idx,
text: text.to_string(),
});
for c in text.chars() {
if c == '\n' {
self.cursor_line += 1;
@@ -65,85 +193,298 @@ impl EditorBuffer {
self.cursor_col += 1;
}
}
self.dirty = true;
}
/// Delete one character before the cursor (backspace).
pub fn backspace(&mut self) {
if self.selection.as_ref().map_or(false, |s| !s.is_empty()) {
self.delete_selection();
return;
}
if self.cursor_col > 0 {
let char_idx = self.cursor_char_idx();
let deleted: String = self.rope.slice(char_idx - 1..char_idx).to_string();
self.history.push(EditAction::Delete {
pos: char_idx - 1,
text: deleted,
});
self.rope.remove(char_idx - 1..char_idx);
self.cursor_col -= 1;
self.dirty = true;
} else if self.cursor_line > 0 {
let prev_line_len = self
.rope
.line(self.cursor_line - 1)
.len_chars()
.saturating_sub(1);
let prev_line_len = self.line_len(self.cursor_line - 1);
let char_idx = self.cursor_char_idx();
let deleted: String = self.rope.slice(char_idx - 1..char_idx).to_string();
self.history.push(EditAction::Delete {
pos: char_idx - 1,
text: deleted,
});
self.rope.remove(char_idx - 1..char_idx);
self.cursor_line -= 1;
self.cursor_col = prev_line_len;
self.dirty = true;
}
}
/// Delete one character after the cursor (delete key).
pub fn delete_forward(&mut self) {
if self.selection.as_ref().map_or(false, |s| !s.is_empty()) {
self.delete_selection();
return;
}
let char_idx = self.cursor_char_idx();
if char_idx < self.rope.len_chars() {
let deleted: String = self.rope.slice(char_idx..char_idx + 1).to_string();
self.history.push(EditAction::Delete {
pos: char_idx,
text: deleted,
});
self.rope.remove(char_idx..char_idx + 1);
self.dirty = true;
}
}
/// Move cursor up one line.
// ── Cursor movement ──────────────────────────────────────
pub fn move_up(&mut self) {
if self.cursor_line > 0 {
self.cursor_line -= 1;
let line_len = self.current_line_len();
self.cursor_col = self.cursor_col.min(line_len);
}
self.clear_selection();
self.move_up_inner();
}
/// Move cursor down one line.
pub fn move_down(&mut self) {
if self.cursor_line + 1 < self.line_count() {
self.cursor_line += 1;
let line_len = self.current_line_len();
self.cursor_col = self.cursor_col.min(line_len);
}
self.clear_selection();
self.move_down_inner();
}
/// Move cursor left one character.
pub fn move_left(&mut self) {
if self.cursor_col > 0 {
self.cursor_col -= 1;
} else if self.cursor_line > 0 {
self.cursor_line -= 1;
self.cursor_col = self.current_line_len();
}
self.clear_selection();
self.move_left_inner();
}
/// Move cursor right one character.
pub fn move_right(&mut self) {
let line_len = self.current_line_len();
if self.cursor_col < line_len {
self.cursor_col += 1;
} else if self.cursor_line + 1 < self.line_count() {
self.cursor_line += 1;
self.cursor_col = 0;
}
self.clear_selection();
self.move_right_inner();
}
/// Move cursor to start of line.
pub fn move_home(&mut self) {
self.clear_selection();
self.cursor_col = 0;
}
/// Move cursor to end of line.
pub fn move_end(&mut self) {
self.clear_selection();
self.cursor_col = self.current_line_len();
}
/// Scroll so the cursor is visible within the given viewport height (in lines).
/// Move cursor to start of previous word.
pub fn move_word_left(&mut self) {
self.clear_selection();
self.move_word_left_inner();
}
/// Move cursor to end of next word.
pub fn move_word_right(&mut self) {
self.clear_selection();
self.move_word_right_inner();
}
/// Move cursor up by a page (viewport height).
pub fn move_page_up(&mut self, page_lines: usize) {
self.clear_selection();
let target = self.cursor_line.saturating_sub(page_lines);
self.cursor_line = target;
let line_len = self.current_line_len();
self.cursor_col = self.cursor_col.min(line_len);
}
/// Move cursor down by a page (viewport height).
pub fn move_page_down(&mut self, page_lines: usize) {
self.clear_selection();
let max_line = self.line_count().saturating_sub(1);
let target = (self.cursor_line + page_lines).min(max_line);
self.cursor_line = target;
let line_len = self.current_line_len();
self.cursor_col = self.cursor_col.min(line_len);
}
// ── Selection movement ───────────────────────────────────
pub fn select_up(&mut self) {
let (new_line, new_col) = self.calc_up();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_down(&mut self) {
let (new_line, new_col) = self.calc_down();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_left(&mut self) {
let (new_line, new_col) = self.calc_left();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_right(&mut self) {
let (new_line, new_col) = self.calc_right();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_home(&mut self) {
self.extend_selection(self.cursor_line, 0);
self.cursor_col = 0;
}
pub fn select_end(&mut self) {
let end = self.current_line_len();
self.extend_selection(self.cursor_line, end);
self.cursor_col = end;
}
pub fn select_word_left(&mut self) {
let (new_line, new_col) = self.calc_word_left();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_word_right(&mut self) {
let (new_line, new_col) = self.calc_word_right();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_page_up(&mut self, page_lines: usize) {
let target = self.cursor_line.saturating_sub(page_lines);
let col = self.cursor_col.min(self.line_len(target));
self.extend_selection(target, col);
self.cursor_line = target;
self.cursor_col = col;
}
pub fn select_page_down(&mut self, page_lines: usize) {
let max_line = self.line_count().saturating_sub(1);
let target = (self.cursor_line + page_lines).min(max_line);
let col = self.cursor_col.min(self.line_len(target));
self.extend_selection(target, col);
self.cursor_line = target;
self.cursor_col = col;
}
/// Select all text.
pub fn select_all(&mut self) {
let last_line = self.line_count().saturating_sub(1);
let last_col = self.line_len(last_line);
self.selection = Some(Selection {
anchor_line: 0,
anchor_col: 0,
head_line: last_line,
head_col: last_col,
});
self.cursor_line = last_line;
self.cursor_col = last_col;
}
/// Select the word at the given position (double-click).
pub fn select_word_at(&mut self, line: usize, col: usize) {
self.set_cursor(line, col);
let line_text = match self.line(self.cursor_line) {
Some(l) => {
let s: String = l.chars().collect();
s.trim_end_matches('\n').to_string()
}
None => return,
};
if line_text.is_empty() {
return;
}
let col = self.cursor_col.min(line_text.len());
let chars: Vec<char> = line_text.chars().collect();
// Find word boundaries
let mut start = col;
while start > 0 && is_word_char(chars[start - 1]) {
start -= 1;
}
let mut end = col;
while end < chars.len() && is_word_char(chars[end]) {
end += 1;
}
if start == end && col < chars.len() {
// Click on non-word char: select just that character
end = col + 1;
start = col;
}
self.set_selection(self.cursor_line, start, self.cursor_line, end);
self.cursor_col = end;
}
// ── Undo/Redo ────────────────────────────────────────────
pub fn undo(&mut self) {
if let Some(action) = self.history.undo() {
match action {
EditAction::Insert { pos, text } => {
let end = pos + text.chars().count();
self.rope.remove(pos..end);
let (line, col) = self.char_idx_to_pos(pos);
self.cursor_line = line;
self.cursor_col = col;
}
EditAction::Delete { pos, text } => {
self.rope.insert(pos, &text);
let end_pos = pos + text.chars().count();
let (line, col) = self.char_idx_to_pos(end_pos);
self.cursor_line = line;
self.cursor_col = col;
}
}
self.clear_selection();
self.dirty = true;
}
}
pub fn redo(&mut self) {
if let Some(action) = self.history.redo() {
match action {
EditAction::Insert { pos, text } => {
self.rope.insert(pos, &text);
let end_pos = pos + text.chars().count();
let (line, col) = self.char_idx_to_pos(end_pos);
self.cursor_line = line;
self.cursor_col = col;
}
EditAction::Delete { pos, text } => {
let end = pos + text.chars().count();
self.rope.remove(pos..end);
let (line, col) = self.char_idx_to_pos(pos);
self.cursor_line = line;
self.cursor_col = col;
}
}
self.clear_selection();
self.dirty = true;
}
}
/// Mark an undo group boundary (e.g. after each keystroke pause).
pub fn mark_undo_group(&mut self) {
self.history.mark_group();
}
// ── Scrolling ────────────────────────────────────────────
pub fn ensure_cursor_visible(&mut self, visible_lines: usize) {
if visible_lines == 0 {
return;
@@ -155,7 +496,6 @@ impl EditorBuffer {
}
}
/// Scroll by a delta (positive = down, negative = up).
pub fn scroll_by(&mut self, delta: isize) {
let max_scroll = self.line_count().saturating_sub(1);
if delta < 0 {
@@ -165,16 +505,39 @@ impl EditorBuffer {
}
}
// ── Internal helpers ─────────────────────────────────────
fn cursor_char_idx(&self) -> usize {
let line_start = self.rope.line_to_char(self.cursor_line);
line_start + self.cursor_col
self.pos_to_char_idx(self.cursor_line, self.cursor_col)
}
fn pos_to_char_idx(&self, line: usize, col: usize) -> usize {
if line >= self.rope.len_lines() {
self.rope.len_chars()
} else {
let line_start = self.rope.line_to_char(line);
let line_len = self.line_len(line);
line_start + col.min(line_len)
}
}
fn char_idx_to_pos(&self, idx: usize) -> (usize, usize) {
let idx = idx.min(self.rope.len_chars());
let line = self.rope.char_to_line(idx);
let line_start = self.rope.line_to_char(line);
let col = idx - line_start;
(line, col)
}
fn current_line_len(&self) -> usize {
if self.cursor_line < self.rope.len_lines() {
let line = self.rope.line(self.cursor_line);
let len = line.len_chars();
if len > 0 && line.char(len - 1) == '\n' {
self.line_len(self.cursor_line)
}
fn line_len(&self, line: usize) -> usize {
if line < self.rope.len_lines() {
let l = self.rope.line(line);
let len = l.len_chars();
if len > 0 && l.char(len - 1) == '\n' {
len - 1
} else {
len
@@ -183,6 +546,146 @@ impl EditorBuffer {
0
}
}
// ── Movement calculation helpers (no selection changes) ──
fn move_up_inner(&mut self) {
let (line, col) = self.calc_up();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_down_inner(&mut self) {
let (line, col) = self.calc_down();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_left_inner(&mut self) {
let (line, col) = self.calc_left();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_right_inner(&mut self) {
let (line, col) = self.calc_right();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_word_left_inner(&mut self) {
let (line, col) = self.calc_word_left();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_word_right_inner(&mut self) {
let (line, col) = self.calc_word_right();
self.cursor_line = line;
self.cursor_col = col;
}
fn calc_up(&self) -> (usize, usize) {
if self.cursor_line > 0 {
let new_line = self.cursor_line - 1;
let new_col = self.cursor_col.min(self.line_len(new_line));
(new_line, new_col)
} else {
(self.cursor_line, self.cursor_col)
}
}
fn calc_down(&self) -> (usize, usize) {
if self.cursor_line + 1 < self.line_count() {
let new_line = self.cursor_line + 1;
let new_col = self.cursor_col.min(self.line_len(new_line));
(new_line, new_col)
} else {
(self.cursor_line, self.cursor_col)
}
}
fn calc_left(&self) -> (usize, usize) {
if self.cursor_col > 0 {
(self.cursor_line, self.cursor_col - 1)
} else if self.cursor_line > 0 {
let new_line = self.cursor_line - 1;
(new_line, self.line_len(new_line))
} else {
(0, 0)
}
}
fn calc_right(&self) -> (usize, usize) {
let line_len = self.current_line_len();
if self.cursor_col < line_len {
(self.cursor_line, self.cursor_col + 1)
} else if self.cursor_line + 1 < self.line_count() {
(self.cursor_line + 1, 0)
} else {
(self.cursor_line, self.cursor_col)
}
}
fn calc_word_left(&self) -> (usize, usize) {
if self.cursor_col == 0 && self.cursor_line == 0 {
return (0, 0);
}
if self.cursor_col == 0 {
let new_line = self.cursor_line - 1;
return (new_line, self.line_len(new_line));
}
let line_text = match self.line(self.cursor_line) {
Some(l) => {
let s: String = l.chars().collect();
s.trim_end_matches('\n').to_string()
}
None => return (self.cursor_line, 0),
};
let chars: Vec<char> = line_text.chars().collect();
let mut col = self.cursor_col.min(chars.len());
// Skip spaces
while col > 0 && !is_word_char(chars[col - 1]) {
col -= 1;
}
// Skip word chars
while col > 0 && is_word_char(chars[col - 1]) {
col -= 1;
}
(self.cursor_line, col)
}
fn calc_word_right(&self) -> (usize, usize) {
let line_len = self.current_line_len();
if self.cursor_col >= line_len {
if self.cursor_line + 1 < self.line_count() {
return (self.cursor_line + 1, 0);
}
return (self.cursor_line, self.cursor_col);
}
let line_text = match self.line(self.cursor_line) {
Some(l) => {
let s: String = l.chars().collect();
s.trim_end_matches('\n').to_string()
}
None => return (self.cursor_line, self.cursor_col),
};
let chars: Vec<char> = line_text.chars().collect();
let mut col = self.cursor_col;
// Skip word chars
while col < chars.len() && is_word_char(chars[col]) {
col += 1;
}
// Skip spaces
while col < chars.len() && !is_word_char(chars[col]) {
col += 1;
}
(self.cursor_line, col)
}
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
#[cfg(test)]
@@ -265,7 +768,7 @@ mod tests {
assert_eq!(buf.cursor(), (1, 1));
buf.move_up();
assert_eq!(buf.cursor(), (0, 1));
buf.move_up(); // at top, no-op
buf.move_up();
assert_eq!(buf.cursor(), (0, 1));
}
@@ -277,7 +780,7 @@ mod tests {
assert_eq!(buf.cursor(), (1, 1));
buf.move_down();
assert_eq!(buf.cursor(), (2, 1));
buf.move_down(); // at bottom, no-op
buf.move_down();
assert_eq!(buf.cursor(), (2, 1));
}
@@ -286,7 +789,7 @@ mod tests {
let mut buf = EditorBuffer::new("long line\nhi");
buf.set_cursor(0, 9);
buf.move_down();
assert_eq!(buf.cursor(), (1, 2)); // "hi" is only 2 chars
assert_eq!(buf.cursor(), (1, 2));
}
#[test]
@@ -325,12 +828,127 @@ mod tests {
assert_eq!(buf.cursor(), (0, 11));
}
#[test]
fn word_movement() {
let mut buf = EditorBuffer::new("hello world test");
buf.set_cursor(0, 0);
buf.move_word_right();
assert_eq!(buf.cursor(), (0, 6)); // after "hello "
buf.move_word_right();
assert_eq!(buf.cursor(), (0, 13)); // after "world "
buf.move_word_left();
assert_eq!(buf.cursor(), (0, 6)); // back to "world"
buf.move_word_left();
assert_eq!(buf.cursor(), (0, 0)); // back to start
}
#[test]
fn page_movement() {
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne\nf\ng\nh\ni\nj");
buf.set_cursor(0, 0);
buf.move_page_down(5);
assert_eq!(buf.cursor(), (5, 0));
buf.move_page_up(3);
assert_eq!(buf.cursor(), (2, 0));
}
#[test]
fn selection_shift_right() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 0);
buf.select_right();
buf.select_right();
buf.select_right();
assert_eq!(buf.selected_text(), "hel");
}
#[test]
fn selection_delete() {
let mut buf = EditorBuffer::new("hello world");
buf.set_cursor(0, 0);
buf.select_right();
buf.select_right();
buf.select_right();
buf.select_right();
buf.select_right();
let deleted = buf.delete_selection();
assert_eq!(deleted, "hello");
assert_eq!(buf.text(), " world");
}
#[test]
fn select_word_at() {
let mut buf = EditorBuffer::new("hello world");
buf.select_word_at(0, 3); // inside "hello"
assert_eq!(buf.selected_text(), "hello");
}
#[test]
fn select_all() {
let mut buf = EditorBuffer::new("hello\nworld");
buf.select_all();
assert_eq!(buf.selected_text(), "hello\nworld");
}
#[test]
fn undo_insert() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 5);
buf.insert(" world");
assert_eq!(buf.text(), "hello world");
buf.undo();
assert_eq!(buf.text(), "hello");
}
#[test]
fn redo_insert() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 5);
buf.insert(" world");
buf.undo();
buf.redo();
assert_eq!(buf.text(), "hello world");
}
#[test]
fn undo_backspace() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 5);
buf.backspace();
assert_eq!(buf.text(), "hell");
buf.undo();
assert_eq!(buf.text(), "hello");
}
#[test]
fn insert_replaces_selection() {
let mut buf = EditorBuffer::new("hello world");
buf.set_cursor(0, 0);
buf.select_right();
buf.select_right();
buf.select_right();
buf.select_right();
buf.select_right();
buf.insert("hi");
assert_eq!(buf.text(), "hi world");
}
#[test]
fn dirty_tracking() {
let mut buf = EditorBuffer::new("hello");
assert!(!buf.is_dirty());
buf.insert("x");
assert!(buf.is_dirty());
buf.set_dirty(false);
assert!(!buf.is_dirty());
}
#[test]
fn scroll_ensures_cursor_visible() {
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne\nf\ng\nh\ni\nj");
buf.set_cursor(8, 0); // line 8
buf.ensure_cursor_visible(5); // viewport shows 5 lines
assert_eq!(buf.scroll_offset(), 4); // scroll so line 8 is visible
buf.set_cursor(8, 0);
buf.ensure_cursor_visible(5);
assert_eq!(buf.scroll_offset(), 4);
}
#[test]

View File

@@ -1,11 +1,15 @@
use std::collections::HashMap;
use syntect::highlighting::{Style, ThemeSet};
use syntect::parsing::{SyntaxReference, SyntaxSet};
/// Syntax highlighter using syntect.
/// Syntax highlighter using syntect with line-level caching.
pub struct Highlighter {
syntax_set: SyntaxSet,
theme_set: ThemeSet,
theme_name: String,
/// Extension aliases (e.g. "liquid" → "html")
extension_aliases: HashMap<String, String>,
}
/// A line of highlighted text: spans of (style, text).
@@ -13,17 +17,29 @@ pub type HighlightedLine = Vec<(Style, String)>;
impl Highlighter {
pub fn new() -> Self {
let mut extension_aliases = HashMap::new();
// Liquid templates use HTML syntax highlighting
extension_aliases.insert("liquid".into(), "html".into());
extension_aliases.insert("njk".into(), "html".into());
Self {
syntax_set: SyntaxSet::load_defaults_newlines(),
theme_set: ThemeSet::load_defaults(),
theme_name: "base16-ocean.dark".to_string(),
extension_aliases,
}
}
/// Find the syntax definition for a file extension.
/// Resolves aliases (e.g. liquid → html) before lookup.
pub fn syntax_for_extension(&self, ext: &str) -> &SyntaxReference {
let resolved = self
.extension_aliases
.get(ext)
.map(|s| s.as_str())
.unwrap_or(ext);
self.syntax_set
.find_syntax_by_extension(ext)
.find_syntax_by_extension(resolved)
.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text())
}
@@ -49,6 +65,43 @@ impl Highlighter {
result
}
/// Highlight only a visible range of lines (start..start+count) for a given text.
/// Re-parses from the beginning to maintain correct parse state, but only
/// collects highlight output for the visible window.
pub fn highlight_visible_range(
&self,
text: &str,
syntax: &SyntaxReference,
start: usize,
count: usize,
) -> Vec<HighlightedLine> {
use syntect::easy::HighlightLines;
let theme = &self.theme_set.themes[&self.theme_name];
let mut h = HighlightLines::new(syntax, theme);
let mut result = Vec::new();
let end = start + count;
for (idx, line) in text.lines().enumerate() {
let line_with_newline = format!("{line}\n");
let ranges = h
.highlight_line(&line_with_newline, &self.syntax_set)
.unwrap_or_default();
if idx >= start && idx < end {
let styled: HighlightedLine = ranges
.into_iter()
.map(|(style, text)| (style, text.to_string()))
.collect();
result.push(styled);
}
if idx >= end {
break;
}
}
result
}
}
impl Default for Highlighter {
@@ -78,4 +131,42 @@ mod tests {
let lines = h.highlight_lines("hello", syntax);
assert_eq!(lines.len(), 1);
}
#[test]
fn liquid_uses_html_syntax() {
let h = Highlighter::new();
let liquid_syntax = h.syntax_for_extension("liquid");
let html_syntax = h.syntax_for_extension("html");
assert_eq!(liquid_syntax.name, html_syntax.name);
}
#[test]
fn json_syntax_available() {
let h = Highlighter::new();
let syntax = h.syntax_for_extension("json");
assert_ne!(syntax.name, "Plain Text");
}
#[test]
fn yaml_syntax_available() {
let h = Highlighter::new();
let syntax = h.syntax_for_extension("yaml");
assert_ne!(syntax.name, "Plain Text");
}
#[test]
fn lua_syntax_available() {
let h = Highlighter::new();
let syntax = h.syntax_for_extension("lua");
assert_ne!(syntax.name, "Plain Text");
}
#[test]
fn highlight_visible_range_returns_subset() {
let h = Highlighter::new();
let syntax = h.syntax_for_extension("md");
let text = "# Line 1\nLine 2\nLine 3\nLine 4\nLine 5";
let visible = h.highlight_visible_range(text, syntax, 1, 2);
assert_eq!(visible.len(), 2);
}
}

View File

@@ -0,0 +1,115 @@
/// A single edit action that can be undone/redone.
#[derive(Debug, Clone)]
pub enum EditAction {
Insert { pos: usize, text: String },
Delete { pos: usize, text: String },
}
/// Undo/redo history with edit grouping support.
pub struct UndoHistory {
undo_stack: Vec<EditAction>,
redo_stack: Vec<EditAction>,
/// Group boundary marker: index in undo_stack where last group ended.
last_group_boundary: usize,
}
impl UndoHistory {
pub fn new() -> Self {
Self {
undo_stack: Vec::new(),
redo_stack: Vec::new(),
last_group_boundary: 0,
}
}
/// Push an edit action onto the undo stack. Clears redo stack.
pub fn push(&mut self, action: EditAction) {
self.undo_stack.push(action);
self.redo_stack.clear();
}
/// Mark a group boundary (e.g. after a pause in typing).
pub fn mark_group(&mut self) {
self.last_group_boundary = self.undo_stack.len();
}
/// Pop a single undo action.
pub fn undo(&mut self) -> Option<EditAction> {
let action = self.undo_stack.pop()?;
self.redo_stack.push(action.clone());
if self.last_group_boundary > self.undo_stack.len() {
self.last_group_boundary = self.undo_stack.len();
}
Some(action)
}
/// Pop a single redo action.
pub fn redo(&mut self) -> Option<EditAction> {
let action = self.redo_stack.pop()?;
self.undo_stack.push(action.clone());
Some(action)
}
pub fn can_undo(&self) -> bool {
!self.undo_stack.is_empty()
}
pub fn can_redo(&self) -> bool {
!self.redo_stack.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_and_undo() {
let mut h = UndoHistory::new();
h.push(EditAction::Insert {
pos: 0,
text: "hello".into(),
});
assert!(h.can_undo());
let action = h.undo().unwrap();
match action {
EditAction::Insert { pos, text } => {
assert_eq!(pos, 0);
assert_eq!(text, "hello");
}
_ => panic!("Expected Insert"),
}
assert!(!h.can_undo());
}
#[test]
fn undo_redo_cycle() {
let mut h = UndoHistory::new();
h.push(EditAction::Insert {
pos: 0,
text: "a".into(),
});
h.undo();
assert!(h.can_redo());
let action = h.redo().unwrap();
match action {
EditAction::Insert { text, .. } => assert_eq!(text, "a"),
_ => panic!("Expected Insert"),
}
}
#[test]
fn new_push_clears_redo() {
let mut h = UndoHistory::new();
h.push(EditAction::Insert {
pos: 0,
text: "a".into(),
});
h.undo();
h.push(EditAction::Insert {
pos: 0,
text: "b".into(),
});
assert!(!h.can_redo());
}
}

View File

@@ -1,7 +1,8 @@
mod buffer;
mod highlight;
pub mod history;
mod widget;
pub use buffer::EditorBuffer;
pub use buffer::{EditorBuffer, Selection};
pub use highlight::Highlighter;
pub use widget::{CodeEditor, mono_metrics};
pub use widget::{CodeEditor, EditorMessage, mono_metrics};

View File

@@ -18,12 +18,19 @@ use crate::highlight::Highlighter;
#[derive(Debug, Clone)]
pub enum EditorMessage {
ContentChanged(String),
SaveRequested,
}
/// Persistent widget state across frames.
#[derive(Default)]
struct EditorState {
is_focused: bool,
/// Track drag state for click-and-drag selection
is_dragging: bool,
/// Last click time for double-click detection (ms)
last_click_time: Option<std::time::Instant>,
last_click_line: usize,
last_click_col: usize,
}
/// Font metrics measured via cosmic-text, cached globally.
@@ -60,7 +67,10 @@ pub fn mono_metrics() -> &'static MonoMetrics {
break;
}
MonoMetrics { char_width, line_height }
MonoMetrics {
char_width,
line_height,
}
})
}
@@ -72,11 +82,19 @@ const TEXT_COLOR: Color = Color::from_rgb(0.85, 0.85, 0.85);
const GUTTER_TEXT: Color = Color::from_rgb(0.45, 0.48, 0.55);
const CURSOR_COLOR: Color = Color::from_rgb(0.9, 0.9, 0.2);
const ACTIVE_LINE_NUM: Color = Color::from_rgb(0.75, 0.78, 0.85);
const SELECTION_BG: Color = Color::from_rgba(0.26, 0.54, 0.79, 0.40);
/// Convert syntect RGBA color to Iced Color.
fn syntect_to_iced(c: syntect::highlighting::Color) -> Color {
Color::from_rgba(
c.r as f32 / 255.0,
c.g as f32 / 255.0,
c.b as f32 / 255.0,
c.a as f32 / 255.0,
)
}
/// A syntax-highlighting code editor widget for Iced.
///
/// M0 PoC: renders highlighted text with line numbers, handles keyboard
/// input for basic editing, supports cursor movement and vertical scrolling.
pub struct CodeEditor<'a, Message> {
buffer: &'a mut EditorBuffer,
highlighter: &'a Highlighter,
@@ -142,7 +160,7 @@ where
_viewport: &Rectangle,
) {
let bounds = layout.bounds();
let _state = tree.state.downcast_ref::<EditorState>();
let state = tree.state.downcast_ref::<EditorState>();
// Background
renderer.fill_quad(
@@ -172,6 +190,12 @@ where
let (cursor_line, cursor_col) = self.buffer.cursor();
let scroll = self.buffer.scroll_offset();
let visible_lines = (bounds.height / metrics.line_height) as usize + 1;
let selection = self.buffer.selection();
// Pre-compute highlighted lines for visible range
let syntax = self.highlighter.syntax_for_extension(self.extension);
let full_text = self.buffer.text();
let highlighted = self.highlighter.highlight_lines(&full_text, syntax);
let font = iced::Font::MONOSPACE;
@@ -187,6 +211,54 @@ where
continue;
}
let text_x = bounds.x + GUTTER_WIDTH + 8.0;
// Draw selection highlight for this line
if let Some(sel) = selection {
if !sel.is_empty() {
let (start, end) = sel.ordered();
let line_len = self
.buffer
.line(line_idx)
.map(|l| {
let len = l.len_chars();
if len > 0 && l.char(len - 1) == '\n' {
len - 1
} else {
len
}
})
.unwrap_or(0);
if line_idx >= start.0 && line_idx <= end.0 {
let sel_start_col = if line_idx == start.0 { start.1 } else { 0 };
let sel_end_col = if line_idx == end.0 {
end.1
} else {
line_len + 1
};
let sel_x = text_x + sel_start_col as f32 * metrics.char_width;
let sel_w =
(sel_end_col - sel_start_col) as f32 * metrics.char_width;
if sel_w > 0.0 {
renderer.fill_quad(
renderer::Quad {
bounds: Rectangle {
x: sel_x,
y,
width: sel_w,
height: metrics.line_height,
},
border: iced::Border::default(),
shadow: iced::Shadow::default(),
},
SELECTION_BG,
);
}
}
}
}
// Line number
let line_num = format!("{:>4}", line_idx + 1);
let num_color = if line_idx == cursor_line {
@@ -199,7 +271,9 @@ where
content: line_num,
bounds: Size::new(GUTTER_WIDTH - 8.0, metrics.line_height),
size: Pixels(FONT_SIZE),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(metrics.line_height)),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(
metrics.line_height,
)),
font,
horizontal_alignment: iced::alignment::Horizontal::Right,
vertical_alignment: iced::alignment::Vertical::Top,
@@ -211,21 +285,57 @@ where
bounds,
);
// Line content
if let Some(line) = self.buffer.line(line_idx) {
// Line content with syntax highlighting
if line_idx < highlighted.len() {
let spans = &highlighted[line_idx];
let mut x_off = text_x;
for (style, span_text) in spans {
let mut display_text = span_text.clone();
if display_text.ends_with('\n') {
display_text.pop();
}
if display_text.is_empty() {
continue;
}
let color = syntect_to_iced(style.foreground);
let span_width = display_text.len() as f32 * metrics.char_width;
renderer.fill_text(
text::Text {
content: display_text,
bounds: Size::new(span_width + metrics.char_width, metrics.line_height),
size: Pixels(FONT_SIZE),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(
metrics.line_height,
)),
font,
horizontal_alignment: iced::alignment::Horizontal::Left,
vertical_alignment: iced::alignment::Vertical::Top,
shaping: iced::widget::text::Shaping::Advanced,
wrapping: iced::widget::text::Wrapping::None,
},
Point::new(x_off, y),
color,
bounds,
);
x_off += span_width;
}
} else if let Some(line) = self.buffer.line(line_idx) {
// Fallback: plain text rendering
let mut line_text: String = line.chars().collect();
// Strip trailing newline for display
if line_text.ends_with('\n') {
line_text.pop();
}
let text_x = bounds.x + GUTTER_WIDTH + 8.0;
renderer.fill_text(
text::Text {
content: line_text,
bounds: Size::new(bounds.width - GUTTER_WIDTH - 8.0, metrics.line_height),
bounds: Size::new(
bounds.width - GUTTER_WIDTH - 8.0,
metrics.line_height,
),
size: Pixels(FONT_SIZE),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(metrics.line_height)),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(
metrics.line_height,
)),
font,
horizontal_alignment: iced::alignment::Horizontal::Left,
vertical_alignment: iced::alignment::Vertical::Top,
@@ -236,24 +346,24 @@ where
TEXT_COLOR,
bounds,
);
}
// Draw cursor on current line
if line_idx == cursor_line {
let cursor_x = text_x + cursor_col as f32 * metrics.char_width;
renderer.fill_quad(
renderer::Quad {
bounds: Rectangle {
x: cursor_x,
y,
width: 2.0,
height: metrics.line_height,
},
border: iced::Border::default(),
shadow: iced::Shadow::default(),
// Draw cursor on current line
if line_idx == cursor_line && state.is_focused {
let cursor_x = text_x + cursor_col as f32 * metrics.char_width;
renderer.fill_quad(
renderer::Quad {
bounds: Rectangle {
x: cursor_x,
y,
width: 2.0,
height: metrics.line_height,
},
CURSOR_COLOR,
);
}
border: iced::Border::default(),
shadow: iced::Shadow::default(),
},
CURSOR_COLOR,
);
}
}
}
@@ -265,8 +375,8 @@ where
layout: Layout<'_>,
cursor: mouse::Cursor,
_renderer: &Renderer,
_clipboard: &mut dyn Clipboard,
_shell: &mut Shell<'_, Message>,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
_viewport: &Rectangle,
) -> Status {
let state = tree.state.downcast_mut::<EditorState>();
@@ -277,60 +387,250 @@ where
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
if cursor.is_over(bounds) {
state.is_focused = true;
// Place cursor at click position
state.is_dragging = true;
if let Some(pos) = cursor.position_in(bounds) {
let line = (pos.y / metrics.line_height) as usize + self.buffer.scroll_offset();
let col = ((pos.x - GUTTER_WIDTH - 8.0).max(0.0) / metrics.char_width) as usize;
self.buffer.set_cursor(line, col);
let line = (pos.y / metrics.line_height) as usize
+ self.buffer.scroll_offset();
let col = ((pos.x - GUTTER_WIDTH - 8.0).max(0.0) / metrics.char_width)
as usize;
// Double-click detection
let now = std::time::Instant::now();
let is_double_click = state
.last_click_time
.map(|t| now.duration_since(t).as_millis() < 400)
.unwrap_or(false)
&& state.last_click_line == line
&& (state.last_click_col as isize - col as isize).unsigned_abs() < 3;
if is_double_click {
self.buffer.select_word_at(line, col);
state.last_click_time = None; // reset
} else {
self.buffer.clear_selection();
self.buffer.set_cursor(line, col);
state.last_click_time = Some(now);
state.last_click_line = line;
state.last_click_col = col;
}
}
return Status::Captured;
} else {
state.is_focused = false;
}
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
state.is_dragging = false;
}
Event::Mouse(mouse::Event::CursorMoved { .. }) => {
if state.is_dragging && state.is_focused {
if let Some(pos) = cursor.position_in(bounds) {
let line = (pos.y / metrics.line_height) as usize
+ self.buffer.scroll_offset();
let col = ((pos.x - GUTTER_WIDTH - 8.0).max(0.0) / metrics.char_width)
as usize;
// Extend selection by simulating shift+movement
let clamped_line = line.min(self.buffer.line_count().saturating_sub(1));
let clamped_col = if clamped_line < self.buffer.line_count() {
col.min(
self.buffer
.line(clamped_line)
.map(|l| {
let len = l.len_chars();
if len > 0 && l.char(len - 1) == '\n' {
len - 1
} else {
len
}
})
.unwrap_or(0),
)
} else {
0
};
self.buffer
.set_selection(
self.buffer
.selection()
.map(|s| s.anchor_line)
.unwrap_or(self.buffer.cursor().0),
self.buffer
.selection()
.map(|s| s.anchor_col)
.unwrap_or(self.buffer.cursor().1),
clamped_line,
clamped_col,
);
self.buffer.set_cursor(clamped_line, clamped_col);
}
return Status::Captured;
}
}
Event::Mouse(mouse::Event::WheelScrolled { delta }) if cursor.is_over(bounds) => {
let lines = match delta {
mouse::ScrollDelta::Lines { y, .. } => -(y * 3.0) as isize,
mouse::ScrollDelta::Pixels { y, .. } => -(y / metrics.line_height) as isize,
mouse::ScrollDelta::Pixels { y, .. } => {
-(y / metrics.line_height) as isize
}
};
self.buffer.scroll_by(lines);
return Status::Captured;
}
Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) if state.is_focused => {
Event::Keyboard(keyboard::Event::KeyPressed {
key, modifiers, ..
}) if state.is_focused => {
let vis = (bounds.height / metrics.line_height) as usize;
let is_cmd = modifiers.command();
let is_shift = modifiers.shift();
let is_alt = modifiers.alt();
match key {
// Cmd+Z = undo, Cmd+Shift+Z = redo
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "z" => {
if is_shift {
self.buffer.redo();
} else {
self.buffer.undo();
}
self.emit_change(shell);
}
// Cmd+Y = redo (Windows convention)
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "y" => {
self.buffer.redo();
self.emit_change(shell);
}
// Cmd+A = select all
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "a" => {
self.buffer.select_all();
}
// Cmd+C = copy
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "c" => {
let text = self.buffer.selected_text();
if !text.is_empty() {
clipboard.write(iced::advanced::clipboard::Kind::Standard, text);
}
}
// Cmd+X = cut
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "x" => {
let text = self.buffer.selected_text();
if !text.is_empty() {
clipboard.write(iced::advanced::clipboard::Kind::Standard, text);
self.buffer.delete_selection();
self.emit_change(shell);
}
}
// Cmd+V = paste
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "v" => {
if let Some(text) =
clipboard.read(iced::advanced::clipboard::Kind::Standard)
{
self.buffer.insert(&text);
self.emit_change(shell);
}
}
// Cmd+S = save
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "s" => {
if let Some(ref on_change) = self.on_change {
shell.publish((on_change)(EditorMessage::SaveRequested));
}
}
// Arrow keys with modifiers
keyboard::Key::Named(keyboard::key::Named::ArrowUp) => {
self.buffer.move_up();
let vis = (bounds.height / metrics.line_height) as usize;
if is_shift {
self.buffer.select_up();
} else {
self.buffer.move_up();
}
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::ArrowDown) => {
self.buffer.move_down();
let vis = (bounds.height / metrics.line_height) as usize;
if is_shift {
self.buffer.select_down();
} else {
self.buffer.move_down();
}
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::ArrowLeft) => {
self.buffer.move_left();
if is_shift && is_alt {
self.buffer.select_word_left();
} else if is_shift {
self.buffer.select_left();
} else if is_alt {
self.buffer.move_word_left();
} else {
self.buffer.move_left();
}
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::ArrowRight) => {
self.buffer.move_right();
if is_shift && is_alt {
self.buffer.select_word_right();
} else if is_shift {
self.buffer.select_right();
} else if is_alt {
self.buffer.move_word_right();
} else {
self.buffer.move_right();
}
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::Home) => {
self.buffer.move_home();
if is_shift {
self.buffer.select_home();
} else {
self.buffer.move_home();
}
}
keyboard::Key::Named(keyboard::key::Named::End) => {
self.buffer.move_end();
if is_shift {
self.buffer.select_end();
} else {
self.buffer.move_end();
}
}
keyboard::Key::Named(keyboard::key::Named::PageUp) => {
if is_shift {
self.buffer.select_page_up(vis);
} else {
self.buffer.move_page_up(vis);
}
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::PageDown) => {
if is_shift {
self.buffer.select_page_down(vis);
} else {
self.buffer.move_page_down(vis);
}
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::Backspace) => {
self.buffer.backspace();
if is_alt {
// Option+Backspace = delete word left
self.buffer.select_word_left();
self.buffer.delete_selection();
} else {
self.buffer.backspace();
}
self.emit_change(shell);
}
keyboard::Key::Named(keyboard::key::Named::Delete) => {
self.buffer.delete_forward();
self.emit_change(shell);
}
keyboard::Key::Named(keyboard::key::Named::Enter) => {
self.buffer.insert("\n");
self.emit_change(shell);
}
keyboard::Key::Character(ref c) => {
keyboard::Key::Named(keyboard::key::Named::Tab) => {
self.buffer.insert(" ");
self.emit_change(shell);
}
keyboard::Key::Character(ref c) if !is_cmd => {
self.buffer.insert(c);
self.emit_change(shell);
}
_ => return Status::Ignored,
}
@@ -342,6 +642,15 @@ where
}
}
impl<'a, Message> CodeEditor<'a, Message> {
fn emit_change(&self, shell: &mut Shell<'_, Message>) {
if let Some(ref on_change) = self.on_change {
let text = self.buffer.text();
shell.publish((on_change)(EditorMessage::ContentChanged(text)));
}
}
}
impl<'a, Message, Renderer> From<CodeEditor<'a, Message>> for Element<'a, Message, Theme, Renderer>
where
Renderer: renderer::Renderer + text::Renderer<Font = iced::Font> + 'a,