continuity-engine 0.2.39

Synchronous, storage-neutral Continuity editor engine
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
//! Storage-neutral line-text edit planning — sort, reverse, unique, and trim
//! whitespace, indent/outdent, tabs↔spaces, and line-ending conversion.
//!
//! These operate on the line block covered by selections and rewrite the
//! covered lines as a single deterministic replacement (one undo group per
//! call). Line-structure ops (newline insertion, duplicate, move, join) live
//! in `edit_lines.rs`.

use continuity_buffer::Buffer;

use crate::edit_line_text_helpers::{indent_text, sort_in_place};
use crate::edit_lines::{lines_covered, rewrite_covered_lines};
use crate::edit_planning::{finalize_specs, line_content_end, EditSpec};
use crate::selection_edit::SelectionEditPlan;
use crate::Error;
use crate::{IndentUnit, LineEnding, SortKind};

pub(crate) fn plan_sort_lines(
    buffer: &Buffer,
    kind: SortKind,
) -> Result<Option<SelectionEditPlan>, Error> {
    rewrite_covered_lines(buffer, |lines| {
        let mut sorted = lines;
        sort_in_place(&mut sorted, kind);
        sorted
    })
}

pub(crate) fn plan_reverse_lines(buffer: &Buffer) -> Result<Option<SelectionEditPlan>, Error> {
    rewrite_covered_lines(buffer, |lines| {
        let mut rev = lines;
        rev.reverse();
        rev
    })
}

pub(crate) fn plan_unique_lines(buffer: &Buffer) -> Result<Option<SelectionEditPlan>, Error> {
    rewrite_covered_lines(buffer, |lines| {
        let mut seen = std::collections::HashSet::new();
        lines
            .into_iter()
            .filter(|l| seen.insert(l.clone()))
            .collect()
    })
}

pub(crate) fn plan_shuffle_lines(
    buffer: &Buffer,
    seed: u64,
) -> Result<Option<SelectionEditPlan>, Error> {
    rewrite_covered_lines(buffer, |mut lines| {
        let mut state = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
        for i in (1..lines.len()).rev() {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1);
            let j = (state >> 33) as usize % (i + 1);
            lines.swap(i, j);
        }
        lines
    })
}

// Whitespace-trimming planners (trailing-only and leading+trailing) live in
// `edit_line_text/trim.rs` so this file stays under the 600-line cap.
// Re-exported so `selection_edit.rs` keeps its import paths.
mod trim;
pub(crate) use trim::{
    plan_trim_trailing_whitespace, plan_trim_trailing_whitespace_all, plan_trim_whitespace_all,
};

pub(crate) fn plan_indent(
    buffer: &Buffer,
    unit: IndentUnit,
) -> Result<Option<SelectionEditPlan>, Error> {
    let rope = buffer.rope();
    let prefix = indent_text(unit);
    let selections_before = buffer.selections().to_vec();
    let lines = lines_covered(buffer);
    let mut specs = Vec::new();
    for &line in &lines {
        let start = rope.line_to_byte(line);
        specs.push(EditSpec::insert(rope, start, prefix.clone())?);
    }
    // Phase-bugfix: shift each selection's byte_in_line by `prefix.len()`
    // on every line that received an indent prefix, so the post-edit
    // selection still highlights the *same* visible characters (the
    // legacy `selections_before` clone left the selection visually
    // anchored to the wrong byte offsets in the new rope).
    let prefix_len = prefix.len() as u32;
    let selections_after: Vec<continuity_text::Selection> = selections_before
        .iter()
        .map(|sel| continuity_text::Selection {
            anchor: shift_after_indent(sel.anchor, &lines, prefix_len),
            head: shift_after_indent(sel.head, &lines, prefix_len),
            kind: sel.kind,
        })
        .collect();
    Ok(finalize_specs(specs, selections_before, selections_after))
}

use crate::edit_indent_shift::{shift_after_indent, shift_after_outdent};

pub(crate) fn plan_outdent(
    buffer: &Buffer,
    unit: IndentUnit,
) -> Result<Option<SelectionEditPlan>, Error> {
    let rope = buffer.rope();
    let selections_before = buffer.selections().to_vec();
    let lines = lines_covered(buffer);
    let mut specs = Vec::new();
    // line -> drop_len map so post-edit selection shifting can subtract
    // exactly what was deleted on each affected line.
    let mut drops: Vec<(usize, u32)> = Vec::new();
    for &line in &lines {
        let start = rope.line_to_byte(line);
        let end = line_content_end(rope, line);
        let slice = rope.byte_slice(start..end).to_string();
        let drop_len = outdent_drop_len(&slice, unit);
        if drop_len > 0 {
            specs.push(EditSpec::delete(rope, start, start + drop_len)?);
            drops.push((line, drop_len as u32));
        }
    }
    let selections_after: Vec<continuity_text::Selection> = selections_before
        .iter()
        .map(|sel| continuity_text::Selection {
            anchor: shift_after_outdent(sel.anchor, &drops),
            head: shift_after_outdent(sel.head, &drops),
            kind: sel.kind,
        })
        .collect();
    Ok(finalize_specs(specs, selections_before, selections_after))
}

pub(crate) fn plan_spaces_to_tabs(
    buffer: &Buffer,
    width: u32,
) -> Result<Option<SelectionEditPlan>, Error> {
    let width = width.max(1) as usize;
    let space_run: String = " ".repeat(width);
    rewrite_covered_lines(buffer, |lines| {
        lines
            .into_iter()
            .map(|line| line.replace(&space_run, "\t"))
            .collect()
    })
}

pub(crate) fn plan_tabs_to_spaces(
    buffer: &Buffer,
    width: u32,
) -> Result<Option<SelectionEditPlan>, Error> {
    let spaces: String = " ".repeat(width as usize);
    rewrite_covered_lines(buffer, |lines| {
        lines
            .into_iter()
            .map(|line| line.replace('\t', &spaces))
            .collect()
    })
}

pub(crate) fn plan_convert_line_endings(
    buffer: &Buffer,
    eol: LineEnding,
) -> Result<Option<SelectionEditPlan>, Error> {
    let rope = buffer.rope();
    let selections_before = buffer.selections().to_vec();
    let target = match eol {
        LineEnding::Lf => "\n",
        LineEnding::Crlf => "\r\n",
    };
    let lines = lines_covered(buffer);
    let mut specs = Vec::new();
    for &line in &lines {
        if line + 1 >= rope.len_lines() {
            continue;
        }
        let content_end = line_content_end(rope, line);
        let next_start = rope.line_to_byte(line + 1);
        if next_start <= content_end {
            continue;
        }
        let current = rope.byte_slice(content_end..next_start).to_string();
        if current != target {
            specs.push(EditSpec::replace(
                rope,
                content_end,
                next_start,
                target.to_string(),
            )?);
        }
    }
    Ok(finalize_specs(
        specs,
        selections_before.clone(),
        selections_before,
    ))
}

use crate::edit_indent_shift::outdent_drop_len;

#[cfg(test)]
mod tests {
    use continuity_buffer::Buffer;
    use continuity_text::{Position, Selection};

    use super::*;
    use crate::selection_edit::{apply_plan, plan, SelectionEdit};

    fn at(line: u32, col: u32) -> Selection {
        Selection::caret_at(Position::new(line, col))
    }

    fn build(text: &str, selections: Vec<Selection>) -> Buffer {
        let mut buffer = Buffer::from_text(text);
        buffer.set_selections(selections);
        buffer
    }

    fn run(buffer: &mut Buffer, edit: SelectionEdit) {
        let plan = plan(buffer, &edit).expect("plan ok").expect("plan some");
        apply_plan(buffer, &plan).expect("apply ok");
    }

    #[test]
    fn sort_lines_ascending() {
        let mut b = Buffer::from_text("c\nb\na");
        b.set_selections(vec![Selection::new(
            Position::new(0, 0),
            Position::new(2, 1),
            continuity_text::SelectionKind::Caret,
        )]);
        run(&mut b, SelectionEdit::SortLines(SortKind::Asc));
        assert_eq!(b.rope().to_string(), "a\nb\nc");
    }

    #[test]
    fn indent_list_line_caret_shifts_preserves_offset() {
        // Phase B10 — Tab on a list line with caret in the body
        // prepends indent at line start and shifts caret right by the
        // indent unit, so the caret stays on the same content char.
        let mut b = Buffer::from_text("- foo");
        b.set_selections(vec![Selection::caret_at(Position::new(0, 4))]);
        run(
            &mut b,
            SelectionEdit::Indent {
                unit: IndentUnit::Spaces(2),
            },
        );
        assert_eq!(b.rope().to_string(), "  - foo");
        let head = b.selections()[0].head;
        assert_eq!(head.byte_in_line, 6);
    }

    #[test]
    fn indent_non_list_line_adds_line_prefix() {
        let mut b = Buffer::from_text("plain");
        b.set_selections(vec![Selection::caret_at(Position::new(0, 3))]);
        run(
            &mut b,
            SelectionEdit::Indent {
                unit: IndentUnit::Spaces(2),
            },
        );
        assert_eq!(b.rope().to_string(), "  plain");
        assert_eq!(b.selections()[0].head, Position::new(0, 5));
    }

    #[test]
    fn indent_multicursor_adds_one_prefix_per_covered_line() {
        let mut b = Buffer::from_text("alpha\nbeta");
        b.set_selections(vec![
            Selection::caret_at(Position::new(0, 2)),
            Selection::caret_at(Position::new(1, 3)),
        ]);
        run(
            &mut b,
            SelectionEdit::Indent {
                unit: IndentUnit::Tab,
            },
        );
        assert_eq!(b.rope().to_string(), "\talpha\n\tbeta");
        assert_eq!(
            b.selections()
                .iter()
                .map(|selection| selection.head)
                .collect::<Vec<_>>(),
            vec![Position::new(0, 3), Position::new(1, 4)]
        );
    }

    #[test]
    fn trim_trailing_whitespace_all_covers_every_line() {
        // Caret on line 0 — the all-variant strips trailing ws on
        // every line regardless of selection coverage.
        let mut b = Buffer::from_text("a   \nb\t\nc d  \n");
        b.set_selections(vec![Selection::caret_at(Position::new(0, 0))]);
        run(&mut b, SelectionEdit::TrimTrailingWhitespaceAll);
        assert_eq!(b.rope().to_string(), "a\nb\nc d\n");
    }

    #[test]
    fn indent_outdent_range_shifts_positions() {
        // Phase-bugfix: shift+tab / tab on a multi-line range shifts
        // positions correctly — selection survives over the same
        // visible characters.
        let mut b = Buffer::from_text("    abc\n    def\n    ghi");
        b.set_selections(vec![Selection::new(
            Position::new(0, 4),
            Position::new(2, 7),
            continuity_text::SelectionKind::Caret,
        )]);
        run(
            &mut b,
            SelectionEdit::Outdent {
                unit: IndentUnit::Spaces(4),
            },
        );
        assert_eq!(b.rope().to_string(), "abc\ndef\nghi");
        let s = b.selections()[0];
        assert_eq!(
            (s.anchor, s.head),
            (Position::new(0, 0), Position::new(2, 3))
        );
        let mut b = Buffer::from_text("abc\ndef");
        b.set_selections(vec![Selection::new(
            Position::new(0, 1),
            Position::new(1, 2),
            continuity_text::SelectionKind::Caret,
        )]);
        run(
            &mut b,
            SelectionEdit::Indent {
                unit: IndentUnit::Spaces(2),
            },
        );
        assert_eq!(b.rope().to_string(), "  abc\n  def");
        let s = b.selections()[0];
        assert_eq!(
            (s.anchor, s.head),
            (Position::new(0, 3), Position::new(1, 4))
        );
    }

    #[test]
    fn outdent_list_line_caret_shifts_left() {
        let mut b = Buffer::from_text("    - foo");
        b.set_selections(vec![Selection::caret_at(Position::new(0, 8))]);
        run(
            &mut b,
            SelectionEdit::Outdent {
                unit: IndentUnit::Spaces(2),
            },
        );
        assert_eq!(b.rope().to_string(), "  - foo");
        let head = b.selections()[0].head;
        assert_eq!(head.byte_in_line, 6);
    }

    #[test]
    fn reverse_lines_flips_block() {
        let mut b = Buffer::from_text("1\n2\n3");
        b.set_selections(vec![Selection::new(
            Position::new(0, 0),
            Position::new(2, 1),
            continuity_text::SelectionKind::Caret,
        )]);
        run(&mut b, SelectionEdit::ReverseLines);
        assert_eq!(b.rope().to_string(), "3\n2\n1");
    }

    #[test]
    fn unique_lines_drops_dupes() {
        let mut b = Buffer::from_text("a\nb\na");
        b.set_selections(vec![Selection::new(
            Position::new(0, 0),
            Position::new(2, 1),
            continuity_text::SelectionKind::Caret,
        )]);
        run(&mut b, SelectionEdit::UniqueLines);
        assert_eq!(b.rope().to_string(), "a\nb");
    }

    #[test]
    fn shuffle_lines_is_deterministic() {
        let make = || {
            let mut buf = Buffer::from_text("1\n2\n3\n4\n5");
            buf.set_selections(vec![Selection::new(
                Position::new(0, 0),
                Position::new(4, 1),
                continuity_text::SelectionKind::Caret,
            )]);
            buf
        };
        let mut a = make();
        let mut b = make();
        run(&mut a, SelectionEdit::ShuffleLines(7));
        run(&mut b, SelectionEdit::ShuffleLines(7));
        assert_eq!(a.rope().to_string(), b.rope().to_string());
    }

    #[test]
    fn trim_trailing_whitespace_only_trailing() {
        let mut b = build("foo  \nbar", vec![at(0, 0)]);
        run(&mut b, SelectionEdit::TrimTrailingWhitespace);
        assert_eq!(b.rope().to_string(), "foo\nbar");
    }

    #[test]
    fn indent_inserts_prefix() {
        let mut b = build("a", vec![at(0, 0)]);
        run(
            &mut b,
            SelectionEdit::Indent {
                unit: IndentUnit::Spaces(2),
            },
        );
        assert_eq!(b.rope().to_string(), "  a");
    }

    #[test]
    fn outdent_drops_prefix() {
        let mut b = build("    a", vec![at(0, 0)]);
        run(
            &mut b,
            SelectionEdit::Outdent {
                unit: IndentUnit::Spaces(2),
            },
        );
        assert_eq!(b.rope().to_string(), "  a");
    }

    #[test]
    fn outdent_tab_unit_drops_leading_spaces_too() {
        // Shift+Tab with tabs as the indent unit must still outdent
        // lines whose indentation is spaces — one indent level per
        // press, not all of it and not nothing.
        let mut b = Buffer::from_text("\tabc\n    def\n  ghi");
        b.set_selections(vec![Selection::new(
            Position::new(0, 0),
            Position::new(2, 5),
            continuity_text::SelectionKind::Caret,
        )]);
        run(
            &mut b,
            SelectionEdit::Outdent {
                unit: IndentUnit::Tab,
            },
        );
        assert_eq!(b.rope().to_string(), "abc\ndef\nghi");
    }

    #[test]
    fn spaces_to_tabs_converts_runs() {
        let mut b = build("    foo", vec![at(0, 0)]);
        run(&mut b, SelectionEdit::SpacesToTabs { tab_width: 4 });
        assert_eq!(b.rope().to_string(), "\tfoo");
    }

    #[test]
    fn tabs_to_spaces_converts() {
        let mut b = build("\tfoo", vec![at(0, 0)]);
        run(&mut b, SelectionEdit::TabsToSpaces { tab_width: 2 });
        assert_eq!(b.rope().to_string(), "  foo");
    }

    #[test]
    fn convert_line_endings_lf_to_crlf() {
        let mut b = Buffer::from_text("a\nb");
        b.set_selections(vec![Selection::new(
            Position::new(0, 0),
            Position::new(1, 1),
            continuity_text::SelectionKind::Caret,
        )]);
        run(&mut b, SelectionEdit::ConvertLineEndings(LineEnding::Crlf));
        assert_eq!(b.rope().to_string(), "a\r\nb");
    }
}