| @@ -0,0 +1,881 @@ |
| 1 | //! Tab completions for iamb |
| 2 | use std::borrow::Cow; |
| 3 | use std::str::FromStr; |
| 4 | |
| 5 | use 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 | |
| 23 | use crate::base::{ChatStore, IambBufferId, IambInfo, MATRIX_ID_WORD, RoomFocus}; |
| 24 | |
| 25 | mod 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. |
| 274 | fn 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.) |
| 284 | fn 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 |
| 299 | fn complete_verification(input: &str, store: &ChatStore) -> Vec<String> { |
| 300 | store.verifications.complete(input) |
| 301 | } |
| 302 | |
| 303 | /// Tab completion for Emoji shortcode names. |
| 304 | fn complete_emoji(input: &str, store: &ChatStore) -> Vec<String> { |
| 305 | store.emojis.complete(input) |
| 306 | } |
| 307 | |
| 308 | /// Tab completion for compile-time known strings |
| 309 | fn 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 |
| 318 | fn 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` |
| 332 | fn 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` |
| 341 | fn 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` |
| 357 | fn 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` |
| 375 | fn 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` |
| 386 | fn 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` |
| 398 | fn 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` |
| 406 | fn 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" |
| 414 | fn 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` |
| 478 | fn 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` |
| 509 | fn 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. |
| 518 | fn 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. |
| 629 | fn 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. |
| 645 | fn 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. |
| 662 | fn 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. |
| 671 | fn 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 | |
| 716 | pub struct IambCompleter; |
| 717 | |
| 718 | impl 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)] |
| 746 | pub 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 | } |