Skip to content
2 changes: 1 addition & 1 deletion crates/helm-bench/benches/vim_objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
//!
//! `di_paren_no_pair_10mb` measures the worst case behind open question 6
//! of `tasks/109-vim-objects.md`: a bracket object with no enclosing pair
//! scans the text before the cursor to its start.
//! scans 1 MiB of the text before the cursor, the cap T-114 set.

use std::hint::black_box;

Expand Down
5 changes: 4 additions & 1 deletion crates/helm-editor/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,10 @@ pub struct Editor {
/// editor that made it, not to its buffer, since two editors can show one
/// buffer.
///
/// The editor owns the only strong reference. A [`Session`](crate::Session)
/// The editor owns the only lasting strong reference:
/// [`CommandRegistry::run_in`](crate::CommandRegistry::run_in) holds a clone
/// while a command runs and drops it before it returns. A
/// [`Session`](crate::Session)
/// keeps a [`Weak`] one with each open record, so it can tell which editor
/// a record belongs to and, once that editor is dropped, that nobody will
/// finish the record. The allocation outlives the editor while any weak
Expand Down
8 changes: 7 additions & 1 deletion crates/helm-editor/src/editor/vim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -883,7 +883,10 @@ impl Editor {
} else {
// Below a last line with no line break: the break moves
// to the front.
// The text's own bytes are moved in place, not copied.
// The text stays in its own allocation: `split_off`
// copies only the line break, 1 or 2 bytes, into a
// small string, and `insert_str` shifts the rest of the
// text along to put the break in front.
let mut text = text;
let body = split_break(&text).0.len();
let end: String = text.split_off(body);
Expand Down Expand Up @@ -1004,6 +1007,9 @@ impl Editor {
o::span(buffer, &mut reads, cursor, object, count)
.filter(|span| !matches!(span, Span::Chars(r) if r.is_empty()))
.map(|span| o::visual_ends(buffer, &mut reads, &span))
} else if matches!(object.kind, o::Kind::Pair { .. }) {
let ends = (anchor.min(cursor), anchor.max(cursor));
o::grow_pair(buffer, &mut reads, ends, object, count)
} else if matches!(object.kind, o::Kind::Word { .. }) && cursor > anchor {
let from = o::after(buffer, &mut reads, cursor);
o::word_from(buffer, &mut reads, from, object, count).map(|span| {
Expand Down
9 changes: 9 additions & 0 deletions crates/helm-editor/src/motion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,15 @@ impl<'a> Backward<'a> {
Self::bounded(buffer, slot, offset, WINDOW, usize::MAX)
}

/// A reader that reads nothing before `floor` (T-114): it stops there as
/// at the limit of a budget, but keeps only its latest window, as one
/// made with [`Backward::new`] does.
fn floored(buffer: &'a Buffer, slot: &'a mut Window, offset: usize, floor: usize) -> Self {
let mut reader = Self::new(buffer, slot, offset);
reader.limit = floor.min(offset);
reader
}

fn bounded(
buffer: &'a Buffer,
slot: &'a mut Window,
Expand Down
112 changes: 96 additions & 16 deletions crates/helm-editor/src/motion/vim/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
//!
//! Word objects read a window at a time from the cursor and stop at the
//! line's ends. Quote objects read the cursor's line from its start.
//! Bracket objects read outward from the cursor and use the line index
//! only for the block rule at the end. Paragraph objects use a fixed
//! number of line-index lookups per line they cross.
//! Bracket objects read outward from the cursor, at most 1 MiB each way,
//! and use the line index only for the block rule at the end. Paragraph
//! objects use a fixed number of line-index lookups per line they cross.

use std::cell::Cell;

Expand All @@ -17,7 +17,7 @@ use super::{
vsettle,
};
use crate::editor::is_word;
use crate::motion::{Backward, Forward, Reads, is_blank, is_break, left, right};
use crate::motion::{Backward, Forward, Reads, WINDOW, is_blank, is_break, left, right};
use crate::vim_commands as ids;

/// What an object's range is made of.
Expand Down Expand Up @@ -298,23 +298,41 @@ fn word(
Some(Span::Chars(back.offset()..end))
}

/// A bracket object from `p` with count `n`: the `n`th pair of `open` and
/// `close` out from the cursor.
fn pair(
/// How far a bracket object reads from where its scan starts, each way
/// (T-114): 1 MiB. A pair with a bracket further away counts as no pair.
const PAIR_SCAN: usize = 1 << 20;

/// The text a bracket scan from `p` may read: from `p - PAIR_SCAN` up to,
/// not including, `p + PAIR_SCAN`.
fn scan_window(p: usize) -> (usize, usize) {
(p.saturating_sub(PAIR_SCAN), p.saturating_add(PAIR_SCAN))
}

/// The `n`th pair of `open` and `close` out from `p`, as the offsets of its
/// two brackets, with both inside `window`. With `on`, an opening bracket
/// at `p` is the first pair's, as for a cursor on it. Without, the scan
/// starts before `p` and the char at `p` doesn't count, as for the start of
/// a visual selection.
#[expect(
clippy::too_many_arguments,
reason = "each argument is one part of the scan"
)]
fn find_pair(
buffer: &Buffer,
reads: &mut Reads,
p: usize,
n: usize,
inner: bool,
open: char,
close: char,
) -> Option<Span> {
on: bool,
(floor, ceiling): (usize, usize),
) -> Option<(usize, usize)> {
// The opening bracket: the one at `p`, or the `n`th unmatched one
// before it.
let mut found = usize::from(char_at(buffer, reads, p) == Some(open));
let mut found = usize::from(on && char_at(buffer, reads, p) == Some(open));
let mut o = p;
if found < n {
let mut back = Backward::new(buffer, &mut reads.backward, p);
let mut back = Backward::floored(buffer, &mut reads.backward, p, floor);
let depth = Cell::new(0usize);
let keep = |c: char| {
if c == close {
Expand All @@ -337,7 +355,8 @@ fn pair(
}
// Its closing bracket.
let after = o + open.len_utf8();
let mut ahead = Forward::new(buffer, &mut reads.forward, after);
let budget = ceiling.saturating_sub(after);
let mut ahead = Forward::bounded(buffer, &mut reads.forward, after, WINDOW, budget);
let depth = Cell::new(0usize);
ahead.skip_while(|c| {
if c == open {
Expand All @@ -352,11 +371,35 @@ fn pair(
});
ahead.peek()?;
let c = ahead.offset();
drop(ahead);
if !inner {
return Some(Span::Chars(o..c + close.len_utf8()));
// A reader reads at least 4 bytes per window, so it can read a few
// bytes past its limit, and a window ends on a char boundary. So check
// both brackets against the window here. Any pair further out is also
// outside it, so this never drops a pair inside the window.
(o >= floor && c < ceiling).then_some((o, c))
}

/// A bracket object from `p` with count `n`: the `n`th pair of `open` and
/// `close` out from the cursor.
fn pair(
buffer: &Buffer,
reads: &mut Reads,
p: usize,
n: usize,
inner: bool,
open: char,
close: char,
) -> Option<Span> {
let (o, c) = find_pair(buffer, reads, p, n, open, close, true, scan_window(p))?;
if inner {
inside(buffer, reads, o + open.len_utf8(), c)
} else {
Some(Span::Chars(o..c + close.len_utf8()))
}
}

/// What `i` covers of the pair whose opening bracket ends at `after` and
/// whose closing bracket starts at `c`, or `None` if that is empty.
fn inside(buffer: &Buffer, reads: &mut Reads, after: usize, c: usize) -> Option<Span> {
// A line break right after the opening bracket is left out.
let mut start = after;
let opens_a_line = char_at(buffer, reads, start).is_some_and(is_break);
Expand All @@ -383,6 +426,41 @@ fn pair(
Some(Span::Chars(start..end))
}

/// A bracket object from a visual selection longer than one char, whose
/// first char is at `lo` and last at `hi`, as Vim 9.1 does it (T-114). The
/// pair is the `n`th out from before `lo`, so an opening bracket at `lo`
/// isn't that pair's: `va(a(` grows to the next pair out. `a` selects that
/// pair. `i` selects its inside, and while that inside lies within the
/// selection and is more than one char, it moves out one pair, so `vi(i(`
/// grows too. Gives the new selection's first and last chars, in that
/// order, or `None` if there is no such pair.
pub(crate) fn grow_pair(
buffer: &Buffer,
reads: &mut Reads,
(lo, hi): (usize, usize),
object: VimObject,
count: Option<usize>,
) -> Option<(usize, usize)> {
let Kind::Pair { open, close } = object.kind else {
return None;
};
let window = scan_window(lo);
let n = count.unwrap_or(1).max(1);
let (mut o, mut c) = find_pair(buffer, reads, lo, n, open, close, false, window)?;
loop {
if !object.inner {
let span = Span::Chars(o..c + close.len_utf8());
return Some(visual_ends(buffer, reads, &span));
}
let span = inside(buffer, reads, o + open.len_utf8(), c)?;
let (first, last) = visual_ends(buffer, reads, &span);
if first < lo || last > hi || first == last {
return Some((first, last));
}
(o, c) = find_pair(buffer, reads, o, 1, open, close, false, window)?;
}
}

/// A quote object from `p` with count `n`, within `p`'s line.
fn quote(
buffer: &Buffer,
Expand Down Expand Up @@ -432,7 +510,9 @@ fn quote(
}
count += 1;
}
escaped = c == '\\';
// A backslash escapes the char after it, another backslash too, so
// a quote is escaped after an odd number of them (T-114).
escaped = c == '\\' && !escaped;
reader.advance();
}
drop(reader);
Expand Down
50 changes: 41 additions & 9 deletions crates/helm-editor/src/vim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,26 @@
//!
//! Visual-mode `d` and `c` weren't part of that run.
//!
//! T-114 measured bracket objects from longer visual selections, escaped
//! quotes and the bracket scan's cap in the same Vim, and found these
//! differences. The first is Khakha's choice; the others follow the rules
//! above:
//!
//! - The bracket scan stops 1 MiB from where it starts and finds no pair
//! (Khakha's answer on PR #42). Vim reads the whole text, so `di(` with a
//! bracket 2 MiB away deletes in Vim and does nothing here.
//! - With no pair around the cursor, Vim looks for the next pair after
//! it, even on a later line, and here a bracket object finds nothing.
//! `di(` from `b` in `a b (c) d` leaves `a b () d` in Vim and changes
//! nothing here. In a visual mode Vim does the same when no pair is out
//! from the selection's start, and can select a pair inside the
//! selection: `va(a(a(` from `c` in `f(a(bc)d)e` leaves `(bc)` selected
//! in Vim, and `(a(bc)d)` stays selected here.
//! - With no unescaped quote before the cursor, Vim takes the line's first
//! quote as the opening one even if it is escaped. `di"` from `a` in
//! `x\"a"b"` leaves `x\""b"` in Vim. Here the escaped quote doesn't
//! count, so the pair is `"b"` and it leaves `x\"a""`.
//!
//! # Visual-mode commands
//!
//! | Id | Keys | What it does |
Expand Down Expand Up @@ -430,10 +450,15 @@
//! lines between, so `di{` on a block of lines leaves `{` and `}` on their
//! own lines and `ci{` leaves one empty line to type in. When both are left
//! out and one empty line is between them, `i` is that line. Any other
//! empty `i` finds nothing. All measured in Vim 9.1.
//!
//! **Quotes.** Only within the cursor's line. A quote right after a
//! backslash doesn't count. On a quote, its index among the line's quotes
//! empty `i` finds nothing. All measured in Vim 9.1. The scan reads at most
//! 1 MiB each way from where it starts (T-114): a pair counts only if both
//! its brackets are in the 1 MiB before that point or the 1 MiB from it on,
//! and a scan that reaches either end without its bracket finds no pair.
//!
//! **Quotes.** Only within the cursor's line. A quote right after an odd
//! number of backslashes doesn't count; after an even number, the
//! backslashes escape each other and the quote counts (T-114, as Vim 9.1
//! does). On a quote, its index among the line's quotes
//! says whether it opens or closes. Elsewhere, the quotes are the nearest
//! one before the cursor and the nearest one after; with none before, the
//! first pair after the cursor. `a` covers the quotes and the white space
Expand All @@ -457,11 +482,18 @@
//!
//! **In a visual mode** an object from a one-char selection replaces it,
//! and from a longer one grows it from the visual cursor: `viwiw` adds the
//! next run. `ip` and `ap` switch to visual-line mode and the rest to
//! visual mode, by the binding's `then_mode`, even when the object finds
//! nothing; then the selection doesn't change. A visual end is never the
//! line break of a line with text (T-108), so an object range that ends
//! right after such a break selects up to the char before it.
//! next run. A bracket object from a longer selection follows Vim 9.1
//! instead (T-114). Its scan starts before the selection's first char, so
//! a bracket there isn't that pair's, and it gives the `n`th pair out:
//! `a` selects that pair, and `i` its inside, moving out one pair at a
//! time while the inside lies within the selection and is more than one
//! char. So `va(a(` and `vi(i(` grow to the next pair out. The selection
//! then runs forward, from the pair's first char to its last. `ip` and
//! `ap` switch to visual-line mode and the rest to visual mode, by the
//! binding's `then_mode`, even when the object finds nothing; then the
//! selection doesn't change. A visual end is never the line break of a
//! line with text (T-108), so an object range that ends right after such
//! a break selects up to the char before it.
//!
//! # Registers (T-109)
//!
Expand Down
Loading
Loading