Commit fc1c1649a8

fc1c1649a87fe84bf8b199a2e0e2b3d8fb200994

parent: 04010126ff

Unregistered key

vaw <git@nlih.de> · 2026-09-04 17:02 UTC
committer: <noreply@github.com>

Improve completions (#520)

Layout: unified · split

src/base.rs +3 −273
@@ -7,7 +7,6 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
7use std::convert::TryFrom; 7use std::convert::TryFrom;
8use std::fmt::{self, Display}; 8use std::fmt::{self, Display};
9use std::hash::Hash; 9use std::hash::Hash;
10use std::str::FromStr;
11use std::sync::Arc; 10use std::sync::Arc;
12use std::time::{Duration, Instant}; 11use std::time::{Duration, Instant};
13 12
@@ -82,14 +81,12 @@ use modalkit::{
82 ApplicationStore, 81 ApplicationStore,
83 ApplicationWindowId, 82 ApplicationWindowId,
84 }, 83 },
85 completion::{Completer, CompletionMap, complete_path}, 84 completion::CompletionMap,
86 context::EditContext, 85 context::EditContext,
87 cursor::Cursor,
88 rope::EditRope,
89 store::Store, 86 store::Store,
90 }, 87 },
91 env::vim::{ 88 env::vim::{
92 command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine}, 89 command::{CommandContext, VimCommand, VimCommandMachine},
93 keybindings::VimMachine, 90 keybindings::VimMachine,
94 }, 91 },
95 errors::{UIError, UIResult}, 92 errors::{UIError, UIResult},
@@ -194,7 +191,6 @@ pub enum MessageAction {
194#[derive(Clone, Debug, Eq, PartialEq)] 191#[derive(Clone, Debug, Eq, PartialEq)]
195pub enum SpaceAction { 192pub enum SpaceAction {
196 /// Add a room or update metadata. 193 /// Add a room or update metadata.
197 ///
198 SetChild { 194 SetChild {
199 /// The room ID, alias, or a user whose DM room should be added to the space. 195 /// The room ID, alias, or a user whose DM room should be added to the space.
200 child: String, 196 child: String,
@@ -1843,7 +1839,7 @@ pub struct ChatStore {
1843 pub presences: CompletionMap<OwnedUserId, PresenceState>, 1839 pub presences: CompletionMap<OwnedUserId, PresenceState>,
1844 1840
1845 /// In-progress and completed verifications. 1841 /// In-progress and completed verifications.
1846 pub verifications: HashMap<String, SasVerification>, 1842 pub verifications: CompletionMap<String, SasVerification>,
1847 1843
1848 /// Settings for the current profile loaded from config file. 1844 /// Settings for the current profile loaded from config file.
1849 pub settings: ApplicationSettings, 1845 pub settings: ApplicationSettings,
@@ -2251,197 +2247,6 @@ impl ApplicationInfo for IambInfo {
2251 } 2247 }
2252} 2248}
2253 2249
2254pub struct IambCompleter;
2255
2256impl Completer<IambInfo> for IambCompleter {
2257 fn complete(
2258 &mut self,
2259 text: &EditRope,
2260 cursor: &mut Cursor,
2261 content: &IambBufferId,
2262 store: &mut ChatStore,
2263 ) -> Vec<String> {
2264 match content {
2265 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
2266 IambBufferId::Command(CommandType::Search) => vec![],
2267 IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
2268 IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
2269
2270 IambBufferId::DirectList => vec![],
2271 IambBufferId::MemberList(_) => vec![],
2272 IambBufferId::RoomList => vec![],
2273 IambBufferId::SpaceList => vec![],
2274 IambBufferId::VerifyList => vec![],
2275 IambBufferId::Welcome => vec![],
2276 IambBufferId::ChatList => vec![],
2277 IambBufferId::UnreadList => vec![],
2278 IambBufferId::MentionsList => vec![],
2279 }
2280 }
2281}
2282
2283/// Tab completion for user IDs.
2284fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2285 let id = text
2286 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2287 .unwrap_or_else(EditRope::empty);
2288 let id = Cow::from(&id);
2289
2290 store
2291 .presences
2292 .complete(id.as_ref())
2293 .into_iter()
2294 .map(|i| i.to_string())
2295 .collect()
2296}
2297
2298/// Tab completion within the message bar.
2299fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2300 let id = text
2301 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2302 .unwrap_or_else(EditRope::empty);
2303 let id = Cow::from(&id);
2304
2305 match id.chars().next() {
2306 // Complete room aliases.
2307 Some('#') => {
2308 return store.names.complete(id.as_ref());
2309 },
2310
2311 // Complete room identifiers.
2312 Some('!') => {
2313 return store
2314 .rooms
2315 .complete(id.as_ref())
2316 .into_iter()
2317 .map(|i| i.to_string())
2318 .collect();
2319 },
2320
2321 // Complete Emoji shortcodes.
2322 Some(':') => {
2323 let list = store.emojis.complete(&id[1..]);
2324 let iter = list.into_iter().take(200).map(|s| format!(":{s}:"));
2325
2326 return iter.collect();
2327 },
2328
2329 // Complete usernames for @ and empty strings.
2330 Some('@') | None => {
2331 return store
2332 .presences
2333 .complete(id.as_ref())
2334 .into_iter()
2335 .map(|i| i.to_string())
2336 .collect();
2337 },
2338
2339 // Unknown sigil.
2340 Some(_) => return vec![],
2341 }
2342}
2343
2344/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
2345fn complete_matrix_names(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2346 let id = text
2347 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2348 .unwrap_or_else(EditRope::empty);
2349 let id = Cow::from(&id);
2350
2351 let list = store.names.complete(id.as_ref());
2352 if !list.is_empty() {
2353 return list;
2354 }
2355
2356 let list = store.presences.complete(id.as_ref());
2357 if !list.is_empty() {
2358 return list.into_iter().map(|i| i.to_string()).collect();
2359 }
2360
2361 store
2362 .rooms
2363 .complete(id.as_ref())
2364 .into_iter()
2365 .map(|i| i.to_string())
2366 .collect()
2367}
2368
2369/// Tab completion for Emoji shortcode names.
2370fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2371 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2372 let sc = sc.unwrap_or_else(EditRope::empty);
2373 let sc = Cow::from(&sc);
2374
2375 store.emojis.complete(sc.as_ref())
2376}
2377
2378/// Tab completion for command names.
2379fn complete_cmdname(
2380 desc: CommandDescription,
2381 text: &EditRope,
2382 cursor: &mut Cursor,
2383 store: &ChatStore,
2384) -> Vec<String> {
2385 // Complete command name and set cursor position.
2386 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2387 store.cmds.complete_name(desc.command.as_str())
2388}
2389
2390/// Tab completion for command arguments.
2391fn complete_cmdarg(
2392 desc: CommandDescription,
2393 text: &EditRope,
2394 cursor: &mut Cursor,
2395 store: &ChatStore,
2396) -> Vec<String> {
2397 let cmd = match store.cmds.get(desc.command.as_str()) {
2398 Ok(cmd) => cmd,
2399 Err(_) => return vec![],
2400 };
2401
2402 match cmd.name.as_str() {
2403 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
2404 "members" | "rooms" | "spaces" | "welcome" => vec![],
2405 "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
2406 "react" | "unreact" => complete_emoji(text, cursor, store),
2407
2408 "invite" => complete_users(text, cursor, store),
2409 "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
2410 "room" => vec![],
2411 "verify" => vec![],
2412 "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
2413 complete_cmd(desc.arg.text.as_str(), text, cursor, store)
2414 },
2415 _ => vec![],
2416 }
2417}
2418
2419/// Tab completion for commands.
2420fn complete_cmd(cmd: &str, text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2421 match CommandDescription::from_str(cmd) {
2422 Ok(desc) => {
2423 if desc.arg.untrimmed.is_empty() {
2424 complete_cmdname(desc, text, cursor, store)
2425 } else {
2426 // Complete command argument.
2427 complete_cmdarg(desc, text, cursor, store)
2428 }
2429 },
2430
2431 // Can't parse command text, so return zero completions.
2432 Err(_) => vec![],
2433 }
2434}
2435
2436/// Tab completion for the command bar.
2437fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2438 let eo = text.cursor_to_offset(cursor);
2439 let slice = text.slice(..eo);
2440 let cow = Cow::from(&slice);
2441
2442 complete_cmd(cow.as_ref(), text, cursor, store)
2443}
2444
2445#[cfg(test)] 2250#[cfg(test)]
2446pub mod tests { 2251pub mod tests {
2447 use std::iter::FromIterator as _; 2252 use std::iter::FromIterator as _;
@@ -2609,81 +2414,6 @@ pub mod tests {
2609 )],); 2414 )],);
2610 } 2415 }
2611 2416
2612 #[tokio::test]
2613 async fn test_complete_msgbar() {
2614 let store = mock_store().await;
2615 let store = store.application;
2616
2617 let text = EditRope::from("going for a walk :walk ");
2618 let mut cursor = Cursor::new(0, 22);
2619 let res = complete_msgbar(&text, &mut cursor, &store);
2620 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2621 assert_eq!(cursor, Cursor::new(0, 17));
2622
2623 let text = EditRope::from("hello @user1 ");
2624 let mut cursor = Cursor::new(0, 12);
2625 let res = complete_msgbar(&text, &mut cursor, &store);
2626 assert_eq!(res, vec!["@user1:example.com"]);
2627 assert_eq!(cursor, Cursor::new(0, 6));
2628
2629 let text = EditRope::from("see #room ");
2630 let mut cursor = Cursor::new(0, 9);
2631 let res = complete_msgbar(&text, &mut cursor, &store);
2632 assert_eq!(res, vec!["#room1:example.com"]);
2633 assert_eq!(cursor, Cursor::new(0, 4));
2634 }
2635
2636 #[tokio::test]
2637 async fn test_complete_cmdbar() {
2638 let store = mock_store().await;
2639 let store = store.application;
2640 let users = vec![
2641 "@user1:example.com",
2642 "@user2:example.com",
2643 "@user3:example.com",
2644 "@user4:example.com",
2645 "@user5:example.com",
2646 ];
2647
2648 let text = EditRope::from("invite ");
2649 let mut cursor = Cursor::new(0, 7);
2650 let id = text
2651 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2652 .unwrap_or_else(EditRope::empty);
2653 assert_eq!(id.to_string(), "");
2654 assert_eq!(cursor, Cursor::new(0, 7));
2655
2656 let text = EditRope::from("invite ");
2657 let mut cursor = Cursor::new(0, 7);
2658 let res = complete_cmdbar(&text, &mut cursor, &store);
2659 assert_eq!(res, users);
2660
2661 let text = EditRope::from("invite ignored");
2662 let mut cursor = Cursor::new(0, 7);
2663 let res = complete_cmdbar(&text, &mut cursor, &store);
2664 assert_eq!(res, users);
2665
2666 let text = EditRope::from("invite @user1ignored");
2667 let mut cursor = Cursor::new(0, 13);
2668 let res = complete_cmdbar(&text, &mut cursor, &store);
2669 assert_eq!(res, vec!["@user1:example.com"]);
2670
2671 let text = EditRope::from("abo hor");
2672 let mut cursor = Cursor::new(0, 7);
2673 let res = complete_cmdbar(&text, &mut cursor, &store);
2674 assert_eq!(res, vec!["horizontal"]);
2675
2676 let text = EditRope::from("abo hor inv");
2677 let mut cursor = Cursor::new(0, 11);
2678 let res = complete_cmdbar(&text, &mut cursor, &store);
2679 assert_eq!(res, vec!["invite"]);
2680
2681 let text = EditRope::from("abo hor invite \n");
2682 let mut cursor = Cursor::new(0, 15);
2683 let res = complete_cmdbar(&text, &mut cursor, &store);
2684 assert_eq!(res, users);
2685 }
2686
2687 #[test] 2417 #[test]
2688 fn test_ambiguous_displaynames() { 2418 fn test_ambiguous_displaynames() {
2689 let mut store = DisplayNameStore::default(); 2419 let mut store = DisplayNameStore::default();
src/commands.rs +1 −1
@@ -962,7 +962,7 @@ fn iamb_logout(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
962 return Ok(step); 962 return Ok(step);
963} 963}
964 964
965fn add_iamb_commands(cmds: &mut ProgramCommands) { 965pub fn add_iamb_commands(cmds: &mut ProgramCommands) {
966 cmds.add_command(ProgramCommand { 966 cmds.add_command(ProgramCommand {
967 name: "cancel".into(), 967 name: "cancel".into(),
968 aliases: vec![], 968 aliases: vec![],
src/completions.rs added +881
@@ -0,0 +1,881 @@
1//! Tab completions for iamb
2use std::borrow::Cow;
3use std::str::FromStr;
4
5use modalkit::{
6 editing::{
7 completion::{Completer, complete_path},
8 cursor::Cursor,
9 rope::EditRope,
10 },
11 env::vim::command::CommandDescription,
12 prelude::{
13 CommandType,
14 Count,
15 CursorMovements,
16 CursorMovementsContext,
17 MoveDir1D,
18 MoveType,
19 WordStyle,
20 },
21};
22
23use crate::base::{ChatStore, IambBufferId, IambInfo, MATRIX_ID_WORD, RoomFocus};
24
25mod parse {
26 use nom::{
27 IResult,
28 Input,
29 OutputMode,
30 Parser,
31 branch::alt,
32 bytes::complete::{escaped_transform, is_not, tag},
33 character::complete::{char, space0, space1},
34 combinator::{cut, eof, opt, value},
35 error::{ErrorKind, ParseError},
36 };
37
38 fn parse_text(input: &str) -> IResult<&str, String> {
39 if input.is_empty() {
40 let err = ParseError::from_error_kind(input, ErrorKind::Eof);
41 let err = nom::Err::Error(err);
42 return Err(err);
43 }
44
45 let _ = is_not("\"")(input)?;
46
47 escaped_transform(
48 is_not("\t\n\\ |\""),
49 '\\',
50 alt((
51 value("\\", tag("\\")),
52 value(" ", tag(" ")),
53 value("#", tag("#")),
54 value("%", tag("%")),
55 value("|", tag("|")),
56 value("\"", tag("\"")),
57 )),
58 )(input)
59 }
60
61 fn parse_unclosed_quote(input: &str) -> IResult<&str, String> {
62 if input.is_empty() {
63 let err = ParseError::from_error_kind(input, ErrorKind::Eof);
64 let err = nom::Err::Error(err);
65 return Err(err);
66 }
67
68 let (input, _) = char('\"')(input)?;
69 let (input, text) = cut(escaped_transform(
70 is_not("\t\n\\\""),
71 '\\',
72 alt((
73 value("\t", tag("t")),
74 value("\r", tag("r")),
75 value("\n", tag("n")),
76 value("\\", tag("\\")),
77 value("\"", tag("\"")),
78 )),
79 ))
80 .parse(input)?;
81
82 Ok((input, text))
83 }
84
85 fn parse_quote(input: &str) -> IResult<&str, String> {
86 let (input, text) = parse_unclosed_quote(input)?;
87 let (input, _) = char('\"')(input)?;
88
89 Ok((input, text))
90 }
91
92 fn parse_string(input: &str) -> IResult<&str, String> {
93 alt((parse_quote, parse_text)).parse(input)
94 }
95
96 /// Acts linke [`separated_list0`](nom::multi::separated_list0) but additionally returns a copy of the last element unparsed.
97 // This implementation is mostely copied from nom.
98 pub fn separated_list0_last_raw<I, E, F, G>(
99 sep: G,
100 f: F,
101 ) -> impl Parser<I, Output = (Vec<<F as Parser<I>>::Output>, I), Error = E>
102 where
103 I: Clone + Input,
104 F: Parser<I, Error = E>,
105 G: Parser<I, Error = E>,
106 E: ParseError<I>,
107 {
108 SeparatedList0LastRaw { parser: f, separator: sep }
109 }
110
111 /// Parser implementation for the [separated_list0_last_raw] combinator
112 pub struct SeparatedList0LastRaw<F, G> {
113 parser: F,
114 separator: G,
115 }
116
117 impl<I, E: ParseError<I>, F, G> Parser<I> for SeparatedList0LastRaw<F, G>
118 where
119 I: Clone + Input,
120 F: Parser<I, Error = E>,
121 G: Parser<I, Error = E>,
122 {
123 type Output = (Vec<<F as Parser<I>>::Output>, I);
124 type Error = <F as Parser<I>>::Error;
125
126 fn process<OM: OutputMode>(
127 &mut self,
128 mut i: I,
129 ) -> nom::PResult<OM, I, Self::Output, Self::Error> {
130 use nom::{Check, Err, Mode, OutputM};
131
132 let mut res = OM::Output::bind(|| (nom::lib::std::vec::Vec::new(), i.clone()));
133
134 match self
135 .parser
136 .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i.clone())
137 {
138 Err(Err::Error(_)) => return Ok((i, res)),
139 Err(Err::Failure(e)) => return Err(Err::Failure(e)),
140 Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
141 Ok((i1, o)) => {
142 res = OM::Output::combine(res, o, |mut res, o| {
143 res.0.push(o);
144 res
145 });
146 i = i1;
147 },
148 }
149
150 loop {
151 let len = i.input_len();
152 match self.separator.process::<OutputM<Check, Check, OM::Incomplete>>(i.clone()) {
153 Err(Err::Error(_)) => return Ok((i, res)),
154 Err(Err::Failure(e)) => return Err(Err::Failure(e)),
155 Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
156 Ok((i1, _)) => {
157 match self
158 .parser
159 .process::<OutputM<OM::Output, Check, OM::Incomplete>>(i1.clone())
160 {
161 Err(Err::Error(_)) => return Ok((i, res)),
162 Err(Err::Failure(e)) => return Err(Err::Failure(e)),
163 Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),
164 Ok((i2, o)) => {
165 // infinite loop check: the parser must always consume
166 if i2.input_len() == len {
167 return Err(Err::Error(OM::Error::bind(|| {
168 <F as Parser<I>>::Error::from_error_kind(
169 i,
170 ErrorKind::SeparatedList,
171 )
172 })));
173 }
174
175 res = OM::Output::combine(res, o, |mut res, o| {
176 res.0.push(o);
177 res.1 = i1;
178 res
179 });
180
181 i = i2;
182 },
183 }
184 },
185 }
186 }
187 }
188 }
189
190 fn parse_last_arg(input: &str) -> IResult<&str, (String, &str)> {
191 let (input, _) = space0(input)?;
192
193 let old_input = input;
194 let (input, arg) = opt(parse_unclosed_quote).parse(input)?;
195
196 Ok((input, (arg.unwrap_or_default(), old_input)))
197 }
198
199 fn parse_trailing_last_arg(input: &str) -> IResult<&str, (String, &str)> {
200 let (input, _) = space1(input)?;
201
202 parse_last_arg(input)
203 }
204
205 /// Returns a list with the parsed strings and a raw version of the last string to be stripped
206 /// from the input before completing.
207 pub fn parse_started_strings(input: &str) -> IResult<&str, (Vec<String>, &str)> {
208 let (input, (mut args, mut last_arg_raw)) =
209 separated_list0_last_raw(space1, parse_string).parse(input)?;
210 // let (input, mut args) = separated_list0_last_raw(space1, parse_string).parse(input)?;
211 // let last_arg_raw = todo!();
212
213 let (input, end_arg) = if args.is_empty() {
214 opt(parse_last_arg).parse(input)?
215 } else {
216 opt(parse_trailing_last_arg).parse(input)?
217 };
218
219 let (input, _) = eof(input)?;
220
221 if let Some((arg, end_arg_raw)) = end_arg {
222 args.push(arg);
223 last_arg_raw = end_arg_raw;
224 }
225
226 if args.is_empty() {
227 args.push(String::new());
228 }
229
230 Ok((input, (args, last_arg_raw)))
231 }
232
233 #[cfg(test)]
234 mod tests {
235 use super::*;
236
237 #[test]
238 fn parse_strings() {
239 let text = "some normal args";
240 let parsed = parse_started_strings(text).unwrap();
241 assert_eq!(("", (vec!["some".into(), "normal".into(), "args".into()], "args")), parsed);
242
243 let text = "started ";
244 let parsed = parse_started_strings(text).unwrap();
245 assert_eq!(("", (vec!["started".into(), "".into()], "")), parsed);
246
247 let text = "args \"with quotes\"";
248 let parsed = parse_started_strings(text).unwrap();
249 assert_eq!(
250 ("", (vec!["args".into(), "with quotes".into()], "\"with quotes\"")),
251 parsed
252 );
253
254 let text = "and \"started ";
255 let parsed = parse_started_strings(text).unwrap();
256 assert_eq!(("", (vec!["and".into(), "started ".into()], "\"started ")), parsed);
257
258 let text = "\"only started ";
259 let parsed = parse_started_strings(text).unwrap();
260 assert_eq!(("", (vec!["only started ".into()], "\"only started ")), parsed);
261
262 let text = " ";
263 let parsed = parse_started_strings(text).unwrap();
264 assert_eq!(("", (vec!["".into()], "")), parsed);
265
266 let text = "escaped\\ spaces here";
267 let parsed = parse_started_strings(text).unwrap();
268 assert_eq!(("", (vec!["escaped spaces".into(), "here".into()], "here")), parsed);
269 }
270 }
271}
272
273/// Tab completion for user IDs.
274fn complete_users(input: &str, store: &ChatStore) -> Vec<String> {
275 store
276 .presences
277 .complete(input)
278 .into_iter()
279 .map(|i| i.to_string())
280 .collect()
281}
282
283/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
284fn complete_matrix_names(input: &str, store: &ChatStore) -> Vec<String> {
285 let list = store.names.complete(input);
286 if !list.is_empty() {
287 return list;
288 }
289
290 let list = store.presences.complete(input);
291 if !list.is_empty() {
292 return list.into_iter().map(|i| i.to_string()).collect();
293 }
294
295 store.rooms.complete(input).into_iter().map(|i| i.to_string()).collect()
296}
297
298/// Tab completion for open verification requests
299fn complete_verification(input: &str, store: &ChatStore) -> Vec<String> {
300 store.verifications.complete(input)
301}
302
303/// Tab completion for Emoji shortcode names.
304fn complete_emoji(input: &str, store: &ChatStore) -> Vec<String> {
305 store.emojis.complete(input)
306}
307
308/// Tab completion for compile-time known strings
309fn complete_choices(input: &str, options: &[&'static str]) -> Vec<String> {
310 options
311 .iter()
312 .filter(|opt| opt.starts_with(input))
313 .map(|opt| opt.to_string())
314 .collect()
315}
316
317/// Tab completion for vim-like options
318fn complete_options(args: &[String], options: &[&'static str]) -> Vec<String> {
319 let opts: Vec<_> = options
320 .iter()
321 .filter(|o| {
322 !args
323 .iter()
324 .any(|arg| arg.as_str() == **o || (o.ends_with('=') && arg.starts_with(*o)))
325 })
326 .copied()
327 .collect();
328 complete_choices(args.last().unwrap(), opts.as_slice())
329}
330
331/// Tab completion for `:invite`
332fn complete_iamb_invite(args: Vec<String>, store: &ChatStore) -> Vec<String> {
333 match args.len() {
334 1 => complete_choices(&args[0], &["accept", "reject", "send"]),
335 2 if args[0] == "send" => complete_users(&args[1], store),
336 _ => vec![],
337 }
338}
339
340/// Tab completion for `:knock`
341fn complete_iamb_knock(args: Vec<String>, store: &ChatStore) -> Vec<String> {
342 match args.len() {
343 1 => complete_choices(&args[0], &["send", "accept", "reject", "ban"]),
344 2 if args[0] == "send" => {
345 // Don't complete with the known room aliases since the users most likely wants to knock
346 // on an unknown room.
347 vec![]
348 },
349 2 if ["accept", "reject", "ban"].contains(&args[0].as_str()) => {
350 complete_users(&args[1], store)
351 },
352 _ => vec![],
353 }
354}
355
356/// Tab completion for `:keys`
357fn complete_iamb_keys(
358 args: Vec<String>,
359 input: &EditRope,
360 orig_cursor: Cursor,
361 cursor: &mut Cursor,
362) -> Vec<String> {
363 let subcmds = ["export", "import"];
364 match args.len() {
365 1 => complete_choices(&args[0], &subcmds),
366 2 if subcmds.contains(&args[0].as_str()) => {
367 *cursor = orig_cursor;
368 complete_path(input, cursor)
369 },
370 _ => vec![],
371 }
372}
373
374/// Tab completion for `:verify`
375fn complete_iamb_verify(args: Vec<String>, store: &ChatStore) -> Vec<String> {
376 let subcmds = ["request", "accept", "confirm", "cancel", "missmatch"];
377 match args.len() {
378 1 => complete_choices(&args[0], &subcmds),
379 2 if args[0] == "request" => complete_users(&args[1], store),
380 2 if subcmds.contains(&args[0].as_str()) => complete_verification(&args[1], store),
381 _ => vec![],
382 }
383}
384
385/// Tab completion for `:self`
386fn complete_iamb_self(args: Vec<String>) -> Vec<String> {
387 let subcmds = ["avatar", "name", "nick", "timezone", "tz"];
388 match args.len() {
389 1 => complete_choices(&args[0], &subcmds),
390 2 if subcmds.contains(&args[0].as_str()) => {
391 complete_choices(&args[1], &["set", "unset", "show"])
392 },
393 _ => vec![],
394 }
395}
396
397/// Tab completion for `:unreads`
398fn complete_iamb_unreads(args: Vec<String>) -> Vec<String> {
399 match args.len() {
400 1 if "clear".starts_with(&args[0]) => vec!["clear".to_string()],
401 _ => vec![],
402 }
403}
404
405/// Tab completion for `:create`
406fn complete_iamb_create(args: Vec<String>) -> Vec<String> {
407 let options = ["++alias=", "++public", "++space", "++encrypted"];
408 complete_options(args.as_slice(), &options)
409}
410
411/// Tab completion for `:room`
412// TODO: Check whether we can get the id of the focused room to improve
413// "kick","ban","unban", ".. unset" and "dm/tag set/unset"
414fn complete_iamb_room(args: Vec<String>, store: &ChatStore) -> Vec<String> {
415 let subcmds = [
416 "dm",
417 "kick",
418 "ban",
419 "unban",
420 "history",
421 "name",
422 "topic",
423 "tag",
424 "notify",
425 "alias",
426 "canonicalalias",
427 "id",
428 "unread",
429 "version",
430 ];
431 if args.len() == 1 {
432 complete_choices(&args[0], &subcmds)
433 } else if args.len() == 2 {
434 let input = &args[1];
435 match args[0].as_str() {
436 "kick" | "ban" | "unban" => complete_users(input, store),
437 "id" => complete_choices(input, &["show"]),
438 "dm" | "name" | "tag" => complete_choices(input, &["set", "unset"]),
439
440 "history" | "topic" | "notify" | "alias" | "canonicalalias" | "canon" => {
441 complete_choices(input, &["show", "set", "unset"])
442 },
443
444 "unread" => complete_choices(input, &["set", "unset", "clear"]),
445 "version" => complete_choices(input, &["show", "upgrade"]),
446
447 _ => vec![],
448 }
449 } else if args.len() == 3 {
450 let input = &args[2];
451 match (args[0].as_str(), args[1].as_str()) {
452 ("history", "set") => {
453 complete_choices(input, &["invited", "joined", "shared", "world_readable"])
454 },
455 ("tag", "set") | ("tag", "unset") => {
456 complete_choices(input, &["favourite", "lowpriority", "server_notice", "u."])
457 },
458 ("notify", "set") => complete_choices(input, &["mute", "mentions", "keywords", "all"]),
459 ("version", "upgrade") => {
460 complete_choices(input, &[
461 "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
462 ])
463 },
464
465 _ => vec![],
466 }
467 } else {
468 let input = args.last().unwrap();
469 match (args[0].as_str(), args[1].as_str()) {
470 ("version", "upgrade") => complete_users(input, store),
471
472 _ => vec![],
473 }
474 }
475}
476
477/// Tab completion for `:space`
478fn complete_iamb_space(args: Vec<String>, store: &ChatStore) -> Vec<String> {
479 if args.len() == 1 {
480 complete_choices(&args[0], &["child"])
481 } else if args.len() == 2 && &args[0] == "child" {
482 complete_choices(&args[1], &["set", "remove"])
483 } else if args.len() > 2 && &args[0] == "child" && args[1] == "set" {
484 let options = ["++suggested", "++order="];
485
486 let has_room = args.iter().skip(2).rev().skip(1).any(|arg| !arg.starts_with('+'));
487
488 let arg = args.last().unwrap();
489
490 if arg.is_empty() {
491 let mut opts = complete_options(args.as_slice(), &options);
492 if !has_room {
493 opts.extend(complete_matrix_names(arg, store));
494 }
495 opts
496 } else if arg.starts_with('+') {
497 complete_options(args.as_slice(), &options)
498 } else if !has_room {
499 complete_matrix_names(arg, store)
500 } else {
501 vec![]
502 }
503 } else {
504 vec![]
505 }
506}
507
508/// Tab completion for `:logout`
509fn complete_iamb_logout(args: Vec<String>, store: &ChatStore) -> Vec<String> {
510 let id = store.settings.profile.user_id.as_str();
511 match args.len() {
512 1 if id.starts_with(&args[0]) => vec![id.to_string()],
513 _ => vec![],
514 }
515}
516
517/// Tab completion for command arguments.
518fn complete_cmdarg(
519 desc: CommandDescription,
520 input: &EditRope,
521 cursor: &mut Cursor,
522 store: &ChatStore,
523) -> Vec<String> {
524 let cmd = match store.cmds.get(desc.command.as_str()) {
525 Ok(cmd) => cmd,
526 Err(_) => return vec![],
527 };
528
529 let Ok((_, (args, to_strip))) = parse::parse_started_strings(&desc.arg.text) else {
530 return vec![];
531 };
532 debug_assert!(!args.is_empty()); // empty string is inserted if text is empty
533
534 // move cursor to start of last arg
535 let ctx = CursorMovementsContext {
536 action: &Default::default(),
537 view: &Default::default(),
538 context: &Default::default(),
539 };
540 let movement = MoveType::Column(MoveDir1D::Previous, true);
541 let count = Count::Exact(to_strip.len());
542 let Some(new_cursor) = input.movement(cursor, &movement, &count, &ctx) else {
543 return vec![];
544 };
545 let orig_cursor = cursor.clone();
546 *cursor = new_cursor;
547
548 let mut completions = match cmd.name.as_str() {
549 "create" => complete_iamb_create(args),
550
551 "follow" => complete_choices(&args[0], &["next", "previous"]),
552
553 "invite" => complete_iamb_invite(args, store),
554
555 "join" if args.len() == 1 => complete_matrix_names(&args[0], store),
556 "join" => vec![],
557
558 "keys" => complete_iamb_keys(args, input, orig_cursor, cursor),
559
560 "knock" => complete_iamb_knock(args, store),
561
562 "logout" => complete_iamb_logout(args, store),
563
564 "react" if args.len() == 1 => complete_emoji(&args[0], store),
565 "react" => vec![],
566
567 // The redaction reason is free text
568 "redact" => vec![],
569
570 "room" => complete_iamb_room(args, store),
571
572 "self" => complete_iamb_self(args),
573
574 "space" => complete_iamb_space(args, store),
575
576 // TODO: Check whether we can get the id of the focused message to improve completion
577 "unreact" if args.len() == 1 => complete_emoji(&args[0], store),
578 "unreact" => vec![],
579
580 "unreads" => complete_iamb_unreads(args),
581
582 "upload" | "download" | "open" => {
583 if input.get_char_at_cursor(cursor) == Some('"') {
584 // Use the escaped instead of the qouted filename.
585 let mut args = args;
586 vec![args.pop().unwrap()]
587 } else {
588 *cursor = orig_cursor;
589 return complete_path(input, cursor);
590 }
591 },
592
593 "verify" => complete_iamb_verify(args, store),
594
595 // These have no arguments
596 "cancel" | "chats" | "dms" | "editor" | "edit" | "forget" | "leave" | "members" |
597 "mentions" | "replied" | "reply" | "rooms" | "spaces" | "welcome" => vec![],
598
599 "abo" | "aboveleft" | "bel" | "belowright" | "hor" | "horizontal" | "lefta" |
600 "leftabove" | "rightb" | "rightbelow" | "tab" | "vert" | "vertical" => {
601 complete_cmd(desc.arg.text.as_str(), input, cursor, store)
602 },
603
604 _cmd => {
605 #[cfg(test)]
606 panic!("trying to complete unknown subcommand `{}`", _cmd);
607
608 #[cfg(not(test))]
609 vec![]
610 },
611 };
612
613 completions.iter_mut().for_each(|completion| {
614 if completion.contains(['\\', ' ', '#', '%', '"', '|']) {
615 *completion = completion
616 .replace('\\', "\\\\")
617 .replace(' ', "\\ ")
618 .replace('#', "\\#")
619 .replace('%', "\\%")
620 .replace('"', "\\\"")
621 .replace('|', "\\|");
622 }
623 });
624
625 completions
626}
627
628/// Tab completion for command names.
629fn complete_cmdname(
630 desc: CommandDescription,
631 text: &EditRope,
632 cursor: &mut Cursor,
633 store: &ChatStore,
634) -> Vec<String> {
635 // Complete command name and set cursor position.
636 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
637 let mut comps = store.cmds.complete_name(desc.command.as_str());
638
639 comps.extend(store.cmds.complete_aliases(desc.command.as_str()));
640
641 comps
642}
643
644/// Tab completion for commands.
645fn complete_cmd(cmd: &str, text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
646 match CommandDescription::from_str(cmd) {
647 Ok(desc) => {
648 if desc.arg.untrimmed.is_empty() {
649 complete_cmdname(desc, text, cursor, store)
650 } else {
651 // Complete command argument.
652 complete_cmdarg(desc, text, cursor, store)
653 }
654 },
655
656 // Can't parse command text, so return zero completions.
657 Err(_) => vec![],
658 }
659}
660
661/// Tab completion for the command bar.
662fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
663 let eo = text.cursor_to_offset(cursor);
664 let slice = text.slice(..eo);
665 let cow = Cow::from(&slice);
666
667 complete_cmd(cow.as_ref(), text, cursor, store)
668}
669
670/// Tab completion within the message bar.
671fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
672 let id = text
673 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
674 .unwrap_or_else(EditRope::empty);
675 let id = Cow::from(&id);
676
677 match id.chars().next() {
678 // Complete room aliases.
679 Some('#') => {
680 return store.names.complete(id.as_ref());
681 },
682
683 // Complete room identifiers.
684 Some('!') => {
685 return store
686 .rooms
687 .complete(id.as_ref())
688 .into_iter()
689 .map(|i| i.to_string())
690 .collect();
691 },
692
693 // Complete Emoji shortcodes.
694 Some(':') => {
695 let list = store.emojis.complete(&id[1..]);
696 let iter = list.into_iter().take(200).map(|s| format!(":{s}:"));
697
698 return iter.collect();
699 },
700
701 // Complete usernames for @ and empty strings.
702 Some('@') | None => {
703 return store
704 .presences
705 .complete(id.as_ref())
706 .into_iter()
707 .map(|i| i.to_string())
708 .collect();
709 },
710
711 // Unknown sigil.
712 Some(_) => return vec![],
713 }
714}
715
716pub struct IambCompleter;
717
718impl Completer<IambInfo> for IambCompleter {
719 fn complete(
720 &mut self,
721 text: &EditRope,
722 cursor: &mut Cursor,
723 content: &IambBufferId,
724 store: &mut ChatStore,
725 ) -> Vec<String> {
726 match content {
727 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
728 IambBufferId::Command(CommandType::Search) => vec![],
729 IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
730 IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
731
732 IambBufferId::DirectList => vec![],
733 IambBufferId::MemberList(_) => vec![],
734 IambBufferId::RoomList => vec![],
735 IambBufferId::SpaceList => vec![],
736 IambBufferId::VerifyList => vec![],
737 IambBufferId::Welcome => vec![],
738 IambBufferId::ChatList => vec![],
739 IambBufferId::UnreadList => vec![],
740 IambBufferId::MentionsList => vec![],
741 }
742 }
743}
744
745#[cfg(test)]
746pub mod tests {
747 use super::*;
748 use crate::{
749 base::{ProgramCommand, ProgramCommands},
750 commands::add_iamb_commands,
751 tests::*,
752 };
753 use modalkit::{commands::CommandResult, env::vim::command::CommandContext};
754 use pretty_assertions::assert_eq;
755
756 #[tokio::test]
757 async fn test_complete_msgbar() {
758 let store = mock_store().await;
759 let store = store.application;
760
761 let text = EditRope::from("going for a walk :walk ");
762 let mut cursor = Cursor::new(0, 22);
763 let res = complete_msgbar(&text, &mut cursor, &store);
764 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
765 assert_eq!(cursor, Cursor::new(0, 17));
766
767 let text = EditRope::from("hello @user1 ");
768 let mut cursor = Cursor::new(0, 12);
769 let res = complete_msgbar(&text, &mut cursor, &store);
770 assert_eq!(res, vec!["@user1:example.com"]);
771 assert_eq!(cursor, Cursor::new(0, 6));
772
773 let text = EditRope::from("see #room ");
774 let mut cursor = Cursor::new(0, 9);
775 let res = complete_msgbar(&text, &mut cursor, &store);
776 assert_eq!(res, vec!["#room1:example.com"]);
777 assert_eq!(cursor, Cursor::new(0, 4));
778 }
779
780 #[tokio::test]
781 async fn test_complete_cmdbar() {
782 let store = mock_store().await;
783 let store = store.application;
784 let cmds = vec!["accept", "reject", "send"];
785 let users = vec![
786 "@user1:example.com",
787 "@user2:example.com",
788 "@user3:example.com",
789 "@user4:example.com",
790 "@user5:example.com",
791 ];
792
793 let text = EditRope::from("invite ");
794 let mut cursor = Cursor::new(0, 7);
795 let id = text
796 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
797 .unwrap_or_else(EditRope::empty);
798 assert_eq!(id.to_string(), "");
799 assert_eq!(cursor, Cursor::new(0, 7));
800
801 let text = EditRope::from("invite ");
802 let mut cursor = Cursor::new(0, 7);
803 let res = complete_cmdbar(&text, &mut cursor, &store);
804 assert_eq!(res, cmds);
805
806 let text = EditRope::from("invite ignored");
807 let mut cursor = Cursor::new(0, 7);
808 let res = complete_cmdbar(&text, &mut cursor, &store);
809 assert_eq!(res, cmds);
810
811 let text = EditRope::from("invite send @user1ignored");
812 let mut cursor = Cursor::new(0, 18);
813 let res = complete_cmdbar(&text, &mut cursor, &store);
814 assert_eq!(res, vec!["@user1:example.com"]);
815
816 let text = EditRope::from("abo hori");
817 let mut cursor = Cursor::new(0, 8);
818 let res = complete_cmdbar(&text, &mut cursor, &store);
819 assert_eq!(res, vec!["horizontal"]);
820
821 let text = EditRope::from("abo hor inv");
822 let mut cursor = Cursor::new(0, 11);
823 let res = complete_cmdbar(&text, &mut cursor, &store);
824 assert_eq!(res, vec!["invite"]);
825
826 let text = EditRope::from("abo hor invite send \n");
827 let mut cursor = Cursor::new(0, 20);
828 let res = complete_cmdbar(&text, &mut cursor, &store);
829 assert_eq!(res, users);
830 }
831
832 #[tokio::test]
833 async fn test_all_commands_complete() {
834 let mut cmds = ProgramCommands::new();
835 add_iamb_commands(&mut cmds);
836
837 let store = mock_store().await;
838 let mut store = store.application;
839 store.cmds = cmds;
840 let cmds = &store.cmds;
841
842 for command in cmds.complete_name("") {
843 let mut text = EditRope::from(command);
844 text += " ".into();
845 let mut cursor = text.last();
846 cursor.right(1);
847 complete_cmdbar(&text, &mut cursor, &store);
848 }
849 }
850
851 fn mock_command(
852 _: CommandDescription,
853 _: &mut CommandContext,
854 ) -> CommandResult<ProgramCommand> {
855 panic!("mock command called");
856 }
857
858 #[tokio::test]
859 #[should_panic(expected = "trying to complete unknown subcommand `testmockcommand`")]
860 async fn test_complete_unknown_panics() {
861 let mut cmds = ProgramCommands::new();
862 cmds.add_command(ProgramCommand {
863 name: "testmockcommand".into(),
864 aliases: vec![],
865 f: mock_command,
866 });
867
868 let store = mock_store().await;
869 let mut store = store.application;
870 store.cmds = cmds;
871 let cmds = &store.cmds;
872
873 for command in cmds.complete_name("") {
874 let mut text = EditRope::from(command);
875 text += " ".into();
876 let mut cursor = text.last();
877 cursor.right(1);
878 complete_cmdbar(&text, &mut cursor, &store);
879 }
880 }
881}
src/main.rs +2 −1
@@ -74,6 +74,7 @@ use ratatui::{
74 74
75mod base; 75mod base;
76mod commands; 76mod commands;
77mod completions;
77mod config; 78mod config;
78mod keybindings; 79mod keybindings;
79mod message; 80mod message;
@@ -93,7 +94,6 @@ use crate::{
93 ChatStore, 94 ChatStore,
94 HomeserverAction, 95 HomeserverAction,
95 IambAction, 96 IambAction,
96 IambCompleter,
97 IambError, 97 IambError,
98 IambId, 98 IambId,
99 IambInfo, 99 IambInfo,
@@ -103,6 +103,7 @@ use crate::{
103 ProgramContext, 103 ProgramContext,
104 ProgramStore, 104 ProgramStore,
105 }, 105 },
106 completions::IambCompleter,
106 config::{ApplicationSettings, Iamb}, 107 config::{ApplicationSettings, Iamb},
107 windows::IambWindow, 108 windows::IambWindow,
108 worker::{ClientWorker, LoginStyle, Requester, create_room}, 109 worker::{ClientWorker, LoginStyle, Requester, create_room},