Skip to main content

reovim_module_textobjects/
word.rs

1//! Word text object commands.
2//!
3//! Implements text objects: `iw`, `aw`, `iW`, `aW`.
4//!
5//! These commands calculate the range of a word under/around the cursor
6//! for use with operators like delete, yank, and change.
7//!
8//! # Mode-Aware Behavior (Epic #465)
9//!
10//! Text objects behave differently based on the current mode:
11//! - **Operator-pending mode** (d, y, c): Store range for operator consumption
12//! - **Visual mode** (v, V, Ctrl-V): Update selection to cover the text object
13
14use {
15    reovim_driver_command::{
16        ArgKind, ArgSpec, Command, CommandContext, CommandHandler, CommandResult,
17    },
18    reovim_driver_session::{
19        OperatorPendingState, SessionRuntime, TextObjRange,
20        api::{ExtensionApi, ModeApi, Selection, SelectionMode},
21    },
22    reovim_kernel::api::v1::{CommandId, Position, TextObject, TextObjectEngine, WordBoundary},
23};
24
25use crate::ids;
26
27// =============================================================================
28// Helper functions
29// =============================================================================
30
31/// Check if the current mode is a visual mode.
32fn is_visual_mode(runtime: &SessionRuntime<'_>) -> bool {
33    let mode = runtime.current_mode();
34    let mode_name = mode.name();
35    mode_name == "visual" || mode_name == "visual-line" || mode_name == "visual-block"
36}
37
38/// Get the selection mode for the current visual mode.
39fn visual_selection_mode(runtime: &SessionRuntime<'_>) -> SelectionMode {
40    let mode = runtime.current_mode();
41    match mode.name() {
42        "visual-line" => SelectionMode::Line,
43        "visual-block" => SelectionMode::Block,
44        _ => SelectionMode::Character,
45    }
46}
47
48/// Execute a word text object and store the range for operator consumption,
49/// or update the selection if in visual mode.
50#[cfg_attr(coverage_nightly, coverage(off))]
51fn execute_word_textobj(
52    runtime: &mut SessionRuntime<'_>,
53    args: &CommandContext,
54    text_object: TextObject,
55) -> CommandResult {
56    let Some(buffer_id) = args.buffer_id() else {
57        return CommandResult::error("No active buffer");
58    };
59
60    let count = args.count().unwrap_or(1);
61
62    // Get cursor from per-client Window (#471)
63    let Some(window) = runtime.windows().active() else {
64        return CommandResult::error("No active window");
65    };
66    let pos = Position::new(window.cursor.line, window.cursor.column);
67
68    // Calculate text object range using with_buffer_read callback
69    let range_result = runtime.with_buffer_read(buffer_id, |buffer| {
70        TextObjectEngine::range(buffer, pos, text_object, count)
71    });
72
73    let Some(range_result) = range_result else {
74        return CommandResult::error("Buffer not found");
75    };
76
77    let Some((start, end)) = range_result else {
78        return CommandResult::Success; // No-op if no range found
79    };
80
81    // Kernel returns inclusive end position, convert to exclusive for Range
82    // end.column points to the last character, we need end.column + 1
83    let end_exclusive = Position::new(end.line, end.column + 1);
84
85    // Check if we're in visual mode
86    if is_visual_mode(runtime) {
87        // Visual mode: update the selection to cover the text object
88        let sel_mode = visual_selection_mode(runtime);
89        if let Some(window) = runtime.windows_mut().active_mut() {
90            window.selection = Some(Selection::new(start, end_exclusive, sel_mode));
91            // Move cursor to end of selection
92            window.cursor = end.into();
93        }
94    } else {
95        // Operator-pending mode: store range for operator consumption (Epic #465)
96        // The operator resolver's on_command_complete will take() this range
97        let state = runtime.ext_mut::<OperatorPendingState>();
98        state.set_textobj_range(TextObjRange::characterwise(start, end_exclusive));
99    }
100
101    CommandResult::Success
102}
103
104// =============================================================================
105// Inner Word (iw)
106// =============================================================================
107
108/// Inner word text object.
109///
110/// Selects the word under the cursor without surrounding whitespace.
111#[derive(Debug, Clone, Copy, Default)]
112pub struct InnerWord;
113
114impl Command for InnerWord {
115    fn id(&self) -> CommandId {
116        ids::INNER_WORD
117    }
118
119    fn description(&self) -> &'static str {
120        "Inner word text object"
121    }
122
123    fn args(&self) -> Vec<ArgSpec> {
124        vec![ArgSpec::optional(
125            "count",
126            ArgKind::Count,
127            "Number of words",
128        )]
129    }
130}
131
132impl CommandHandler for InnerWord {
133    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
134        execute_word_textobj(runtime, args, TextObject::InnerWord(WordBoundary::Word))
135    }
136}
137
138// =============================================================================
139// A Word (aw)
140// =============================================================================
141
142/// A word text object.
143///
144/// Selects the word under the cursor including trailing (or leading) whitespace.
145#[derive(Debug, Clone, Copy, Default)]
146pub struct AWord;
147
148impl Command for AWord {
149    fn id(&self) -> CommandId {
150        ids::AROUND_WORD
151    }
152
153    fn description(&self) -> &'static str {
154        "A word text object (including whitespace)"
155    }
156
157    fn args(&self) -> Vec<ArgSpec> {
158        vec![ArgSpec::optional(
159            "count",
160            ArgKind::Count,
161            "Number of words",
162        )]
163    }
164}
165
166impl CommandHandler for AWord {
167    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
168        execute_word_textobj(runtime, args, TextObject::AWord(WordBoundary::Word))
169    }
170}
171
172// =============================================================================
173// Inner WORD (iW)
174// =============================================================================
175
176/// Inner WORD text object.
177///
178/// Selects the WORD (whitespace-delimited) under the cursor.
179#[derive(Debug, Clone, Copy, Default)]
180pub struct InnerWordBig;
181
182impl Command for InnerWordBig {
183    fn id(&self) -> CommandId {
184        ids::INNER_WORD_BIG
185    }
186
187    fn description(&self) -> &'static str {
188        "Inner WORD text object"
189    }
190
191    fn args(&self) -> Vec<ArgSpec> {
192        vec![ArgSpec::optional(
193            "count",
194            ArgKind::Count,
195            "Number of WORDs",
196        )]
197    }
198}
199
200impl CommandHandler for InnerWordBig {
201    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
202        execute_word_textobj(runtime, args, TextObject::InnerWord(WordBoundary::BigWord))
203    }
204}
205
206// =============================================================================
207// A WORD (aW)
208// =============================================================================
209
210/// A WORD text object.
211///
212/// Selects the WORD (whitespace-delimited) including surrounding whitespace.
213#[derive(Debug, Clone, Copy, Default)]
214pub struct AWordBig;
215
216impl Command for AWordBig {
217    fn id(&self) -> CommandId {
218        ids::AROUND_WORD_BIG
219    }
220
221    fn description(&self) -> &'static str {
222        "A WORD text object (including whitespace)"
223    }
224
225    fn args(&self) -> Vec<ArgSpec> {
226        vec![ArgSpec::optional(
227            "count",
228            ArgKind::Count,
229            "Number of WORDs",
230        )]
231    }
232}
233
234impl CommandHandler for AWordBig {
235    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
236        execute_word_textobj(runtime, args, TextObject::AWord(WordBoundary::BigWord))
237    }
238}
239
240// =============================================================================
241// Command Registration
242// =============================================================================
243
244/// Get all word text object commands as boxed trait objects.
245#[must_use]
246pub fn all_commands() -> Vec<Box<dyn CommandHandler>> {
247    vec![
248        Box::new(InnerWord),
249        Box::new(AWord),
250        Box::new(InnerWordBig),
251        Box::new(AWordBig),
252    ]
253}
254
255// =============================================================================
256// Tests
257// =============================================================================