mnml-rs 0.2.20

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
//! Pure free-function helpers extracted from `app/mod.rs` (A-5 of the
//! file-split refactor — 2026-06-28). These functions have no `App`
//! access — they take only their explicit arguments. Lifting them
//! here makes them easier to find and lets `mod.rs` shrink toward the
//! "App state + lifecycle" core it should have been all along.
//!
//! Re-exported from `app/mod.rs` via `pub(crate) use util::*;` so call
//! sites in sibling files (which use `use super::*;`) keep working
//! unchanged.

use std::path::Path;

/// True for files mnml renders as Markdown (md/markdown/mdx/mkd).
pub(crate) fn is_markdown_path(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some("md" | "markdown" | "mdx" | "mkd")
    )
}

/// True when `path` is the user's home directory (canonicalized). Used
/// by `App::add_workspace_runtime` to detect the empty-state landing
/// and promote the new folder to primary rather than adding as extra.
/// Mirrors the predicate in `ui::tree_view::is_empty_workspace` —
/// keep both in sync.
pub(crate) fn is_home_workspace(path: &Path) -> bool {
    let Some(home) = std::env::var_os("HOME") else {
        return false;
    };
    let home = std::path::PathBuf::from(home);
    let home_c = std::fs::canonicalize(&home).unwrap_or(home);
    path == home_c
}

/// True when `target` looks like a URL (any scheme mnml's external-
/// open path handles). Conservative — only the schemes listed.
pub(crate) fn is_url_like(target: &str) -> bool {
    const SCHEMES: &[&str] = &[
        "http://",
        "https://",
        "mailto:",
        "ftp://",
        "ftps://",
        "file://",
        "ssh://",
        "git://",
        "data:",
        "javascript:",
    ];
    SCHEMES.iter().any(|s| target.starts_with(s))
}

/// True for files mnml renders as inline images (png/jpg/jpeg/gif/
/// webp/bmp). Case-insensitive on the extension.
pub(crate) fn is_image_extension(path: &Path) -> bool {
    matches!(
        path.extension()
            .and_then(|e| e.to_str())
            .map(str::to_ascii_lowercase)
            .as_deref(),
        Some("png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp")
    )
}

/// OS-aware label for "Reveal in `<file browser>`". The underlying
/// `RevealInFinder` `MenuAction` handler shells out to the right
/// system command per OS.
pub(crate) fn reveal_in_files_label() -> &'static str {
    if cfg!(target_os = "macos") {
        "Reveal in Finder"
    } else if cfg!(target_os = "windows") {
        "Reveal in Explorer"
    } else {
        "Reveal in file browser"
    }
}

/// `p` made relative to `workspace` (for `git` arguments). Falls
/// back to `p` if it isn't under `workspace`.
pub(crate) fn rel_path(workspace: &Path, p: &Path) -> String {
    p.strip_prefix(workspace)
        .unwrap_or(p)
        .to_string_lossy()
        .into_owned()
}

/// #20 v4 — count directory entries recursively, capped at `max`
/// so a huge tree doesn't stall the delete prompt. Returns the
/// running total; when the cap is hit, the caller should show
/// `>= max entries` instead of the exact number.
pub(crate) fn walk_entry_count(dir: &Path, depth: u32, max: usize) -> usize {
    if depth > 8 {
        return 0;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return 0;
    };
    let mut total = 0usize;
    for entry in entries.flatten() {
        total += 1;
        if total >= max {
            return max;
        }
        let p = entry.path();
        if p.is_dir() {
            let sub = walk_entry_count(&p, depth + 1, max - total);
            total += sub;
            if total >= max {
                return max;
            }
        }
    }
    total
}

/// Pick the first free `stem-copy[.ext]` / `stem-copy-N[.ext]` name
/// next to `path`. Used by `file.duplicate` + `file.paste` when the
/// destination already exists in the same directory. 2026-07-07.
pub(crate) fn collision_free_copy_name(path: &Path) -> std::path::PathBuf {
    let Some(parent) = path.parent() else {
        return path.to_path_buf();
    };
    let stem_raw = path
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    let ext = path
        .extension()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    // #polish 2026-07-07 (vscode-mouse SEV-3 #12) — strip a trailing
    // `-copy` / `-copy-N` so duplicating `foo-copy.ext` produces
    // `foo-copy-2.ext`, not `foo-copy-copy.ext`. Matches Finder /
    // VS Code duplicate semantics.
    let stem = if let Some(base) = stem_raw
        .rsplit_once("-copy-")
        .and_then(|(base, tail)| tail.parse::<usize>().ok().map(|_| base))
    {
        base.to_string()
    } else if let Some(base) = stem_raw.strip_suffix("-copy") {
        base.to_string()
    } else {
        stem_raw
    };
    let make = |suffix: &str| {
        if ext.is_empty() {
            parent.join(format!("{stem}{suffix}"))
        } else {
            parent.join(format!("{stem}{suffix}.{ext}"))
        }
    };
    let first = make("-copy");
    if !first.exists() && first != path {
        return first;
    }
    for n in 2..1000 {
        let candidate = make(&format!("-copy-{n}"));
        if !candidate.exists() && candidate != path {
            return candidate;
        }
    }
    // Astronomical fallback — 1000 copies of the same file in one dir.
    make("-copy-lots")
}

/// True when `dst` IS `src` or sits underneath it — the shape that makes
/// a recursive copy eat its own output.
///
/// Compares canonicalised paths so `..`, symlinks and differing spellings
/// of the same directory are caught. `dst` usually does not exist yet, so
/// its PARENT is canonicalised and the final component appended; if even
/// the parent cannot be resolved the paths are compared as given, which
/// still catches the common literal case.
pub(crate) fn is_self_or_descendant(src: &Path, dst: &Path) -> bool {
    let canon_src = src.canonicalize().unwrap_or_else(|_| src.to_path_buf());
    let canon_dst = dst
        .canonicalize()
        .unwrap_or_else(|_| match (dst.parent(), dst.file_name()) {
            (Some(parent), Some(name)) => parent
                .canonicalize()
                .map(|p| p.join(name))
                .unwrap_or_else(|_| dst.to_path_buf()),
            _ => dst.to_path_buf(),
        });
    canon_dst.starts_with(&canon_src)
}

/// Recursive `cp` — files use `fs::copy`, directories walk children.
/// Returns Err with a human-readable string on the first failure.
pub(crate) fn copy_recursively(src: &Path, dst: &Path) -> Result<(), String> {
    // Refuse to copy a directory into itself or into one of its own
    // descendants.
    //
    // Without this the walk keeps finding what it has just written:
    // `read_dir(src)` yields the freshly-created copy inside `src`, which
    // is copied again, forever. It does not error — it recurses until the
    // stack runs out and the PROCESS ABORTS, taking any unsaved work with
    // it. CI caught it as `fatal runtime error: stack overflow` on Linux;
    // macOS's larger default stack merely made it slower to die.
    //
    // Trivial for a user to reach: mark a folder and paste it into
    // itself, which is one keystroke away in a file browser.
    if is_self_or_descendant(src, dst) {
        return Err(format!(
            "cannot copy {} into itself",
            src.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| src.display().to_string())
        ));
    }
    let meta =
        std::fs::symlink_metadata(src).map_err(|e| format!("stat {}: {e}", src.display()))?;
    if meta.is_dir() {
        std::fs::create_dir_all(dst).map_err(|e| format!("mkdir {}: {e}", dst.display()))?;
        for entry in
            std::fs::read_dir(src).map_err(|e| format!("read_dir {}: {e}", src.display()))?
        {
            let entry = entry.map_err(|e| e.to_string())?;
            let child_src = entry.path();
            let Some(name) = child_src.file_name() else {
                continue;
            };
            let child_dst = dst.join(name);
            copy_recursively(&child_src, &child_dst)?;
        }
        Ok(())
    } else if meta.file_type().is_symlink() {
        let target = std::fs::read_link(src).map_err(|e| e.to_string())?;
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&target, dst)
                .map_err(|e| format!("symlink {}: {e}", dst.display()))?;
        }
        // Windows symlinks require admin/dev-mode; fall back to
        // copying the resolved target (matches Git-for-Windows
        // behavior — visible file content, no dangling reference).
        #[cfg(windows)]
        {
            let resolved = if target.is_absolute() {
                target
            } else {
                src.parent()
                    .unwrap_or(std::path::Path::new("."))
                    .join(&target)
            };
            std::fs::copy(&resolved, dst)
                .map(|_| ())
                .map_err(|e| format!("symlink-as-copy {}: {e}", dst.display()))?;
        }
        Ok(())
    } else {
        std::fs::copy(src, dst)
            .map(|_| ())
            .map_err(|e| format!("copy {}{}: {e}", src.display(), dst.display()))
    }
}

/// Resolve `input` to an absolute path — `~` expands to the user's
/// home dir, relative paths join to `workspace`.
pub(crate) fn expand_tilde_and_resolve(workspace: &Path, input: &str) -> std::path::PathBuf {
    if let Some(rest) = input.strip_prefix("~/")
        && let Some(home) = std::env::var_os("HOME")
    {
        return std::path::PathBuf::from(home).join(rest);
    }
    if input == "~"
        && let Some(home) = std::env::var_os("HOME")
    {
        return std::path::PathBuf::from(home);
    }
    let p = std::path::PathBuf::from(input);
    if p.is_absolute() {
        p
    } else {
        workspace.join(p)
    }
}

/// Walk `text` and return every `(row, col_chars, len_chars)` for a
/// whole-word occurrence of `word`. Char columns (not byte) so the
/// renderer's per-cell painter can align without re-decoding UTF-8.
/// Caps at 5000 hits — a hard safeguard against pathological cases
/// (every occurrence of `the` in a novel-sized file).
pub fn collect_whole_word_occurrences(text: &str, word: &str) -> Vec<(usize, usize, usize)> {
    let word_chars: Vec<char> = word.chars().collect();
    if word_chars.is_empty() {
        return Vec::new();
    }
    let wlen = word_chars.len();
    let is_id = |c: char| c.is_alphanumeric() || c == '_';
    let mut out = Vec::new();
    for (row, line) in text.split('\n').enumerate() {
        let chars: Vec<char> = line.chars().collect();
        let n = chars.len();
        if n < wlen {
            continue;
        }
        let mut i = 0;
        while i + wlen <= n {
            if chars[i..i + wlen] == word_chars[..]
                && (i == 0 || !is_id(chars[i - 1]))
                && (i + wlen == n || !is_id(chars[i + wlen]))
            {
                out.push((row, i, wlen));
                if out.len() >= 5000 {
                    return out;
                }
                i += wlen;
            } else {
                i += 1;
            }
        }
    }
    out
}

/// Snap a byte offset to the nearest char boundary at or before
/// `byte`. crash-investigator 2026-06-28 SEV-3 fix: session restore
/// reads cursor_byte from disk; if the file was externally edited
/// to put astral-plane (4-byte) UTF-8 characters at the prior
/// position, slicing `text[..byte]` mid-char would panic. Always
/// snap before slicing.
fn snap_to_char_boundary(text: &str, byte: usize) -> usize {
    let byte = byte.min(text.len());
    // text.is_char_boundary(text.len()) is always true; this loop
    // terminates by byte == 0 at the latest. UTF-8 chars are at
    // most 4 bytes wide, so this scans at most 3 steps backward
    // — O(1) in practice despite the unbounded-looking range.
    // code-reviewer 3rd 2026-06-29 N-2: comment-clarifies the
    // false-alarm O(n) read.
    (0..=byte)
        .rev()
        .find(|&b| text.is_char_boundary(b))
        .unwrap_or(0)
}

/// Byte offset → `(line, col_chars)`. Used by find / search / mark
/// flows to convert match positions into editor-cursor coords.
pub(crate) fn byte_to_line_col(text: &str, byte: usize) -> (usize, usize) {
    let cap = snap_to_char_boundary(text, byte);
    let line = text[..cap].bytes().filter(|&b| b == b'\n').count();
    let line_start = text[..cap].rfind('\n').map(|i| i + 1).unwrap_or(0);
    let col = text[line_start..cap].chars().count();
    (line, col)
}

/// Synonym of `byte_to_line_col` — kept for the snippet / LSP edit
/// sites that named the line as "row".
pub(crate) fn byte_to_row_col(text: &str, byte: usize) -> (usize, usize) {
    let byte = snap_to_char_boundary(text, byte);
    let row = text[..byte].bytes().filter(|&b| b == b'\n').count();
    let line_start = text[..byte].rfind('\n').map(|i| i + 1).unwrap_or(0);
    let col = text[line_start..byte].chars().count();
    (row, col)
}

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

    #[test]
    fn byte_to_row_col_snaps_mid_emoji_to_boundary() {
        // crash-investigator 2026-06-28 SEV-3: a session-restored
        // cursor_byte landing inside a multi-byte char must NOT
        // panic. The snap-to-boundary helper keeps the slice safe.
        let text = "a\u{1F600}b"; // a + 😀 (4 bytes) + b — 6 bytes total
        // Boundaries: 0 (a), 1 (start of 😀), 5 (start of b), 6 (end).
        // byte=3 lands inside 😀 — should snap back to 1.
        let (row, col) = byte_to_row_col(text, 3);
        assert_eq!(row, 0);
        assert_eq!(col, 1, "cursor lands between 'a' and the emoji");
        // byte=4 (still inside 😀) snaps to 1.
        let (row, col) = byte_to_row_col(text, 4);
        assert_eq!((row, col), (0, 1));
        // byte=6 (end) stays at end → col 3 (a + emoji + b = 3 chars).
        let (row, col) = byte_to_row_col(text, 6);
        assert_eq!((row, col), (0, 3));
        // Past-end clamps.
        let (row, col) = byte_to_row_col(text, 999);
        assert_eq!((row, col), (0, 3));
    }

    #[test]
    fn byte_to_line_col_snaps_too() {
        let text = "x\u{1F600}\nfoo";
        let (line, col) = byte_to_line_col(text, 3);
        assert_eq!((line, col), (0, 1));
        let (line, col) = byte_to_line_col(text, 8);
        assert_eq!((line, col), (1, 2));
    }
}

#[cfg(test)]
mod self_copy_guard_tests {
    use super::*;

    /// The crash CI caught: copying a directory into itself recursed
    /// until the stack ran out and the PROCESS ABORTED. Not an error
    /// return — a hard abort, taking unsaved work with it.
    #[test]
    fn copying_a_directory_into_itself_is_refused_not_fatal() {
        let d = tempfile::tempdir().unwrap();
        let src = d.path().join("folder");
        std::fs::create_dir(&src).unwrap();
        std::fs::write(src.join("f.txt"), "x").unwrap();

        let err = copy_recursively(&src, &src.join("folder"))
            .expect_err("copying a directory into itself must be refused");
        assert!(err.contains("itself"), "unhelpful message: {err}");
    }

    /// And into a deeper descendant, which is the same trap one level
    /// down.
    #[test]
    fn copying_into_a_descendant_is_refused() {
        let d = tempfile::tempdir().unwrap();
        let src = d.path().join("folder");
        std::fs::create_dir_all(src.join("nested").join("deeper")).unwrap();
        assert!(
            copy_recursively(&src, &src.join("nested").join("deeper").join("copy")).is_err(),
            "copying into a descendant must be refused"
        );
    }

    /// A NORMAL copy must still work — a guard that refuses everything
    /// would pass the two tests above.
    #[test]
    fn copying_to_a_sibling_still_works() {
        let d = tempfile::tempdir().unwrap();
        let src = d.path().join("folder");
        std::fs::create_dir(&src).unwrap();
        std::fs::write(src.join("f.txt"), "x").unwrap();
        let dst = d.path().join("copy");

        copy_recursively(&src, &dst).expect("a sibling copy must succeed");
        assert!(dst.join("f.txt").is_file(), "contents were not copied");
    }

    /// The check is on canonicalised paths, so a `..` spelling of the
    /// same destination is caught too.
    #[test]
    fn a_dotdot_spelling_of_the_same_target_is_caught() {
        let d = tempfile::tempdir().unwrap();
        let src = d.path().join("folder");
        std::fs::create_dir_all(src.join("sub")).unwrap();
        // folder/sub/../inner == folder/inner — inside `src`.
        let sneaky = src.join("sub").join("..").join("inner");
        assert!(
            is_self_or_descendant(&src, &sneaky),
            "a `..` path into the source was not recognised"
        );
    }

    #[test]
    fn an_unrelated_directory_is_not_a_descendant() {
        let d = tempfile::tempdir().unwrap();
        let a = d.path().join("a");
        let b = d.path().join("b");
        std::fs::create_dir_all(&a).unwrap();
        std::fs::create_dir_all(&b).unwrap();
        assert!(!is_self_or_descendant(&a, &b.join("x")));
    }

    /// `a` must not be treated as a parent of `ab` — a plain string
    /// prefix check would get this wrong.
    #[test]
    fn a_sibling_with_a_shared_name_prefix_is_not_a_descendant() {
        let d = tempfile::tempdir().unwrap();
        let a = d.path().join("proj");
        let ab = d.path().join("project");
        std::fs::create_dir_all(&a).unwrap();
        std::fs::create_dir_all(&ab).unwrap();
        assert!(
            !is_self_or_descendant(&a, &ab.join("x")),
            "`proj` was treated as an ancestor of `project`"
        );
    }
}