shoin 0.1.9

A no-clutter terminal Markdown editor with modal editing
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
//! Saving files. SPEC.md §10.
//!
//! Atomic: write `.<file>.swtmp` in the SAME directory (so `rename` stays on
//! one filesystem), fsync, then rename over the target. A crash mid-save leaves
//! the original intact. Original mode bits are preserved.
//!
//! No swap files, and autosave is OFF unless `[editor] autosave` asks for it —
//! a writing tool should not surprise the user with writes they did not ask
//! for. When it IS on it writes through this same `write_atomic`, guard
//! included, so a timer can never clobber what `:w` would have refused to.

use std::io::Write;
use std::path::Path;
use std::time::{Duration, SystemTime};

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

use crate::text::buffer::LineEnding;

pub struct SaveOptions {
    pub line_ending: LineEnding,
    pub final_newline: bool,
    pub trim_trailing_whitespace: bool,
}

/// What `[editor] final_newline` asks of a save.
///
/// `Preserve` is the default and the one that surprises nobody: a file that
/// arrived without a trailing newline leaves without one. The other two exist
/// because a repository with a lint on it wants the same answer every time,
/// whatever each file happened to have.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FinalNewline {
    #[default]
    Preserve,
    Always,
    Never,
}

impl FinalNewline {
    /// `None` for a spelling this does not know — the caller reports it rather
    /// than silently picking one, which is how this setting sat unread for a
    /// release.
    pub fn parse(s: &str) -> Option<FinalNewline> {
        Some(match s.trim().to_ascii_lowercase().as_str() {
            "preserve" | "keep" | "as-is" => FinalNewline::Preserve,
            "always" | "true" | "yes" | "on" => FinalNewline::Always,
            "never" | "false" | "no" | "off" => FinalNewline::Never,
            _ => return None,
        })
    }

    /// Resolve against what the file had when it was opened.
    pub fn resolve(self, had_one: bool) -> bool {
        match self {
            FinalNewline::Preserve => had_one,
            FinalNewline::Always => true,
            FinalNewline::Never => false,
        }
    }
}

/// The `[editor]` settings a save consults, gathered once so `save`/`save_as`
/// take one argument that says what it is instead of a row of bare bools.
#[derive(Clone, Copy, Debug, Default)]
pub struct SavePolicy {
    pub trim_trailing_whitespace: bool,
    pub final_newline: FinalNewline,
}

impl SavePolicy {
    pub fn from_config(cfg: &crate::config::schema::EditorConfig) -> SavePolicy {
        SavePolicy {
            trim_trailing_whitespace: cfg.trim_on_save,
            // An unrecognised spelling falls back to the default here; startup
            // has already flagged it through `config::validate`.
            final_newline: FinalNewline::parse(&cfg.final_newline).unwrap_or_default(),
        }
    }
}

/// How often `[editor] autosave` writes, in whole minutes.
///
/// A ladder of five rather than a free number of seconds. The point of a bound
/// is that both ends are wrong for the feature: a 10-second autosave is a swap
/// file with the document's own name on it, and an hourly one has not saved
/// anything you would miss. Minutes also keep the setting readable — `3` is a
/// number a reader can hold in their head, `180000` is one they copy.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AutosaveInterval(u8);

impl AutosaveInterval {
    pub const MIN: u8 = 1;
    pub const MAX: u8 = 5;
    pub const DEFAULT: u8 = 3;

    /// `None` outside 1–5, so the caller reports the number instead of quietly
    /// rounding it — the same rule `FinalNewline::parse` follows, and for the
    /// same reason: a setting that silently ignores what you wrote reads as a
    /// setting that does not work.
    pub fn parse(minutes: u8) -> Option<AutosaveInterval> {
        (Self::MIN..=Self::MAX)
            .contains(&minutes)
            .then_some(AutosaveInterval(minutes))
    }

    pub fn minutes(self) -> u8 {
        self.0
    }

    pub fn duration(self) -> Duration {
        Duration::from_secs(self.0 as u64 * 60)
    }
}

impl Default for AutosaveInterval {
    fn default() -> Self {
        AutosaveInterval(AutosaveInterval::DEFAULT)
    }
}

/// `[editor] autosave` and `autosave_interval` reduced to the one question the
/// event loop asks: how long until the next write, or nothing at all.
///
/// Two fields rather than one `Option<u8>` because they answer to two different
/// people. Turning autosave on and off is the decision; the interval is a
/// preference that should still be there, unchanged, the next time it goes on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Autosave {
    pub enabled: bool,
    pub every: AutosaveInterval,
}

impl Autosave {
    pub fn from_config(cfg: &crate::config::schema::EditorConfig) -> Autosave {
        Autosave {
            enabled: cfg.autosave,
            // Out of range falls back here; `config::validate` is what makes
            // the number visible rather than this silently taking 3.
            every: AutosaveInterval::parse(cfg.autosave_interval).unwrap_or_default(),
        }
    }

    /// The gap between writes, or `None` when autosave is off — which is also
    /// the disarmed timer, so the loop has one thing to ask and not two.
    pub fn interval(self) -> Option<Duration> {
        self.enabled.then(|| self.every.duration())
    }
}

/// Returns the new mtime, for external-modification tracking.
///
/// A symlink is written through to the file it names: renaming over the link
/// itself would swap it for a regular file and leave the real one unedited.
pub fn write_atomic(path: &Path, rope: &Rope, opts: &SaveOptions) -> Result<SystemTime> {
    let resolved = path
        .is_symlink()
        .then(|| std::fs::canonicalize(path).ok())
        .flatten();
    let path = resolved.as_deref().unwrap_or(path);
    let mut text: String = rope.chunks().collect();

    if opts.trim_trailing_whitespace {
        let mut out = String::with_capacity(text.len());
        for (i, line) in text.split('\n').enumerate() {
            if i > 0 {
                out.push('\n');
            }
            out.push_str(line.trim_end());
        }
        text = out;
    }

    if opts.final_newline {
        if !text.ends_with('\n') {
            text.push('\n');
        }
    } else {
        while text.ends_with('\n') {
            text.pop();
        }
    }

    if opts.line_ending == LineEnding::Crlf {
        text = text.replace('\n', "\r\n");
    }

    let dir = path.parent().filter(|p| !p.as_os_str().is_empty());
    let dir = dir.unwrap_or_else(|| Path::new("."));
    let stem = path
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "unnamed".to_string());
    let tmp = dir.join(format!(".{stem}.swtmp"));

    // Everything from here can fail, and a failure must not leave `.a.md.swtmp`
    // sitting beside the file — a dotfile the editor hides and the reader never
    // asked for. One closure so there is a single place to clean up from.
    let attempt = || -> Result<SystemTime> {
        {
            let mut f = std::fs::File::create(&tmp)
                .with_context(|| format!("creating temp file {}", tmp.display()))?;
            f.write_all(text.as_bytes())?;
            f.sync_all()?;
        }

        // Preserve the original's mode bits if it already existed.
        if let Ok(meta) = std::fs::metadata(path) {
            let _ = std::fs::set_permissions(&tmp, meta.permissions());
        }

        std::fs::rename(&tmp, path)
            .with_context(|| format!("replacing {} with {}", path.display(), tmp.display()))?;

        Ok(std::fs::metadata(path)
            .and_then(|m| m.modified())
            .unwrap_or_else(|_| SystemTime::now()))
    };

    let result = attempt();
    if result.is_err() {
        // Best effort: if this fails too there is nothing further to try, and
        // the error worth reporting is the one from the save itself.
        let _ = std::fs::remove_file(&tmp);
    }
    result
}

/// Compare the recorded mtime against the file on disk. `true` means someone
/// else changed it and we must prompt rather than clobber.
pub fn changed_externally(path: &Path, known: Option<SystemTime>) -> bool {
    let known = match known {
        Some(k) => k,
        None => return false,
    };
    match std::fs::metadata(path).and_then(|m| m.modified()) {
        Ok(actual) => actual != known,
        Err(_) => false,
    }
}

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

    fn dir(tag: &str) -> std::path::PathBuf {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static N: AtomicUsize = AtomicUsize::new(0);
        let t = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let n = N.fetch_add(1, Ordering::Relaxed);
        let d = std::env::temp_dir().join(format!("shoin-save-{tag}-{t}-{n}"));
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    fn opts(final_newline: bool, trim: bool) -> SaveOptions {
        SaveOptions {
            line_ending: LineEnding::Lf,
            final_newline,
            trim_trailing_whitespace: trim,
        }
    }

    /// The three spellings, and the aliases people reach for.
    #[test]
    fn the_final_newline_ladder_parses() {
        assert_eq!(FinalNewline::parse("preserve"), Some(FinalNewline::Preserve));
        assert_eq!(FinalNewline::parse("  ALWAYS "), Some(FinalNewline::Always));
        assert_eq!(FinalNewline::parse("never"), Some(FinalNewline::Never));
        assert_eq!(FinalNewline::parse("true"), Some(FinalNewline::Always));
        // A typo is reported, not silently taken as the default — that is what
        // let this setting sit unread.
        assert_eq!(FinalNewline::parse("alway"), None);
    }

    /// `preserve` answers with the file's own habit; the other two overrule it.
    #[test]
    fn the_policy_resolves_against_what_the_file_had() {
        assert!(FinalNewline::Preserve.resolve(true));
        assert!(!FinalNewline::Preserve.resolve(false));
        assert!(FinalNewline::Always.resolve(false), "always overrules");
        assert!(!FinalNewline::Never.resolve(true), "never overrules");
    }

    /// The bound is the feature: five values, and a number outside it is
    /// reported rather than rounded into range.
    #[test]
    fn the_autosave_interval_is_one_to_five_minutes() {
        for m in 1..=5u8 {
            let i = AutosaveInterval::parse(m).expect("in range");
            assert_eq!(i.minutes(), m);
            assert_eq!(i.duration(), Duration::from_secs(m as u64 * 60));
        }
        assert_eq!(AutosaveInterval::parse(0), None, "0 is not an interval");
        assert_eq!(AutosaveInterval::parse(6), None);
        assert_eq!(AutosaveInterval::parse(255), None);
        assert_eq!(AutosaveInterval::default().minutes(), 3);
    }

    /// The `[editor]` section reaches the timer, and the default is OFF — the
    /// one assertion that has to hold whatever else changes here.
    #[test]
    fn the_editor_section_reaches_the_autosave_timer() {
        use crate::config::schema::EditorConfig;
        let mut cfg = EditorConfig::default();
        assert!(!cfg.autosave, "autosave is off unless asked for");
        assert_eq!(
            Autosave::from_config(&cfg).interval(),
            None,
            "off means no deadline at all, not a deadline nobody acts on"
        );

        cfg.autosave = true;
        assert_eq!(
            Autosave::from_config(&cfg).interval(),
            Some(Duration::from_secs(180)),
            "the default interval is three minutes"
        );

        cfg.autosave_interval = 5;
        assert_eq!(
            Autosave::from_config(&cfg).interval(),
            Some(Duration::from_secs(300))
        );

        // Out of range falls back rather than refusing the config;
        // `config::validate` is what makes the number visible.
        cfg.autosave_interval = 9;
        assert_eq!(
            Autosave::from_config(&cfg).every.minutes(),
            AutosaveInterval::DEFAULT
        );

        // Turning it off keeps the interval, so turning it back on remembers.
        cfg.autosave = false;
        cfg.autosave_interval = 2;
        assert_eq!(Autosave::from_config(&cfg).interval(), None);
        assert_eq!(Autosave::from_config(&cfg).every.minutes(), 2);
    }

    /// The `[editor]` section actually reaches a save. This is the assertion
    /// that was missing: `final_newline` was parsed, defaulted, documented in
    /// `shoin/editor.conf`, and read by nothing at all.
    #[test]
    fn the_editor_section_reaches_the_save() {
        use crate::config::schema::EditorConfig;
        let mut cfg = EditorConfig::default();
        assert_eq!(
            SavePolicy::from_config(&cfg).final_newline,
            FinalNewline::Preserve
        );

        cfg.final_newline = "never".into();
        cfg.trim_on_save = true;
        let p = SavePolicy::from_config(&cfg);
        assert_eq!(p.final_newline, FinalNewline::Never);
        assert!(p.trim_trailing_whitespace);

        // A value nothing understands falls back rather than refusing the
        // config; `config::validate` is what makes that visible.
        cfg.final_newline = "alway".into();
        assert_eq!(
            SavePolicy::from_config(&cfg).final_newline,
            FinalNewline::Preserve
        );
    }

    #[test]
    fn a_final_newline_is_added_or_stripped_as_asked() {
        let d = dir("nl");
        let p = d.join("a.md");

        write_atomic(&p, &Rope::from_str("one\ntwo"), &opts(true, false)).unwrap();
        assert_eq!(std::fs::read_to_string(&p).unwrap(), "one\ntwo\n");

        write_atomic(&p, &Rope::from_str("one\ntwo\n\n\n"), &opts(false, false)).unwrap();
        assert_eq!(
            std::fs::read_to_string(&p).unwrap(),
            "one\ntwo",
            "every trailing newline goes, not just the last"
        );
        std::fs::remove_dir_all(&d).ok();
    }

    #[test]
    fn trailing_whitespace_goes_only_when_asked() {
        let d = dir("trim");
        let p = d.join("a.md");

        write_atomic(&p, &Rope::from_str("a  \nb\t\n"), &opts(true, false)).unwrap();
        assert_eq!(std::fs::read_to_string(&p).unwrap(), "a  \nb\t\n");

        write_atomic(&p, &Rope::from_str("a  \nb\t\n"), &opts(true, true)).unwrap();
        assert_eq!(std::fs::read_to_string(&p).unwrap(), "a\nb\n");
        std::fs::remove_dir_all(&d).ok();
    }

    /// The rope holds `\n` only; the file gets whatever the original used.
    #[test]
    fn crlf_is_reapplied_on_the_way_out() {
        let d = dir("crlf");
        let p = d.join("a.md");
        let o = SaveOptions {
            line_ending: LineEnding::Crlf,
            final_newline: true,
            trim_trailing_whitespace: false,
        };
        write_atomic(&p, &Rope::from_str("one\ntwo\n"), &o).unwrap();
        assert_eq!(std::fs::read_to_string(&p).unwrap(), "one\r\ntwo\r\n");
        std::fs::remove_dir_all(&d).ok();
    }

    /// The temp file is an implementation detail and must not outlive the save
    /// — including the save that fails.
    #[test]
    fn no_temp_file_is_left_behind() {
        let d = dir("tmp");
        let p = d.join("a.md");
        write_atomic(&p, &Rope::from_str("body\n"), &opts(true, false)).unwrap();

        let left: Vec<String> = std::fs::read_dir(&d)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.ends_with(".swtmp"))
            .collect();
        assert!(left.is_empty(), "temp files left: {left:?}");

        // A destination that cannot be renamed over: the rename fails, and the
        // temp file must still be gone.
        let blocked = d.join("sub");
        std::fs::create_dir_all(&blocked).unwrap();
        assert!(
            write_atomic(&blocked, &Rope::from_str("x\n"), &opts(true, false)).is_err(),
            "a directory is not a file to overwrite"
        );
        let left: Vec<String> = std::fs::read_dir(&d)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.ends_with(".swtmp"))
            .collect();
        assert!(left.is_empty(), "temp file survived a failed save: {left:?}");
        std::fs::remove_dir_all(&d).ok();
    }

    /// The external-change guard is what `:w` consults before clobbering.
    #[test]
    fn an_external_write_is_noticed() {
        let d = dir("mtime");
        let p = d.join("a.md");
        let t = write_atomic(&p, &Rope::from_str("mine\n"), &opts(true, false)).unwrap();
        assert!(!changed_externally(&p, Some(t)));
        assert!(!changed_externally(&p, None), "nothing known, nothing to guard");

        std::thread::sleep(std::time::Duration::from_millis(1100));
        std::fs::write(&p, "theirs\n").unwrap();
        assert!(changed_externally(&p, Some(t)));
        std::fs::remove_dir_all(&d).ok();
    }

    /// A symlink is written through: the file it names gets the text, and the
    /// link itself survives as a link.
    #[cfg(unix)]
    #[test]
    fn a_symlink_is_written_through_not_replaced() {
        let d = dir("link");
        let real = d.join("real.md");
        let link = d.join("link.md");
        std::fs::write(&real, "old\n").unwrap();
        std::os::unix::fs::symlink(&real, &link).unwrap();

        write_atomic(&link, &Rope::from_str("new\n"), &opts(true, false)).unwrap();
        assert_eq!(std::fs::read_to_string(&real).unwrap(), "new\n");
        assert!(link.is_symlink(), "the link is still a link");
        std::fs::remove_dir_all(&d).ok();
    }
}