Damson/src/ui/editor.rs
astar76 65defa1ae3 Damson: a Material You code editor in Rust
Runs Kate's syntax definitions directly, on a hand-written editor core.
Spring-driven UI with a pop-out scrolling preview, baked-in terminal
grown from a morphing button, jelly tabs, command palette, side panels,
git, language servers and hot exit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 17:05:28 -06:00

639 lines
30 KiB
Rust

//! The text surface: gutter, code, selections and carets, all drawn by hand. Scroll position, the
//! current-line bubble and the caret are springs, so nothing here ever jumps.
use super::morph::{self, Morph};
use super::{fonts, widgets::*};
use crate::app::{App, Pane};
use crate::motion::{self, spring, Preset, Spring};
use crate::syntax::Registry;
use crate::text::commands::{Move, Prefs};
use crate::text::{Doc, EditKind, Sel};
use crate::theme::{alpha, Theme};
use eframe::egui::{self, pos2, text::LayoutJob, vec2, Color32, Event, FontId, Key, Modifiers, PointerButton, Pos2, Rect, Sense, TextFormat, Ui};
use std::sync::Arc;
use unicode_width::UnicodeWidthChar;
const CARET: Preset = Preset { stiffness: 1700.0, damping: 0.78 };
const SCROLL: Preset = Preset { stiffness: 520.0, damping: 1.0 };
/// Visual rows, when wrapping or folding make them differ from lines.
#[derive(Default)]
pub struct Rows {
key: (u64, u64, usize, usize),
/// (line, first char column) of each row; `None` means rows and lines are the same.
map: Option<Arc<Vec<(u32, u32)>>>,
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Metrics {
pub cw: f32,
pub lh: f32,
pub font: f32,
}
pub struct Tab {
pub doc: u64,
pub scroll: Spring,
pub scroll_x: f32,
pub caret: [Spring; 2],
pub rows: Rows,
pub beacon: Option<(usize, f64)>,
pub block_anchor: Option<Pos2>,
pub click: (f64, usize, u8),
pub drag_word: Option<std::ops::Range<usize>>,
pub born: f64,
}
impl Tab {
pub fn new(doc: u64, now: f64) -> Tab {
Tab { doc, scroll: Spring::new(0.0), scroll_x: 0.0, caret: [Spring::new(0.0), Spring::new(0.0)], rows: Rows::default(), beacon: None, block_anchor: None, click: (0.0, 0, 0), drag_word: None, born: now }
}
}
pub fn cell_width(c: char, x: usize, tab: usize) -> usize {
if c == '\t' { tab - x % tab } else { c.width().unwrap_or(0).max(if c.is_control() { 0 } else { 1 }) }
}
/// Screen cells before char column `col` of `line`.
pub fn vis_col(line: &str, col: usize, tab: usize) -> usize {
let mut x = 0;
for c in line.chars().take(col) {
x += cell_width(c, x, tab);
}
x
}
/// The char column nearest to `cells` screen cells into `line`.
pub fn col_at(line: &str, cells: f32, tab: usize) -> usize {
let mut x = 0;
for (i, c) in line.chars().enumerate() {
let w = cell_width(c, x, tab);
if (x as f32 + w as f32 / 2.0) > cells {
return i;
}
x += w;
}
line.chars().count()
}
/// Builds the coloured text of part of a line, with tabs opened out into spaces.
pub fn line_job(doc: &Doc, reg: &Registry, t: &Theme, line: usize, cols: (usize, usize), font: &FontId, tab: usize, ws: bool) -> LayoutJob {
let text = doc.buf.line_text(line);
let spans: &[crate::syntax::Span] = doc.hl.get(line).map(|h| h.spans.as_slice()).unwrap_or(&[]);
let mut job = LayoutJob::default();
job.wrap.max_width = f32::INFINITY;
let normal = t.syntax[0];
let (mut si, mut x, mut byte) = (0, 0usize, 0u32);
let mut run = String::new();
let mut cur: Option<(Color32, bool, bool)> = None;
let flush = |job: &mut LayoutJob, run: &mut String, st: Option<(Color32, bool, bool)>| {
if run.is_empty() { return }
let (color, italics, underline) = st.unwrap_or((normal, false, false));
let fmt = TextFormat { font_id: font.clone(), color, italics, underline: if underline { egui::Stroke::new(1.0, color) } else { egui::Stroke::NONE }, ..Default::default() };
job.append(run, 0.0, fmt);
run.clear();
};
for (i, c) in text.chars().enumerate() {
let w = cell_width(c, x, tab);
if i >= cols.0 && i < cols.1 {
while si < spans.len() && spans[si].end <= byte { si += 1 }
let style = spans.get(si).filter(|s| s.start <= byte).and_then(|s| reg.compiled.styles.get(s.style as usize));
let st = match style {
Some(s) => (t.syntax[s.base as usize], s.italic.unwrap_or(matches!(s.base, crate::syntax::DefStyle::Comment | crate::syntax::DefStyle::Documentation)), s.underline),
None => (normal, false, false),
};
if cur != Some(st) {
flush(&mut job, &mut run, cur);
cur = Some(st);
}
if c == '\t' {
run.extend(std::iter::repeat_n(' ', w));
} else if ws && c == ' ' {
run.push('·');
} else {
run.push(c);
}
}
x += w;
byte += c.len_utf8() as u32;
}
flush(&mut job, &mut run, cur);
job
}
impl Rows {
fn refresh(&mut self, doc: &Doc, wrap: usize, tab: usize) {
let folds = doc.folded.iter().fold(doc.folded.len() as u64, |h, l| h.wrapping_mul(31).wrapping_add(*l as u64));
let key = (doc.buf.version, folds, wrap, tab);
if self.key == key {
return;
}
self.key = key;
if wrap == 0 && doc.folded.is_empty() {
self.map = None;
return;
}
let hidden = doc.hidden_lines();
let mut v = Vec::with_capacity(doc.buf.lines());
let (mut h, mut l, total) = (0, 0, doc.buf.lines());
while l < total {
if h < hidden.len() && l >= hidden[h].0 {
l = hidden[h].1 + 1;
h += 1;
continue;
}
v.push((l as u32, 0));
if wrap > 0 && doc.buf.rope.line(l).len_chars() > wrap / 2 {
// long-line break at a word gap where one is close enough
let text = doc.buf.line_text(l);
let (mut x, mut last_gap, mut start) = (0, 0, 0);
for (i, c) in text.chars().enumerate() {
let w = cell_width(c, x, tab);
if x + w > wrap {
let cut = if last_gap > start + wrap / 3 { last_gap } else { i };
v.push((l as u32, cut as u32));
start = cut;
x = text.chars().skip(cut).take(i - cut).fold(0, |a, ch| a + cell_width(ch, a, tab));
}
if c == ' ' { last_gap = i + 1 }
x += w;
}
}
l += 1;
}
self.map = Some(Arc::new(v));
}
pub fn count(&self, doc: &Doc) -> usize {
self.map.as_ref().map_or(doc.buf.lines(), |m| m.len())
}
/// (line, first column) of a row.
pub fn row(&self, r: usize) -> (usize, usize) {
match &self.map {
Some(m) => m.get(r).map_or((usize::MAX, 0), |x| (x.0 as usize, x.1 as usize)),
None => (r, 0),
}
}
/// The last column shown in a row (exclusive).
fn row_end(&self, r: usize, doc: &Doc) -> usize {
let (l, _) = self.row(r);
match self.map.as_ref().and_then(|m| m.get(r + 1)) {
Some(n) if n.0 as usize == l => n.1 as usize,
_ => doc.buf.line_len(l),
}
}
pub fn row_of(&self, line: usize, col: usize) -> usize {
match &self.map {
None => line,
Some(m) => m.partition_point(|x| (x.0 as usize, x.1 as usize) <= (line, col)).saturating_sub(1),
}
}
}
fn prefs(a: &App) -> Prefs {
Prefs { tab_width: a.s.tab_width, spaces: a.s.spaces, auto_close: a.s.auto_close }
}
impl App {
pub fn metrics(&self, ui: &Ui) -> Metrics {
let font = self.s.font_size;
let id = fonts::mono(font);
let cw = ui.fonts_mut(|f| f.glyph_width(&id, 'M'));
Metrics { cw, lh: (font * 1.55).round(), font }
}
/// Draws one open tab of a pane in `rect`.
pub fn editor(&mut self, ui: &mut Ui, pane: usize, rect: Rect) {
let m = self.metrics(ui);
let t = self.t.clone();
let id = self.pane_focus_id(pane);
let Some(doc_id) = self.panes[pane].tabs.get(self.panes[pane].active).map(|x| x.doc) else { return };
let digits = self.docs.get(&doc_id).map_or(3, |d| d.buf.lines().to_string().len().max(3));
let gutter = if self.s.line_numbers { digits as f32 * m.cw * 0.92 + 42.0 } else { 34.0 };
let code = Rect::from_min_max(pos2(rect.left() + gutter, rect.top()), rect.max);
let wrap = if self.s.word_wrap { ((code.width() - 24.0) / m.cw).max(20.0) as usize } else { 0 };
let tab_w = self.s.tab_width;
let (rect_h, resp) = (rect.height(), ui.interact(rect, id, Sense::click_and_drag()));
if resp.hovered() {
ui.ctx().set_cursor_icon(if ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.x >= code.left()) { egui::CursorIcon::Text } else { egui::CursorIcon::Default });
}
if resp.clicked() || resp.drag_started() {
resp.request_focus();
self.focus_pane = pane;
}
let focused = resp.has_focus();
if focused {
ui.ctx().memory_mut(|mem| mem.set_focus_lock_filter(id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false }));
self.keyboard(ui, pane, m, rect_h);
}
{
let doc = self.docs.get_mut(&doc_id).unwrap();
doc.sync_edits();
doc.refresh_folds(tab_w);
let p = &mut self.panes[pane];
let tb = &mut p.tabs[p.active];
tb.rows.refresh(doc, wrap, tab_w);
}
self.pointer(ui, pane, doc_id, &resp, code, m);
// scrolling, with a small rubber band past either end
let (count, head_row) = {
let doc = &self.docs[&doc_id];
let tb = &self.panes[pane].tabs[self.panes[pane].active];
let (l, c) = doc.buf.pos(doc.buf.head());
(tb.rows.count(doc), tb.rows.row_of(l, c))
};
let max = (count as f32 * m.lh - rect.height() * 0.5).max(0.0);
let wheel = if resp.hovered() || ui.rect_contains_pointer(rect) { (crate::ui::widgets::wheel(ui), ui.input(|i| i.modifiers)) } else { (egui::Vec2::ZERO, Modifiers::NONE) };
let pending_reveal = focused && std::mem::take(&mut self.reveal);
{
let tb = { let p = &mut self.panes[pane]; let a = p.active; &mut p.tabs[a] };
if wheel.1.command {
if wheel.0.y != 0.0 {
self.s.font_size = (self.s.font_size + wheel.0.y.signum()).clamp(8.0, 40.0);
}
} else {
tb.scroll.target -= wheel.0.y * 1.6;
tb.scroll_x = (tb.scroll_x - wheel.0.x).max(0.0);
}
if tb.scroll.target < 0.0 {
tb.scroll.target = if tb.scroll.target < -60.0 { -60.0 } else { tb.scroll.target * 0.8 };
} else if tb.scroll.target > max {
tb.scroll.target = max + (tb.scroll.target - max).min(60.0) * 0.8;
}
if tb.scroll.target.abs() < 0.5 { tb.scroll.target = 0.0 }
if pending_reveal && focused {
let y = head_row as f32 * m.lh;
let (top, bot) = (tb.scroll.target + m.lh * 2.0, tb.scroll.target + rect.height() - m.lh * 3.0);
if y < top { tb.scroll.target = (y - m.lh * 2.0).max(0.0) }
else if y > bot { tb.scroll.target = y - rect.height() + m.lh * 3.0 }
}
tb.scroll.step(SCROLL);
}
let (scroll, scroll_x) = { let tb = &self.panes[pane].tabs[self.panes[pane].active]; (tb.scroll.x, tb.scroll_x) };
// make sure what's on screen, and a bit beyond, has colours
let first = (scroll / m.lh).floor().max(0.0) as usize;
let shown = (rect.height() / m.lh).ceil() as usize + 1;
let last_line = {
let tb = &self.panes[pane].tabs[self.panes[pane].active];
let d = &self.docs[&doc_id];
let r = tb.rows.row((first + shown).min(tb.rows.count(d).saturating_sub(1))).0;
r.min(d.buf.lines())
};
let doc = self.docs.get_mut(&doc_id).unwrap();
doc.highlight(&self.reg, last_line + 40, 0);
let doc = &self.docs[&doc_id];
let tb = &self.panes[pane].tabs[self.panes[pane].active];
let clip = rect.shrink2(vec2(0.0, 4.0));
let painter = ui.painter_at(clip);
let code_clip = Rect::from_min_max(pos2(code.left(), clip.top()), clip.max);
let code_p = ui.painter_at(code_clip);
let font = fonts::mono(m.font);
let y_of = |row: usize| rect.top() + 6.0 + row as f32 * m.lh - scroll;
let x0 = code.left() + 6.0 - scroll_x;
// indent guides, selections and search hits sit behind the text
let rows: Vec<(usize, (usize, usize), usize)> = (first..(first + shown).min(count)).map(|r| (r, tb.rows.row(r), tb.rows.row_end(r, doc))).collect();
let cur_line = doc.buf.pos(doc.buf.head()).0;
// the current line is a bubble that slides between lines
let bubble_y = spring(format!("cur/{pane}"), rect.top() + 6.0 + head_row as f32 * m.lh, Preset { stiffness: 1100.0, damping: 0.72 }) - scroll;
if doc.buf.sels.len() == 1 && doc.buf.sels[0].is_empty() {
let r = Rect::from_min_size(pos2(rect.left() + 6.0, bubble_y), vec2(rect.width() - 12.0, m.lh));
painter.rect_filled(r, cr(10.0), alpha(t.primary, if focused { 0.08 } else { 0.04 }));
}
for (_, (line, _), _) in &rows {
if *line >= doc.buf.lines() { continue }
}
let line_cols = |line: usize| doc.buf.line_text(line);
for s in doc.buf.sels.iter().filter(|s| !s.is_empty()) {
let r = s.range();
let (a, b) = (doc.buf.pos(r.start), doc.buf.pos(r.end));
for (row, (line, c0), c1) in &rows {
if *line < a.0 || *line > b.0 || *line >= doc.buf.lines() { continue }
let text = line_cols(*line);
let from = if *line == a.0 { a.1.max(*c0) } else { *c0 };
let to = if *line == b.0 { b.1.min(*c1) } else { *c1 };
if from > to || (*line == a.0 && a.1 > *c1) { continue }
let base = vis_col(&text, *c0, tab_w);
let xa = (vis_col(&text, from, tab_w) - base) as f32 * m.cw;
let eol = if *line < b.0 && to == *c1 { m.cw * 0.6 } else { 0.0 };
let xb = (vis_col(&text, to, tab_w) - base) as f32 * m.cw + eol;
let sr = Rect::from_min_max(pos2(x0 + xa, y_of(*row)), pos2(x0 + xb, y_of(*row) + m.lh));
code_p.rect_filled(sr, cr(5.0), alpha(t.primary, 0.3));
}
}
for (a, b, is_current) in self.find_hits_in(doc_id, doc, &rows) {
let (line, c0) = doc.buf.pos(a);
let text = doc.buf.line_text(line);
let Some(row) = rows.iter().find(|r| r.1.0 == line && r.1.1 <= c0 && c0 <= r.2) else { continue };
let base = vis_col(&text, row.1.1, tab_w);
let xa = (vis_col(&text, c0, tab_w) - base) as f32 * m.cw;
let xb = (vis_col(&text, c0 + (b - a), tab_w) - base) as f32 * m.cw;
let sr = Rect::from_min_max(pos2(x0 + xa - 1.0, y_of(row.0) + 1.0), pos2(x0 + xb + 1.0, y_of(row.0) + m.lh - 1.0));
code_p.rect_filled(sr, cr(5.0), if is_current { alpha(t.tertiary, 0.6) } else { alpha(t.tertiary, 0.24) });
}
if let Some((a, b)) = doc.buf.matching_bracket(doc.buf.head()) {
for at in [a, b] {
let (line, col) = doc.buf.pos(at);
let Some(row) = rows.iter().find(|r| r.1.0 == line && r.1.1 <= col && col < r.2) else { continue };
let text = doc.buf.line_text(line);
let x = (vis_col(&text, col, tab_w) - vis_col(&text, row.1.1, tab_w)) as f32 * m.cw;
let r = Rect::from_min_size(pos2(x0 + x - 1.0, y_of(row.0) + 1.0), vec2(m.cw + 2.0, m.lh - 2.0));
let pop = spring(format!("br/{pane}/{}", (at == a) as u8), 1.0, motion::FAST);
code_p.rect_filled(scale_rect(r, pop), cr(5.0), alpha(t.primary, 0.26));
}
}
let g_font = fonts::mono((m.font * 0.86).round());
for (row, (line, c0), c1) in &rows {
if *line >= doc.buf.lines() { continue }
let y = y_of(*row);
if *c0 == 0 {
if self.s.line_numbers {
let col = if *line == cur_line { t.primary } else { alpha(t.on_variant, 0.55) };
painter.text(pos2(rect.left() + gutter - 22.0, y + m.lh / 2.0), egui::Align2::RIGHT_CENTER, (line + 1).to_string(), g_font.clone(), col);
}
if doc.bookmarks.contains(line) {
painter.circle_filled(pos2(rect.left() + 11.0, y + m.lh / 2.0), 4.0, t.tertiary);
}
self.gutter_marks(&painter, doc, *line, pos2(rect.left() + gutter - 2.0, y), m.lh);
if doc.fold_ends.contains_key(line) {
let folded = doc.folded.contains(line);
let hover = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| rect.contains(p) && p.x < code.left() + 4.0);
let vis = if folded { 1.0 } else { spring(format!("foldv/{pane}"), hover as u8 as f32, motion::EFFECT) };
if vis > 0.01 {
let turn = spring(format!("fold/{doc_id}/{line}"), !folded as u8 as f32, motion::DEFAULT);
morph::paint(&painter, pos2(rect.left() + gutter - 12.0, y + m.lh / 2.0), 15.0, Morph::Fold, turn, alpha(t.on_variant, vis * 0.9), t.low);
}
}
}
if self.s.indent_guides && *c0 == 0 {
let text = doc.buf.line_text(*line);
let lead = vis_col(&text, text.chars().take_while(|c| *c == ' ' || *c == '\t').count(), tab_w);
let mut g = tab_w;
while g < lead {
let x = x0 + g as f32 * m.cw;
code_p.line_segment([pos2(x, y), pos2(x, y + m.lh)], egui::Stroke::new(1.0, alpha(t.outline_variant, 0.5)));
g += tab_w;
}
}
let job = line_job(doc, &self.reg, &t, *line, (*c0, *c1), &font, tab_w, self.s.show_whitespace);
let galley = ui.painter().layout_job(job);
let gy = y + (m.lh - galley.size().y) / 2.0;
code_p.galley(pos2(x0, gy), galley, t.syntax[0]);
if doc.folded.contains(line) {
let px = (doc.buf.line_len(*line) + 2) as f32 * m.cw;
let tag = Rect::from_min_size(pos2(x0 + px, y + 3.0), vec2(m.cw * 5.0, m.lh - 6.0));
code_p.rect_filled(tag, cr(tag.height() / 2.0), t.secondary_container);
let n = doc.fold_ends.get(line).map_or(0, |e| e - line);
code_p.text(tag.center(), egui::Align2::CENTER_CENTER, n.to_string(), fonts::mono(m.font * 0.75), t.on_secondary_container);
}
}
if let Some((line, born)) = tb.beacon {
let age = (ui.input(|i| i.time) - born) as f32;
if age < 0.9 {
let row = tb.rows.row_of(line, 0);
let k = 1.0 - (age / 0.9);
let r = Rect::from_min_size(pos2(rect.left() + 6.0, y_of(row)), vec2(rect.width() - 12.0, m.lh));
let grow = motion::stagger(age, 0.0, 0.35);
painter.rect_filled(r.expand2(vec2(0.0, 5.0 * (1.0 - grow))), cr(10.0), alpha(t.primary, 0.34 * k * k));
motion::keep_alive();
}
}
// carets: the primary glides, the rest are placed directly
let now = ui.input(|i| i.time);
let idle = (now - self.last_input) as f32;
let blink = if focused { if idle < 0.7 { 1.0 } else { (0.5 + 0.5 * ((idle - 0.7) * 3.6).cos()).clamp(0.0, 1.0) } } else { 0.0 };
let primary = doc.buf.primary;
let caret_at = |at: usize| -> Option<Pos2> {
let (line, col) = doc.buf.pos(at);
let row = tb.rows.row_of(line, col);
let text = doc.buf.line_text(line);
let (_, c0) = tb.rows.row(row);
let x = (vis_col(&text, col, tab_w) - vis_col(&text, c0, tab_w)) as f32 * m.cw;
Some(pos2(x, row as f32 * m.lh))
};
let positions: Vec<Option<Pos2>> = doc.buf.sels.iter().map(|s| caret_at(s.head)).collect();
for (i, p) in positions.iter().enumerate() {
let Some(p) = p else { continue };
if i != primary {
let pos = pos2(x0 + p.x, rect.top() + 6.0 + p.y - scroll);
code_p.rect_filled(Rect::from_min_size(pos, vec2(2.0, m.lh)), cr(1.0), alpha(t.primary, blink));
}
}
let target = positions.get(primary).copied().flatten();
let tb_mut = { let p = &mut self.panes[pane]; let a = p.active; &mut p.tabs[a] };
if let Some(p) = target {
tb_mut.caret[0].target = p.x;
tb_mut.caret[1].target = p.y;
let (x, y) = (tb_mut.caret[0].step(CARET), tb_mut.caret[1].step(CARET));
let speed = tb_mut.caret[0].v.abs() + tb_mut.caret[1].v.abs();
let stretch = (speed / 900.0).min(1.0);
let squash = spring(format!("caret-kick/{pane}"), 0.0, motion::FAST);
let w = 2.2 + stretch * 5.0 + squash.abs() * 3.0;
let h = m.lh * (1.0 - 0.2 * squash.abs());
let r = Rect::from_min_size(pos2(x0 + x - w / 2.0 + 1.0, rect.top() + 6.0 + y - scroll + (m.lh - h) / 2.0), vec2(w, h));
code_p.rect_filled(r, cr(w / 2.0), alpha(t.primary, blink.max(stretch)));
}
if focused && idle < 30.0 {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(40));
}
}
fn keyboard(&mut self, ui: &mut Ui, pane: usize, m: Metrics, height: f32) {
let Some(doc_id) = self.panes[pane].tabs.get(self.panes[pane].active).map(|x| x.doc) else { return };
let events = ui.input(|i| i.events.clone());
let p = prefs(self);
let page = (height / m.lh) as usize;
let mut acted = false;
let mut typed = false;
for ev in events {
let doc = self.docs.get_mut(&doc_id).unwrap();
match ev {
Event::Text(s) => {
if s.chars().all(|c| !c.is_control()) {
doc.buf.type_text(&s, &p);
acted = true;
typed = true;
}
}
Event::Ime(egui::ImeEvent::Commit(s)) => {
doc.buf.insert(&s, EditKind::Typing);
acted = true;
}
Event::Paste(s) => {
doc.buf.insert(&s.replace("\r\n", "\n"), EditKind::Other);
acted = true;
}
Event::Copy => {
let t = doc.buf.selected_text();
if !t.is_empty() { ui.ctx().copy_text(t) }
}
Event::Cut => {
let t = doc.buf.selected_text();
if !t.is_empty() {
ui.ctx().copy_text(t);
doc.buf.insert("", EditKind::Other);
acted = true;
}
}
Event::Key { key, pressed: true, modifiers: md, .. } => {
let (cmd, sh, alt) = (md.command, md.shift, md.alt);
acted = true;
let mv = |doc: &mut Doc, k: Move| doc.buf.move_cursors(k, sh);
match key {
Key::ArrowLeft if !alt => mv(doc, if cmd { Move::WordLeft } else { Move::Left }),
Key::ArrowRight if !alt => mv(doc, if cmd { Move::WordRight } else { Move::Right }),
Key::ArrowUp if !cmd && !alt => mv(doc, Move::Up),
Key::ArrowDown if !cmd && !alt => mv(doc, Move::Down),
Key::Home => mv(doc, if cmd { Move::DocStart } else { Move::Home }),
Key::End => mv(doc, if cmd { Move::DocEnd } else { Move::End }),
Key::PageUp if !alt => mv(doc, Move::PageUp(page)),
Key::PageDown if !alt => mv(doc, Move::PageDown(page)),
Key::Enter if !cmd => doc.buf.newline(&p),
Key::Backspace => if cmd { doc.buf.delete_word(false) } else { doc.buf.backspace(&p) },
Key::Delete => if cmd { doc.buf.delete_word(true) } else { doc.buf.delete_forward() },
Key::Tab if !cmd => if sh { doc.buf.unindent(&p) } else { doc.buf.indent(&p) },
Key::Escape => {
let keep = doc.buf.sels[doc.buf.primary];
doc.buf.set_sels(vec![Sel::cursor(keep.head)]);
}
_ => acted = false,
}
}
_ => {}
}
}
if acted {
self.reveal = true;
self.last_input = ui.input(|i| i.time);
if typed {
motion::spring(format!("caret-kick/{pane}"), 0.0, motion::FAST);
motion::kick(format!("caret-kick/{pane}"), 4.0);
}
ui.ctx().request_repaint();
}
}
fn pointer(&mut self, ui: &mut Ui, pane: usize, doc_id: u64, resp: &egui::Response, code: Rect, m: Metrics) {
let hover = ui.input(|i| i.pointer.interact_pos());
let Some(pos) = hover else { return };
let mods = ui.input(|i| i.modifiers);
let now = ui.input(|i| i.time);
let tab_w = self.s.tab_width;
let doc = self.docs.get_mut(&doc_id).unwrap();
let p = &mut self.panes[pane];
let a = p.active;
let tb = &mut p.tabs[a];
let locate = |tb: &Tab, doc: &Doc, pos: Pos2| -> usize {
let row = ((pos.y - code.top() - 6.0 + tb.scroll.x) / m.lh).floor().max(0.0) as usize;
let (line, c0) = tb.rows.row(row.min(tb.rows.count(doc).saturating_sub(1)));
if line >= doc.buf.lines() { return doc.buf.len() }
let text = doc.buf.line_text(line);
let base = vis_col(&text, c0, tab_w);
let cells = (pos.x - code.left() - 6.0 + tb.scroll_x) / m.cw + base as f32;
doc.buf.at(line, col_at(&text, cells, tab_w))
};
if resp.contains_pointer() && ui.input(|i| i.pointer.button_pressed(PointerButton::Primary)) {
if pos.x < code.left() {
let row = ((pos.y - code.top() - 6.0 + tb.scroll.x) / m.lh).floor().max(0.0) as usize;
let (line, _) = tb.rows.row(row);
if line < doc.buf.lines() {
if doc.fold_ends.contains_key(&line) { doc.toggle_fold(line) }
else {
let at = doc.buf.at(line, 0);
doc.buf.set_cursor(at);
}
}
return;
}
let at = locate(tb, doc, pos);
let multi = if now - tb.click.0 < 0.35 && tb.click.1 == at { (tb.click.2 % 3) + 1 } else { 1 };
tb.click = (now, at, multi);
self.last_input = now;
let (line, _) = doc.buf.pos(at);
if mods.alt {
tb.block_anchor = Some(pos);
} else if mods.command {
let mut v = doc.buf.sels.clone();
v.push(Sel::cursor(at));
doc.buf.set_sels(v);
} else if mods.shift {
let s = doc.buf.sels[doc.buf.primary];
doc.buf.set_sels(vec![Sel { anchor: s.anchor, head: at, want_col: None }]);
} else {
match multi {
2 => {
let r = doc.buf.word_at(at);
tb.drag_word = Some(r.clone());
doc.buf.set_sels(vec![Sel { anchor: r.start, head: r.end, want_col: None }]);
}
3 => {
let end = if line + 1 < doc.buf.lines() { doc.buf.at(line + 1, 0) } else { doc.buf.len() };
let s = doc.buf.at(line, 0);
tb.drag_word = Some(s..end);
doc.buf.set_sels(vec![Sel { anchor: s, head: end, want_col: None }]);
}
_ => {
tb.drag_word = None;
doc.buf.set_cursor(at);
}
}
}
}
if resp.dragged_by(PointerButton::Primary) && pos.x >= code.left() - 40.0 {
if let Some(anchor) = tb.block_anchor {
// Alt-drag: one cursor per line, a block selection
let (r0, r1) = (anchor.y.min(pos.y), anchor.y.max(pos.y));
let (c0, c1) = (anchor.x, pos.x);
let top = ((r0 - code.top() - 6.0 + tb.scroll.x) / m.lh).floor().max(0.0) as usize;
let bot = ((r1 - code.top() - 6.0 + tb.scroll.x) / m.lh).floor().max(0.0) as usize;
let cell = |x: f32| (x - code.left() - 6.0 + tb.scroll_x) / m.cw;
let mut v = vec![];
for row in top..=bot.min(tb.rows.count(doc).saturating_sub(1)) {
let (line, _) = tb.rows.row(row);
let text = doc.buf.line_text(line);
let (a, b) = (doc.buf.at(line, col_at(&text, cell(c0), tab_w)), doc.buf.at(line, col_at(&text, cell(c1), tab_w)));
v.push(Sel { anchor: a, head: b, want_col: None });
}
doc.buf.set_sels(v);
} else {
let at = locate(tb, doc, pos);
if let Some(w) = tb.drag_word.clone() {
let (anchor, head) = if at < w.start { (w.end, at) } else { (w.start, at.max(w.end)) };
doc.buf.set_sels(vec![Sel { anchor, head, want_col: None }]);
} else if doc.buf.sels.len() == 1 {
let s = doc.buf.sels[0];
doc.buf.set_sels(vec![Sel { anchor: s.anchor, head: at, want_col: None }]);
}
}
// keep selecting past the edges
if pos.y < code.top() + 10.0 { tb.scroll.target -= 18.0; motion::keep_alive() }
if pos.y > code.bottom() - 10.0 { tb.scroll.target += 18.0; motion::keep_alive() }
}
if resp.drag_stopped() {
tb.block_anchor = None;
tb.drag_word = None;
}
if resp.secondary_clicked() {
let at = locate(tb, doc, pos);
if !doc.buf.sels.iter().any(|s| s.range().contains(&at)) {
doc.buf.set_cursor(at);
}
self.editor_menu(pos);
}
}
pub fn editor_scroll_of(pane: &Pane) -> f32 {
pane.tabs.get(pane.active).map_or(0.0, |t| t.scroll.x)
}
}