strop-editor 0.2.0

strop — a modal text editor in Rust: see the cut before you make it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Rendering: gutter, buffer text, overlay layers, statusline.
//! Overlay precedence (0001 §5.8 subset): search/incsearch < operator
//! preview < cursor. One accent color (0001 §4).

use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use ratatui::Frame;

use strop_core::Range;
use strop_grammar as grammar;

use crate::editor::{Editor, LayoutDir, Mode};

mod blame_card;
mod cmd_card;
mod hover_card;
mod hunk_card;
mod keybinds;
mod picker_card;
mod which_key;

// strop default palette (plan 0004 site, --accent amber)
pub const BASE: Color = Color::Rgb(0x16, 0x16, 0x1e);
pub const TEXT: Color = Color::Rgb(0xe8, 0xe4, 0xda);
pub const MUTED: Color = Color::Rgb(0x6b, 0x6f, 0x7e);
pub const ACCENT: Color = Color::Rgb(0xf0, 0xa3, 0x5e);
pub const PREVIEW_BG: Color = Color::Rgb(0x4a, 0x33, 0x1c); // accent, dimmed
pub const FLASH_BG: Color = Color::Rgb(0x6b, 0x47, 0x22); // accent, stronger
pub const SELECT_BG: Color = Color::Rgb(0x2a, 0x2c, 0x3a);

const GUTTER: u16 = 5; // 4-digit numbers + one empty column (0001 §4)

/// Syntax class → color (strop palette; theme engine swaps these later).
pub(crate) fn class_color(class: strop_syntax::Class) -> Color {
    use strop_syntax::Class as C;
    match class {
        C::Keyword => Color::Rgb(0xc5, 0x8a, 0xe8),
        C::Function => Color::Rgb(0x7f, 0xb4, 0xca),
        C::Type => Color::Rgb(0x94, 0xd2, 0xbd),
        C::String => Color::Rgb(0xa9, 0xc4, 0x7c),
        C::Comment => MUTED,
        C::Number => Color::Rgb(0xe8, 0x97, 0x7a),
        C::Operator => Color::Rgb(0x9a, 0xa0, 0xae),
        C::Punctuation => Color::Rgb(0x56, 0x5b, 0x6e),
        C::Constant => ACCENT,
        C::Attribute => Color::Rgb(0xd0, 0xa4, 0x5e),
        C::Variable => TEXT,
    }
}

pub fn render(editor: &mut Editor, frame: &mut Frame) {
    let area = frame.area();
    let text_rows = area.height.saturating_sub(1) as usize;
    editor.scroll_to_cursor(text_rows);
    editor.refresh_hunks();

    if editor.panes.len() == 1 {
        render_text(editor, frame, area, text_rows);
    } else {
        render_panes(editor, frame, area, text_rows);
    }
    render_statusline(editor, frame, area);
    cmd_card::render_cmd_card(editor, frame);
    if !cmd_card_active(editor) {
        place_cursor(editor, frame, area);
    }
    render_welcome(editor, frame);
    picker_card::render_picker(editor, frame);
    hunk_card::render_hunk_card(editor, frame);
    blame_card::render_blame_card(editor, frame);
    hover_card::render_hover_card(editor, frame);
    keybinds::render_keybinds(editor, frame);
    which_key::render_which_key(editor, frame);
}

/// Mode chip colors (0001 §4: mode = accent color change, not bars).
pub(crate) fn mode_color(mode: Mode) -> Color {
    match mode {
        Mode::Normal => ACCENT,
        Mode::Insert => Color::Rgb(0xa9, 0xc4, 0x7c), // green
        Mode::Visual | Mode::VisualLine => Color::Rgb(0xc5, 0x8a, 0xe8), // violet
    }
}

/// Pull a color toward the base for the picker's dimmed backdrop.
pub(crate) fn dim_color(c: Color) -> Color {
    fn mix(c: (u8, u8, u8), base: (u8, u8, u8), t: u8) -> Color {
        let m =
            |a: u8, b: u8| (a as u16 * (100 - t) as u16 / 100 + b as u16 * t as u16 / 100) as u8;
        Color::Rgb(m(c.0, base.0), m(c.1, base.1), m(c.2, base.2))
    }
    const BASE_RGB: (u8, u8, u8) = (0x16, 0x16, 0x1e);
    match c {
        Color::Rgb(r, g, b) => mix((r, g, b), BASE_RGB, 55),
        other => other,
    }
}

fn in_range(r: Range, pos: usize) -> bool {
    pos >= r.start && pos < r.end
}

/// Smallest span covering pos (syntax spans are nested).
fn spans_for(pos: usize, spans: &[strop_syntax::Span]) -> Option<strop_syntax::Class> {
    spans
        .iter()
        .filter(|s| s.start <= pos && pos < s.end)
        .min_by_key(|s| s.end - s.start)
        .map(|s| s.class)
}

/// All panes, with a muted │ divider column between them. Only the
/// active pane carries overlays (preview/search/selection/flash) and the
/// caret — inactive panes render their own cursor position statically.
fn render_panes(editor: &mut Editor, frame: &mut Frame, area: Rect, _text_rows: usize) {
    let n = editor.panes.len();
    let is_row = editor.layout == LayoutDir::Row;
    let total_w = area.width as usize;
    let total_h = area.height as usize - 1;
    let dividers = n - 1;
    let (mut x, mut y) = (area.x, area.y);
    for i in 0..n {
        let (w, h): (u16, u16) = if is_row {
            let w = ((total_w - dividers) / n) as u16;
            let w = if i == n - 1 {
                (total_w - dividers) as u16 - w * (n as u16 - 1)
            } else {
                w
            };
            (w, total_h as u16)
        } else {
            let h = ((total_h - dividers) / n) as u16;
            let h = if i == n - 1 {
                (total_h - dividers) as u16 - h * (n as u16 - 1)
            } else {
                h
            };
            (total_w as u16, h)
        };
        let rect = Rect {
            x,
            y,
            width: w,
            height: h,
        };
        render_text_for_pane(editor, frame, rect, i);
        if i < n - 1 {
            // divider column/row
            if is_row {
                let dx = x + w;
                for dy in y..y + h {
                    let cell = &mut frame.buffer_mut()[(dx, dy)];
                    cell.set_symbol("");
                    cell.set_fg(Color::Rgb(0x3a, 0x3d, 0x4d));
                }
                x = dx + 1;
            } else {
                let dy = y + h;
                for dx in x..x + w {
                    let cell = &mut frame.buffer_mut()[(dx, dy)];
                    cell.set_symbol("");
                    cell.set_fg(Color::Rgb(0x3a, 0x3d, 0x4d));
                }
                y = dy + 1;
            }
        }
    }
}

/// Render one pane: active panes read live editor state; inactive panes
/// read their saved cursor/view (overlays suppressed).
fn render_text_for_pane(editor: &mut Editor, frame: &mut Frame, area: Rect, pane_idx: usize) {
    if pane_idx == editor.active_pane {
        render_text(editor, frame, area, area.height as usize);
        return;
    }
    let pane = editor.panes[pane_idx].clone();
    let buf_idx = pane.buffer.min(editor.buffers.len() - 1);
    // syntax is per-buffer, not per-active-pane (inactive panes keep
    // their colors; only overlays are active-only)
    let rope = editor.buffers[buf_idx].rope.clone();
    let syn_spans = editor
        .highlighters
        .get_mut(buf_idx)
        .and_then(|h| h.as_mut())
        .map(|h| h.highlight(&rope, 0, rope.len_bytes()))
        .unwrap_or_default();
    let total_lines = editor.buffers[buf_idx].last_content_line() + 1;
    let mut lines: Vec<Line> = Vec::with_capacity(area.height as usize);
    for row in 0..area.height as usize {
        let line_idx = pane.view_top + row;
        if line_idx >= total_lines {
            lines.push(Line::from(Span::styled("~", Style::default().fg(MUTED))));
            continue;
        }
        let line_num_style = if line_idx == editor.buffers[buf_idx].line_of(pane.cursor) {
            Style::default().fg(ACCENT)
        } else {
            Style::default().fg(MUTED)
        };
        let text = editor.buffers[buf_idx].line_text(line_idx);
        let mut spans = vec![
            Span::styled(" ", Style::default()),
            Span::styled(format!("{:>3} ", line_idx + 1), line_num_style),
        ];
        let start = editor.buffers[buf_idx].line_start(line_idx);
        for (i, ch) in text.chars().enumerate() {
            let pos = start + i;
            let mut style = Style::default().fg(TEXT);
            if let Some(sp) = spans_for(pos, &syn_spans) {
                style = style.fg(class_color(sp));
                if sp == strop_syntax::Class::Comment {
                    style = style.add_modifier(Modifier::ITALIC);
                }
            }
            spans.push(Span::styled(ch.to_string(), style));
        }
        lines.push(Line::from(spans));
    }
    let block = Paragraph::new(lines).style(Style::default().bg(BASE));
    frame.render_widget(block, area);
    // static caret: the inactive pane's position, unfocused (muted block)
    let line = editor.buffers[buf_idx].line_of(pane.cursor);
    let row = line.saturating_sub(pane.view_top) as u16;
    let col = 5 + editor.buffers[buf_idx].col_of(pane.cursor) as u16;
    if row < area.height && col < area.width {
        let cell = &mut frame.buffer_mut()[(area.x + col, area.y + row)];
        cell.set_bg(Color::Rgb(0x3a, 0x3d, 0x4d));
    }
}

fn render_text(editor: &mut Editor, frame: &mut Frame, area: Rect, text_rows: usize) {
    let preview = editor.preview().map(|r| r.range);
    let flash = editor.flash_range();
    let selection = editor.visual_range();
    let search_hits: Vec<usize> = editor
        .search_pattern()
        .map(|p| grammar::search_all(editor.buf(), p))
        .unwrap_or_default();
    let find = editor.find_candidates();

    let cur_line = editor.buf().line_of(editor.cursor);
    let mut lines: Vec<Line> = Vec::with_capacity(text_rows);

    // tree-sitter spans for the visible window (base layer, 0001 §5.8)
    let first_byte = editor.buf().line_start(editor.view_top);
    let last_line = (editor.view_top + text_rows).min(editor.buf().len_lines());
    let last_byte = editor.buf().line_end(last_line.saturating_sub(1));
    let rope = editor.buffers[editor.current].rope.clone();
    let syn_spans: Vec<strop_syntax::Span> = match editor.highlighter() {
        Some(h) => h.highlight(&rope, first_byte, last_byte),
        None => Vec::new(),
    };

    for row in 0..text_rows {
        let line_idx = editor.view_top + row;
        if line_idx > editor.buf().last_content_line() {
            lines.push(Line::from(Span::styled("~", Style::default().fg(MUTED))));
            continue;
        }
        let start = editor.buf().line_start(line_idx);
        let text = editor.buf().line_text(line_idx);

        // gutter: muted numbers, current line in accent (0001 §4)
        let num_style = if line_idx == cur_line {
            Style::default().fg(ACCENT)
        } else {
            Style::default().fg(MUTED)
        };
        // Helix-grade gutter: a colored ▎ bar in the leftmost column —
        // green add, amber change, red delete (0001 pillar 3.1)
        let (bar, bar_color) = match editor.diag_at(line_idx + 1).or(editor
            .sign_at(line_idx + 1)
            .map(|c| c.to_string())
            .as_deref())
        {
            Some("E") => ("E", Color::Rgb(0xe8, 0x67, 0x7a)),
            Some("W") => ("W", Color::Rgb(0xf0, 0xa3, 0x5e)),
            Some("I") | Some("H") => ("", Color::Rgb(0x7f, 0xb4, 0xca)),
            Some("+") => ("", Color::Rgb(0xa9, 0xc4, 0x7c)),
            Some("~") => ("", ACCENT),
            Some("-") => ("", Color::Rgb(0xe8, 0x67, 0x7a)),
            _ => (" ", MUTED),
        };
        let mut spans = vec![
            Span::styled(
                bar,
                Style::default().fg(bar_color).add_modifier(Modifier::BOLD),
            ),
            Span::styled(format!("{:>3} ", line_idx + 1), num_style),
        ];

        let is_delta = matches!(editor.surface(), Some(crate::editor::Surface::DeltaView));
        let diff_line_style = if is_delta {
            match text.as_bytes().first() {
                Some(b'+') => Some(Color::Rgb(0xa9, 0xc4, 0x7c)),
                Some(b'-') => Some(Color::Rgb(0xe8, 0x67, 0x7a)),
                Some(b'@') => Some(ACCENT),
                _ => None,
            }
        } else {
            None
        };
        // indent guides: dim │ at each indent level within leading
        // whitespace (v1: spaces only, no empty-line continuation;
        // scope tracking + config toggle land with 0005)
        let lead_ws = if editor.config.indent_guides {
            text.chars().take_while(|c| *c == ' ').count()
        } else {
            0
        };
        let tab = editor.config.tab_size.max(1);
        let mut syn_idx = syn_spans.partition_point(|s| s.end <= start);
        for (i, ch) in text.chars().enumerate() {
            let pos = start + i; // prototype is ASCII-honest (0001 §5.9 later)
            while syn_idx < syn_spans.len() && syn_spans[syn_idx].end <= pos {
                syn_idx += 1;
            }
            let mut style = Style::default().fg(diff_line_style.unwrap_or(TEXT));
            let is_guide = i < lead_ws && (i + 1) % tab == 0;
            if syn_idx < syn_spans.len() && syn_spans[syn_idx].start <= pos {
                let class = syn_spans[syn_idx].class;
                style = style.fg(class_color(class));
                if class == strop_syntax::Class::Comment {
                    style = style.add_modifier(Modifier::ITALIC);
                }
            }
            if selection.is_some_and(|r| in_range(r, pos)) {
                style = style.bg(SELECT_BG);
            }
            if search_hits
                .iter()
                .any(|&h| pos >= h && pos < h + editor.search_pattern().map_or(0, str::len))
            {
                style = style.fg(ACCENT).add_modifier(Modifier::BOLD);
            }
            if let Some((_, backward)) = find {
                // leap-style: candidates bold-accent on the pending side
                let on_line = editor.buf().line_of(pos) == cur_line;
                let ahead = if backward {
                    pos < editor.cursor
                } else {
                    pos > editor.cursor
                };
                if on_line && ahead && !ch.is_whitespace() {
                    style = style.fg(ACCENT).add_modifier(Modifier::BOLD);
                }
            }
            if let Some(r) = preview {
                if in_range(r, pos) {
                    style = style.fg(ACCENT).bg(PREVIEW_BG);
                }
            }
            if let Some(r) = flash {
                if in_range(r, pos) {
                    style = style.bg(FLASH_BG);
                }
            }
            if is_guide {
                spans.push(Span::styled("", style.fg(Color::Rgb(0x2e, 0x30, 0x42))));
            } else {
                spans.push(Span::styled(ch.to_string(), style));
            }
        }
        lines.push(Line::from(spans));
    }

    let block = Paragraph::new(lines).style(Style::default().bg(BASE));
    frame.render_widget(
        block,
        Rect {
            height: text_rows as u16,
            ..area
        },
    );
}

fn render_statusline(editor: &Editor, frame: &mut Frame, area: Rect) {
    let y = area.height - 1;
    let mode = editor.mode.chip();
    let file = editor
        .buf()
        .path
        .as_deref()
        .or(editor.buf().name.as_deref())
        .unwrap_or("[scratch]");
    let dirty = if editor.buf().dirty { "" } else { "" };
    let line = editor.buf().line_of(editor.cursor) + 1;
    let col = editor.buf().col_of(editor.cursor) + 1;

    let spec = if let Some(p) = editor.preview() {
        format!("{}  ", p.spec)
    } else if !editor.pending.is_empty() && !cmd_card_active(editor) {
        format!("{}  ", editor.pending.trim_end_matches('\r'))
    } else if !editor.message.is_empty() {
        format!("{}  ", editor.message)
    } else {
        String::new()
    };
    let pos = format!("{line}:{col} ");

    // One Line, one Paragraph — two overlapping Paragraphs repaint each
    // other's cells (the mode chip went base-on-base and vanished).
    let chip = format!(" {mode} ");
    let name = format!(" {file}{dirty}");
    let used = 1 + chip.len() + name.len() + spec.len() + pos.len();
    let pad = (area.width as usize).saturating_sub(used);
    let row = Line::from(vec![
        Span::styled("", Style::default().fg(mode_color(editor.mode))),
        Span::styled(
            chip,
            Style::default()
                .fg(BASE)
                .bg(mode_color(editor.mode))
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(name, Style::default().fg(MUTED)),
        Span::raw(" ".repeat(pad)),
        Span::styled(spec, Style::default().fg(ACCENT)),
        Span::styled(pos, Style::default().fg(MUTED)),
    ]);
    let rect = Rect {
        y,
        height: 1,
        ..area
    };
    frame.render_widget(Paragraph::new(row).style(Style::default().bg(BASE)), rect);
}

fn place_cursor(editor: &Editor, frame: &mut Frame, area: Rect) {
    let line = editor.buf().line_of(editor.cursor);
    let row = line.saturating_sub(editor.view_top) as u16;
    let col = GUTTER + editor.buf().col_of(editor.cursor) as u16;
    if row < area.height - 1 && col < area.width {
        frame.set_cursor_position((col, row));
    }
}

/// First-launch card: brand + the three keys that matter. Only on an
/// empty scratch buffer — once you're editing, it never intrudes.
fn render_welcome(editor: &Editor, frame: &mut Frame) {
    if editor.buf().path.is_some() || editor.buf().len_bytes() > 0 || editor.picker_open() {
        return;
    }
    use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
    let area = frame.area();
    let (w, h) = (58u16, 9u16);
    if area.width < w + 4 || area.height < h + 4 {
        return;
    }
    let card = Rect {
        x: (area.width - w) / 2,
        y: (area.height - h) / 3,
        width: w,
        height: h,
    };
    frame.render_widget(Clear, card);
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(MUTED))
        .style(Style::default().bg(BASE));
    let inner = block.inner(card);
    frame.render_widget(block, card);
    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            " strop",
            Style::default().fg(TEXT).add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::styled(
            " see the cut before you make it.",
            Style::default().fg(ACCENT),
        )),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                " space ",
                Style::default()
                    .fg(ACCENT)
                    .bg(SELECT_BG)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" everything · ", Style::default().fg(MUTED)),
            Span::styled(
                " ? ",
                Style::default()
                    .fg(ACCENT)
                    .bg(SELECT_BG)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" keybindings · ", Style::default().fg(MUTED)),
            Span::styled(
                " :w ",
                Style::default()
                    .fg(ACCENT)
                    .bg(SELECT_BG)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" save", Style::default().fg(MUTED)),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "  git signs paint the gutter · ci[ previews the cut",
            Style::default().fg(MUTED),
        )),
    ];
    frame.render_widget(Paragraph::new(lines), inner);
}

/// True when the floating command/search card owns the caret.
pub(crate) fn cmd_card_active(editor: &Editor) -> bool {
    !editor.picker_open()
        && (editor.pending.starts_with(':') || editor.pending.contains('/'))
        && !editor.pending.is_empty()
}