iced-code-editor 0.5.0

A custom code editor widget for the Iced GUI framework with syntax highlighting, line numbers, and scrolling support.
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Efficient text buffer for storing and manipulating editor content.
//!
//! This module provides a line-based text buffer optimized for:
//! - Fast line access for virtual scrolling
//! - Efficient insertions and deletions
//! - Memory-efficient storage

use self::text_utils::{char_range_to_byte_range, char_to_byte_index};

pub(crate) mod text_utils;

/// The line-ending style a buffer was loaded with, and reproduces on
/// [`TextBuffer::to_string`].
///
/// Lines are always stored without their terminator (see [`TextBuffer`]), so
/// this is the only record of whether the source text used `\n` or `\r\n`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LineEnding {
    Lf,
    CrLf,
}

impl LineEnding {
    /// Detects the dominant line ending in `content` by majority vote: if at
    /// least half of the newlines are part of a `\r\n` pair, the buffer is
    /// treated as CRLF, otherwise LF. Content with no newlines defaults to LF.
    fn detect(content: &str) -> Self {
        let crlf_count = content.matches("\r\n").count();
        let lf_count = content.matches('\n').count();
        if crlf_count > 0 && crlf_count * 2 >= lf_count {
            Self::CrLf
        } else {
            Self::Lf
        }
    }

    /// The literal terminator string for this line ending.
    fn as_str(self) -> &'static str {
        match self {
            Self::Lf => "\n",
            Self::CrLf => "\r\n",
        }
    }
}

/// A line-based text buffer optimized for editor operations.
///
/// Lines are stored around a movable gap:
///
/// - `lines_before` is in document order.
/// - `lines_after` is in reverse document order.
///
/// Random line reads remain O(1). Once the gap has moved to an edit location,
/// inserting/removing nearby lines is O(1) instead of shifting the entire tail
/// of a `Vec<String>`. This mirrors the locality principle behind piece-table
/// editors while preserving the editor's existing borrowed `&str` line API.
///
/// Line terminators are stripped from every stored line (`str::lines()`
/// already discards a final `\n` and normalizes `\r\n`/`\n`), so the buffer
/// separately records the source's line-ending style and whether it ended
/// with a trailing newline. [`Self::to_string`] reproduces both, so loading
/// and saving a file round-trips its exact line endings instead of silently
/// converting CRLF to LF or dropping the final newline.
#[derive(Debug, Clone)]
pub struct TextBuffer {
    /// Lines before the gap, in document order.
    lines_before: Vec<String>,
    /// Lines after the gap, in reverse document order.
    lines_after: Vec<String>,
    /// Line ending style to use when joining lines in [`Self::to_string`].
    line_ending: LineEnding,
    /// Whether the source content ended with a trailing line terminator.
    trailing_newline: bool,
}

impl TextBuffer {
    /// Creates a new text buffer from a string.
    ///
    /// # Arguments
    ///
    /// * `content` - Initial text content (will be split into lines)
    ///
    /// # Returns
    ///
    /// A new `TextBuffer` instance
    pub fn new(content: &str) -> Self {
        let mut lines_after: Vec<String> = if content.is_empty() {
            vec![String::new()]
        } else {
            content.lines().map(String::from).collect()
        };
        lines_after.reverse();

        Self {
            lines_before: Vec::new(),
            lines_after,
            line_ending: LineEnding::detect(content),
            trailing_newline: content.ends_with('\n'),
        }
    }

    /// Returns the number of lines in the buffer.
    #[must_use]
    pub fn line_count(&self) -> usize {
        self.lines_before.len() + self.lines_after.len()
    }

    /// Returns a reference to a specific line.
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based line index
    ///
    /// # Returns
    ///
    /// The line content, or an empty string if index is out of bounds
    #[must_use]
    pub fn line(&self, index: usize) -> &str {
        if let Some(line) = self.lines_before.get(index) {
            return line;
        }

        let relative_index = index.saturating_sub(self.lines_before.len());
        self.lines_after
            .len()
            .checked_sub(relative_index.saturating_add(1))
            .and_then(|after_index| self.lines_after.get(after_index))
            .map_or("", String::as_str)
    }

    /// Moves the line gap to the logical boundary at `index`.
    fn move_gap_to(&mut self, index: usize) {
        let target = index.min(self.line_count());
        while self.lines_before.len() < target {
            let Some(line) = self.lines_after.pop() else { break };
            self.lines_before.push(line);
        }
        while self.lines_before.len() > target {
            let Some(line) = self.lines_before.pop() else { break };
            self.lines_after.push(line);
        }
    }

    /// Returns a mutable line after moving the gap immediately after it.
    fn line_mut(&mut self, index: usize) -> Option<&mut String> {
        if index >= self.line_count() {
            return None;
        }
        self.move_gap_to(index.saturating_add(1));
        self.lines_before.last_mut()
    }

    /// Iterates all lines in document order.
    fn iter_lines(&self) -> impl Iterator<Item = &String> {
        self.lines_before.iter().chain(self.lines_after.iter().rev())
    }

    /// Inserts a character at the specified position.
    ///
    /// # Arguments
    ///
    /// * `line` - Line index
    /// * `column` - Column position (UTF-8 character index)
    /// * `ch` - Character to insert
    pub fn insert_char(&mut self, line: usize, column: usize, ch: char) {
        let Some(line_str) = self.line_mut(line) else { return };
        let byte_pos = char_to_byte_index(line_str, column);
        line_str.insert(byte_pos, ch);
    }

    /// Inserts a newline at the specified position, splitting the line.
    ///
    /// # Arguments
    ///
    /// * `line` - Line index
    /// * `column` - Column position where to split
    pub fn insert_newline(&mut self, line: usize, column: usize) {
        let Some(line_str) = self.line_mut(line) else { return };
        let byte_pos = char_to_byte_index(line_str, column);
        let right = line_str.split_off(byte_pos);
        // `line_mut` leaves the gap after `line`; pushing here inserts the new
        // right half directly after it without moving the document tail.
        self.lines_before.push(right);
    }

    /// Deletes a character before the cursor (backspace).
    ///
    /// # Arguments
    ///
    /// * `line` - Line index
    /// * `column` - Column position
    ///
    /// # Returns
    ///
    /// `true` if a line merge occurred, `false` otherwise
    pub fn delete_char(&mut self, line: usize, column: usize) -> bool {
        if column > 0 {
            // Delete character in current line
            if let Some(line_str) = self.line_mut(line) {
                let byte_pos = char_to_byte_index(line_str, column);
                if byte_pos > 0 {
                    let char_start = char_to_byte_index(line_str, column - 1);
                    line_str.drain(char_start..byte_pos);
                }
            }
            false
        } else if line > 0 && line < self.line_count() {
            // Merge with previous line
            self.move_gap_to(line.saturating_add(1));
            if let Some(current_line) = self.lines_before.pop()
                && let Some(previous_line) = self.lines_before.last_mut()
            {
                previous_line.push_str(&current_line);
                return true;
            }
            false
        } else {
            false
        }
    }

    /// Deletes a character at the cursor (delete key).
    ///
    /// # Arguments
    ///
    /// * `line` - Line index
    /// * `column` - Column position
    pub fn delete_forward(&mut self, line: usize, column: usize) {
        if line >= self.line_count() {
            return;
        }

        let char_count = self.line(line).chars().count();

        if column < char_count {
            // Delete character at cursor
            if let Some(line_str) = self.line_mut(line) {
                let byte_pos = char_to_byte_index(line_str, column);
                let next_byte_pos = char_to_byte_index(line_str, column + 1);
                line_str.drain(byte_pos..next_byte_pos);
            }
        } else if line + 1 < self.line_count() {
            // Merge with next line
            self.move_gap_to(line.saturating_add(1));
            if let Some(next_line) = self.lines_after.pop()
                && let Some(line_str) = self.lines_before.last_mut()
            {
                line_str.push_str(&next_line);
            }
        }
    }

    /// Replaces a range of characters in a line with new text.
    ///
    /// # Arguments
    ///
    /// * `line` - Line index
    /// * `col_start` - Column position to start replacing
    /// * `length` - Number of characters to replace
    /// * `new_text` - The text to insert
    pub fn replace_range(
        &mut self,
        line: usize,
        col_start: usize,
        length: usize,
        new_text: &str,
    ) {
        let Some(line_str) = self.line_mut(line) else { return };
        let (start_byte, end_byte) =
            char_range_to_byte_range(line_str, col_start, col_start + length);

        line_str.replace_range(start_byte..end_byte, new_text);
    }

    /// Returns the entire buffer content as a single string.
    ///
    /// Lines are joined with the line ending the buffer was loaded with
    /// (`\n` or `\r\n`), and a trailing terminator is appended if the source
    /// content had one — both recorded by [`Self::new`] — so this is a true
    /// inverse of `new` for the whole-document round trip.
    #[must_use]
    #[allow(clippy::inherent_to_string)]
    pub fn to_string(&self) -> String {
        let eol = self.line_ending.as_str();
        let line_count = self.line_count();
        let content_len = self.iter_lines().map(String::len).sum::<usize>()
            + line_count.saturating_sub(1) * eol.len()
            + if self.trailing_newline { eol.len() } else { 0 };
        let mut content = String::with_capacity(content_len);
        for (index, line) in self.iter_lines().enumerate() {
            if index > 0 {
                content.push_str(eol);
            }
            content.push_str(line);
        }
        if self.trailing_newline {
            content.push_str(eol);
        }
        content
    }

    /// Returns a contiguous logical-line range as replacement text.
    ///
    /// When `end_exclusive` is before the end of the buffer, the returned text
    /// includes the newline that separates the range from the following line.
    /// This form maps directly to an LSP range ending at column zero.
    ///
    /// Uses the buffer's own line-ending style so this stays consistent with
    /// [`Self::to_string`] — the two feed the same LSP document sync, and a
    /// CRLF file must not have some change payloads joined with `\n` while
    /// the full-text sync path (via `to_string`) uses `\r\n`.
    pub(crate) fn line_range_to_string(
        &self,
        start: usize,
        end_exclusive: usize,
    ) -> String {
        let eol = self.line_ending.as_str();
        let line_count = self.line_count();
        let start = start.min(line_count);
        let end_exclusive = end_exclusive.min(line_count).max(start);
        let mut content = String::new();
        for line_index in start..end_exclusive {
            if line_index > start {
                content.push_str(eol);
            }
            content.push_str(self.line(line_index));
        }
        if end_exclusive < line_count && start < end_exclusive {
            content.push_str(eol);
        }
        content
    }

    /// Returns the character count of a specific line.
    ///
    /// # Arguments
    ///
    /// * `line` - Line index
    ///
    /// # Returns
    ///
    /// The number of characters in the line
    #[must_use]
    pub fn line_len(&self, line: usize) -> usize {
        self.line(line).chars().count()
    }

    /// Inserts a full line at the given index, shifting following lines down.
    ///
    /// The new line is inserted *before* the line currently at `index`. An
    /// `index` equal to (or greater than) the line count appends the line at
    /// the end of the buffer.
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based position where the line is inserted
    /// * `content` - The line content (without trailing newline)
    pub fn insert_line(&mut self, index: usize, content: String) {
        self.move_gap_to(index);
        self.lines_before.push(content);
    }

    /// Removes the line at the given index, returning its content.
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based index of the line to remove
    ///
    /// # Returns
    ///
    /// The removed line content, or `None` if `index` is out of bounds
    pub fn remove_line(&mut self, index: usize) -> Option<String> {
        if index >= self.line_count() {
            return None;
        }
        self.move_gap_to(index);
        self.lines_after.pop()
    }
}

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

    #[test]
    fn test_new_buffer() {
        let buffer = TextBuffer::new("line1\nline2\nline3");
        assert_eq!(buffer.line_count(), 3);
        assert_eq!(buffer.line(0), "line1");
        assert_eq!(buffer.line(1), "line2");
        assert_eq!(buffer.line(2), "line3");
    }

    #[test]
    fn test_empty_buffer() {
        let buffer = TextBuffer::new("");
        assert_eq!(buffer.line_count(), 1);
        assert_eq!(buffer.line(0), "");
    }

    #[test]
    fn test_insert_char() {
        let mut buffer = TextBuffer::new("hello");
        buffer.insert_char(0, 5, '!');
        assert_eq!(buffer.line(0), "hello!");
    }

    #[test]
    fn test_insert_newline() {
        let mut buffer = TextBuffer::new("hello world");
        buffer.insert_newline(0, 5);
        assert_eq!(buffer.line_count(), 2);
        assert_eq!(buffer.line(0), "hello");
        assert_eq!(buffer.line(1), " world");
    }

    #[test]
    fn test_delete_char() {
        let mut buffer = TextBuffer::new("hello");
        let merged = buffer.delete_char(0, 5);
        assert!(!merged);
        assert_eq!(buffer.line(0), "hell");
    }

    #[test]
    fn test_delete_char_merge() {
        let mut buffer = TextBuffer::new("line1\nline2");
        let merged = buffer.delete_char(1, 0);
        assert!(merged);
        assert_eq!(buffer.line_count(), 1);
        assert_eq!(buffer.line(0), "line1line2");
    }

    #[test]
    fn test_to_string() {
        let buffer = TextBuffer::new("line1\nline2\nline3");
        assert_eq!(buffer.to_string(), "line1\nline2\nline3");
    }

    #[test]
    fn test_to_string_round_trips_trailing_newline() {
        // A POSIX-style file ending in a newline must not lose it on save.
        let buffer = TextBuffer::new("a\n");
        assert_eq!(buffer.to_string(), "a\n");

        // No trailing newline in, none out.
        let buffer = TextBuffer::new("a");
        assert_eq!(buffer.to_string(), "a");
    }

    #[test]
    fn test_to_string_round_trips_crlf() {
        // A CRLF file must not be silently normalized to LF on save.
        let buffer = TextBuffer::new("a\r\nb");
        assert_eq!(buffer.to_string(), "a\r\nb");
        assert_eq!(buffer.line(0), "a");
        assert_eq!(buffer.line(1), "b");

        // CRLF with a trailing newline preserves both.
        let buffer = TextBuffer::new("a\r\nb\r\n");
        assert_eq!(buffer.to_string(), "a\r\nb\r\n");
    }

    #[test]
    fn test_to_string_round_trips_empty_content() {
        let buffer = TextBuffer::new("");
        assert_eq!(buffer.to_string(), "");
    }

    #[test]
    fn test_to_string_lf_by_default_for_single_line_content() {
        // No newlines to infer a style from: defaults to LF once a newline
        // actually gets typed, rather than surprising the user with CRLF.
        let mut buffer = TextBuffer::new("hello");
        buffer.insert_newline(0, 5);
        assert_eq!(buffer.to_string(), "hello\n");
    }

    #[test]
    fn test_to_string_edits_after_load_use_the_loaded_line_ending() {
        // Editing a CRLF-loaded buffer must keep emitting CRLF, not switch
        // to LF just because a new line was created by an edit rather than
        // present in the original content.
        let mut buffer = TextBuffer::new("a\r\nb");
        buffer.insert_newline(0, 1);
        assert_eq!(buffer.to_string(), "a\r\n\r\nb");
    }

    #[test]
    fn test_replace_range() {
        let mut buffer = TextBuffer::new("hello world");
        // Replace "world" with "rust"
        buffer.replace_range(0, 6, 5, "rust");
        assert_eq!(buffer.line(0), "hello rust");

        // Replace "hello" with "hi"
        buffer.replace_range(0, 0, 5, "hi");
        assert_eq!(buffer.line(0), "hi rust");

        // Insert at end
        buffer.replace_range(0, 7, 0, "!");
        assert_eq!(buffer.line(0), "hi rust!");
    }

    #[test]
    fn test_insert_line() {
        let mut buffer = TextBuffer::new("line1\nline3");

        // Insert in the middle
        buffer.insert_line(1, "line2".to_string());
        assert_eq!(buffer.line_count(), 3);
        assert_eq!(buffer.line(0), "line1");
        assert_eq!(buffer.line(1), "line2");
        assert_eq!(buffer.line(2), "line3");

        // Insert at the start
        buffer.insert_line(0, "line0".to_string());
        assert_eq!(buffer.line(0), "line0");

        // Insert at the end (index beyond bounds is clamped)
        buffer.insert_line(99, "last".to_string());
        assert_eq!(buffer.line(buffer.line_count() - 1), "last");
    }

    #[test]
    fn test_remove_line() {
        let mut buffer = TextBuffer::new("line1\nline2\nline3");

        // Remove from the middle
        assert_eq!(buffer.remove_line(1), Some("line2".to_string()));
        assert_eq!(buffer.line_count(), 2);
        assert_eq!(buffer.line(0), "line1");
        assert_eq!(buffer.line(1), "line3");

        // Out of bounds returns None
        assert_eq!(buffer.remove_line(5), None);
        assert_eq!(buffer.line_count(), 2);
    }

    #[test]
    fn test_gap_buffer_preserves_order_across_distant_edits() {
        let content = (0..100)
            .map(|line| format!("line-{line}"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut buffer = TextBuffer::new(&content);

        buffer.insert_line(50, "middle".to_string());
        buffer.insert_char(50, 6, '!');
        buffer.insert_line(0, "first".to_string());
        buffer.insert_line(buffer.line_count(), "last".to_string());

        assert_eq!(buffer.line(0), "first");
        assert_eq!(buffer.line(51), "middle!");
        assert_eq!(buffer.line(52), "line-50");
        assert_eq!(buffer.line(buffer.line_count() - 1), "last");

        assert_eq!(buffer.remove_line(51), Some("middle!".to_string()));
        assert_eq!(buffer.remove_line(0), Some("first".to_string()));
        assert_eq!(buffer.line(50), "line-50");
        assert_eq!(
            buffer.remove_line(buffer.line_count() - 1),
            Some("last".to_string())
        );
        assert_eq!(buffer.to_string(), content);
    }

    #[test]
    fn test_line_range_to_string_matches_line_boundary_replacement() {
        let buffer = TextBuffer::new("zero\none\ntwo\nthree");
        assert_eq!(buffer.line_range_to_string(1, 3), "one\ntwo\n");
        assert_eq!(buffer.line_range_to_string(2, 4), "two\nthree");
        assert_eq!(buffer.line_range_to_string(99, 100), "");
    }

    #[test]
    fn test_line_range_to_string_uses_the_buffer_line_ending() {
        // The LSP incremental-sync path (`line_range_to_string`) must join
        // with the same line ending as the full-text sync path
        // (`to_string`), or the two would disagree about a CRLF document's
        // text mid-sync.
        let buffer = TextBuffer::new("zero\r\none\r\ntwo\r\nthree");
        assert_eq!(buffer.line_range_to_string(1, 3), "one\r\ntwo\r\n");
    }

    #[test]
    fn test_line_ending_detect_majority_vote() {
        assert_eq!(LineEnding::detect("a\nb\nc"), LineEnding::Lf);
        assert_eq!(LineEnding::detect("a\r\nb\r\nc"), LineEnding::CrLf);
        assert_eq!(LineEnding::detect("a"), LineEnding::Lf);
        // Mixed content: majority of newlines are CRLF.
        assert_eq!(LineEnding::detect("a\r\nb\r\nc\nd"), LineEnding::CrLf);
        // Mixed content: majority of newlines are plain LF.
        assert_eq!(LineEnding::detect("a\nb\nc\r\nd"), LineEnding::Lf);
    }
}