edamame 0.1.6

A Terminal Markdown editor that stays rendered while you edit
Documentation
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
//! Integration tests for the footnote feature.
//!
//! Covers the library-facing `footnote_edit` API, the `EditorState`-level
//! `edit_ops` wrappers, and the two-layer mouse path (`MouseAction` →
//! `mouse_ops::apply` → `pending_link_follow`) that turns a click on a
//! rendered footnote reference into a follow — the layer CLAUDE.md asks be
//! tested as a pure function of input event + editor state.

use crossterm::event::KeyModifiers;
use edamame::config::Theme;
use edamame::document::Buffer;
use edamame::editor::link::LinkTarget;
use edamame::editor::{edit_ops, footnote_edit, mouse_ops, EditorState, Mode};
use edamame::input::MouseAction;

const VP: usize = 40;
const VW: usize = 80;

fn theme() -> &'static Theme {
    Box::leak(Box::new(Theme::default()))
}

fn state(text: &str) -> EditorState {
    EditorState::new(Buffer::from_str(text), theme())
}

// ── Library API ───────────────────────────────────────────────────────────────

#[test]
fn footnote_edit_api_is_reachable_and_correct() {
    let src = "A[^2] B[^1]\n\n[^2]: two\n[^1]: one\n";
    assert_eq!(footnote_edit::next_footnote_number(src), 3);
    // `2` is referenced before `1`, so renumber produces a (non-empty)
    // delta; already-sequential input produces none.
    assert!(footnote_edit::renumber_footnotes(src).is_some());
    assert!(footnote_edit::renumber_footnotes("A[^1] B[^2]\n\n[^1]: x\n[^2]: y\n").is_none());
}

#[test]
fn renumber_wrapper_reorders_buffer_by_first_reference() {
    let mut st = state("A[^2] B[^1]\n\n[^2]: two\n[^1]: one\n");
    st.mode = Mode::Rendered;
    assert!(edit_ops::renumber_footnotes(&mut st, VP, VW));
    assert_eq!(st.contents(), "A[^1] B[^2]\n\n[^1]: two\n[^2]: one\n");
}

// ── EditorState wrappers ────────────────────────────────────────────────────────

#[test]
fn insert_footnote_wrapper_auto_numbers() {
    let mut st = state("Claim.\n\n[^1]: prior note.\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = st.buffer.rope().byte_to_char("Claim.".len());
    edit_ops::insert_footnote_at_cursor(&mut st, VP, VW);
    assert!(
        st.contents().starts_with("Claim.[^2]"),
        "got: {:?}",
        st.contents()
    );
}

#[test]
fn delete_footnote_wrapper_off_a_footnote_returns_false() {
    let mut st = state("plain text\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 3;
    assert!(!edit_ops::delete_footnote_at_cursor(&mut st, VP, VW));
}

// ── Two-layer mouse path ────────────────────────────────────────────────────────

#[test]
fn mouse_click_on_reference_stages_footnote_follow() {
    // Preview mode: a plain click on the rendered marker stages a footnote
    // follow.  Rendered line 0 is "Body[1] more." — the marker's opening
    // bracket sits at column 4 (after "Body"), and the 1:1 raw-column map
    // sends it onto the `[^1]` source.
    let mut st = state("Body[^1] more.\n\n[^1]: the note.\n");
    assert_eq!(st.mode, Mode::Preview);
    let action = MouseAction::Click {
        col: 4,
        row: 0,
        modifiers: KeyModifiers::NONE,
    };
    let mut drag = None;
    mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
    assert_eq!(
        st.pending_link_follow,
        Some(LinkTarget::Footnote("1".into())),
        "click on the marker should stage a footnote follow"
    );
}

#[test]
fn hover_over_reference_marker_is_clickable() {
    // The pointer-shape hit-test should report the reference marker as
    // clickable (hand cursor), but not the surrounding text.
    let st = state("Body[^1] more.\n\n[^1]: the note.\n");
    // Rendered line 0: "Body[1] more." — the marker starts at col 4.
    assert!(
        mouse_ops::hit_test_clickable(&st, 4, 0, VW, &[]),
        "the footnote marker should be clickable"
    );
    assert!(
        !mouse_ops::hit_test_clickable(&st, 1, 0, VW, &[]),
        "plain text should not be clickable"
    );
}

#[test]
fn click_inside_a_fused_marker_follows_the_label_clicked() {
    // Adjacent references render as one marker — `Body[^1][^2] more.`
    // shows "Body[1,2] more." — and each label stays separately clickable
    // because `InlineColMap` collapses the fused run exactly (two chars per
    // abutting reference: its `^` *and* its `[`).  Drop only the carets and
    // the map runs a column long, landing this click on footnote 1.
    //
    // The reference sits on a line away from the cursor so it renders
    // normally; a click on the cursor's own revealed line maps 1:1 against
    // the raw source instead, which is a different path.
    //
    // Rendered: B0 o1 d2 y3 [4 15 ,6 27 ]8 ' '9 …
    let src = "First line.\n\nBody[^1][^2] more.\n\n[^1]: one.\n\n[^2]: two.\n";
    for (col, label) in [(5u16, "1"), (7u16, "2")] {
        let mut st = state(src);
        st.cursor.offset = 0;
        let row = row_containing(&st, "Body");
        let action = MouseAction::Click {
            col,
            row,
            modifiers: KeyModifiers::NONE,
        };
        let mut drag = None;
        mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
        assert_eq!(
            st.pending_link_follow,
            Some(LinkTarget::Footnote(label.into())),
            "click at col {col} should follow footnote {label}"
        );
    }
}

#[test]
fn hover_over_definition_back_link_is_clickable() {
    // The definition leader (`↩ N.`) maps onto the `[^1]:` source and
    // should be clickable; the definition's body text should not.
    let st = state("Body[^1] more.\n\n[^1]: the note.\n");
    // Find the rendered row of the definition line.
    let def_row = st
        .parsed
        .lines
        .iter()
        .position(|l| {
            l.spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>()
                .contains("the note.")
        })
        .expect("definition line") as u16;
    // Column 0 is the leading space of the `  1.  ` leader, which is
    // column-matched to the raw `[^1]:` source, so it resolves as the
    // back-link.
    assert!(
        mouse_ops::hit_test_clickable(&st, 0, def_row, VW, &[]),
        "the definition leader should be clickable"
    );
    // The trailing `↩` glyph (last cell of the line) is also clickable.
    let def_line: String = st.parsed.lines[def_row as usize]
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect();
    let glyph_col = (def_line.chars().count() - 1) as u16;
    assert!(
        def_line.ends_with('↩'),
        "definition should end with the back-link glyph: {def_line:?}"
    );
    assert!(
        mouse_ops::hit_test_clickable(&st, glyph_col, def_row, VW, &[]),
        "the trailing back-link glyph should be clickable"
    );
}

fn row_containing(st: &EditorState, needle: &str) -> u16 {
    st.parsed
        .lines
        .iter()
        .position(|l| {
            l.spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>()
                .contains(needle)
        })
        .expect("line present") as u16
}

#[test]
fn rendered_mode_plain_click_on_reference_follows() {
    // A plain (non-Ctrl) click on the marker in Rendered mode must
    // follow the footnote, just like Preview.  The reference is on a line
    // away from the cursor so it renders normally (not revealed as raw).
    let mut st = state("First line.\n\nBody[^1] more.\n\n[^1]: the note.\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 0;
    let row = row_containing(&st, "Body"); // "Body[1] more." — marker at col 4
    let action = MouseAction::Click {
        col: 4,
        row,
        modifiers: KeyModifiers::NONE,
    };
    let mut drag = None;
    mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
    assert_eq!(
        st.pending_link_follow,
        Some(LinkTarget::Footnote("1".into())),
        "plain click on the marker should follow in Rendered mode"
    );
}

#[test]
fn rendered_mode_plain_click_on_back_link_follows() {
    let mut st = state("First line.\n\nBody[^1] more.\n\n[^1]: the note.\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 0;
    let row = row_containing(&st, "the note."); // "  1.  the note. ↩"
                                                // Column 0 is the leader, column-matched to the raw `[^1]:` source.
    let action = MouseAction::Click {
        col: 0,
        row,
        modifiers: KeyModifiers::NONE,
    };
    let mut drag = None;
    mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
    assert_eq!(
        st.pending_link_follow,
        Some(LinkTarget::FootnoteBack("1".into())),
        "plain click on the leader should follow in Rendered mode"
    );
}

#[test]
fn rendered_mode_plain_click_on_trailing_glyph_follows() {
    // The visible `↩` affordance at the end of the definition follows the
    // back-link even though it has no raw source byte.
    let mut st = state("First line.\n\nBody[^1] more.\n\n[^1]: the note.\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 0;
    let row = row_containing(&st, "the note.");
    let def_line: String = st.parsed.lines[row as usize]
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect();
    assert!(def_line.ends_with('↩'), "got: {def_line:?}");
    let glyph_col = (def_line.chars().count() - 1) as u16;
    let action = MouseAction::Click {
        col: glyph_col,
        row,
        modifiers: KeyModifiers::NONE,
    };
    let mut drag = None;
    mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
    assert_eq!(
        st.pending_link_follow,
        Some(LinkTarget::FootnoteBack("1".into())),
        "plain click on the trailing ↩ glyph should follow"
    );
}

#[test]
fn rendered_mode_click_on_space_before_glyph_follows() {
    // The space we render before the `↩` (the `" ↩"` chrome) is part of the
    // back-link hit zone.
    let mut st = state("First line.\n\nBody[^1] more.\n\n[^1]: the note.\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 0;
    let row = row_containing(&st, "the note.");
    let width = st.parsed.lines[row as usize]
        .spans
        .iter()
        .map(|s| s.content.chars().count())
        .sum::<usize>();
    let space_col = (width - 2) as u16; // cell before the trailing glyph
    let action = MouseAction::Click {
        col: space_col,
        row,
        modifiers: KeyModifiers::NONE,
    };
    let mut drag = None;
    mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
    assert_eq!(
        st.pending_link_follow,
        Some(LinkTarget::FootnoteBack("1".into())),
        "the space before the glyph should follow"
    );
}

#[test]
fn rendered_mode_click_past_glyph_places_cursor_not_follow() {
    // Clicking in the blank area beyond the glyph must place the cursor at
    // line end, not follow the back-link.
    let mut st = state("First line.\n\nBody[^1] more.\n\n[^1]: the note.\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 0;
    let row = row_containing(&st, "the note.");
    let width = st.parsed.lines[row as usize]
        .spans
        .iter()
        .map(|s| s.content.chars().count())
        .sum::<usize>();
    let action = MouseAction::Click {
        col: (width + 5) as u16, // well past the glyph
        row,
        modifiers: KeyModifiers::NONE,
    };
    let mut drag = None;
    mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
    assert_eq!(
        st.pending_link_follow, None,
        "a click past the glyph should not follow the back-link"
    );
}

#[test]
fn rendered_mode_plain_click_on_text_places_cursor_not_follow() {
    // A plain click on ordinary text in Rendered mode must NOT follow — it
    // places the cursor as usual.
    let mut st = state("First line.\n\nBody[^1] more.\n\n[^1]: the note.\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 0;
    let row = row_containing(&st, "Body");
    let action = MouseAction::Click {
        col: 1, // on "o" of "Body"
        row,
        modifiers: KeyModifiers::NONE,
    };
    let mut drag = None;
    mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
    assert_eq!(st.pending_link_follow, None);
}

#[test]
fn mouse_click_on_plain_text_stages_nothing() {
    let mut st = state("Body[^1] more.\n\n[^1]: the note.\n");
    let action = MouseAction::Click {
        col: 1, // on "o" of "Body" — not the marker
        row: 0,
        modifiers: KeyModifiers::NONE,
    };
    let mut drag = None;
    mouse_ops::apply(&mut st, action, &mut drag, &[], VP, VW);
    assert_eq!(st.pending_link_follow, None);
}

// ── Back-link hit zone where chars aren't cells (issue #60) ──────────────────

/// The columns of visual `row` where a plain Rendered-mode click on `src`, `width` cells wide,
/// follows the back-link, and those where the pointer shows a hand, each from a fresh state.
fn back_link_cols(src: &str, width: u16, row: u16) -> (Vec<u16>, Vec<u16>) {
    let fresh = || {
        let mut st = state(src);
        st.mode = Mode::Rendered;
        st.set_viewport_width(usize::from(width));
        st.cursor.offset = 0;
        st
    };
    let mut follows = Vec::new();
    let mut hovers = Vec::new();
    for col in 0..width {
        if mouse_ops::hit_test_clickable_non_link(&fresh(), col, row, usize::from(width), &[]) {
            hovers.push(col);
        }
        let mut st = fresh();
        let action = MouseAction::Click {
            col,
            row,
            modifiers: KeyModifiers::NONE,
        };
        mouse_ops::apply(&mut st, action, &mut None, &[], VP, usize::from(width));
        if st.pending_link_follow == Some(LinkTarget::FootnoteBack("1".into())) {
            follows.push(col);
        }
    }
    (follows, hovers)
}

/// `  1.  日本語の注釈です。 ↩` is 17 chars but 26 cells: the hit zone is the space and glyph at
/// cells 24–25, not the char count's 15–16 in the middle of the text.
#[test]
fn the_back_link_after_wide_text_is_where_it_paints() {
    let src = "First line.\n\nBody[^1] more.\n\n[^1]: 日本語の注釈です。\n";
    let (follows, hovers) = back_link_cols(src, 80, 4);
    // Cells 0–5 are the leader, which maps onto the raw `[^1]: ` and follows on its own.
    let past_leader = |cols: Vec<u16>| cols.into_iter().filter(|&c| c >= 6).collect::<Vec<_>>();
    assert_eq!(past_leader(follows), [24, 25]);
    assert_eq!(past_leader(hovers), [24, 25]);
}

/// A reflowed definition wraps, and its `↩` paints on the last row, behind the hanging indent.
/// It once never hit there: the click's column was compared with the length of the whole line.
#[test]
fn the_back_link_on_a_wrapped_definitions_last_row_is_clickable() {
    let src =
        "First line.\n\nBody[^1] more.\n\n[^1]: alpha bravo charlie delta echo foxtrot golf\n";
    // Rows 4–6, hung under the text (issue #71): `  1.  alpha bravo charlie` /
    // `      delta echo foxtrot` / `      golf ↩`.
    assert_eq!(back_link_cols(src, 26, 5), (vec![], vec![]));
    assert_eq!(back_link_cols(src, 26, 6), (vec![10, 11], vec![10, 11]));
}

/// The hover hit test measures a row in cells: a footnote marker after wide text, past the
/// row's char count, still shows the pointer.
#[test]
fn a_footnote_marker_after_wide_text_hovers() {
    let mut st = state("日本語日本語日本語日本語[^1] tail\n\n[^1]: n\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = st.buffer.rope().len_chars();
    // `[1]` paints at cells 24–26, after twelve two-cell glyphs.
    for col in 24..=26 {
        assert!(
            mouse_ops::hit_test_clickable_non_link(&st, col, 0, VW, &[]),
            "col {col}"
        );
    }
    assert!(!mouse_ops::hit_test_clickable_non_link(&st, 28, 0, VW, &[]));
}