edamame 0.1.2

A fast TUI Markdown editor and viewer
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
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use ropey::Rope;

/// Wraps a `ropey::Rope` with file-level I/O and basic edit operations.
///
/// All positions and lengths are in Unicode scalar values (Rust `char`s),
/// matching ropey's native char-index API.
#[derive(Debug, Clone)]
pub struct Buffer {
    rope: Rope,
    /// The file this buffer was loaded from or last saved to.
    path: Option<PathBuf>,
    /// Monotonically-increasing counter bumped on every content mutation.
    /// Consumers that cache buffer-derived data (e.g. the raw-mode visual
    /// row cache in `EditorState`) compare this against their stored
    /// version to invalidate stale entries without rebuilding eagerly.
    /// Wraps on overflow — wrap-equality is fine because adjacent edits
    /// always differ, and wrap-around requires 2^64 mutations.
    version: u64,
}

impl Buffer {
    /// Create an empty buffer with no associated file.
    pub fn new() -> Self {
        Self {
            rope: Rope::new(),
            path: None,
            version: 0,
        }
    }

    /// Create a buffer pre-filled with `text` and no associated file.
    ///
    /// The pathless entry point: used by `App::load_doc_into_editor`
    /// for a page of the embedded manual, whose text lives in the
    /// binary rather than on disk, and by integration tests in
    /// `tests/`.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(text: &str) -> Self {
        Self {
            rope: Rope::from_str(text),
            path: None,
            version: 0,
        }
    }

    /// Create a buffer wrapping a pre-built rope with no associated
    /// file.  Used by the diff subsystem (`DiffState::new`) so the
    /// new-side text gets the same `Buffer` API as the main buffer
    /// without re-allocating the rope from a `String`.
    pub fn from_rope(rope: Rope) -> Self {
        Self {
            rope,
            path: None,
            version: 0,
        }
    }

    /// Load a file from disk into the buffer.
    pub fn load_file(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read file: {}", path.display()))?;
        Ok(Self {
            rope: Rope::from_str(&content),
            path: Some(path.to_owned()),
            version: 0,
        })
    }

    /// Empty buffer associated with `path`, used when the user names a
    /// file that does not yet exist.  Saving will create the file.
    pub fn for_new_file(path: &Path) -> Self {
        Self {
            rope: Rope::new(),
            path: Some(path.to_owned()),
            version: 0,
        }
    }

    /// Rebuild a buffer from a fresh on-disk read.  Used by
    /// `App::reload_buffer_from_disk` when an external edit replaces
    /// the file under us.  The new buffer's `version` starts at
    /// `previous_version.wrapping_add(1)` so the monotonic-version
    /// invariant other consumers rely on (e.g. the autosave
    /// edit-detection check in `tick_autosave`) is preserved across
    /// the buffer swap.  Unlike [`Self::load_file`], the bytes come
    /// from the caller — the watcher worker has already read them —
    /// so there is no second disk hit and no chance of racing the
    /// next watcher event.
    pub fn reload(path: &Path, contents: &str, previous_version: u64) -> Self {
        Self {
            rope: Rope::from_str(contents),
            path: Some(path.to_owned()),
            version: previous_version.wrapping_add(1),
        }
    }

    /// Write the buffer contents to disk at the associated path.
    ///
    /// Returns an error if no path is set.
    pub fn save_file(&self) -> Result<()> {
        let path = self
            .path
            .as_deref()
            .ok_or_else(|| anyhow::anyhow!("Buffer has no associated file path"))?;
        let content = self.rope.to_string();
        std::fs::write(path, content)
            .with_context(|| format!("Failed to write file: {}", path.display()))?;
        Ok(())
    }

    /// Save to an explicit path and adopt it as the buffer's associated
    /// path.  The shared write primitive behind every "Save As" flow
    /// (command palette, a path-less `Save`, vim `:w <path>` / `:saveas`,
    /// and the file-deleted recovery flow) via
    /// [`crate::app::App::save_buffer_as`], plus integration tests in
    /// `tests/`.
    ///
    /// Overwrites `path` **unconditionally** — this is the low-level
    /// force primitive.  Callers are responsible for confirming an
    /// overwrite of a *different* existing file first (see
    /// [`Self::would_overwrite`] and the `OverwriteConfirmModal` flow);
    /// saving over the buffer's own path is a normal in-place save and
    /// needs no confirmation.
    pub fn save_as(&mut self, path: &Path) -> Result<()> {
        let content = self.rope.to_string();
        std::fs::write(path, &content)
            .with_context(|| format!("Failed to write file: {}", path.display()))?;
        self.path = Some(path.to_owned());
        Ok(())
    }

    /// True when writing to `path` would clobber a *different* existing
    /// file — i.e. `path` already exists and is not this buffer's own
    /// associated path.  Saving over the buffer's current file is a
    /// normal in-place save (never an "overwrite" in this sense), so a
    /// Save As to the seeded current path passes.  Callers use this to
    /// decide whether to confirm before [`Self::save_as`], which writes
    /// unconditionally.
    ///
    /// Comparison is by stored path value, so an unusual spelling of the
    /// same file (e.g. relative vs. absolute) may prompt a harmless extra
    /// confirmation — saying yes simply re-saves that same file.
    pub fn would_overwrite(&self, path: &Path) -> bool {
        path.exists() && self.path.as_deref() != Some(path)
    }

    /// Write the buffer contents to `path` without touching the
    /// buffer's associated path.  The user keeps editing the original
    /// file; `path` receives a snapshot of the current contents.
    pub fn save_copy(&self, path: &Path) -> Result<()> {
        let content = self.rope.to_string();
        std::fs::write(path, &content)
            .with_context(|| format!("Failed to write file: {}", path.display()))?;
        Ok(())
    }

    // ── Query ─────────────────────────────────────────────────────

    /// The file path associated with this buffer, if any.
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Total number of Unicode scalar values in the buffer.
    pub fn len_chars(&self) -> usize {
        self.rope.len_chars()
    }

    /// Total number of lines (including a trailing empty line if the buffer
    /// ends with a newline).
    pub fn line_count(&self) -> usize {
        self.rope.len_lines()
    }

    /// Return the content of line `idx` (0-indexed) as an owned `String`.
    ///
    /// Returns `None` if `idx >= line_count()`.
    pub fn line(&self, idx: usize) -> Option<String> {
        if idx >= self.rope.len_lines() {
            return None;
        }
        Some(self.rope.line(idx).to_string())
    }

    /// Return the entire buffer contents as a `String`.
    pub fn contents(&self) -> String {
        self.rope.to_string()
    }

    /// Return a reference to the underlying rope for read-only access.
    pub fn rope(&self) -> &Rope {
        &self.rope
    }

    /// Return the char offset for the start of `line_idx` (0-indexed).
    pub fn line_to_char(&self, line_idx: usize) -> usize {
        self.rope.line_to_char(line_idx)
    }

    /// Return the line index (0-indexed) that contains `char_idx`.
    pub fn char_to_line(&self, char_idx: usize) -> usize {
        self.rope.char_to_line(char_idx)
    }

    /// Return the line index (0-indexed) that contains `byte_idx`.
    /// Convenience for the common `char_to_line(byte_to_char(b))` pair —
    /// callers that have a byte offset (block ranges, source-map
    /// lookups) avoid the double-call and the chance of getting the
    /// argument order wrong.
    pub fn byte_to_line(&self, byte_idx: usize) -> usize {
        self.rope.char_to_line(self.rope.byte_to_char(byte_idx))
    }

    /// Buffer line index for the `raw_line_idx`-th line within a block
    /// whose byte range starts at `block_byte_start`.
    pub fn block_line_to_buffer_line(&self, block_byte_start: usize, raw_line_idx: usize) -> usize {
        let block_start_char = self.rope.byte_to_char(block_byte_start);
        let block_start_line = self.rope.char_to_line(block_start_char);
        block_start_line + raw_line_idx
    }

    /// Monotonic version counter — increments on every content mutation.
    /// Consumers cache derived state keyed by `(version, ...)` so
    /// invalidation is a cheap `u64` comparison.
    pub fn version(&self) -> u64 {
        self.version
    }

    // ── Edit ──────────────────────────────────────────────────────

    /// Insert `text` at char offset `char_idx`.
    pub fn insert(&mut self, char_idx: usize, text: &str) {
        self.rope.insert(char_idx, text);
        self.version = self.version.wrapping_add(1);
    }

    /// Insert a single char at char offset `char_idx`.
    /// Used by tests in this crate.
    #[allow(dead_code)]
    pub fn insert_char(&mut self, char_idx: usize, ch: char) {
        self.rope.insert_char(char_idx, ch);
        self.version = self.version.wrapping_add(1);
    }

    /// Remove chars in the range `start..end` (char offsets).
    pub fn remove(&mut self, start: usize, end: usize) {
        self.rope.remove(start..end);
        self.version = self.version.wrapping_add(1);
    }

    /// Remove a single char at `char_idx` (if in bounds).
    /// Used by tests in this crate.
    #[allow(dead_code)]
    pub fn remove_char(&mut self, char_idx: usize) {
        if char_idx < self.rope.len_chars() {
            self.rope.remove(char_idx..char_idx + 1);
            self.version = self.version.wrapping_add(1);
        }
    }

    /// Return a slice of the buffer as a `String`, from `start` to `end`
    /// (char offsets, exclusive end).
    pub fn slice_to_string(&self, start: usize, end: usize) -> String {
        self.rope.slice(start..end).to_string()
    }

    /// Return the source between byte offsets `start..end` as a `String`,
    /// or `None` when the range is out of bounds or lands mid-character.
    ///
    /// The byte-addressed counterpart of [`Buffer::slice_to_string`], for
    /// the callers that already hold a byte range — a source-map block
    /// range, say.  The whole point is to *not* be `contents()`: a link
    /// hit-test runs on every mouse-move event, and materializing the
    /// document to slice one block out of it is O(document) per pointer
    /// report.  Non-panicking (ropey's `get_byte_slice`) so the caller
    /// keeps the defensive fallback it had when it was slicing a `String`.
    pub fn byte_slice_to_string(&self, start: usize, end: usize) -> Option<String> {
        self.rope
            .get_byte_slice(start..end)
            .map(|slice| slice.to_string())
    }

    /// Total length of the buffer in bytes.
    pub fn len_bytes(&self) -> usize {
        self.rope.len_bytes()
    }

    /// Replace the underlying rope wholesale while preserving the
    /// buffer's `path`.  Bumps `version` so downstream consumers
    /// (autosave detector, raw-view visual-row cache, parsed-doc
    /// invalidation) treat the swap as a fresh mutation.  Used by the
    /// diff-mode resolution path to swap the merged rope in place
    /// (§3, §6).  The caller is responsible for refreshing
    /// any derived state on `EditorState` (`refresh_parsed`,
    /// `update_cursor_block`, clamping the cursor).
    pub fn set_rope(&mut self, rope: Rope) {
        self.rope = rope;
        self.version = self.version.wrapping_add(1);
    }
}

impl Default for Buffer {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn buf(text: &str) -> Buffer {
        Buffer {
            rope: Rope::from_str(text),
            path: None,
            version: 0,
        }
    }

    #[test]
    fn byte_slice_to_string_extracts_a_range_and_declines_a_bad_one() {
        let b = buf("héllo wörld");
        // `é` is two bytes, so the byte range is not the char range.
        assert_eq!(b.byte_slice_to_string(0, 6).as_deref(), Some("héllo"));
        assert_eq!(
            b.byte_slice_to_string(0, b.len_bytes()).as_deref(),
            Some("héllo wörld")
        );
        // Mid-character and out-of-bounds both decline rather than panic —
        // the link hit-test relies on that for its defensive fallback.
        assert_eq!(b.byte_slice_to_string(2, 6), None);
        assert_eq!(b.byte_slice_to_string(0, b.len_bytes() + 1), None);
    }

    #[test]
    fn new_buffer_is_empty() {
        let b = Buffer::new();
        assert_eq!(b.len_chars(), 0);
        assert_eq!(b.line_count(), 1); // ropey always reports at least one line
    }

    #[test]
    fn would_overwrite_only_for_a_different_existing_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let existing = dir.path().join("there.md");
        std::fs::write(&existing, "x").expect("seed");
        let missing = dir.path().join("absent.md");

        let mut b = buf("body");
        // Path-less buffer: any existing target is an overwrite; a
        // nonexistent one is not.
        assert!(b.would_overwrite(&existing));
        assert!(!b.would_overwrite(&missing));

        // Saving over the buffer's own file is never an "overwrite".
        b.path = Some(existing.clone());
        assert!(!b.would_overwrite(&existing));
        // …but a *different* existing file still is.
        let other = dir.path().join("other.md");
        std::fs::write(&other, "y").expect("seed");
        assert!(b.would_overwrite(&other));
    }

    #[test]
    fn insert_and_length() {
        let mut b = Buffer::new();
        b.insert(0, "hello");
        assert_eq!(b.len_chars(), 5);
        assert_eq!(b.contents(), "hello");
    }

    #[test]
    fn insert_char() {
        let mut b = buf("hllo");
        b.insert_char(1, 'e');
        assert_eq!(b.contents(), "hello");
    }

    #[test]
    fn remove_range() {
        let mut b = buf("hello world");
        b.remove(5, 11);
        assert_eq!(b.contents(), "hello");
    }

    #[test]
    fn remove_char_in_bounds() {
        let mut b = buf("hello");
        b.remove_char(2); // remove first 'l'
        assert_eq!(b.contents(), "helo");
    }

    #[test]
    fn remove_char_out_of_bounds_is_noop() {
        let mut b = buf("hi");
        b.remove_char(100); // must not panic
        assert_eq!(b.contents(), "hi");
    }

    #[test]
    fn line_count_and_line() {
        let b = buf("line1\nline2\nline3");
        assert_eq!(b.line_count(), 3);
        assert_eq!(b.line(0).unwrap(), "line1\n");
        assert_eq!(b.line(1).unwrap(), "line2\n");
        assert_eq!(b.line(2).unwrap(), "line3");
        assert!(b.line(3).is_none());
    }

    #[test]
    fn slice_to_string() {
        let b = buf("hello world");
        assert_eq!(b.slice_to_string(6, 11), "world");
    }

    #[test]
    fn line_to_char_and_char_to_line() {
        let b = buf("abc\ndef\nghi");
        assert_eq!(b.line_to_char(0), 0);
        assert_eq!(b.line_to_char(1), 4); // after "abc\n"
        assert_eq!(b.line_to_char(2), 8); // after "abc\ndef\n"
        assert_eq!(b.char_to_line(5), 1); // 'd' is on line 1
    }

    #[test]
    fn save_copy_writes_to_path_but_does_not_change_buffer_path() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let original = dir.path().join("orig.md");
        std::fs::write(&original, "# Hello")?;
        let buf = Buffer::load_file(&original)?;

        let copy = dir.path().join("copy.md");
        buf.save_copy(&copy)?;

        // The copy was written.
        assert_eq!(std::fs::read_to_string(&copy)?, "# Hello");
        // The buffer's associated path is unchanged — that's the
        // semantic difference from `save_as`.
        assert_eq!(buf.path(), Some(original.as_path()));
        Ok(())
    }

    #[test]
    fn load_and_save_file() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path().join("test.md");
        std::fs::write(&path, "# Hello\n\nWorld")?;

        let buf = Buffer::load_file(&path)?;
        assert!(buf.contents().contains("Hello"));

        let path2 = dir.path().join("out.md");
        let mut buf2 = buf.clone();
        buf2.save_as(&path2)?;

        let buf3 = Buffer::load_file(&path2)?;
        assert_eq!(buf3.contents(), buf.contents());

        Ok(())
    }
}