Skip to main content

reovim_module_textobjects/
quote.rs

1//! Quote text object commands.
2//!
3//! Implements text objects: `i"`, `a"`, `i'`, `a'`, `` i` ``, `` a` ``.
4//!
5//! These commands select text within or around quote characters.
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 quote 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_quote_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 quotes
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 Double Quote (i")
104// =============================================================================
105
106/// Inner double quote text object.
107///
108/// Selects text inside double quotes, excluding the quotes.
109#[derive(Debug, Clone, Copy, Default)]
110pub struct InnerDoubleQuote;
111
112impl Command for InnerDoubleQuote {
113    fn id(&self) -> CommandId {
114        ids::INNER_DOUBLE_QUOTE
115    }
116
117    fn description(&self) -> &'static str {
118        "Inner double quote text object"
119    }
120
121    fn args(&self) -> Vec<ArgSpec> {
122        vec![ArgSpec::optional(
123            "count",
124            ArgKind::Count,
125            "Quote nesting level",
126        )]
127    }
128}
129
130impl CommandHandler for InnerDoubleQuote {
131    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
132        execute_quote_textobj(runtime, args, TextObject::InnerQuote('"'))
133    }
134}
135
136// =============================================================================
137// Around Double Quote (a")
138// =============================================================================
139
140/// Around double quote text object.
141///
142/// Selects text including the double quotes.
143#[derive(Debug, Clone, Copy, Default)]
144pub struct AroundDoubleQuote;
145
146impl Command for AroundDoubleQuote {
147    fn id(&self) -> CommandId {
148        ids::AROUND_DOUBLE_QUOTE
149    }
150
151    fn description(&self) -> &'static str {
152        "Around double quote text object"
153    }
154
155    fn args(&self) -> Vec<ArgSpec> {
156        vec![ArgSpec::optional(
157            "count",
158            ArgKind::Count,
159            "Quote nesting level",
160        )]
161    }
162}
163
164impl CommandHandler for AroundDoubleQuote {
165    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
166        execute_quote_textobj(runtime, args, TextObject::AQuote('"'))
167    }
168}
169
170// =============================================================================
171// Inner Single Quote (i')
172// =============================================================================
173
174/// Inner single quote text object.
175///
176/// Selects text inside single quotes, excluding the quotes.
177#[derive(Debug, Clone, Copy, Default)]
178pub struct InnerSingleQuote;
179
180impl Command for InnerSingleQuote {
181    fn id(&self) -> CommandId {
182        ids::INNER_SINGLE_QUOTE
183    }
184
185    fn description(&self) -> &'static str {
186        "Inner single quote text object"
187    }
188
189    fn args(&self) -> Vec<ArgSpec> {
190        vec![ArgSpec::optional(
191            "count",
192            ArgKind::Count,
193            "Quote nesting level",
194        )]
195    }
196}
197
198impl CommandHandler for InnerSingleQuote {
199    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
200        execute_quote_textobj(runtime, args, TextObject::InnerQuote('\''))
201    }
202}
203
204// =============================================================================
205// Around Single Quote (a')
206// =============================================================================
207
208/// Around single quote text object.
209///
210/// Selects text including the single quotes.
211#[derive(Debug, Clone, Copy, Default)]
212pub struct AroundSingleQuote;
213
214impl Command for AroundSingleQuote {
215    fn id(&self) -> CommandId {
216        ids::AROUND_SINGLE_QUOTE
217    }
218
219    fn description(&self) -> &'static str {
220        "Around single quote text object"
221    }
222
223    fn args(&self) -> Vec<ArgSpec> {
224        vec![ArgSpec::optional(
225            "count",
226            ArgKind::Count,
227            "Quote nesting level",
228        )]
229    }
230}
231
232impl CommandHandler for AroundSingleQuote {
233    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
234        execute_quote_textobj(runtime, args, TextObject::AQuote('\''))
235    }
236}
237
238// =============================================================================
239// Inner Backtick (i`)
240// =============================================================================
241
242/// Inner backtick text object.
243///
244/// Selects text inside backticks, excluding the backticks.
245#[derive(Debug, Clone, Copy, Default)]
246pub struct InnerBacktick;
247
248impl Command for InnerBacktick {
249    fn id(&self) -> CommandId {
250        ids::INNER_BACKTICK
251    }
252
253    fn description(&self) -> &'static str {
254        "Inner backtick text object"
255    }
256
257    fn args(&self) -> Vec<ArgSpec> {
258        vec![ArgSpec::optional(
259            "count",
260            ArgKind::Count,
261            "Quote nesting level",
262        )]
263    }
264}
265
266impl CommandHandler for InnerBacktick {
267    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
268        execute_quote_textobj(runtime, args, TextObject::InnerQuote('`'))
269    }
270}
271
272// =============================================================================
273// Around Backtick (a`)
274// =============================================================================
275
276/// Around backtick text object.
277///
278/// Selects text including the backticks.
279#[derive(Debug, Clone, Copy, Default)]
280pub struct AroundBacktick;
281
282impl Command for AroundBacktick {
283    fn id(&self) -> CommandId {
284        ids::AROUND_BACKTICK
285    }
286
287    fn description(&self) -> &'static str {
288        "Around backtick text object"
289    }
290
291    fn args(&self) -> Vec<ArgSpec> {
292        vec![ArgSpec::optional(
293            "count",
294            ArgKind::Count,
295            "Quote nesting level",
296        )]
297    }
298}
299
300impl CommandHandler for AroundBacktick {
301    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
302        execute_quote_textobj(runtime, args, TextObject::AQuote('`'))
303    }
304}
305
306// =============================================================================
307// Command Registration
308// =============================================================================
309
310/// Get all quote text object commands as boxed trait objects.
311#[must_use]
312pub fn all_commands() -> Vec<Box<dyn CommandHandler>> {
313    vec![
314        Box::new(InnerDoubleQuote),
315        Box::new(AroundDoubleQuote),
316        Box::new(InnerSingleQuote),
317        Box::new(AroundSingleQuote),
318        Box::new(InnerBacktick),
319        Box::new(AroundBacktick),
320    ]
321}
322
323// =============================================================================
324// Tests
325// =============================================================================