alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
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
//! Pure Vim text-object resolution.
//!
//! Text objects are target producers. They prove a byte range for a text
//! snapshot, but they do not mutate text, registers, selection, or ECS state.

use std::ops::Range;

use super::{TargetResolutionError, motion::clamp_to_boundary};

/// Text-object extent.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TextObjectScope {
    /// Inner object, excluding surrounding separators.
    Inner,
    /// Around object, including adjacent separators when present.
    Around,
}

/// Supported text-object families.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TextObjectKind {
    /// Vim lowercase `w` word.
    Word,
    /// Blank-line-delimited paragraph.
    Paragraph,
}

/// A parsed text object such as `iw`, `aw`, `ip`, or `ap`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TextObject {
    /// Inner or around extent.
    scope: TextObjectScope,
    /// Object family.
    kind: TextObjectKind,
}

impl TextObject {
    /// Creates a text object.
    #[must_use]
    pub const fn new(scope: TextObjectScope, kind: TextObjectKind) -> Self {
        Self { scope, kind }
    }

    /// Returns the object extent.
    #[must_use]
    pub const fn scope(self) -> TextObjectScope {
        self.scope
    }

    /// Returns the object family.
    #[must_use]
    pub const fn kind(self) -> TextObjectKind {
        self.kind
    }
}

/// Resolves a text object into a half-open byte range.
///
/// # Errors
///
/// Returns [`TargetResolutionError::NoTextObject`] when the snapshot has no
/// matching object at or after the cursor.
pub fn resolve_text_object_range(
    text: &str,
    cursor_byte_index: usize,
    object: TextObject,
    count: usize,
) -> Result<Range<usize>, TargetResolutionError> {
    let count = count.max(1);
    match object.kind {
        TextObjectKind::Word => word_object_range(text, cursor_byte_index, object.scope, count),
        TextObjectKind::Paragraph => {
            paragraph_object_range(text, cursor_byte_index, object.scope, count)
        }
    }
}

/// Returns whether a character belongs to Vim's lowercase word class.
fn is_keyword_character(character: char) -> bool {
    character == '_' || character.is_alphanumeric()
}

/// Returns whether a character is a word-object body character.
const fn is_word_object_character(character: char) -> bool {
    !character.is_whitespace()
}

/// Resolves `iw` or `aw`.
fn word_object_range(
    text: &str,
    cursor_byte_index: usize,
    scope: TextObjectScope,
    count: usize,
) -> Result<Range<usize>, TargetResolutionError> {
    let cursor = clamp_to_boundary(text, cursor_byte_index);
    let runs = word_runs(text);
    let Some(first_index) = runs
        .iter()
        .position(|run| run.start <= cursor && cursor < run.end)
        .or_else(|| runs.iter().position(|run| run.start >= cursor))
    else {
        return Err(TargetResolutionError::NoTextObject);
    };
    let last_index = first_index.saturating_add(count - 1).min(runs.len() - 1);
    let inner = runs[first_index].start..runs[last_index].end;

    Ok(match scope {
        TextObjectScope::Inner => inner,
        TextObjectScope::Around => around_word_range(text, inner),
    })
}

/// Expands a word range to include adjacent whitespace.
fn around_word_range(text: &str, inner: Range<usize>) -> Range<usize> {
    let trailing = following_whitespace_end(text, inner.end);
    if trailing > inner.end {
        return inner.start..trailing;
    }

    preceding_whitespace_start(text, inner.start)..inner.end
}

/// Resolves `ip` or `ap`.
fn paragraph_object_range(
    text: &str,
    cursor_byte_index: usize,
    scope: TextObjectScope,
    count: usize,
) -> Result<Range<usize>, TargetResolutionError> {
    let cursor = clamp_to_boundary(text, cursor_byte_index);
    let paragraphs = paragraph_runs(text);
    let Some(first_index) = paragraphs
        .iter()
        .position(|paragraph| paragraph.start <= cursor && cursor < paragraph.end)
        .or_else(|| {
            paragraphs
                .iter()
                .position(|paragraph| paragraph.start >= cursor)
        })
    else {
        return Err(TargetResolutionError::NoTextObject);
    };
    let last_index = first_index
        .saturating_add(count - 1)
        .min(paragraphs.len() - 1);
    let inner = paragraphs[first_index].start..paragraphs[last_index].end;

    Ok(match scope {
        TextObjectScope::Inner => inner,
        TextObjectScope::Around => around_paragraph_range(text, inner),
    })
}

/// Expands a paragraph range to include one neighboring blank separator run.
fn around_paragraph_range(text: &str, inner: Range<usize>) -> Range<usize> {
    let trailing = following_blank_lines_end(text, inner.end);
    if trailing > inner.end {
        return inner.start..trailing;
    }

    preceding_blank_lines_start(text, inner.start)..inner.end
}

/// A contiguous non-whitespace object run.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct WordRun {
    /// First byte in the run.
    start: usize,
    /// Exclusive end byte.
    end: usize,
}

/// Returns contiguous lowercase-word and punctuation runs.
fn word_runs(text: &str) -> Vec<WordRun> {
    let mut runs = Vec::new();
    let mut current: Option<(WordRun, bool)> = None;

    for (byte_index, character) in text.char_indices() {
        if !is_word_object_character(character) {
            if let Some((run, _class)) = current.take() {
                runs.push(run);
            }
            continue;
        }

        let class = is_keyword_character(character);
        match current {
            Some((mut run, current_class)) if current_class == class => {
                run.end = byte_index + character.len_utf8();
                current = Some((run, current_class));
            }
            Some((run, _current_class)) => {
                runs.push(run);
                current = Some((
                    WordRun {
                        start: byte_index,
                        end: byte_index + character.len_utf8(),
                    },
                    class,
                ));
            }
            None => {
                current = Some((
                    WordRun {
                        start: byte_index,
                        end: byte_index + character.len_utf8(),
                    },
                    class,
                ));
            }
        }
    }

    if let Some((run, _class)) = current {
        runs.push(run);
    }

    runs
}

/// A nonblank paragraph run.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ParagraphRun {
    /// First byte in the paragraph.
    start: usize,
    /// Exclusive end byte.
    end: usize,
}

/// Returns blank-line-delimited nonblank paragraphs.
fn paragraph_runs(text: &str) -> Vec<ParagraphRun> {
    let mut runs = Vec::new();
    let mut current_start = None;
    let mut current_end = 0;

    for line in lines(text) {
        if line.is_blank {
            if let Some(start) = current_start.take() {
                runs.push(ParagraphRun {
                    start,
                    end: current_end,
                });
            }
            continue;
        }

        if current_start.is_none() {
            current_start = Some(line.start);
        }
        current_end = line.end_with_newline;
    }

    if let Some(start) = current_start {
        runs.push(ParagraphRun {
            start,
            end: current_end,
        });
    }

    runs
}

/// Physical line metadata.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct TextLine {
    /// First byte in the line.
    start: usize,
    /// Exclusive content end.
    end: usize,
    /// Exclusive end including newline when present.
    end_with_newline: usize,
    /// Whether visible content is empty after Unicode whitespace trimming.
    is_blank: bool,
}

/// Iterates physical lines.
fn lines(text: &str) -> impl Iterator<Item = TextLine> + '_ {
    let mut start = 0;

    std::iter::from_fn(move || {
        if start > text.len() {
            return None;
        }

        let line_start = start;
        let line_end = text[start..]
            .find('\n')
            .map_or(text.len(), |offset| start + offset);
        let end_with_newline = text[line_end..]
            .chars()
            .next()
            .filter(|character| *character == '\n')
            .map_or(line_end, |newline| line_end + newline.len_utf8());
        start = end_with_newline
            .checked_add(usize::from(
                end_with_newline == line_end && line_end == text.len(),
            ))
            .unwrap_or(text.len() + 1);

        Some(TextLine {
            start: line_start,
            end: line_end,
            end_with_newline,
            is_blank: text[line_start..line_end].trim().is_empty(),
        })
    })
}

/// Returns the byte after whitespace following `index`.
fn following_whitespace_end(text: &str, index: usize) -> usize {
    let mut end = index;
    for (offset, character) in text[index..].char_indices() {
        if !character.is_whitespace() {
            break;
        }
        end = index + offset + character.len_utf8();
    }
    end
}

/// Returns the byte before contiguous whitespace preceding `index`.
fn preceding_whitespace_start(text: &str, index: usize) -> usize {
    let mut start = index;
    for (byte_index, character) in text[..index].char_indices().rev() {
        if !character.is_whitespace() {
            break;
        }
        start = byte_index;
    }
    start
}

/// Returns the end of blank lines following `index`.
fn following_blank_lines_end(text: &str, index: usize) -> usize {
    let mut end = index;
    for line in lines(&text[index..]) {
        if !line.is_blank {
            break;
        }
        end = index + line.end_with_newline;
    }
    end
}

/// Returns the start of blank lines preceding `index`.
fn preceding_blank_lines_start(text: &str, index: usize) -> usize {
    let mut start = index;
    for line in lines(text).take_while(|line| line.end_with_newline <= index) {
        if line.is_blank {
            start = start.min(line.start);
        } else {
            start = index;
        }
    }
    start
}

#[cfg(test)]
mod tests {
    use super::{TextObject, TextObjectKind, TextObjectScope, resolve_text_object_range};
    use crate::vim::TargetResolutionError;

    #[test]
    fn inner_word_resolves_utf8_keyword_run() {
        let text = "one λ_two!";

        assert_eq!(
            resolve_text_object_range(
                text,
                "one ".len(),
                TextObject::new(TextObjectScope::Inner, TextObjectKind::Word),
                1,
            ),
            Ok("one ".len().."one λ_two".len())
        );
    }

    #[test]
    fn around_word_includes_trailing_space_when_present() {
        let text = "one two  three";

        assert_eq!(
            resolve_text_object_range(
                text,
                "one ".len(),
                TextObject::new(TextObjectScope::Around, TextObjectKind::Word),
                1,
            ),
            Ok("one ".len().."one two  ".len())
        );
    }

    #[test]
    fn counted_word_object_extends_across_runs() {
        let text = "one two three";

        assert_eq!(
            resolve_text_object_range(
                text,
                0,
                TextObject::new(TextObjectScope::Inner, TextObjectKind::Word),
                2,
            ),
            Ok(0.."one two".len())
        );
    }

    #[test]
    fn paragraph_objects_use_blank_line_boundaries() {
        let text = "one\ntwo\n\nthree\n\n";

        assert_eq!(
            resolve_text_object_range(
                text,
                "one\n".len(),
                TextObject::new(TextObjectScope::Inner, TextObjectKind::Paragraph),
                1,
            ),
            Ok(0.."one\ntwo\n".len())
        );
        assert_eq!(
            resolve_text_object_range(
                text,
                "one\ntwo\n\n".len(),
                TextObject::new(TextObjectScope::Around, TextObjectKind::Paragraph),
                1,
            ),
            Ok("one\ntwo\n\n".len()..text.len())
        );
    }

    #[test]
    fn missing_text_object_is_typed() {
        assert_eq!(
            resolve_text_object_range(
                " \n\t",
                0,
                TextObject::new(TextObjectScope::Inner, TextObjectKind::Word),
                1,
            ),
            Err(TargetResolutionError::NoTextObject)
        );
    }
}