kimun-notes 0.24.5

A terminal-based notes application
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
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Markdown-aware edits over the **rope buffer**: list continuation on Enter,
//! **auto-surround**, the emphasis markers behind Bold / Italic / Strikethrough,
//! and the heading jump the OUTLINE drawer asks for.
//!
//! Every operation here takes `&mut RopeBuffer` and nothing else — the same
//! shape as the plain key table and the vim engine — so each is tested against
//! a bare buffer, not an editor. The two lookups beside them (`surround_pair`,
//! `emphasis_marker`) map a key or a `TextAction` to its markers and touch no
//! buffer at all. The buffer knows text; this module knows
//! markdown; the component that calls both knows which backend is live, what a
//! vim Visual selection includes, and what an edit owes it afterwards (the
//! selection mirror, the typing run, the outcome drain). None of that is here.

use super::markdown;
use super::rope_buffer::{CursorMove, RopeBuffer};
use crate::keys::action_shortcuts::TextAction;

/// Auto-surround pair for `c`: typing an opening pair character or a
/// symmetric one while a selection is active wraps the selection instead of
/// replacing it. Closing characters return `None` — they replace, like any
/// other key. See CONTEXT.md **Auto-surround**.
pub fn surround_pair(c: char) -> Option<(&'static str, &'static str)> {
    match c {
        '(' => Some(("(", ")")),
        '[' => Some(("[", "]")),
        '{' => Some(("{", "}")),
        '<' => Some(("<", ">")),
        '"' => Some(("\"", "\"")),
        '\'' => Some(("'", "'")),
        '`' => Some(("`", "`")),
        '*' => Some(("*", "*")),
        '_' => Some(("_", "_")),
        '~' => Some(("~", "~")),
        _ => None,
    }
}

/// The marker an emphasis action wraps a selection in, or `None` for the
/// actions that are not emphasis — Link, Image and the headers, which nothing
/// here handles.
pub fn emphasis_marker(action: TextAction) -> Option<&'static str> {
    match action {
        TextAction::Bold => Some("**"),
        TextAction::Italic => Some("*"),
        TextAction::Strikethrough => Some("~~"),
        _ => None,
    }
}

/// Wrap the selection in `open` … `close` and reselect the inner text, so
/// wraps chain — `[` `[` builds a wikilink. One **undo group**: the replace is
/// a single transaction. `false`, touching nothing, without a selection of
/// some width.
pub fn wrap_selection(buf: &mut RopeBuffer, open: &str, close: &str) -> bool {
    let Some(((sr, sc), (er, ec))) = buf.selection_range() else {
        return false;
    };
    let Some(text) = buf.selection_text() else {
        return false;
    };
    buf.insert_str(format!("{open}{text}{close}"));
    // The open marker shifts columns on the first selected row only; columns
    // are chars, matching `selection_range`.
    let shift = open.chars().count();
    let inner_end_col = if sr == er { ec + shift } else { ec };
    buf.set_selection((sr, sc + shift), (er, inner_end_col));
    true
}

/// Insert `open` and `close` at the cursor and leave the cursor between them —
/// what Bold does with nothing selected: `****`, cursor in the middle.
pub fn insert_pair(buf: &mut RopeBuffer, open: &str, close: &str) {
    buf.insert_str(format!("{open}{close}"));
    for _ in 0..close.chars().count() {
        buf.move_cursor(CursorMove::Back);
    }
}

/// Smart Enter at the end of a row: continue a list marker (an ordered one
/// incremented), carry the indent, dedent an indent-only row, and clear an
/// empty list item — dedenting it first while it is indented. `true` when
/// handled, so the caller does not insert a plain newline; `false` mid-row,
/// with a selection of some width, or on a row that is neither indented nor a
/// list item.
pub fn smart_enter(buf: &mut RopeBuffer) -> bool {
    enum Action {
        ClearRow { chars: usize },
        InsertPrefix(String),
        Dedent,
    }
    // A mouse click leaves a zero-width selection active, so only a selection
    // of some width declines.
    if buf
        .selection_range()
        .is_some_and(|(start, end)| start != end)
    {
        return false;
    }
    let (row, action) = {
        let (row, col) = buf.cursor();
        let Some(line) = buf.row(row) else {
            return false;
        };
        let total_chars = line.chars().count();
        if col != total_chars {
            return false;
        }
        // ASCII whitespace, so byte index == char index here.
        let ws_end = markdown::leading_ws_byte_len(&line);
        let (ws, after_ws) = line.split_at(ws_end);
        let action = if let Some(marker_len) = markdown::list_marker_len(after_ws) {
            if after_ws.len() == marker_len {
                // An empty item: dedent while indented, then clear the marker
                // once fully unindented.
                if ws_end > 0 {
                    Action::Dedent
                } else {
                    Action::ClearRow { chars: total_chars }
                }
            } else {
                let marker = &after_ws[..marker_len];
                let next = increment_ordered_marker(marker).unwrap_or_else(|| marker.to_string());
                Action::InsertPrefix(format!("{ws}{next}"))
            }
        } else if ws_end > 0 && total_chars == ws_end {
            Action::Dedent
        } else if ws_end > 0 {
            Action::InsertPrefix(ws.to_string())
        } else {
            return false;
        };
        (row, action)
    };
    match action {
        // Reports what the dedent did — always a change here, since the row
        // has leading whitespace and a step is never zero.
        Action::Dedent => return buf.indent_rows(row..=row, true),
        Action::ClearRow { chars } => {
            buf.move_cursor(CursorMove::Head);
            buf.delete_str(chars);
        }
        Action::InsertPrefix(prefix) => {
            // Newline plus prefix is two history entries; one `edit()` scope
            // makes continuing a list one undo.
            buf.edit(|buf| {
                buf.insert_newline();
                buf.insert_str(prefix);
            });
        }
    }
    true
}

/// Move the cursor to the first heading row whose rendered text equals
/// `heading`, at any level — the OUTLINE drawer's jump. `false`, cursor
/// untouched, when none matches.
///
/// "Rendered" is what the OUTLINE shows, and the row is rendered by the same
/// core function that produced the entry (`scan::heading_display_text`:
/// wikilinks and links to their text, hashtag markers dropped, emphasis and
/// ATX markers gone), so the two agree wherever a line can be rendered alone —
/// `heading_display_text` names the limits (setext headings, reference-style
/// links, a `#` line inside a fence). A normaliser of our own once lived here
/// and missed every heading holding a link or a tag.
pub fn jump_to_heading(buf: &mut RopeBuffer, heading: &str) -> bool {
    let row = (0..buf.row_count()).find(|&row| {
        buf.row(row).is_some_and(|line| {
            kimun_core::note::scan::heading_display_text(&line).as_deref() == Some(heading)
        })
    });
    match row {
        Some(row) => {
            // A jump is a cursor move, not a selection gesture: drop any live
            // selection (a mouse click leaves a zero-width one) before moving.
            buf.cancel_selection();
            buf.jump_to(row, 0)
        }
        None => false,
    }
}

/// If `marker` is an ordered-list marker like `"3. "`, the next one (`"4. "`).
/// `None` for unordered markers or unrecognised input.
fn increment_ordered_marker(marker: &str) -> Option<String> {
    let trimmed = marker.trim_end_matches(' ');
    let dot = trimmed.strip_suffix('.')?;
    let n: u32 = dot.parse().ok()?;
    Some(format!("{}. ", n + 1))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ropetext::Text;

    fn buffer(text: &str) -> RopeBuffer {
        RopeBuffer::new(Text::from(text))
    }

    /// A buffer with the cursor at the very end of its text.
    fn at_end(text: &str) -> RopeBuffer {
        let mut buf = buffer(text);
        buf.move_cursor(CursorMove::Bottom);
        buf.move_cursor(CursorMove::End);
        buf
    }

    fn text(buf: &RopeBuffer) -> String {
        buf.text().to_string()
    }

    // ── surround / wrap ───────────────────────────────────────────────────

    #[test]
    fn surround_pair_maps_open_and_symmetric_chars() {
        assert_eq!(surround_pair('('), Some(("(", ")")));
        assert_eq!(surround_pair('['), Some(("[", "]")));
        assert_eq!(surround_pair('{'), Some(("{", "}")));
        assert_eq!(surround_pair('<'), Some(("<", ">")));
        assert_eq!(surround_pair('"'), Some(("\"", "\"")));
        assert_eq!(surround_pair('\''), Some(("'", "'")));
        assert_eq!(surround_pair('`'), Some(("`", "`")));
        assert_eq!(surround_pair('*'), Some(("*", "*")));
        assert_eq!(surround_pair('_'), Some(("_", "_")));
        assert_eq!(surround_pair('~'), Some(("~", "~")));
        assert_eq!(surround_pair(')'), None);
        assert_eq!(surround_pair(']'), None);
        assert_eq!(surround_pair('}'), None);
        assert_eq!(surround_pair('>'), None);
        assert_eq!(surround_pair('a'), None);
    }

    #[test]
    fn emphasis_marker_covers_bold_italic_and_strikethrough_only() {
        assert_eq!(emphasis_marker(TextAction::Bold), Some("**"));
        assert_eq!(emphasis_marker(TextAction::Italic), Some("*"));
        assert_eq!(emphasis_marker(TextAction::Strikethrough), Some("~~"));
        assert_eq!(emphasis_marker(TextAction::Underline), None);
        assert_eq!(emphasis_marker(TextAction::Link), None);
        assert_eq!(emphasis_marker(TextAction::Image), None);
        assert_eq!(emphasis_marker(TextAction::ToggleHeader), None);
        assert_eq!(emphasis_marker(TextAction::Header(1)), None);
    }

    #[test]
    fn wrap_reselects_the_inner_text_so_wraps_chain() {
        let mut buf = buffer("my note");
        assert!(buf.set_selection((0, 0), (0, 7)));
        assert!(wrap_selection(&mut buf, "[", "]"));
        assert_eq!(text(&buf), "[my note]");
        assert_eq!(buf.selection_range(), Some(((0, 1), (0, 8))));
        assert!(wrap_selection(&mut buf, "[", "]"));
        assert_eq!(text(&buf), "[[my note]]");
        assert_eq!(buf.selection_range(), Some(((0, 2), (0, 9))));
    }

    #[test]
    fn wrap_spans_a_multi_row_selection() {
        let mut buf = buffer("abc\ndef");
        assert!(buf.set_selection((0, 0), (1, 3)));
        assert!(wrap_selection(&mut buf, "(", ")"));
        assert_eq!(text(&buf), "(abc\ndef)");
        // The open marker shifts only the first row.
        assert_eq!(buf.selection_range(), Some(((0, 1), (1, 3))));
    }

    #[test]
    fn wrap_counts_columns_in_chars() {
        let mut buf = buffer("héllo🦀 x");
        assert!(buf.set_selection((0, 0), (0, 6))); // "héllo🦀" = 6 chars
        assert!(wrap_selection(&mut buf, "`", "`"));
        assert_eq!(text(&buf), "`héllo🦀` x");
        assert_eq!(buf.selection_range(), Some(((0, 1), (0, 7))));
    }

    #[test]
    fn wrap_handles_a_selection_made_right_to_left() {
        let mut buf = buffer("hello world");
        assert!(buf.jump_to(0, 5));
        buf.start_selection();
        assert!(buf.jump_to(0, 0));
        assert!(wrap_selection(&mut buf, "(", ")"));
        assert_eq!(text(&buf), "(hello) world");
        assert_eq!(buf.selection_range(), Some(((0, 1), (0, 6))));
    }

    #[test]
    fn wrap_uses_a_word_selection_as_it_stands() {
        let mut buf = buffer("hello world");
        buf.move_cursor(CursorMove::Head);
        buf.start_selection();
        buf.move_cursor(CursorMove::WordForward);
        assert!(wrap_selection(&mut buf, "~~", "~~"));
        assert_eq!(text(&buf), "~~hello ~~world");
    }

    #[test]
    fn wrap_handles_a_non_ascii_selection() {
        let mut buf = buffer("hello 你好 world");
        buf.move_cursor(CursorMove::Head);
        buf.move_cursor(CursorMove::WordForward);
        buf.start_selection();
        buf.move_cursor(CursorMove::WordForward);
        assert!(wrap_selection(&mut buf, "**", "**"));
        assert_eq!(text(&buf), "hello **你好 **world");
    }

    #[test]
    fn wrap_without_a_selection_touches_nothing() {
        let mut buf = at_end("hello");
        assert!(!wrap_selection(&mut buf, "(", ")"));
        assert_eq!(text(&buf), "hello");
        assert!(!buf.take_outcome().changed);
    }

    #[test]
    fn a_zero_width_selection_does_not_wrap() {
        let mut buf = buffer("hello");
        assert!(buf.jump_to(0, 2));
        buf.start_selection();
        assert!(!wrap_selection(&mut buf, "(", ")"));
        assert_eq!(text(&buf), "hello");
    }

    #[test]
    fn a_wrap_is_one_undo_group() {
        // The replace is a single transaction, so the gesture is one history
        // entry. Asserting what each undo *returns* is what makes this a claim
        // about grouping rather than about the final text.
        let mut buf = buffer("hello world");
        assert!(buf.set_selection((0, 0), (0, 5)));
        assert!(wrap_selection(&mut buf, "(", ")"));
        assert_eq!(text(&buf), "(hello) world");
        assert!(buf.undo(), "the wrap is one entry");
        assert_eq!(text(&buf), "hello world");
        assert!(!buf.undo(), "and has no second half left to take back");
    }

    #[test]
    fn insert_pair_leaves_the_cursor_between_the_markers() {
        let mut buf = at_end("hello");
        insert_pair(&mut buf, "**", "**");
        assert_eq!(text(&buf), "hello****");
        assert_eq!(buf.cursor(), (0, 7));
    }

    #[test]
    fn insert_pair_with_a_single_char_marker() {
        let mut buf = buffer("");
        insert_pair(&mut buf, "*", "*");
        assert_eq!(text(&buf), "**");
        assert_eq!(buf.cursor(), (0, 1));
    }

    // ── smart enter ───────────────────────────────────────────────────────

    #[test]
    fn smart_enter_continues_an_unordered_list() {
        let mut buf = at_end("- foo");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "- foo\n- ");
    }

    #[test]
    fn smart_enter_increments_an_ordered_list() {
        let mut buf = at_end("1. foo");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "1. foo\n2. ");
    }

    #[test]
    fn smart_enter_continues_an_indented_list() {
        let mut buf = at_end("  - foo");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "  - foo\n  - ");
    }

    #[test]
    fn smart_enter_continues_a_list_with_non_ascii_content() {
        let mut buf = at_end("- 你好");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "- 你好\n- ");
    }

    #[test]
    fn smart_enter_on_an_empty_list_marker_clears_the_row() {
        let mut buf = at_end("- ");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "");
    }

    #[test]
    fn smart_enter_on_an_empty_indented_list_marker_dedents_keeping_the_marker() {
        let mut buf = at_end("    - ");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "- ");
    }

    #[test]
    fn smart_enter_clears_an_empty_list_marker_once_fully_dedented() {
        let mut buf = at_end("    - ");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "- ");
        buf.move_cursor(CursorMove::End);
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "");
    }

    #[test]
    fn smart_enter_carries_the_indent() {
        let mut buf = at_end("    body");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "    body\n    ");
    }

    #[test]
    fn smart_enter_carries_an_existing_tab_indent() {
        // Carrying is not inserting: a tab the row already has is kept as it is.
        let mut buf = at_end("\tbody");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "\tbody\n\t");
    }

    #[test]
    fn smart_enter_on_an_indent_only_row_dedents() {
        let mut buf = at_end("    ");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "");
    }

    #[test]
    fn smart_enter_on_a_tab_only_row_dedents_one_tab() {
        let mut buf = at_end("\t\t");
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "\t");
    }

    #[test]
    fn smart_enter_declines_a_plain_row() {
        let mut buf = at_end("plain");
        assert!(!smart_enter(&mut buf));
        assert_eq!(text(&buf), "plain");
    }

    #[test]
    fn smart_enter_declines_mid_row() {
        let mut buf = buffer("- foo");
        assert!(buf.jump_to(0, 2));
        assert!(!smart_enter(&mut buf));
        assert_eq!(text(&buf), "- foo");
    }

    #[test]
    fn smart_enter_declines_a_selection_of_width() {
        let mut buf = at_end("- foo");
        assert!(buf.set_selection((0, 0), (0, 2)));
        assert!(!smart_enter(&mut buf));
        assert_eq!(text(&buf), "- foo");
    }

    #[test]
    fn a_zero_width_selection_does_not_stop_smart_enter() {
        // A mouse click leaves one behind.
        let mut buf = at_end("- foo");
        buf.start_selection();
        assert!(smart_enter(&mut buf));
        assert_eq!(text(&buf), "- foo\n- ");
    }

    #[test]
    fn continuing_a_list_is_one_undo_group() {
        let mut buf = at_end("- foo");
        assert!(smart_enter(&mut buf));
        assert!(buf.undo(), "newline plus marker is one entry");
        assert_eq!(text(&buf), "- foo");
        assert!(!buf.undo());
    }

    // ── heading jump ──────────────────────────────────────────────────────

    #[test]
    fn jump_to_heading_finds_any_level_and_normalises_markup() {
        let mut buf = buffer("intro\n# Top\nbody\n## **Sub** One ##\nmore\n");
        assert!(jump_to_heading(&mut buf, "Sub One"));
        assert_eq!(buf.cursor(), (3, 0));
        assert!(jump_to_heading(&mut buf, "Top"));
        assert_eq!(buf.cursor(), (1, 0));
    }

    #[test]
    fn an_unknown_heading_leaves_the_cursor_where_it_was() {
        let mut buf = buffer("intro\n# Top\nbody");
        assert!(buf.jump_to(2, 1));
        assert!(!jump_to_heading(&mut buf, "Nope"));
        assert_eq!(buf.cursor(), (2, 1));
    }

    #[test]
    fn jump_to_heading_drops_a_live_selection_instead_of_extending_it() {
        let mut buf = buffer("intro\n# Top\nbody");
        assert!(buf.jump_to(2, 1));
        buf.start_selection(); // the zero-width anchor a mouse click leaves
        assert!(jump_to_heading(&mut buf, "Top"));
        assert_eq!(buf.cursor(), (1, 0));
        assert_eq!(buf.selection_range(), None);
    }

    #[test]
    fn a_hash_inside_a_row_is_not_a_heading() {
        let mut buf = buffer("see #tag here\n# Real");
        assert!(jump_to_heading(&mut buf, "Real"));
        assert_eq!(buf.cursor(), (1, 0));
        assert!(!jump_to_heading(&mut buf, "tag here"));
    }

    #[test]
    fn jump_to_heading_finds_headings_holding_links_and_tags() {
        // What the OUTLINE lists for these rows, per core's chunker.
        let mut buf =
            buffer("# See [[other note]]\na\n# Sprint #42\nb\n# Docs [here](https://x.y)\nc\n");
        assert!(jump_to_heading(&mut buf, "Docs here"));
        assert_eq!(buf.cursor(), (4, 0));
        assert!(jump_to_heading(&mut buf, "Sprint 42"));
        assert_eq!(buf.cursor(), (2, 0));
        assert!(jump_to_heading(&mut buf, "See other note"));
        assert_eq!(buf.cursor(), (0, 0));
        assert!(
            !jump_to_heading(&mut buf, "See [[other note]]"),
            "raw source is not what the OUTLINE shows"
        );
    }
}