Skip to main content

lattice_magit/
buffer_io.rs

1//! B1: writing a whole buffer, in one place.
2//!
3//! Every magit mode replaces its buffer's entire contents after a git
4//! command returns, and every one of them spelled out the same six
5//! lines: snapshot, find the last line, build the end position, one
6//! `Edit::replace` over the lot. Ten sites — five as a private
7//! `apply_full_replace` copied verbatim between modes (identical to
8//! the byte), five inlined into `on_activate` without even a name.
9
10use std::sync::Arc;
11
12use lattice_protocol::edit::Edit;
13use lattice_protocol::position::{Position, Range};
14use lattice_runtime::Document;
15
16/// Replace everything in `handle`'s buffer with `text`.
17///
18/// The end position is computed from the *current* snapshot, so this
19/// is a full-extent replace rather than a truncate-and-append: a
20/// shorter `text` leaves nothing of the old content behind.
21///
22/// Errors are dropped, matching every call site this replaces. A
23/// failed `apply_edit_batch` on a synthetic buffer means the buffer
24/// went away underneath the task that was filling it — the buffer the
25/// user would be told about no longer exists.
26pub(crate) async fn replace_buffer_text(handle: &Arc<dyn Document>, text: String) {
27    let snap = handle.snapshot();
28    let last = snap.buffer.rope_line_count().saturating_sub(1); // CV.3: rope — full-extent replace
29    let last_line = snap.buffer.line(last).unwrap_or_default();
30    let end = Position::new(last, last_line.len() as u32);
31    let _ = handle
32        .apply_edit_batch(vec![Edit::replace(Range::new(Position::ZERO, end), text)])
33        .await;
34}