Skip to main content

reovim_module_textobjects/
bracket.rs

1//! Bracket text object commands.
2//!
3//! Implements text objects: `i(`, `a(`, `i[`, `a[`, `i{`, `a{`, `i<`, `a<`.
4//!
5//! These commands select text within or around bracket pairs.
6//!
7//! # Mode-Aware Behavior (Epic #465)
8//!
9//! Text objects behave differently based on the current mode:
10//! - **Operator-pending mode** (d, y, c): Store range for operator consumption
11//! - **Visual mode** (v, V, Ctrl-V): Update selection to cover the text object
12
13use {
14    reovim_driver_command::{
15        ArgKind, ArgSpec, Command, CommandContext, CommandHandler, CommandResult,
16    },
17    reovim_driver_session::{
18        OperatorPendingState, SessionRuntime, TextObjRange,
19        api::{ExtensionApi, ModeApi, Selection, SelectionMode},
20    },
21    reovim_kernel::api::v1::{CommandId, Position, TextObject, TextObjectEngine},
22};
23
24use crate::ids;
25
26// =============================================================================
27// Helper functions
28// =============================================================================
29
30/// Check if the current mode is a visual mode.
31fn is_visual_mode(runtime: &SessionRuntime<'_>) -> bool {
32    let mode = runtime.current_mode();
33    let mode_name = mode.name();
34    mode_name == "visual" || mode_name == "visual-line" || mode_name == "visual-block"
35}
36
37/// Get the selection mode for the current visual mode.
38fn visual_selection_mode(runtime: &SessionRuntime<'_>) -> SelectionMode {
39    let mode = runtime.current_mode();
40    match mode.name() {
41        "visual-line" => SelectionMode::Line,
42        "visual-block" => SelectionMode::Block,
43        _ => SelectionMode::Character,
44    }
45}
46
47/// Execute a bracket text object and store the range for operator consumption,
48/// or update the selection if in visual mode.
49#[cfg_attr(coverage_nightly, coverage(off))]
50fn execute_bracket_textobj(
51    runtime: &mut SessionRuntime<'_>,
52    args: &CommandContext,
53    text_object: TextObject,
54) -> CommandResult {
55    let Some(buffer_id) = args.buffer_id() else {
56        return CommandResult::error("No active buffer");
57    };
58
59    let count = args.count().unwrap_or(1);
60
61    // Get cursor from per-client Window (#471)
62    let Some(window) = runtime.windows().active() else {
63        return CommandResult::error("No active window");
64    };
65    let pos = Position::new(window.cursor.line, window.cursor.column);
66
67    // Calculate text object range using with_buffer_read callback
68    let range_result = runtime.with_buffer_read(buffer_id, |buffer| {
69        TextObjectEngine::range(buffer, pos, text_object, count)
70    });
71
72    let Some(range_result) = range_result else {
73        return CommandResult::error("Buffer not found");
74    };
75
76    let Some((start, end)) = range_result else {
77        return CommandResult::Success; // No-op if no matching brackets
78    };
79
80    // Kernel returns inclusive end, convert to exclusive
81    let end_exclusive = Position::new(end.line, end.column + 1);
82
83    // Check if we're in visual mode
84    if is_visual_mode(runtime) {
85        // Visual mode: update the selection to cover the text object
86        let sel_mode = visual_selection_mode(runtime);
87        if let Some(window) = runtime.windows_mut().active_mut() {
88            window.selection = Some(Selection::new(start, end_exclusive, sel_mode));
89            // Move cursor to end of selection
90            window.cursor = end.into();
91        }
92    } else {
93        // Operator-pending mode: store range for operator consumption (Epic #465)
94        // The operator resolver's on_command_complete will take() this range
95        let state = runtime.ext_mut::<OperatorPendingState>();
96        state.set_textobj_range(TextObjRange::characterwise(start, end_exclusive));
97    }
98
99    CommandResult::Success
100}
101
102// =============================================================================
103// Inner Parenthesis (i(, i), ib)
104// =============================================================================
105
106/// Inner parenthesis text object.
107///
108/// Selects text inside parentheses, excluding the parens.
109#[derive(Debug, Clone, Copy, Default)]
110pub struct InnerParen;
111
112impl Command for InnerParen {
113    fn id(&self) -> CommandId {
114        ids::INNER_PAREN
115    }
116
117    fn description(&self) -> &'static str {
118        "Inner parenthesis text object"
119    }
120
121    fn args(&self) -> Vec<ArgSpec> {
122        vec![ArgSpec::optional("count", ArgKind::Count, "Nesting level")]
123    }
124}
125
126impl CommandHandler for InnerParen {
127    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
128        execute_bracket_textobj(runtime, args, TextObject::InnerBracket('('))
129    }
130}
131
132// =============================================================================
133// Around Parenthesis (a(, a), ab)
134// =============================================================================
135
136/// Around parenthesis text object.
137///
138/// Selects text including the parentheses.
139#[derive(Debug, Clone, Copy, Default)]
140pub struct AroundParen;
141
142impl Command for AroundParen {
143    fn id(&self) -> CommandId {
144        ids::AROUND_PAREN
145    }
146
147    fn description(&self) -> &'static str {
148        "Around parenthesis text object"
149    }
150
151    fn args(&self) -> Vec<ArgSpec> {
152        vec![ArgSpec::optional("count", ArgKind::Count, "Nesting level")]
153    }
154}
155
156impl CommandHandler for AroundParen {
157    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
158        execute_bracket_textobj(runtime, args, TextObject::ABracket('('))
159    }
160}
161
162// =============================================================================
163// Inner Square Bracket (i[, i])
164// =============================================================================
165
166/// Inner square bracket text object.
167///
168/// Selects text inside square brackets, excluding the brackets.
169#[derive(Debug, Clone, Copy, Default)]
170pub struct InnerSquareBracket;
171
172impl Command for InnerSquareBracket {
173    fn id(&self) -> CommandId {
174        ids::INNER_BRACKET
175    }
176
177    fn description(&self) -> &'static str {
178        "Inner square bracket text object"
179    }
180
181    fn args(&self) -> Vec<ArgSpec> {
182        vec![ArgSpec::optional("count", ArgKind::Count, "Nesting level")]
183    }
184}
185
186impl CommandHandler for InnerSquareBracket {
187    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
188        execute_bracket_textobj(runtime, args, TextObject::InnerBracket('['))
189    }
190}
191
192// =============================================================================
193// Around Square Bracket (a[, a])
194// =============================================================================
195
196/// Around square bracket text object.
197///
198/// Selects text including the square brackets.
199#[derive(Debug, Clone, Copy, Default)]
200pub struct AroundSquareBracket;
201
202impl Command for AroundSquareBracket {
203    fn id(&self) -> CommandId {
204        ids::AROUND_BRACKET
205    }
206
207    fn description(&self) -> &'static str {
208        "Around square bracket text object"
209    }
210
211    fn args(&self) -> Vec<ArgSpec> {
212        vec![ArgSpec::optional("count", ArgKind::Count, "Nesting level")]
213    }
214}
215
216impl CommandHandler for AroundSquareBracket {
217    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
218        execute_bracket_textobj(runtime, args, TextObject::ABracket('['))
219    }
220}
221
222// =============================================================================
223// Inner Brace (i{, i}, iB)
224// =============================================================================
225
226/// Inner brace text object.
227///
228/// Selects text inside braces, excluding the braces.
229#[derive(Debug, Clone, Copy, Default)]
230pub struct InnerBrace;
231
232impl Command for InnerBrace {
233    fn id(&self) -> CommandId {
234        ids::INNER_BRACE
235    }
236
237    fn description(&self) -> &'static str {
238        "Inner brace text object"
239    }
240
241    fn args(&self) -> Vec<ArgSpec> {
242        vec![ArgSpec::optional("count", ArgKind::Count, "Nesting level")]
243    }
244}
245
246impl CommandHandler for InnerBrace {
247    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
248        execute_bracket_textobj(runtime, args, TextObject::InnerBracket('{'))
249    }
250}
251
252// =============================================================================
253// Around Brace (a{, a}, aB)
254// =============================================================================
255
256/// Around brace text object.
257///
258/// Selects text including the braces.
259#[derive(Debug, Clone, Copy, Default)]
260pub struct AroundBrace;
261
262impl Command for AroundBrace {
263    fn id(&self) -> CommandId {
264        ids::AROUND_BRACE
265    }
266
267    fn description(&self) -> &'static str {
268        "Around brace text object"
269    }
270
271    fn args(&self) -> Vec<ArgSpec> {
272        vec![ArgSpec::optional("count", ArgKind::Count, "Nesting level")]
273    }
274}
275
276impl CommandHandler for AroundBrace {
277    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
278        execute_bracket_textobj(runtime, args, TextObject::ABracket('{'))
279    }
280}
281
282// =============================================================================
283// Inner Angle Bracket (i<, i>)
284// =============================================================================
285
286/// Inner angle bracket text object.
287///
288/// Selects text inside angle brackets, excluding the brackets.
289#[derive(Debug, Clone, Copy, Default)]
290pub struct InnerAngle;
291
292impl Command for InnerAngle {
293    fn id(&self) -> CommandId {
294        ids::INNER_ANGLE
295    }
296
297    fn description(&self) -> &'static str {
298        "Inner angle bracket text object"
299    }
300
301    fn args(&self) -> Vec<ArgSpec> {
302        vec![ArgSpec::optional("count", ArgKind::Count, "Nesting level")]
303    }
304}
305
306impl CommandHandler for InnerAngle {
307    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
308        execute_bracket_textobj(runtime, args, TextObject::InnerBracket('<'))
309    }
310}
311
312// =============================================================================
313// Around Angle Bracket (a<, a>)
314// =============================================================================
315
316/// Around angle bracket text object.
317///
318/// Selects text including the angle brackets.
319#[derive(Debug, Clone, Copy, Default)]
320pub struct AroundAngle;
321
322impl Command for AroundAngle {
323    fn id(&self) -> CommandId {
324        ids::AROUND_ANGLE
325    }
326
327    fn description(&self) -> &'static str {
328        "Around angle bracket text object"
329    }
330
331    fn args(&self) -> Vec<ArgSpec> {
332        vec![ArgSpec::optional("count", ArgKind::Count, "Nesting level")]
333    }
334}
335
336impl CommandHandler for AroundAngle {
337    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
338        execute_bracket_textobj(runtime, args, TextObject::ABracket('<'))
339    }
340}
341
342// =============================================================================
343// Command Registration
344// =============================================================================
345
346/// Get all bracket text object commands as boxed trait objects.
347#[must_use]
348pub fn all_commands() -> Vec<Box<dyn CommandHandler>> {
349    vec![
350        Box::new(InnerParen),
351        Box::new(AroundParen),
352        Box::new(InnerSquareBracket),
353        Box::new(AroundSquareBracket),
354        Box::new(InnerBrace),
355        Box::new(AroundBrace),
356        Box::new(InnerAngle),
357        Box::new(AroundAngle),
358    ]
359}
360
361// =============================================================================
362// Tests
363// =============================================================================