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
//! R code completer using R's built-in completion functions with fuzzy namespace support.
mod context;
mod namespace;
mod quoting;
use super::string_context::{complete_path_in_string, detect_string_context};
use context::{CompletionContext, completion_context, detect_library_context};
use namespace::{NamespaceExportCache, NamespaceFuzzyCache, parse_namespace_token};
use quoting::has_special_suffix;
use reedline::{Completer, CompletionResult, Span, Suggestion};
use std::collections::HashMap;
use std::time::{Duration, Instant};
/// Cache for completion results to avoid repeated R calls.
#[derive(Debug, Clone)]
struct CompletionCache {
/// The token that was used for the R completion query.
token: String,
/// The input before the token, used to identify the completion context.
prefix: String,
/// The input after the cursor, used to identify the completion context.
suffix: String,
/// The full completion results from R.
completions: Vec<String>,
/// When the completion was fetched.
timestamp: Instant,
}
/// R code completer using R's built-in completion functions.
pub struct RCompleter {
/// Timeout in milliseconds for R completion (0 = no timeout).
timeout_ms: u64,
/// Debounce delay in milliseconds.
debounce_ms: u64,
/// Number of completions to check for function type (0 = disable).
auto_paren_limit: usize,
/// Cached completion results.
cache: Option<CompletionCache>,
/// Whether fuzzy namespace completion is enabled.
fuzzy_namespace: bool,
/// Function names that trigger package-name completion (e.g., "library", "require").
package_functions: Vec<String>,
/// Runtime policy for installed-package static formal completion.
static_formals: arf_harp::completion::StaticFormalsPolicy,
/// Per-package cache of namespace exports.
namespace_cache: HashMap<String, NamespaceExportCache>,
/// Debounce cache for fuzzy namespace completion results.
namespace_fuzzy_cache: Option<NamespaceFuzzyCache>,
}
impl RCompleter {
/// Create a new RCompleter with default settings (50ms timeout, 100ms debounce, 50 function check limit).
pub fn new() -> Self {
RCompleter {
timeout_ms: 50,
debounce_ms: 100,
auto_paren_limit: 50,
cache: None,
fuzzy_namespace: false,
package_functions: vec!["library".to_string(), "require".to_string()],
static_formals: arf_harp::completion::StaticFormalsPolicy::off(),
namespace_cache: HashMap::new(),
namespace_fuzzy_cache: None,
}
}
/// Create a completer with all settings, including static formal policy.
pub fn with_settings_full_and_static_formals(
timeout_ms: u64,
debounce_ms: u64,
auto_paren_limit: usize,
fuzzy_namespace: bool,
package_functions: Vec<String>,
static_formals: arf_harp::completion::StaticFormalsPolicy,
) -> Self {
RCompleter {
timeout_ms,
debounce_ms,
auto_paren_limit,
cache: None,
fuzzy_namespace,
package_functions,
static_formals,
namespace_cache: HashMap::new(),
namespace_fuzzy_cache: None,
}
}
/// Check if the new token extends the cached token (prefix extension).
fn is_prefix_extension(&self, context: &CompletionContext) -> bool {
if let Some(cache) = &self.cache {
if cache.prefix != context.prefix || cache.suffix != context.suffix {
return false;
}
// Only reuse the cache when the extension consists solely of identifier
// characters (alphanumeric, `.`, `_`). Structural operators such as `$`,
// `@`, `[`, or `:` change the completion context entirely, so a fresh
// fetch is required.
// Example: "l$a$" extends "l$" by "a$" — the `$` means we are now
// completing inside a nested list and the old completions are irrelevant.
let Some(extension) = context.token.strip_prefix(cache.token.as_str()) else {
return false;
};
!extension.is_empty()
&& extension
.chars()
.all(|c| c.is_alphanumeric() || c == '.' || c == '_')
} else {
false
}
}
/// Check if we should use cached results (within debounce window, same token).
fn should_use_cache(&self, context: &CompletionContext) -> bool {
if let Some(cache) = &self.cache {
// Don't use empty cache
if cache.completions.is_empty() {
return false;
}
// Don't use cache for empty tokens (context likely changed)
if context.token.is_empty() || cache.token.is_empty() {
return false;
}
// A token alone is not a sufficient cache key: qualified calls,
// named arguments, and cursor suffixes can all change its meaning.
if cache.prefix != context.prefix || cache.suffix != context.suffix {
return false;
}
// Don't use cache for package:: completions (always fetch fresh, worth waiting)
if context.token.contains("::") || cache.token.contains("::") {
return false;
}
// Use cache if:
// 1. Same token and within debounce window
// 2. Token is a prefix extension of cached token
if cache.token == context.token {
cache.timestamp.elapsed() < Duration::from_millis(self.debounce_ms)
} else {
self.is_prefix_extension(context)
}
} else {
false
}
}
/// Filter cached completions for a new token (prefix extension).
fn filter_cached(&self, token: &str) -> Vec<String> {
if let Some(cache) = &self.cache {
cache
.completions
.iter()
.filter(|c| c.starts_with(token))
.cloned()
.collect()
} else {
vec![]
}
}
/// Invalidate the completion cache.
///
/// Only clears the debounce/prefix cache. Namespace export cache is
/// preserved since package exports are stable and use TTL-based expiry.
fn invalidate_cache(&mut self) {
self.cache = None;
self.namespace_fuzzy_cache = None;
}
}
impl Default for RCompleter {
fn default() -> Self {
Self::new()
}
}
impl Completer for RCompleter {
fn complete(&mut self, line: &str, pos: usize) -> CompletionResult {
CompletionResult::fresh(self.complete_impl(line, pos))
}
}
impl RCompleter {
fn complete_impl(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
// Check if we're inside a string - use Rust path completion with fuzzy matching
// This provides better UX than R's built-in completion:
// - Fuzzy matching: "rdm" matches "README.md"
// - Faster: no R evaluation needed
// - Hidden files shown last
if let Some(ctx) = detect_string_context(line, pos) {
return complete_path_in_string(line, pos, &ctx);
}
// Fuzzy namespace completion: intercept pkg::partial before R's built-in
if self.fuzzy_namespace
&& let Some(ns_token) = parse_namespace_token(line, pos)
{
let input = &line[ns_token.start_pos..pos];
// Debounce: reuse cached results if same input at same position within window
if self.is_namespace_fuzzy_cache_hit(input, ns_token.start_pos) {
return self
.namespace_fuzzy_cache
.as_ref()
.unwrap()
.suggestions
.clone();
}
let suggestions = self.complete_namespace_fuzzy(&ns_token, pos);
// Cache the results
self.namespace_fuzzy_cache = Some(NamespaceFuzzyCache {
input: input.to_string(),
start_pos: ns_token.start_pos,
suggestions: suggestions.clone(),
timestamp: Instant::now(),
});
return suggestions;
}
// Fuzzy library completion: intercept library()/require() before R's built-in
if self.fuzzy_namespace
&& let Some(lib_ctx) = detect_library_context(line, pos, &self.package_functions)
{
return self.complete_library_fuzzy(&lib_ctx, pos);
}
// Get the token being completed (for filtering and span calculation)
let token = arf_harp::completion::get_token(line, pos).unwrap_or_default();
let context = completion_context(line, pos, &token);
// Try to use cache for prefix extensions or debounced requests
let completions = if context
.as_ref()
.is_some_and(|context| self.should_use_cache(context))
{
// Use cached results, filtering for the current token
self.filter_cached(&token)
} else {
// Fetch fresh completions using the configured static/R policy.
let fresh = match arf_harp::completion::get_completions_with_policy(
line,
pos,
self.timeout_ms,
&self.static_formals,
) {
Ok(c) => c,
Err(_) => {
// On error, invalidate cache and return empty
self.invalidate_cache();
return vec![];
}
};
// Only cache non-empty results with non-empty tokens
if !fresh.is_empty()
&& !token.is_empty()
&& let Some(context) = context
{
self.cache = Some(CompletionCache {
token: context.token,
prefix: context.prefix,
suffix: context.suffix,
completions: fresh.clone(),
timestamp: Instant::now(),
});
}
fresh
};
if completions.is_empty() {
return vec![];
}
// Filter completions: include if starts with token and (different from token OR is a function)
// This allows "foo" -> "foo(" completion when foo is a function
let filtered: Vec<String> = completions
.into_iter()
.filter(|c| c.starts_with(&token))
.collect();
if filtered.is_empty() {
return vec![];
}
// Determine which completions are functions (for parenthesis insertion)
let is_function = if self.auto_paren_limit > 0 {
self.check_function_types(&filtered)
} else {
vec![false; filtered.len()]
};
// Convert to reedline Suggestions
let match_len = token.len();
filtered
.into_iter()
.zip(is_function)
.filter(|(c, is_func)| {
// Include if: different from token, OR is a function (will get "(" added)
c != &token || (*is_func && !has_special_suffix(c))
})
.map(|(c, is_func)| {
let start = pos - token.len();
let indices = if match_len > 0 {
Some((0..match_len).collect())
} else {
None
};
// Add "()" suffix for functions
// FunctionAwareMenu will move cursor back to place it inside: foo(|)
let (value, extra_info) = if is_func && !has_special_suffix(&c) {
(format!("{}()", c), Some("function".to_string()))
} else {
(c, None)
};
Suggestion {
value,
display_override: None,
description: extra_info,
extra: None,
span: Span { start, end: pos },
append_whitespace: false,
style: None,
match_indices: indices,
}
})
.collect()
}
}
impl RCompleter {
/// Check which completions are functions.
///
/// Only checks up to `auto_paren_limit` items for performance.
fn check_function_types(&self, completions: &[String]) -> Vec<bool> {
// Only check the first N items
let check_count = completions.len().min(self.auto_paren_limit);
if check_count == 0 {
return vec![false; completions.len()];
}
// Collect names to check (exclude items with special suffixes)
let names_to_check: Vec<&str> = completions[..check_count]
.iter()
.map(|s| {
if has_special_suffix(s) {
// Don't check items with special suffixes
""
} else {
s.as_str()
}
})
.collect();
// Call R to check function types
let checked = arf_harp::completion::check_if_functions(&names_to_check).unwrap_or_default();
// Extend with false for remaining items (not checked)
let mut result = checked;
result.resize(completions.len(), false);
result
}
}
#[cfg(test)]
mod tests;